var _prototypeLibURL="/WOF/TCExtensions.framework/WebServerResources/prototype.js";
if ("undefined" == typeof Prototype) {
	// include prototype library, if needed
	// the variable _prototypeLibURL will be set by the application delivering this file
	document.writeln("<"+"script type=\"text/javascript\" src=\""+_prototypeLibURL+"\"></"+"script>");
}

function TCNewsService(settings, elementMap) { 
	this.uId = ++TCNewsService.identifier;
	if (!settings) { TCNewsService.fatalMessage("Missing settings dictionary"); return; }
	if (!settings.channelId) { TCNewsService.fatalMessage("Missing channel id"); return; }
	this.channelId = settings.channelId;
	if (!elementMap) { TCNewsService.fatalMessage("Missing element map"); return; }
	this.serviceURL = settings.serviceURL?settings.serviceURL:"/cgi-bin/WebObjects/NewsService.woa/";
	if (!this.serviceURL) { TCNewsService.fatalMessage("Missing service URL"); return; }
	this.websiteContext = settings.context;
	switch (settings.mode) {
		default:
		case TCNewsService.MODE_APPLICATION:
			// set up for news main view
			this.batchIndex = 1;
			this.batchSize = settings.newsCount?settings.newsCount:5; //settings.batchSize?settings.batchSize:5;
			// create DOM objects
			$(elementMap.list).update(
				TC.tag("div",{id:"TCNErrorMessage"+this.uId,style:"display:none;position:absolute;background:#f90;color:#fff;padding:10px;z-index:20000",onclick:"this.style.display='none'"}," ") +
				TC.tag("div",{id:"TCNSWait"+this.uId,_class:"TCNSWait",style:"display:none"}," ")+
				TC.tag("div",{id:"TCNewsList"+this.uId}," ")	
			);
			this.eList = $("TCNewsList"+this.uId);
			this.eError = $("TCNErrorMessage"+this.uId);
			this.eWait = $("TCNSWait"+this.uId);
			this.eDetail = $(elementMap.detail);
			this.eDetailView = $(elementMap.detailView);
			this.eBatchCount = $(elementMap.batchCount);
			this.eDetailView.hide();
			// attach back/next handlers
			Event.observe($(elementMap.batchNext), "click", this.nextBatchAction.bindAsEventListener(this));
			Event.observe($(elementMap.batchBack), "click", this.prevBatchAction.bindAsEventListener(this));
			Event.observe($(elementMap.detailClose), "click", this.closeDetail.bindAsEventListener(this));
			this.eList.update(TCNewsService.emptyList());
			this.requestNews();
			break;
		case TCNewsService.MODE_OVERVIEW:
			// set up for overview
			this.eOverview = $(elementMap.overview);
			this.newsCount = settings.newsCount?settings.newsCount:5;
			this.columnCount = settings.columnCount?settings.columnCount:1;
			this.targetURL = settings.teaserTargetURL;
			this.requestOverview();
			break;
	}
}

/*static*/TCNewsService.identifier = (TCNewsService.identifier)?0:TCNewsService.identifier;
/*static*/TCNewsService.MODE_APPLICATION = 0;
/*static*/TCNewsService.MODE_OVERVIEW = 1;

/*static*/TCNewsService.emptyList = function() {
	return TC.tag("div",{_class:"TCNSTableWidth"},
 		TC.tag("table",{border:0,cellpadding:0,cellspacing:0,width:"100%",_class:"TCNewsList"}, 
 			TC.tag("tr",null,TC.tag("td",{colspan:3}," ")) +
 			TC.tag("tr",null,TC.tag("td",{colspan:3}," ")) + 
 			TC.tag("tr",null,TC.tag("td",{colspan:3}," ")) +
 			TC.tag("tr",null,TC.tag("td",{colspan:3}," ")) +
 			TC.tag("tr",null,TC.tag("td",{colspan:3}," "))
 		)
 	);
}

/*static*/TCNewsService.fatalMessage = function(message) {
	window.status = message;
	TC.debug("Fatal: "+message);
}

/**** AJAX request methods *******************************************/

