/**
 *	Kyte Show Browser Batch
 *	==================================================================
 *	
 *	This is the official source file of the Kyte Badge framework.
 *	Feel free to use and edit the code for personal purpose.
 *
 *	==================================================================
 *
 *	Newest tested version available on:
 *	http://beta.kyte.com/badges/show_browser/kyteBadge.js
 *
 *	Change log (latest edits):
 *	Edit: Don't print Show Views value is 0 (2010-02-19 by Kyte/MS)
 *	v1.3:	Extended retrieval (criteria-support) (2009-12-15 by Kyte/MS)
 *	v1.2:	Added information header to source file (2009-12-10 by Kyte/MS) 
 *	v1.1: Added ad serving control to badges (2009-11-30 by Kyte/MS)
 *
 *	==================================================================
 */
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.showsPerPage == undefined) this.showsPerPage = 5;
  	if (this.layout != "vertical") {
  		this.layout = "horizontal";
  		if (this.showsPerRow == undefined) this.showsPerRow = this.showsPerPage;
  		if (this.rowsPerPage == undefined) this.rowsPerPage = 1;  		
  	} else {
  		if (this.showsPerRow == undefined) this.showsPerRow = 1;
  		if (this.rowsPerPage == undefined) this.rowsPerPage = this.showsPerPage;   		
  	}
  	this.totalPages = 0;
  	this.showsPerPage = this.showsPerRow*this.rowsPerPage;
  	if (this.criteria == undefined) this.criteria = false;
  	if (this.pagingControl == undefined) this.pagingControl = false;
  	if (this.pagingControlExtended == undefined) this.pagingControlExtended = false;
  	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 = "api.kyte.tv";
  	this.root = "http://"+ this.kyteServer +"/services/rest/";
  	if (this.stampFormat == undefined) this.stampFormat = "date";
  	if (this.noCache == undefined) this.noCache = false;  	

  	if (this.defaultSortMode == undefined) this.defaultSortMode = "createdTime-d";    	
		this.currentSortMode = this.defaultSortMode;
  	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.filterPlaylist == undefined) this.filterPlaylist = false;
  	else this.PlItems = 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.metaDuration == undefined) this.metaDuration = 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.metaNumberFormat == undefined) this.metaNumberFormat = false;
  	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.thumbOverlayImage == undefined) this.thumbOverlayImage = false;
  	if (this.cssClass == undefined) {
  		if (this.layout == "vertical") this.cssClass = 'kyteBadgeVert';
  		else this.cssClass = 'kyteBadgeHori'; 		
  	}

		this.wording = false;
		try {		
  		if (this.wordingObj != undefined) this.wording = new window[this.wordingObj]();
  	} catch (err) { }
  	
  	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;
  	if (this.outerPadding == undefined) this.outerPadding = this.padding;
  	
  	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.outerPadding = parseInt(this.outerPadding);
  	this.showsPerPage = parseInt(this.showsPerPage);
  	this.showsPerRow = parseInt(this.showsPerRow);
  	this.rowsPerPage = parseInt(this.rowsPerPage);
  	this.page = parseInt(this.page);

		if (this.firstPageAct == undefined) this.firstPageAct = false;
  	if (this.firstPageDeact == undefined) this.firstPageDeact = false;
  	if (this.lastPageAct == undefined) this.lastPageAct = false;
  	if (this.lastPageDeact == undefined) this.lastPageDeact = false;
		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;
  	
  	if (this.adThumbData == undefined) this.adThumbData = false;
  	if (this.adThumbFreq == undefined) this.adThumbFreq = 1
  	if (this.adThumbSponsor == undefined) this.adThumbSponsor = false;
  	if (this.adSplashData == undefined) this.adSplashData = false;
  	if (this.adSplashFreq == undefined) this.adSplashFreq = 2
  	if (this.adSplashOnce == undefined) this.adSplashOnce = false;
  	
  	this.GetJSON = KyteBadgeGetJSON;
  	this.Build = KyteBadgeBuild;
  	this.Browse = KyteBadgeBrowse;
  	this.GetText = KyteBadgeGetText;
  	this.FormatStamp = KyteBadgeFormatStamp;
  	this.CreateLink = KyteBadgeCreateLink;
  	this.PlGet = KyteBadgePlGet;
  	this.AdClose = KyteBadgeAdClose;
  	
  	this.firstShowItem = false;
  	this.eventAction = new Array();
  	this.addEventListener = KyteBadgeAddEventListener;
  	this.eventFire = KyteBadgeEventFire;
  	this.removeEventListener = KyteBadgeRemoveEventListener;
 
  	this.GetJSON();
  }
  
  function KyteBadgePlGet(data) {
  	try {
  		if (data["result"]["items"].length < 1) this.defaultSortMode = "noPlaylist";
  		else this.PlItems = data["result"]["items"][0]["showUris"];
  		this.GetJSON();
  	} catch (err) {
  		try {
  			this.Build(data);
  		} catch (err) { }
  	}
  }

  function KyteBadgeGetJSON() {
  	var url;
  	var sortMode = ((this.defaultSortMode == "noPlaylist" && (this.currentSortMode == "playlist" || this.filterSearchKeyword || this.filterTagKeyword)) || (this.defaultSortMode == "playlist" && (this.filterSearchKeyword || this.filterTagKeyword)))? "createdTime-d":this.currentSortMode;
  	var cta = new Array();
  	if (this.criteria) cta = cta.concat(this.criteria);
  	cta.push('"orderSpec":"'+ sortMode +'"');
  	if (this.noCache) cta.push('"noCache":""');

  	if (this.channelId == "ALL") cta.push('"accountUri":"account/apikey"');
  	else if (this.channelId) cta.push('"parentUri":"channels/'+ this.channelId +'"');

		if (this.filterSearchKeyword != "") {
			var searchKeys = new Array();
			searchKeys = this.filterSearchKeyword.split(" ");
			var searchString = '["%'+ searchKeys.join('%","%') +'%"]';
			cta.push('"title-like":'+ searchString +'');
		}
		if (this.filterTagKeyword != "") {
			var tagKeys = new Array();
			tagKeys = this.filterTagKeyword.split(" ");
			var tagSearchString = '["%'+ tagKeys.join('%","%') +'%"]';
			cta.push('"tags-like":'+ tagSearchString +'');
		}
  
  	if (this.currentSortMode == "playlist" && this.defaultSortMode != "noPlaylist" && !this.filterSearchKeyword && !this.filterTagKeyword) {
  		if (this.PlItems) {
  			var uris = new Array();
  			for (var i = this.page * this.showsPerPage; i < (this.page+1) * this.showsPerPage; i++) {
  				if (this.PlItems[i] != undefined) uris.push('"'+ this.PlItems[i] +'"');
  			}
  			url = this.root +'utilService.batchFetchMetaData?ak='+ this.ak +'&uris=['+ uris.join() +']&callback=KyteShowBrowser['+ this.index +'].Build';
  		} else url = this.root +'channels/'+ this.channelId +'.findPlaylists?ak='+ this.ak +'&cta={}&frt='+ 0 +'&mrs='+ 1 +'&callback=KyteShowBrowser['+ this.index +'].PlGet';
  	//} else url = this.root +'channels/'+ this.channelId +'.findShows?ak='+ this.ak +'&cta={'+ escape(cta.join()) +'}&frt='+ (this.page * this.showsPerPage) +'&mrs='+ this.showsPerPage +'&callback=KyteShowBrowser['+ this.index +'].Build';
  	} else url = this.root +'channelService.findShows?ak='+ this.ak +'&cta={'+ escape(cta.join()) +'}&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 KyteBadgeGetText(tagName, x, y, z) {
		if (this.wording) {
			var text = this.wording[tagName];
			if (text != undefined) {
				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;
			}
		}

		switch (tagName) {
			case "paging_index":					return "Page "+ x +" of "+ y;
			case "paging_prev":						return "<";
			case "paging_next":						return ">";
			case "paging_first":					return "<< ";
			case "paging_last":						return " >>";			
			case "filter_just_produced":	return "Just Produced";
			case "filter_playlist":				return "All Videos";
			case "filter_most_watched": 	return "Most Watched";
			case "filter_best_rated":			return "Best Rated";
			case "filter_most_commented":	return "Most Commented";
			case "search_go_button":			return "Go";
			case "search_find":						return "Find: ";
			case "meta_tag_by":						return "<span>By:</span> "+ x;
			case "meta_tag_views":				return "<span>Views:</span> "+ x;
			case "meta_tag_rating":				return "<span>Rating:</span> "+ x;
			case "meta_tag_comments":			return "<span>Comments:</span> "+ x;
			case "meta_tag_duration":			return "<span>Duration:</span> "+ x +":" + y;
			case "info_no_matches":				return "No matching videos!";
			case "info_no_shows":					return "No videos available!";
			case "date_format_day":				return x +" "+ y;
			case "date_format_time":			return ((x > 12)? (x-12):x) +":"+ y + ((x > 12)? "pm":"am");
			case "date_format":						return x +" "+ y;
			case "month_1": 							return "Jan";
			case "month_2":								return "Feb";
			case "month_3":								return "Mar";
			case "month_4":								return "Apr";
			case "month_5":								return "May";
			case "month_6":								return "Jun";
			case "month_7":								return "Jul";
			case "month_8":								return "Aug";
			case "month_9":								return "Sep";
			case "month_10":							return "Oct";
			case "month_11":							return "Nov";
			case "month_12":							return "Dec";
			case "time_ago":							return x + " "+ y +" ago";
			case "just_now":							return "Just now";
			case "minute":								return "minute";
			case "minutes":								return "minutes";
			case "hour":									return "hour";
			case "hours":									return "hours";
			case "day":										return "day";
			case "days":									return "days";
			case "week":									return "week";
			case "weeks":									return "weeks";
			case "month":									return "month";
			case "months":								return "months";
			case "year":									return "year";
			case "years":									return "years";
			case "error":									return "(Error "+ x +": "+ y +")";
			case "advertisement":					return "ADVERTISEMENT";
			case "sponsored":							return "SPONSORED";
			case "close_ad":							return "[Close ad]";
			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 if (direction == "last") this.page = this.totalPages-1;
  	else this.page = 0;
  	
  	if (tagFilterKey) this.filterTagKeyword = tagFilterKey;
  	
   	if (mode) {
  		this.currentSortMode = mode;
  		if (document.getElementById("KB_"+ this.index +"_sk")) document.getElementById("KB_"+ this.index +"_sk").value = '';
  		this.filterTagKeyword = '';
  	} else if (!mode && !direction) {
  		this.currentSortMode = this.defaultSortMode;		
  	}
  	
 		try {
			this.filterSearchKeyword = 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 +'\'; }" '+ ((this.thumbOverlayImage)? 'onmouseover="document.getElementById(\'thumbOverlay_'+ this.index +'_'+ data.uri +'\').style.display = \'block\';" onmouseout="document.getElementById(\'thumbOverlay_'+ this.index +'_'+ data.uri +'\').style.display = \'none\';"':'') +'>';
				break;
			case "permalink":
				aTag = '<a href="'+ data.permalink +'" target="new" '+ ((this.thumbOverlayImage)? 'onmouseover="document.getElementById(\'thumbOverlay_'+ this.index +'_'+ data.uri +'\').style.display = \'block\';" onmouseout="document.getElementById(\'thumbOverlay_'+ this.index +'_'+ data.uri +'\').style.display = \'none\';"':'') +'>';
				break;
			default:
				aTag = '<a href="javascript: try { '+ this.onClickThumb +'(\''+ data.uri +'\'); } catch (err) { }" '+ ((this.thumbOverlayImage)? 'onmouseover="document.getElementById(\'thumbOverlay_'+ this.index +'_'+ data.uri +'\').style.display = \'block\';" onmouseout="document.getElementById(\'thumbOverlay_'+ this.index +'_'+ data.uri +'\').style.display = \'none\';"':'') +'>';
				break;				
		}
		
		return (aTag)? aTag + linkedHTML + '</a>':linkedHTML;
	} 
	
	function KyteBadgeAdClose(id) {
		document.getElementById(id).style.display = 'none';
		return;
	}
  
  function KyteBadgeBuild(data) {

		function truncate(text, len) {
			try {
				if (text.length > len) {
				text = text.substring(0, len-3) + "...";
				}
			} catch (err) {
				text = "";
			}
			return text;     	
		}
		
		function formatNumber(num, sep) {
			if (!sep) return num;
			
			var temp = "";
			var formatted = "";			
			num = num.toString();

    	for (var i=num.length-1;i>=0;i--) temp += num.charAt(i);
    	temp = temp.replace(/(\d{3})/g, "$1" + sep);
			if (temp.slice(-sep.length) == sep) temp = temp.slice(0, -sep.length);
			for (var i=temp.length-1;i>=0;i--) formatted += temp.charAt(i);

			return formatted;
		}
		
  	var items = new Array();
  	var totalSize;
  	var showCount = 0;
  	var page = 0;
  	var errMsg = "";
  	try {	
  		if (data["result"]["items"] != undefined) {
  			items = data["result"]["items"];
  			totalSize = data["result"]["totalSize"];
  		} else {
  			for (var i = this.page * this.showsPerPage; i < (this.page+1) * this.showsPerPage; i++) {
  				if (this.PlItems[i] != undefined && data["result"][this.PlItems[i]] != undefined) items.push(data["result"][this.PlItems[i]]);
  			}  			
  			totalSize = this.PlItems.length;
  		}
  		showCount = items.length;
  		if (totalSize > 0) {
  			this.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 adSplashAdd = (this.adSplashData && Math.ceil(Math.random()*this.adSplashFreq) == 1)
		var thumbAdIdx = showCount;
		if (!adSplashAdd && this.adThumbData && Math.ceil(Math.random()*this.adThumbFreq) == 1) {
			var thumbAdIdx = Math.round(Math.random()*(showCount-1));
		}

  	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 = (this.rowsPerPage*(this.padding+this.thumbHeight+this.metaHeight)+(this.rowsPerPage-1)*this.padding+2*this.outerPadding+this.headerHeight+this.footerHeight);
			elemWidth = (this.showsPerRow*dominantWidth+(this.showsPerRow-1)*this.padding+2*this.outerPadding);
		}else{
			elemHeight = (this.footerHeight+this.headerHeight+this.rowsPerPage*dominantHeight+(this.rowsPerPage-1)*this.padding+2*this.outerPadding);
			elemWidth = (this.showsPerRow*(this.metaWidth+this.thumbWidth+this.padding)+(this.showsPerRow-1)*this.padding+2*this.outerPadding);
		}
		/* modificacion */
		if (page > 1) {
			badgeHTML +='<div class="narrow-previous-noticias"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'prev\');">'+ ((this.prevPageAct)? ' <img src="'+ this.prevPageAct +'" /> ':this.GetText("paging_prev")) +'</a></div>';
		} else {				
			badgeHTML +='<div class="narrow-previous-noticias"><img src="'+ this.prevPageDeact +'" /></div>';
		}		
		/* fin */
		
		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 || this.filterPlaylist) {
			badgeHTML += '		<div class="sorting">';
			if (this.filterPlaylist) {
				badgeHTML += '		<span class="sortingMode'+ ((this.currentSortMode == "playlist" && !this.filterSearchKeyword && !this.filterTagKeyword)?' active': '') +'"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(false, \'playlist\', false);">'+ this.GetText("filter_playlist") +'</a></span>';
			}			
			if (this.filterJustProduced) {
				badgeHTML += '		<span class="sortingMode'+ ((this.currentSortMode == "createdTime-d" && !this.filterSearchKeyword && !this.filterTagKeyword)?' 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.currentSortMode == "totalWatches-d" && !this.filterSearchKeyword && !this.filterTagKeyword)?' 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.currentSortMode == "averageTenths-d" && !this.filterSearchKeyword && !this.filterTagKeyword)?' 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.currentSortMode == "totalMessageCount-d" && !this.filterSearchKeyword && !this.filterTagKeyword)?' 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"><span>'+ this.badgeTitle +'</span></div>';   
		if (this.pagingControl) {  	
			badgeHTML += '		<div class="pager">';
			badgeHTML += '			<span class="prev">';
			if (page > 1) {
				if (this.pagingControlExtended) badgeHTML += '<a href="javascript: KyteShowBrowser['+ this.index +'].Browse();">'+ ((this.firstPageAct)? ' <img src="'+ this.firstPageAct +'" /> ':this.GetText("paging_first")) +'</a>';
				badgeHTML += '<a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'prev\');">'+ ((this.prevPageAct)? ' <img src="'+ this.prevPageAct +'" /> ':this.GetText("paging_prev")) +'</a>';
			} else {
				if (this.pagingControlExtended) badgeHTML += 	(this.firstPageDeact)? ' <img src="'+ this.firstPageDeact +'" /> ':this.GetText("paging_first");
				badgeHTML += 	(this.prevPageDeact)? '<img src="'+ this.prevPageDeact +'" /> ':this.GetText("paging_prev");
				}
			badgeHTML += '			</span>';
			badgeHTML += 	'			<span class="pageIndex">'+ this.GetText("paging_index", page, this.totalPages) +'</span>';
			badgeHTML += '			<span class="next">';
			if (page < this.totalPages) {
				badgeHTML += '			<a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'next\');">'+ ((this.nextPageAct)? ' <img src="'+ this.nextPageAct +'" /> ':this.GetText("paging_next")) +'</a>';
				if (this.pagingControlExtended) badgeHTML += '			<a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'last\');">'+ ((this.lastPageAct)? ' <img src="'+ this.lastPageAct +'" /> ':this.GetText("paging_last")) +'</a>';
			} else {
				badgeHTML +=		(this.nextPageDeact)? ' <img src="'+ this.nextPageDeact +'" /> ':this.GetText("paging_next");
				if (this.pagingControlExtended) badgeHTML +=		(this.lastPageDeact)? ' <img src="'+ this.lastPageDeact +'" /> ':this.GetText("paging_last");
			}
			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="'+ this.filterSearchKeyword +'" class="text" /><input type="submit" value="'+ this.GetText("search_go_button") +'" class="button" />';
			badgeHTML += '		</form></div>';
		}
		if (this.layout == "horizontal") elemHeight = (this.rowsPerPage*(this.padding+this.thumbHeight+this.metaHeight)+(this.rowsPerPage-1)*this.padding+2*this.outerPadding);
		else elemHeight = (this.rowsPerPage*dominantHeight+(this.rowsPerPage-1)*this.padding+2*this.outerPadding);
		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") {
					elemLeft = (i%this.showsPerRow)*(dominantWidth+this.padding)+((i%this.showsPerRow > 0)?this.outerPadding-this.padding:0);
					elemHeight = (this.thumbHeight+this.metaHeight+this.padding+((Math.floor(i/this.showsPerRow) > 0)?this.padding:this.outerPadding));	
					elemTop = (Math.floor(i/this.showsPerRow)*elemHeight+((Math.floor(i/this.showsPerRow) > 0)?(this.outerPadding-this.padding):0));
					elemWidth = (dominantWidth+((i%this.showsPerRow == 0)?this.outerPadding:this.padding)+(((i+1)%this.showsPerRow == 0)?this.outerPadding:this.padding));
					if (thumbAdIdx == i) var thumbAdCellHTML = '<div id="KB_'+ this.index +'_AdCell" class="adThumbCell" style="width: '+ (elemWidth-(parseInt(((i%this.showsPerRow == 0)?this.outerPadding:this.padding)/2)+parseInt((((i+1)%this.showsPerRow == 0)?this.outerPadding:this.padding)/2))) +'px; height: '+ (elemHeight - ((Math.floor(i/this.showsPerRow)+1 == this.rowsPerPage && Math.floor(i/this.showsPerRow) > 1)?(parseInt(this.padding/2)-parseInt(this.outerPadding/2)):(Math.floor(i/this.showsPerRow) == 0 && this.rowsPerPage > 1)?parseInt(this.outerPadding/2)-parseInt(this.padding/2):0)) +'px; top: '+ parseInt(((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding)/2) +'px; left: '+ parseInt(((i%this.showsPerRow == 0)?this.outerPadding:this.padding)/2) +'px;">';
				} else {
					elemLeft = (i%this.showsPerRow)*(this.thumbWidth+this.metaWidth+2*this.padding)+((i%this.showsPerRow > 0)?this.outerPadding-this.padding:0);
					elemHeight = (dominantHeight+((Math.floor(i/this.showsPerRow) > 0)?this.padding:this.outerPadding));	
					elemTop = (Math.floor(i/this.showsPerRow)*elemHeight+((Math.floor(i/this.showsPerRow) > 0)?(this.outerPadding-this.padding):0));
					elemWidth = (this.thumbWidth+this.metaWidth+this.padding+((i%this.showsPerRow == 0)?this.outerPadding:this.padding)+(((i+1)%this.showsPerRow == 0)?this.outerPadding:this.padding));
					if (thumbAdIdx == i) var thumbAdCellHTML = '<div id="KB_'+ this.index +'_AdCell" class="adThumbCell" style="width: '+ (elemWidth-(parseInt((i%this.showsPerRow == 0)?this.outerPadding/2:this.padding/2)+parseInt(((i+1)%this.showsPerRow == 0)?this.outerPadding/2:this.padding/2))) +'px; height: '+ (elemHeight - parseInt((Math.floor(i/this.showsPerRow) < 1)?parseInt(this.outerPadding/2):parseInt(this.padding/2)) + parseInt((Math.floor(i/this.showsPerRow)+1 == this.rowsPerPage)?parseInt(this.outerPadding/2):parseInt(this.padding/2))) +'px; top: '+ parseInt(((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding)/2) +'px; left: '+ parseInt(((i%this.showsPerRow == 0)?this.outerPadding:this.padding)/2) +'px;">';
				}
				badgeHTML += '<div id="KB_'+ this.index +'_'+ items[i]["uri"].replace(/\//gi,"_") +'" class="cell channels_'+ items[i]["uri"].split("/")[1] +'" style="top: '+ elemTop +'px; left: '+ elemLeft +'px; height: '+ elemHeight +'px; width: '+ elemWidth +'px;">';
				if (this.layout == "horizontal") {
					elemHeight = this.thumbHeight;
					elemWidth = dominantWidth;
				} else {
					elemHeight = dominantHeight;
					elemWidth = this.thumbWidth;
				}
				badgeHTML += '	<div class="thumb" style="top: '+ ((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding) +'px; left: '+ ((i%this.showsPerRow == 0)?this.outerPadding: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;" alt="'+ items[i]["title"] +'" title="'+ items[i]["title"] +'" />') +'</div>';		
				if (this.thumbOverlayImage) badgeHTML += '	<div class="thumb" id="thumbOverlay_'+ this.index +'_'+ items[i]["uri"] +'" style="display: none; top: '+ ((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding) +'px; left: '+ ((i%this.showsPerRow == 0)?this.outerPadding:this.padding) +'px; height: '+ elemHeight +'px; width: '+ elemWidth +'px;">'+ this.CreateLink(items[i], '<img src="'+ this.thumbOverlayImage +'" style="width: '+ this.thumbWidth +'px; height: '+ this.thumbHeight +'px;" alt="'+ items[i]["title"] +'" title="'+ items[i]["title"] +'" />') +'</div>';		
				if (this.metaTitle || this.metaDescription || this.metaProducer || this.metaTime || this.metaDuration || this.metaViews || this.metaRating || this.metaComments) {
					if (this.layout == "horizontal") {
						elemTop = (this.padding+((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding)+this.thumbHeight);
						elemLeft = (i%this.showsPerRow == 0)?this.outerPadding:this.padding;
						elemHeight = this.metaHeight;
					} else {
						elemTop = ((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding);
						elemLeft = (((i%this.showsPerRow == 0)?this.outerPadding:this.padding)+this.padding+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.metaDuration && items[i]["mediaDurationMillis"]) badgeHTML 		+= '<div class="metaDuration">'+ this.GetText("meta_tag_duration", Math.floor(items[i]["mediaDurationMillis"]/1000/60), ((Math.floor((items[i]["mediaDurationMillis"]/1000)%60) < 10)?'0':'') + Math.floor((items[i]["mediaDurationMillis"]/1000)%60)) +'</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"])? formatNumber(items[i]["totalWatches"], this.metaNumberFormat):0)) +'</div>';
					if (this.metaViews) badgeHTML 			+= '<div class="metaViews">'+ ((items[i]["totalWatches"] > 0)? (this.GetText("meta_tag_views", formatNumber(items[i]["totalWatches"], this.metaNumberFormat))):'') +'</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"])? formatNumber(items[i]["totalMessageCount"], this.metaNumberFormat):0)) +'</div>'; 				
					badgeHTML += '	</div>';
				}
				if (thumbAdIdx == i) {
					badgeHTML += thumbAdCellHTML;
					badgeHTML += '	<div class="adThumbSource" style="top: '+ parseInt(((Math.floor(i/this.showsPerRow) == 0)?this.outerPadding:this.padding)/2) +'px; left: '+ parseInt(((i%this.showsPerRow == 0)?this.outerPadding:this.padding)/2) +'px;">'+ ((this.adThumbSponsor)?(this.CreateLink(items[i],this.adThumbData)):this.adThumbData) +'</div>';
					badgeHTML += '	<div class="adThumbLabel">'+ ((this.adThumbSponsor)?this.GetText("sponsored"):this.GetText("advertisement")) +'</div>';
					badgeHTML += '	<div class="adThumbClose"><a href="javascript: KyteShowBrowser['+ this.index +'].AdClose(\'KB_'+ this.index +'_AdCell\');">'+ this.GetText("close_ad") +'</a></div>';
					badgeHTML += '</div>';
				}
				badgeHTML += '	</div>';			
      }
     } else {
      	if (this.layout == "horizontal") elemTop = Math.round((this.rowsPerPage*(this.padding+this.thumbHeight+this.metaHeight)+(this.rowsPerPage-1)*this.padding+this.outerPadding)/2);
   			else elemTop = Math.round((this.rowsPerPage*dominantHeight+(this.rowsPerPage-1)*this.padding+this.outerPadding)/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>';
    if (adSplashAdd) {
    	badgeHTML += '<div id="KB_'+ this.index +'_AdSplash" class="adSplash">';
			badgeHTML += '	<div class="adSplashSource">'+ this.adSplashData +'</div>';
			badgeHTML += '	<div class="adSplashLabel">'+ this.GetText("advertisement") +'</div>';
			badgeHTML += '	<div class="adSplashClose"><a href="javascript: KyteShowBrowser['+ this.index +'].AdClose(\'KB_'+ this.index +'_AdSplash\');">'+ this.GetText("close_ad") +'</a></div>';    	
    	badgeHTML += '</div>';
    	if (this.adSplashOnce) this.adSplashData = false;
    }
    badgeHTML += '	</div>';	
    
	/* modificacion */	
	if (page < this.totalPages) {
		badgeHTML += '<div class="narrow-next-noticias"><a href="javascript: KyteShowBrowser['+ this.index +'].Browse(\'next\');">'+ ((this.nextPageAct)? ' <img src="'+ this.nextPageAct +'" /> ':this.GetText("paging_next")) +'</a></div>';
	} else {
		badgeHTML +='<div class="narrow-next-noticias"><img src="'+ this.nextPageDeact +'" /></div>';				
	}
	
/* fin */
    
  	if (this.domId != undefined) document.getElementById(this.domId).innerHTML = badgeHTML;
  	
  	if (items[0]) {
  		this.firstShowItem = items[0];
  		this.eventFire("badge.pageChanged");
  		this.eventFire("badge.loaded");
  	}
  }
  
  function KyteBadgeAddEventListener(type, fn) {
 		this.eventAction[type] = fn;
		this.eventFire(type);
 	}
 	 
 	function KyteBadgeEventFire(type) {
 			if (this.eventAction[type]) {
	 			switch (type) {
	 				case "badge.pageChanged":
	 				case "badge.loaded":
	 					if (this.firstShowItem) {
	 						this.eventAction[type](this.firstShowItem);
	 						this.removeEventListener("badge.loaded"); 				
	 						this.firstShowItem = false;
	 					}
	 					break;	
	 			}
 			}
 	}
 	
 	function KyteBadgeRemoveEventListener(type) {
 			this.eventAction[type] = false;
 	}
};