if (typeof KyteBadge == "undefined") {
	var KyteShowBrowser = false;
  
  function KyteBadge(channelId, params, domId) {
  	if (!KyteShowBrowser) KyteShowBrowser = new Array();
  	this.index = KyteShowBrowser.length;
  	KyteShowBrowser[this.index] = this;

  	for (key in params){
  		this[key] = params[key];
		}

  	this.channelId = channelId;	
  	this.domId = domId;

  	if (this.page == undefined) this.page = 0;
  	if (this.layout != "vertical") this.layout = "horizontal";
  	if (this.pagingControl == undefined) this.pagingControl = false;
  	if (this.showsPerPage == undefined) this.showsPerPage = 5;
  	if (this.onClickThumb == undefined) this.onClickThumb = 'player';
  	if (this.relatedKytePlayer == undefined) this.relatedKytePlayer = 'kyteplayer';
  	if (this.badgeTitle == undefined) this.badgeTitle = "";
  	if (this.kyteServer == undefined) this.kyteServer = "www.kyte.tv";
  	if (this.stampFormat == undefined) this.stampFormat = "date";

  	if (this.defaultSortMode == undefined) this.defaultSortMode = "createdTime-d";    	
  	if (this.filterJustProduced == undefined) this.filterJustProduced = false;
  	if (this.filterMostWatched == undefined) this.filterMostWatched = false;
  	if (this.filterBestRated == undefined) this.filterBestRated = false;
  	if (this.filterMostCommented == undefined) this.filterMostCommented = false;
  	if (this.filterSearch == undefined) this.filterSearch = false;
  	if (this.filterSearchKeyword == undefined) this.filterSearchKeyword = ""; 
  	if (this.filterTagKeyword == undefined) this.filterTagKeyword = "";  	

  	if (this.metaTitle == undefined) this.metaTitle = false;
  	if (this.metaTitleLength == undefined) this.metaTitleLength = 15;
  	if (this.metaProducer == undefined) this.metaProducer = false;
  	if (this.metaProducerLength == undefined) this.metaProducerLength = 15;
  	if (this.metaTime == undefined) this.metaTime = false;
  	if (this.metaViews == undefined) this.metaViews = false;
  	if (this.metaRating == undefined) this.metaRating = false;
  	if (this.metaComments == undefined) this.metaComments = false;
  	if (this.metaDescription == undefined) this.metaDescription = false;
  	if (this.metaDescriptionLength == undefined) this.metaDescriptionLength = 50;
  	if (this.cssFile == undefined) {
  		if (this.layout == "vertical") {
				if (this.styleTemplate == "light") this.cssFile = 'http://media01.kyte.tv/assets/badges/styleTemplateVertLight.css';
				else this.cssFile = 'http://media01.kyte.tv/assets/badges/styleTemplateVert.css'; 
  			}
  		else {
				if (this.styleTemplate == "light") this.cssFile = 'http://media01.kyte.tv/assets/badges/styleTemplateHoriLight.css'; 
				else this.cssFile = 'http://media01.kyte.tv/assets/badges/styleTemplateHori.css'; 
  		}
  	}
  	if (this.cssClass == undefined) {
  		if (this.layout == "vertical") this.cssClass = 'kyteBadgeVert';
  		else this.cssClass = 'kyteBadgeHori'; 		
  	}
  	if (this.xmlFile == undefined) this.xmlFile = false;
  	this.wording = false;
  	if (this.thumbWidth == undefined) this.thumbWidth = 120;
  	if (this.thumbHeight == undefined) this.thumbHeight = 90;
  	if (this.metaWidth == undefined) this.metaWidth = 120;
  	if (this.metaHeight == undefined) this.metaHeight = 90;
  	if (this.headerHeight == undefined) this.headerHeight = 33;
  	if (this.footerHeight == undefined) {
  		if (this.layout == "vertical") this.footerHeight = 50;
  		else this.footerHeight = 0;
  	}
  	if (this.padding == undefined) this.padding = 5;
  	
  	this.thumbWidth = parseInt(this.thumbWidth);
  	this.thumbHeight = parseInt(this.thumbHeight);
  	this.metaWidth = parseInt(this.metaWidth);
  	this.metaHeight = parseInt(this.metaHeight);
  	this.headerHeight = parseInt(this.headerHeight);
  	this.footerHeight = parseInt(this.footerHeight);
  	this.padding = parseInt(this.padding);
  	this.showsPerPage = parseInt(this.showsPerPage);
  	this.page = parseInt(this.page);
  	
		if (this.prevPageAct == undefined) this.prevPageAct = false;
  	if (this.prevPageDeact == undefined) this.prevPageDeact = false;
  	if (this.nextPageAct == undefined) this.nextPageAct = false;
  	if (this.nextPageDeact == undefined) this.nextPageDeact = false;
  	if (this.ratingImgAct == undefined) this.ratingImgAct = false;
  	if (this.ratingImgDeact == undefined) this.ratingImgDeact = false;
  	
  	this.GetWording = KyteBadgeGetWording;
  	this.GetJSON = KyteBadgeGetJSON;
  	this.Build = KyteBadgeBuild;
  	this.Browse = KyteBadgeBrowse;
  	this.GetText = KyteBadgeGetText;
  	this.FormatStamp = KyteBadgeFormatStamp;
  	this.CreateLink = KyteBadgeCreateLink;
  	
		if (this.xmlFile) this.GetWording();
		this.GetJSON();
  }

  function KyteBadgeGetJSON() {
  	var cta	 = '{';
  	cta 		+= '"orderSpec":"'+ this.defaultSortMode +'"';
  	if (this.filterSearchKeyword != "") {
  		cta		+= ',"title-like":"%'+ this.filterSearchKeyword +'%"';
  	} else if (this.filterTagKeyword != "") {
  		cta		+= ',"tags-like":"%'+ this.filterTagKeyword +'%"';
  	}
  	cta			+=	'}';
  	cta = escape(cta);
  
  	var url = 'http://'+ this.kyteServer +'/services/rest/channels/'+ this.channelId +'.findShows?ak='+ this.ak +'&cta='+ cta +'&frt='+ (this.page * this.showsPerPage) +'&mrs='+ this.showsPerPage +'&callback=KyteShowBrowser['+ this.index +'].Build';
  
  	importFile("KB_SCR_"+ this.index, url, "script");
  	importFile("KB_CSS_"+ this.index, this.cssFile, "link");
  	
  	function importFile(id, url, type) {
			oFile = document.getElementById(id);
			var head = document.getElementsByTagName("head")[0];
			if(oFile) head.removeChild(oFile);
			
			switch (type) {
				case "script":
					oFile = document.createElement("script");
					oFile.type = "text/javascript";
					oFile.setAttribute("src", url);
					break;
				case "link":
					oFile = document.createElement("link");
					oFile.type = 'text/css';
					oFile.rel = 'stylesheet';
					oFile.href = url;
					oFile.media = 'screen';
					break;		
			}
			oFile.setAttribute("id",id);
			head.appendChild(oFile);				
		}  	
	} 
  
  function KyteBadgeGetWording() {
		try {
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		} catch(err) {
			try {
				xmlDoc=document.implementation.createDocument("","",null);
			} catch(err) {
				return;
			}
		}
		try {
			xmlDoc.async=false;
			xmlDoc.load(this.xmlFile);
			this.wording = xmlDoc; 
		}	catch (err) { }
  }
  
	function KyteBadgeGetText(tagName, x, y, z) {
		try {
			var text = this.wording.getElementsByTagName(tagName)[0].childNodes[0].nodeValue;
			if (x != undefined) text = text.replace("[x]", x);
			if (y != undefined) text = text.replace("[y]", y);
			if (z != undefined) text = text.replace("[z]", z);
			return text;
		} catch (err) {
			if (err.message == "this.wording.getElementsByTagName(tagName)[0].childNodes[0] is undefined") return "";
			switch (tagName) {
				case "paging_index":					return "Seite "+ x +" / "+ y;
				case "paging_prev":						return "<";
				case "paging_next":						return ">";
				case "filter_just_produced":	return "Neue Videos";
				case "filter_most_watched": 	return "Beliebte Videos";
				case "filter_best_rated":			return "Top Videos";
				case "filter_most_commented":	return "Most Commented";
				case "search_go_button":			return "Go";
				case "search_find":						return "Suche: ";
				case "meta_tag_by":						return "<span>Von:</span> "+ x;
				case "meta_tag_views":				return "";
				/* case "meta_tag_views":				return "<span>"+ x +"</span> Views"; */
				case "meta_tag_rating":				return "<span>Rating:</span> "+ x;
				case "meta_tag_comments":			return "<span>"+ x +"</span> Kommentare";
				case "info_no_matches":				return "Keine Treffer!";
				case "info_no_shows":					return "Es sind keine Shows erh&auml;ltlich!";
				case "date_format_day":				return y +". "+ x;
				case "date_format_time":			return ""+ x +":"+ y +" Uhr";
				case "date_format":						return x +" "+ y;
				case "month_1": 							return "Januar";
				case "month_2":								return "Februar";
				case "month_3":								return "M&auml;rz";
				case "month_4":								return "April";
				case "month_5":								return "Mai";
				case "month_6":								return "Juni";
				case "month_7":								return "July";
				case "month_8":								return "August";
				case "month_9":								return "Sept.";
				case "month_10":							return "Okt.";
				case "month_11":							return "Nov.";
				case "month_12":							return "Dez.";
				case "time_ago":							return "Vor "+ x + " "+ y;
				case "just_now":							return "Jetzt gerade";
				case "minute":								return "Minute";
				case "minutes":								return "Minuten";
				case "hour":									return "Stunde";
				case "hours":									return "Stunden";
				case "day":										return "Tag";
				case "days":									return "Tagen";
				case "week":									return "Woche";
				case "weeks":									return "Wochen";
				case "month":									return "Monat";
				case "months":								return "Monaten";
				case "year":									return "Jahr";
				case "years":									return "Jahren";
				case "error":									return "(Fehler "+ x +": "+ y +")";
				default:											return (x != undefined)? x:"";
			}
		}
	}
	
	function KyteBadgeFormatStamp(ISO8061) {
	  var currentDate = new Date();
	 	var timeDiff = new Date(currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000)) - new Date(ISO8061.substring(0,4),((ISO8061.substring(4,6))-1),ISO8061.substring(6,8),ISO8061.substring(9,11),ISO8061.substring(11,13),ISO8061.substring(13,15));		
		
		if (this.stampFormat == "date") {
			var localDate = new Date(currentDate - timeDiff);
			var time = this.GetText("date_format_time", localDate.getHours(), ((localDate.getMinutes() < 10)? '0':'') + localDate.getMinutes());
			var day = this.GetText("date_format_day", this.GetText("month_"+(localDate.getMonth()+1)), localDate.getDate(), localDate.getFullYear());
			return this.GetText("date_format", day, time);
		} else {
	  	var second = 1000;
	  	var minute = second*60;
	  	var hour = minute*60;
	  	var day = hour*24;
	  	var week = day*7;
	  	var month = week*4.35;
	  	var year = month*12;
	  	
	  	if (timeDiff < minute) return this.GetText("just_now");
	  	else if (timeDiff < hour) return this.GetText("time_ago", Math.floor(timeDiff/minute), ((Math.floor(timeDiff/minute) > 1)? this.GetText("minutes"): this.GetText("minute")));
	  	else if (timeDiff < day) return this.GetText("time_ago", Math.floor(timeDiff/hour), ((Math.floor(timeDiff/hour) > 1)? this.GetText("hours"): this.GetText("hour")));
	  	else if (timeDiff < week) return this.GetText("time_ago", Math.floor(timeDiff/day), ((Math.floor(timeDiff/day) > 1)? this.GetText("days"): this.GetText("day")));
	  	else if (timeDiff < month) return this.GetText("time_ago", Math.floor(timeDiff/week), ((Math.floor(timeDiff/week) > 1)? this.GetText("weeks"): this.GetText("week")));
	  	else if (timeDiff < year) return this.GetText("time_ago", Math.floor(timeDiff/month), ((Math.floor(timeDiff/month) > 1)? this.GetText("months"): this.GetText("month")));
	  	else return this.GetText("time_ago", Math.floor(timeDiff/year), ((Math.floor(timeDiff/year) > 1)? this.GetText("years"): this.GetText("year")));;			
		}
	}
  
  function KyteBadgeBrowse(direction, mode, startSearch, tagFilterKey) {  	
  	if (direction == "next") this.page++;
  	else if (direction == "prev" && this.page > 0) this.page--;
  	else this.page = 0;
  	
  	if (tagFilterKey) this.filterTagKeyword = tagFilterKey;
  	
   	if (mode) {
  		this.defaultSortMode = mode;
  		if (document.getElementById("KB_"+ this.index +"_sk")) document.getElementById("KB_"+ this.index +"_sk").value = '';
  		this.filterTagKeyword = '';
  	} else if (!mode && !direction) {
  		this.defaultSortMode = "createdTime-d"; 		
  	}
  	
 		try {
			this.filterSearchKeyword = escape((document.getElementById("KB_"+ this.index +"_sk").value).replace(/"/g, ""));
		} catch (err) { } 

		this.GetJSON();
  }
  
	function KyteBadgeCreateLink(data, linkedHTML) {
		var aTag = false;
		
		switch (this.onClickThumb) {
			case "player":
				aTag = '<a href="javascript: try { '+ this.relatedKytePlayer +'.setURI(\''+ data.uri +'\'); } catch (err) { window.location = \''+ data.permalink +'\'; }">';
				break;
			case "permalink":
				aTag = '<a href="'+ data.permalink +'" target="new">';
				break;
		}
		
		return (aTag)? aTag + linkedHTML + '</a>':linkedHTML;
	} 
  
  function KyteBadgeBuild(data) {
  
		function truncate(text, len) {
			try {
				if (text.length > len) {
				text = text.substring(0, len-3) + "...";
				}
			} catch (err) {
				text = "";
			}
			return text;     	
		}
		
  	var items;
  	var totalSize;
  	var totalPages = 0;
  	var showCount = 0;
  	var page = 0;
  	var errMsg = "";
  	try {	
  		items = data["result"]["items"];
  		totalSize = data["result"]["totalSize"];
  		showCount = items.length;
  		if (totalSize > 0) {
  			totalPages = Math.ceil(totalSize / this.showsPerPage);
  			page = this.page + 1;
  		}
  	} catch (err) {
  		try {
  			errMsg = this.GetText('error', data["error"]["code"], data["error"]["message"]);
  		} catch (err) { }
  	}  	
  	var dominantHeight = this.thumbHeight;
  	if (this.metaHeight > dominantHeight) dominantHeight = this.metaHeight;
  	var dominantWidth = this.thumbWidth;
  	if (this.metaWidth > dominantWidth) dominantWidth = this.metaWidth;
  	
		var offset = this.page * this.showsPerPage;
			
		var badgeHTML = "";
		var elemHeight = 0;
		var elemWidth = 0;
		var elemTop = 0;
		var elemLeft = 0;
		
		if (this.layout == "horizontal") {
			elemHeight = (3*this.padding+this.thumbHeight+this.metaHeight+this.headerHeight+this.footerHeight);
			elemWidth = (this.showsPerPage*dominantWidth+(this.showsPerPage+1)*this.padding);
		} else {
			elemHeight = (this.footerHeight+this.headerHeight+this.showsPerPage*dominantHeight+(this.showsPerPage+1)*this.padding);
			elemWidth = (this.metaWidth+this.thumbWidth+2*this.padding);
		}
		badgeHTML += '		<div id="KB_'+ this.index +'" class="'+ this.cssClass +'" style="width: '+ elemWidth +'px; height: '+ elemHeight +'px;">';
		badgeHTML += '			<div class="header" style="height:'+ this.headerHeight +'px;"></div>';
		badgeHTML += '			<div class="footer" style="height:'+ this.footerHeight +'px;"></div>';	
		if (this.filterJustProduced || this.filterMostWatched || this.filterMostCommented || this.filterSearch || this.filterBestRated) {
			badgeHTML += '		<div class="sorting">';
			if (this.filterJustProduced) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "createdTime-d" && this.filterSearchKeyword == "")?' active': '') +'"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(false, \'createdTime-d\', false);">'+ this.GetText("filter_just_produced") +'</a></span>';
			}
			if (this.filterMostWatched) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "totalWatches-d")?' active': '') +'"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(false, \'totalWatches-d\', false);">'+ this.GetText("filter_most_watched") +'</a></span>';
			}	
			if (this.filterBestRated) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "averageTenths-d")?' active': '') +'"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(false, \'averageTenths-d\', false);">'+ this.GetText("filter_best_rated") +'</a></span>';
			}										
			if (this.filterMostCommented) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "totalMessageCount-d")?' active': '') +'"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(false, \'totalMessageCount-d\', false);">'+ this.GetText("filter_most_commented") +'</a></span>';
			}
			badgeHTML += '		</div>';
		}				
		badgeHTML += '			<div class="badgeTitle">'+ this.badgeTitle +'</div>';   
		if (this.pagingControl) {  	
			badgeHTML += '		<div class="pager">';
			badgeHTML += '			<span class="prev">';
			if (page > 1) badgeHTML += '<a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'prev\');">'+ ((this.prevPageAct)? ' <img src="'+ this.prevPageAct +'" /> ':this.GetText("paging_prev")) +'</a>';
			else badgeHTML += 	(this.prevPageDeact)? ' <img src="'+ this.prevPageDeact +'" /> ':this.GetText("paging_prev");
			badgeHTML += '			</span>';
			badgeHTML += 	'			<span class="pageIndex">'+ this.GetText("paging_index", page, totalPages) +'</span>';
			badgeHTML += '			<span class="next">';
			if (page < totalPages) badgeHTML += '			<a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'next\');">'+ ((this.nextPageAct)? ' <img src="'+ this.nextPageAct +'" /> ':this.GetText("paging_next")) +'</a>';
			else badgeHTML +=		(this.nextPageDeact)? ' <img src="'+ this.nextPageDeact +'" /> ':this.GetText("paging_next");
			badgeHTML += '			</span>';
			badgeHTML += '		</div>';
		}
		if (this.filterSearch) {
			badgeHTML += '		<div class="finder"><form action="javascript: KyteShowBrowser['+ this.index +'].Browse(false, false, false);";>';
			badgeHTML += 			this.GetText("search_find") + '<input type="text" id="KB_'+ this.index +'_sk" value="'+ unescape(this.filterSearchKeyword) +'" class="text" /><input type="submit" value="'+ this.GetText("search_go_button") +'" class="button" />';
			badgeHTML += '		</form></div>';
		}
		if (this.layout == "horizontal") elemHeight = (this.thumbHeight+this.metaHeight+3*this.padding); 
		else elemHeight = (this.showsPerPage*dominantHeight+(this.showsPerPage+1)*this.padding);
		badgeHTML += '			<div class="showList" style="top: '+ this.headerHeight +'px; height: '+ elemHeight +'px;">';	  
		if (showCount > 0) {   	
			for (var i=0; i < showCount; i++) {
				if (this.layout == "horizontal") {
					elemTop = 0;
					elemLeft = (i*dominantWidth+i*this.padding);
					elemHeight = (this.thumbHeight+this.metaHeight+3*this.padding);
					elemWidth = (dominantWidth+2*this.padding) +"px";
				} else {
					elemTop = (i*dominantHeight+i*this.padding);
					elemHeight = (dominantHeight+2*this.padding);
					elemLeft = 0;
					elemWidth = "100%";
				}
				badgeHTML += '<div class="cell" style="top: '+ elemTop +'px; left: '+ elemLeft +'px; height: '+ elemHeight +'px; width: '+ elemWidth +';">';
				if (this.layout == "horizontal") {
					elemHeight = this.thumbHeight;
					elemWidth = dominantWidth;
				} else {
					elemHeight = dominantHeight;
					elemWidth = this.thumbWidth;
				}
				badgeHTML += '	<div class="thumb" style="top: '+ this.padding +'px; left: '+ this.padding +'px; height: '+ elemHeight +'px; width: '+ elemWidth +'px;">'+ this.CreateLink(items[i], '<img src="'+ items[i]["thumb120x90Url"] +'" style="width: '+ this.thumbWidth +'px; height: '+ this.thumbHeight +'px;" />') +'</div>';		
				if (this.metaTitle || this.metaDescription || this.metaProducer || this.metaTime || this.metaViews || this.metaRating || this.metaComments) {
					if (this.layout == "horizontal") {
						elemTop = (this.padding*2+this.thumbHeight);
						elemLeft = this.padding;
						elemHeight = this.metaHeight;
					} else {
						elemTop = this.padding;
						elemLeft = (this.padding*2+ this.thumbWidth);
						elemWidth = this.metaWidth;
					}
					badgeHTML += '<div class="meta" style="top: '+ elemTop +'px; left: '+ elemLeft +'px; height: '+ elemHeight +'px; width: '+ elemWidth +'px;">';
					if (this.metaTitle) badgeHTML 			+= '<div class="metaTitle">'+ this.GetText("meta_tag_title", this.CreateLink(items[i], truncate(items[i]["title"], this.metaTitleLength))) +'</div>';
					if (this.metaTime) badgeHTML 				+= '<div class="metaTime">'+ this.GetText("meta_tag_time", this.FormatStamp(items[i]["createdTime"])) +'</div>';
					if (this.metaDescription) badgeHTML	+= '<div class="metaDescription">'+ this.GetText("meta_tag_description", truncate(items[i]["synopsis"], this.metaDescriptionLength)) +'</div>';
					if (this.metaProducer) badgeHTML 		+= '<div class="metaProducer">'+ this.GetText("meta_tag_by", truncate(items[i]["ownerName"], this.metaProducerLength)) +'</div>';
					if (this.metaViews) badgeHTML 			+= '<div class="metaViews">'+ this.GetText("meta_tag_views", ((items[i]["totalWatches"])? items[i]["totalWatches"]:0)) +'</div>';
					if (this.metaRating) {
						var ratingHTML = "";
						var currentRating = (items[i]["rateCount"] > 0)? Math.round((items[i]["rateSum"]/items[i]["rateCount"])*10)/10:0;
						if (this.ratingImgAct && this.ratingImgDeact) {
							ratingHTML += '<img src="'+ ((currentRating >= 1)? this.ratingImgAct:this.ratingImgDeact) +'" />';
							ratingHTML += '<img src="'+ ((currentRating >= 2)? this.ratingImgAct:this.ratingImgDeact) +'" />';
							ratingHTML += '<img src="'+ ((currentRating >= 3)? this.ratingImgAct:this.ratingImgDeact) +'" />';
							ratingHTML += '<img src="'+ ((currentRating >= 4)? this.ratingImgAct:this.ratingImgDeact) +'" />';
							ratingHTML += '<img src="'+ ((currentRating == 5)? this.ratingImgAct:this.ratingImgDeact) +'" />';					
						} else {
							ratingHTML = this.GetText("meta_tag_rating", currentRating);
						}
						badgeHTML += '<div class="metaRating">'+ ratingHTML +'</div>';
					}
					if (this.metaComments) badgeHTML 		+= '<div class="metaComments">'+ this.GetText("meta_tag_comments", ((items[i]["totalMessageCount"])? items[i]["totalMessageCount"]:0)) +'</div>'; 				
					badgeHTML += '	</div>';
				}
				badgeHTML += '	</div>';
      }
     } else {
      	if (this.layout == "horizontal") elemTop = Math.round((this.thumbHeight+this.metaHeight)/2);
   			else elemTop = Math.round((this.showsPerPage*dominantHeight+(this.showsPerPage+1)*this.padding)/2);
     		badgeHTML += '	<div class="infoMessage" style="top: '+ elemTop +'px;">'+ ((this.filterSearchKeyword != "")? this.GetText("info_no_matches"):this.GetText("info_no_shows")) + " "+ errMsg +'</div>';
     } 
    badgeHTML += '		</div>';	
    badgeHTML += '	</div>';	
  	if (this.domId != undefined) document.getElementById(this.domId).innerHTML = badgeHTML;
  }
  
};

    