/*static*/TCNewsService.dispatchResponse = function(transport, handler) {
	var ctype = transport.getResponseHeader("content-type");
	if (ctype.indexOf("application/json")<0 && ctype.indexOf("text/json")<0) throw "Invalid server response!";
	TC.debug("Received "+transport.responseText.length+" bytes");
	handler(transport);
	if (TCNewsService.refreshCallback) TCNewsService.refreshCallback();
}

TCNewsService.prototype.request = function(params, responseHandler) {
	var surl = this.serviceURL+params;
	if (this.websiteContext) surl += ",ctx="+this.websiteContext;
	TC.debug("Requesting "+surl);
	this.showWait();
	new Ajax.Request(surl, {
		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(result) { 
			TCNewsService.dispatchResponse(result,responseHandler.bind(this));
		}.bind(this),
		onException: this.handleException.bind(this)
	});
}

TCNewsService.prototype.requestNews = function() {
	this.selectedSubject = null;
	this.request("news/list,c="+this.channelId+",bs="+this.batchSize+",i="+this.batchIndex, this.updateNewsList);
}

TCNewsService.prototype.requestOverview = function() {
	this.request("news/list,c="+this.channelId+",bs="+this.newsCount+",i=1", this.updateOverview);
}

TCNewsService.prototype.requestSubjectGallery = function(subjectId) {
   	this.request("subject/gallery,s="+subjectId+",c="+this.channelId, this.updateGallery);
}

TCNewsService.prototype.requestSubjectInfo = function(subjectId) {
   	this.request("subject/info,s="+subjectId, this.updateSubject);
}

TCNewsService.prototype.requestNewsForSubject = function(subjectId) {
	this.request("news/list,c="+this.channelId+",s="+subjectId, this.updateSubjectNewsList);
}

TCNewsService.prototype.handleException = function(transport, exc) {
	var msg;
	this.eError.show();
	if (exc instanceof Error) msg = exc.name+": "+exc.message; else msg = ""+exc; 
	TC.debug("Error during request: "+msg);
	this.eError.update(msg);
	this.hideWait();
}

/* TODO: finishing */

TCNewsService.prototype.sendPageRefresh = function(desc) {
	if (TCNewsService.refreshCallback) TCNewsService.refreshCallback("NewsService/"+this.channelId+"/"+desc);
}



/**** Render methods *******************************************/

TCNewsService.prototype.updateNewsList = function(transport) {
	var json = eval(transport.responseText);
	this.batchIndex = json.batchIndex;
	this.batchCount = json.batchCount;
	this.newsList = $A(json.result);
	TC.debug("Displaying news list "+this.batchIndex+"/"+this.batchCount+" ("+this.newsList.length+" news)");
	if (this.eBatchCount) this.eBatchCount.update(this.batchIndex+" von "+this.batchCount+" "/*last space for ie*/);	
	this.eList.update(this.renderNewsList(this.newsList)); 
	this.attachClickHandlers(this.eList,this.clickDetailHandler);
	this.eDetailView.hide();
	this.hideWait();
}

TCNewsService.prototype.updateOverview = function(transport) {
	var json = eval(transport.responseText);
	var list = $A(json.result);
	TC.debug("Displaying overview list with "+list.length+" news in "+this.columnCount+" column(s)");
	var colOffset = Math.ceil(this.newsCount/this.columnCount);
	var tableHTML = "";
	for (var row=0;row<colOffset;++row) {
		var rowClass = (row%2==0)?"even":"odd";
		var colHTML = "";
		for (var col=0;col<this.columnCount;++col) {
			var index = row+col*colOffset;
			if (index<list.length) {
				var aNews = list[index];
				colHTML += TC.tag("td",{style:"width:40px;"},
							TC.tag("a",{href:this.targetURL},
								TC.tagIf(aNews.medium_thumbURI,"img",{src:this.serviceURL+'medium'+aNews.medium_thumbURI,width:40,height:40}))
					)+
					TC.tag("td",{_class:"TCNSOverviewHeadline"},
						TC.tag("a",{href:this.targetURL},aNews.headline)
					);
			}
		}
		tableHTML += TC.tag("tr",{_class:rowClass}, colHTML);
	}
	var replaceElement = $("NSLoading");
	if (replaceElement) {
		replaceElement.replace(TC.tag("table",{_class:"MusicNewsOverview",cellpadding:0,cellspacing:0,border:0},tableHTML));
	}else {
		var insertionElement = this.eOverview.getElementsByTagName("h1")[0];
		new Insertion.After(insertionElement, TC.tag("table",{_class:"MusicNewsOverview",cellpadding:0,cellspacing:0,border:0},tableHTML));	
	}
	this.hideWait();
}

TCNewsService.prototype.updateSubjectNewsList = function(transport) {
	var json = eval(transport.responseText); 
	this.newsList = $A(json.result);
	TC.debug("Displaying subject news list ("+this.newsList.length+" news)");
	var html = 
		TC.tag("h1",{style:"padding: 0 10px;margin-top:10px"},"Nachrichten von "+json.subject.name) +
		this.renderNewsList(this.newsList)+
		TC.tag("div",{style:"margin: 0 0 10px 10px",_class:"TCNBack"},
			TC.tag("a",{href:"#",rel:"all"},"Alle Nachrichten")
		);
	this.eDetailView.show();
	this.eDetail.update(html); 
	this.attachClickHandlers(this.eDetail,this.clickDetailHandler);
	this.hideWait();
}

TCNewsService.prototype.renderNewsList = function(newsList) {
	var tableHTML = "";
	newsList.each(function(aNews, index) {
		var rowClass = (index%2==0)?"odd":"even";
		tableHTML += TC.tag("tr",{_class:rowClass},
			TC.tag("td",{_class:"imgCell"}, 
				TC.tagIf(aNews.medium_thumbURI, "a", {rel:index,href:"#details"},
					TC.tag("img",{src:this.serviceURL+'medium'+aNews.medium_thumbURI,width:40,height:40})
				)
			) +
			TC.tag("td",{_class:"descriptionCell"}, 
				TC.tag("h2",null, 
					TC.tag("a",{rel:index,href:"#details"},aNews.headline)) +
				TC.tag("p",null, aNews.text_abstract)
			) +
			TC.tag("td",{_class:"moreCell"}, 
				TC.tag("a",{rel:index,href:"#details"}, "mehr")
			)
		);
 	}.bind(this));
 	if (newsList.length<this.batchSize) {
 		for (var i=0;i<this.batchSize-newsList.length;++i) {
 			tableHTML += TC.tag("tr",null,TC.tag("td",{colspan:3}," "));
 		}
 	}
 	return TC.tag("div",{_class:"TCNSTableWidth"},
 		TC.tag("table",{border:0,cellpadding:0,cellspacing:0,width:"100%",_class:"TCNewsList"}, tableHTML)
 	);
}

TCNewsService.prototype.updateGallery = function(transport) {
	var json = eval(transport.responseText);
	this.gallerySubject = json.subject;
	this.galleryList = $A(json.result);
	this.galleryTease = json.more;
	this.galleryItems = this.galleryList.length;
	this.galleryIndex = 0;
	this.displayCurrentGalleryImage();
	this.eDetailView.show();
	this.hideWait();
}

TCNewsService.prototype.displayCurrentGalleryImage = function() {
	TC.debug("Displaying gallery image "+(this.galleryIndex+1)+"/"+this.galleryItems);
	var img = this.galleryList[this.galleryIndex];
	var more = this.galleryTease;
	var teaseHTML = "";
	more.each(function(aSubject) {
		teaseHTML += TC.tag("div",null,
			TC.tag("a",{rel:"gal:"+aSubject.id,href:"#galerie"},
				TC.tag("img",{src:this.serviceURL+'medium'+aSubject.latestMedium_thumbURI}) +
				aSubject.name
			)
		);
	}.bind(this));
	var html = TC.tag("table",{_class:"TCNSGallery",border:0,cellpadding:0,cellspacing:0},
		TC.tag("tr",null,
			TC.tag("td",{colspan:4,_class:"TCNSTitle"}, "Bildergalerie von "+this.gallerySubject.name) +
			TC.tag("td",{_class:"TCNSFurther",rowspan:4},
				TC.tag("h1",null,"Weitere Bildergalerien") +
				teaseHTML
			)
		) +
		TC.tag("tr", null,
			TC.tag("td",{_class:"TCNSCaption",colspan:4}, img.caption?img.caption:"")
		) +
		TC.tag("tr", null,
			TC.tag("td",{_class:"TCNSImage",colspan:4},
				TC.tag("a",{rel:1,href:"#"},
					TC.tag("img",{title:img.caption?img.caption:"",src:this.serviceURL+'medium'+img.fullURI})
				)
			)
		) +
		TC.tag("tr",null,
			TC.tag("td",{_class:"TCNSBack"},
				TC.tag("div",{_class:"TCNBack"},
					TC.tag("a",{href:"#",rel:0},"Zur&uuml;ck zum Artikel")
				)
			) +
			TC.tag("td",{_class:"TCNSNav"},
				TC.tag("a",{href:"#",rel:-1},"&lt; zur&uuml;ck")+
				TC.tag("span",null," "+(this.galleryIndex+1)+" von "+this.galleryItems+" ") + 
				TC.tag("a",{href:"#",rel:1},"vor &gt;")
				+ "&nbsp;"
			)
		)
	);
	this.eDetail.update(html);
	this.attachClickHandlers(this.eDetail,this.clickGalleryNavHandler);
}

TCNewsService.prototype.displayNewsDetail = function() {
	TC.debug("Displaying news detail: " + this.currentNewsDetail);
	var aNews = this.newsList[this.currentNewsDetail];
	var text = aNews.text;
	text = text.replace(/\n/g,"<br />");
	var html = 
		TC.tag("div",{_class:"TCNSTableWidth"},
			TC.tag("table",{cellpadding:0,cellspacing:0,width:"100%"},
				TC.tag("tr",{style:"vertical-align:top"},
					TC.tag("td",{style:"width:160px"},
						TC.tagIf(aNews.medium_quadURI,"img",{src:this.serviceURL+'medium'+aNews.medium_quadURI,width:150,height:150}) +
						TC.tagIf(aNews.medium_caption,"div",{_class:"caption"},aNews.medium_caption) +
						TC.tag("div",{_class:"TCNLinks"},
							TC.tagIf(aNews.videoHTML,"a",{_class:"TCNVid",rel:"vid:"+aNews.id,href:"#video"},"Video anschauen") +
							TC.tagIf(0<aNews.subject_media_count,"a",{rel:"gal:"+aNews.subject_id,_class:"TCNGal",href:"#galerie"},"Bildergalerie") +
							TC.tagIf(aNews.subject_url,"a",{target:"_blank",_class:"TCNWeb",href:TC.linkWithProtocol(aNews.subject_url)},"Offizielle Website") +
							TC.tag("a",{rel:"news:"+aNews.subject_id,_class:"TCNMore",href:"#mehr"},"Mehr Artikel zu "+aNews.subject_name) +
							TC.tag("a",{rel:"info:"+aNews.subject_id,_class:"TCNInfo",href:"#mehr"},"Mehr Infos zu "+aNews.subject_name)
						)) +
					TC.tag("td",null,
						TC.tag("div",{_class:"NewsHead"},""+aNews.subject_name+" - "+TC.displayDate(aNews.publishDate)) +
						TC.tag("h1",null,aNews.headline) + 
						TC.tag("p",null,text)
					)
				)
			) +
			TC.tag("div",{_class:"TCNBack"},
				TC.tag("a",{rel:"back:0",href:"#zurueck"},"Zur&uuml;ck zur Artikelauswahl")
			)
		); 
	this.eDetail.update(html);
	this.attachClickHandlers(this.eDetail,this.clickNewsHandler);
	if (TCNewsService.refreshCallback) TCNewsService.refreshCallback();
}

TCNewsService.prototype.updateSubject = function(transport) {
	TC.debug("Displaying subject details");
	var json = eval(transport.responseText); 
	var subject = json.subject;
	var html = 
		TC.tag("div",{_class:"TCNSTableWidth"},
			TC.tag("table",{cellpadding:0,cellspacing:0,width:"100%"},
				TC.tag("tr",{style:"vertical-align:top"},
					TC.tag("td",{style:"width:160px"},
						TC.tagIf(subject.latestMedium_quadURI,"img",{src:this.serviceURL+'medium'+subject.latestMedium_quadURI,width:150,height:150}) +
						TC.tagIf(subject.latestMedium_caption,"div",{_class:"caption"},subject.latestMedium_caption) +
						TC.tag("div",{_class:"TCNLinks"},
							TC.tagIf(0<subject.media_count,"a",{rel:"gal:"+subject.id,_class:"TCNGal",href:"#galerie"},"Bildergalerie") +
							TC.tagIf(subject.url,"a",{target:"_blank",_class:"TCNWeb",href:subject.url},"Offizielle Website") +
							TC.tag("a",{rel:"news:"+subject.id,_class:"TCNMore",href:"#mehr"},"Alle Artikel zu "+subject.name)
						)) +
					TC.tag("td",null,
						TC.tag("h1",null,subject.name) + 
						TC.tag("p",null,subject.text)
					)
				)
			) +
			TC.tag("div",{_class:"TCNBack"},
				TC.tag("a",{rel:"back:"+subject.id,href:"#zurueck"},"Zur&uuml;ck zum Artikel")
			)
		); 
	this.eDetail.update(html);
	this.attachClickHandlers(this.eDetail,this.clickNewsHandler);
	this.hideWait();
}

/**** UI event handling *******************************************/

TCNewsService.prototype.showWait = function() {
	if (!this.eWait) return;
	if (!this.waitTimer)
		this.waitTimer = window.setTimeout(this.showWaitTrigger.bind(this),100);
}

TCNewsService.prototype.showWaitTrigger = function() {
	if (this.waitTimer) {
		this.eWait.show();
	}
}

TCNewsService.prototype.hideWait = function() {
	if (!this.eWait) return;
	if (this.waitTimer) {
		window.clearTimeout(this.waitTimer);
		this.waitTimer = null;
	}
	this.eWait.hide();
}

TCNewsService.prototype.attachClickHandlers = function(element, handlerFunc) {
	var links = $A(element.getElementsByTagName("a"));
	links.each(function(aLink){
		if (aLink.rel) {
			Event.observe($(aLink), "click", handlerFunc.bindAsEventListener(this));
		}
	}.bind(this));
}

TCNewsService.prototype.clickDetailHandler = function(event) {
	var element = $(Event.findElement(event, "a"));
	var rel = element.rel;
	Event.stop(event);
	this.eDetailView.show();
	if ("all"==rel) {
		this.currentNewsDetail = null;
		this.requestNews();
	}
	else {
		this.currentNewsDetail = rel;
		this.displayNewsDetail();
	}
}

TCNewsService.prototype.clickGalleryNavHandler = function(event) {
	var element = $(Event.findElement(event, "a"));
	Event.stop(event);
	var action = element.rel;
	switch (action) {
		case "-1":
			if (this.galleryIndex>0) this.galleryIndex--; else this.galleryIndex=this.galleryItems-1;
			this.displayCurrentGalleryImage();
			break;
		case "1":
			if (this.galleryIndex<this.galleryItems-1) this.galleryIndex++; else this.galleryIndex=0;
			this.displayCurrentGalleryImage();
			break;
		case "0":
			this.displayNewsDetail();
			break;
		default:
			action = action.split(":");
			this.requestSubjectGallery(action[1]);
			break;
	}
}

TCNewsService.prototype.clickNewsHandler = function(event) {
	var element = $(Event.findElement(event, "a"));
	Event.stop(event);
	var rel =element.rel;
	var action = element.rel.split(":");
	switch (action[0]) {
		case "gal":
			this.requestSubjectGallery(action[1]);
			break;
		case "news":
			this.selectedSubject = action[1];
			this.requestNewsForSubject(action[1]);	
			break;
		case "back":
			if (this.selectedSubject == action[1]) {
				this.displayNewsDetail();
			}
			else {
				this.requestNews();
			}
			break;
		case "info":
			this.selectedSubject = action[1];
			this.requestSubjectInfo(action[1]);
			break;
		case "vid":
			var aNews = this.newsList[this.currentNewsDetail];
			var videoHTML = aNews.videoHTML;
			var wp = videoHTML.match(/width=\"(\d+)\"/);
			var hp = videoHTML.match(/height=\"(\d+)\"/);
			var width = (wp && wp[1])?wp[1]:"480";
			var height = (hp && hp[1])?hp[1]:"450";
			var win = window.open("","TCNSVideo","width="+width+",height="+height+",resizable=yes");
			var html = 
				TC.tag("html",null,
					TC.tag("head",null,
						TC.tag("title",null, "Video: "+ aNews.headline) +
						TC.tag("style",null,"a,p,br {display:none;}")
					) +
					TC.tag("body",{style:"background:#000;margin:0;padding:0;text-align:center"},aNews.videoHTML)
				);
			win.document.open("text/html");
			win.document.write(html);
			win.document.close();
			win.focus();
			break;
	}
}

TCNewsService.prototype.nextBatchAction = function() { 
	if (this.batchIndex<this.batchCount) this.batchIndex++; else this.batchIndex=1;
	this.requestNews();
}

TCNewsService.prototype.prevBatchAction = function() {
	if (this.batchIndex>1) this.batchIndex--; else this.batchIndex=this.batchCount;
	this.requestNews();
}

TCNewsService.prototype.closeDetail = function() {
	TC.debug("Detail view closed");
	this.eDetailView.hide();
	this.requestNews();
}


/**** TC Utilities *******************************************/

var TC = (TC)?TC:{
	tag: function(tag, attributes, body) {
			if (tag.charAt(0)=="_") tag = tag.substring(1);
			var result = "<"+tag;
			if (attributes) {
				var attr = $H(attributes);
				attr.each( function(pair){
					var key = pair.key;
					if (key.charAt(0)=="_") {
						key = key.substr(1);
					}
					result += " "+key+"=\"";
					result += pair.value+"\"";
				});
			}
			if (body) {
				if (typeof body=="boolean") {
					if (!body) result +=" />"; else	result += ">";
				}
				else {
					result += ">"+body+"</"+tag+">";
				}
			}
			else {
				if (tag.charAt(0)!="/") result +=" />";	else result +=">";
			}
			return result;
		},
	tagIf: function(value, tag, attributes, body) {
			if (value) return TC.tag(tag, attributes, body); else return "";
		},
	displayDate: function(date) {
		return TC.formatNumber(date.getDate(),2)+"."+TC.formatNumber(date.getMonth()+1,2)+"."+date.getFullYear();
	},
	debugWin: null,
	debugDisabled: null,
	debug: function(msg) {
		if (TC.debugDisabled) return;
		if (TC.debugDisabled==null) {
			var qp = window.location.href.toQueryParams();
			if (qp.TCDebug=="on") {
				TC.debugDisabled = false;
			}
			else {
				TC.debugDisabled = true;
				return;
			}
		}
		if (TC.debugWin==null || TC.debugWin.closed) {
			TC.debugWin = window.open("about:blank","TCDebugConsole","width=600,height=300,resizable=yes,scrollbars=yes");
			if (TC.debugWin) {
				TC.debugWin.document.open();
				TC.debugWin.document.writeln(
					TC.tag("html",null,
						TC.tag("head",null,
							TC.tag("title",null,"TCDEBUG WINDOW") +
							TC.tag("style",null,"body {color:black;background:#eee;font-family:monospace;font-size:12px;} span {color:#888;} div {margin:4px 0;border-bottom:1px dotted #ccc}")
						) +
						TC.tag("body",null,
							TC.tag("div",{id:"debug"},"<div><span>"+TC.debugDate()+"</span> Log start</div>")
						)
					)
				);
				TC.debugWin.document.close();
				TC.debugWin.focus();
			}
		}
		if (TC.debugWin) {
			new Insertion.Top(TC.debugWin.document.getElementById("debug"),"<div><span>"+TC.debugDate()+"</span> "+msg.escapeHTML()+"</div>");
		}
	},
	debugDate: function() {
		var date = new Date();
		return TC.formatNumber(date.getHours(),2)+":"+TC.formatNumber(date.getMinutes(),2)+":"+TC.formatNumber(date.getSeconds(),2)+"'"+TC.formatNumber(date.getMilliseconds(),4);
	},
	formatNumber: function(v, len) {
		var result = new String(v);
		while (result.length<len) result = "0"+result;
		return result;
	},
	linkWithProtocol: function(u) {
		if (!u) return u;
		if (!u.startsWith("http://") && !u.startsWith("/")) {
			return "http://"+u;
		}
		return u;
	}
}