
//if(typeof Kyte == "undefined") var Kyte = {};
//if(typeof KyteBadge == "undefined") var KyteBadge = {

	KyteBadge.instances = [];

  function KyteBadgeServiceCallback(json) {
    this.Build(json);
  }

  function KyteBadgeGetJSON(sortMode) {
  	//var as = "";

  	var cta	 = '{';
  	cta 		+= '"orderSpec":"'+ this.defaultSortMode +'"';
  	if (this.searchAccount) {
  		cta	+= ',"accountUri":"account/apikey"';
  		cta += ', "hidden-any":""';
  		cta += ', "includeChildAccounts":""';
  	}
  	if (this.filterSearchKeyword != "") {
  		cta		+= ',"title-like":"%'+ this.filterSearchKeyword +'%"';
  	}
  	cta			+=	'}';
  	cta = escape(cta);
  
  	if (this.searchAccount) {
  		var url = 'http://'+ this.kyteServer +'/services/rest/channelService.findShows?ak='+ this.ak +'&cta='+ cta +'&frt='+ (this.page * this.showsPerPage) +'&mrs='+ this.showsPerPage +'&callback=KyteBadge.instances['+ this.index +'].ServiceCallback';
  	} else {
  		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=KyteBadge.instances['+ this.index +'].ServiceCallback';
  	}
  
  	var id = "KB_SCR_"+ this.index;
		oScript = document.getElementById(id);
		var head = document.getElementsByTagName("head")[0];
		if(oScript) {
			head.removeChild(oScript);
		}    
		oScript = document.createElement("script");
		oScript.type = "text/javascript";
		oScript.setAttribute("src", url);
		oScript.setAttribute("id",id);
		head.appendChild(oScript);
	}
  
  function KyteBadge(channelId, params, domId) {
  	this.index = KyteBadge.instances.length;
  	KyteBadge.instances[this.index] = this;

  	this.channelId = channelId;	
  	this.page = 0;
  	this.domId = domId;
  	
  	this.layout = "horizontal";
  	this.pagingControl = false;
  	this.showsPerPage = 5;
  	this.onClickThumb = 'player';
  	this.relatedKytePlayer = 'kyteplayer';
  	this.badgeTitle = "";
  	this.ak = false;
  	this.kyteServer = "www.kyte.tv";

  	this.defaultSortMode = "createdTime-d";    	
  	this.filterJustProduced = false;
  	this.filterMostWatched = false;
  	this.filterBestRated = false;
  	this.filterMostCommented = false;
  	this.filterSearch = false;
  	this.filterSearchKeyword = ""; 
  	this.searchAccount = false;  	

  	this.metaTitle = false;
  	this.metaTitleLength = 15;
  	this.metaProducer = false;
  	this.metaProducerLength = 15;
  	this.metaTime = false;
  	this.metaViews = false;
  	this.metaRating = false;
  	this.metaComments = false;
  	this.metaDescription = false;
  	this.metaDescriptionLength = 40;
  	
  	this.cssFile = 'http://www.mockup.tv/apps/badge/show_browser/styleTemplate.css'; 
  	this.cssClass = 'defaultBadgeLayout';
  	this.thumbWidth = 120;
  	this.thumbHeight = 90;
  	this.metaWidth = 120;
  	this.metaHeight = 90;
  	this.headerHeight = 33;
  	this.footerHeight = 0;
  	this.padding = 5;
  	
  	/*this.prevPageAct = "../prev.png";
  	this.prevPageDeact = "../prevDe.png";
  	this.nextPageAct = "../next.png";
  	this.nextPageDeact = "../nextDe.png";*/    	
		this.prevPageAct = false;
  	this.prevPageDeact = false;
  	this.nextPageAct = false;
  	this.nextPageDeact = false;

  	for (key in params){
  		this[key] = params[key];
		}
		
  	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.LoadData = KyteBadgeLoad;
  	this.GetJSON = KyteBadgeGetJSON;
  	this.Build = KyteBadgeBuild;
  	this.Browse = KyteBadgeBrowse;
  	this.ServiceCallback = KyteBadgeServiceCallback;
  	
  	this.LoadData();
  }
  
  function KyteBadgeLoad() {
  	this.GetJSON();
  }
  
  function KyteBadgeBrowse(direction, mode, startSearch) {  	
  	if (direction == "next") this.page++;
  	else if (direction == "prev" && this.page > 0) this.page--;
  	
  	if (mode || startSearch) {
  		this.page = 0;
  		this.defaultSortMode = mode;
  		try {
  			this.filterSearchKeyword = document.getElementById("KB_"+ this.index +"_sk").value;
  		} catch (err) { }
  	}

		this.GetJSON(mode);
  }
  
  function KyteBadgeBuild(data) {
  
		function createHyperLink(data, BadgeObj) {
			var linkHTML = "";
  	
			switch (BadgeObj.onClickThumb) {
				case "player":
					linkHTML += '<a href="#content" onclick="try { '+ BadgeObj.relatedKytePlayer +'.setURI(\''+ data.uri +'\'); } catch (err) { window.location = \''+ data.permalink +'\'; }">';
					break;
  			case "permalink":
  				linkHTML += '<a href="'+ data.permalink +'" target="new">';
  				break;
  			case "dynamic":
  				// div popup
  				break;
  			
			}
  	
			return linkHTML;
		}
  
		function truncate(text, len, dontelide) {
   				text += "";
   				if (text.length > len)
    			text = ( dontelide || text.length<4 ) ? text.substring(0,len) : ( text.substring(0, len-3) + "..." );
   				return text;      
 				 }
		
		function timeCalculator(ISO8061) {
			var showDate = new Date();
			var temp = ISO8061.substring(0,4) +' '+ ISO8061.substring(4,6) + ' '+ISO8061.substring(6,8)
			showDate.setFullYear(ISO8061.substring(0,4));
			showDate.setMonth(ISO8061.substring(4,6));
			showDate.setDate(ISO8061.substring(6,8));
			showDate.setHours(ISO8061.substring(6,11));
			showDate.setMinutes(ISO8061.substring(11,13));
			showDate.setSeconds(ISO8061.substring(13,15));
			
			
			//showDate = items[i]["createdTime"].parse();			
			
			return showDate.toString();
		}
		
		function importCSS(id, cssFile) {
			oCSS = document.getElementById(id);
			
			var head = document.getElementsByTagName("head")[0];
		
			if (oCSS) head.removeChild(oCSS);
		  
			oCSS = document.createElement("link"); 
			oCSS.type = 'text/css';
			oCSS.rel = 'stylesheet';
			oCSS.href = cssFile;
			oCSS.media = 'screen';
			head.appendChild(oCSS);		     		
		}		
  	
  	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 = " (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 prevAct = (this.prevPageAct)? ' <img src="'+ this.prevPageAct +'" /> ' : ' \< ';
		var prevDeact = (this.prevPageDeact)? ' <img src="'+ this.prevPageDeact +'" /> ' : ' \< ';
		var nextAct = (this.nextPageAct)? ' <img src="'+ this.nextPageAct +'" /> ' : ' \> ';
		var nextDeact = (this.nextPageDeact)? ' <img src="'+ this.nextPageDeact +'" /> ' : ' \> ';		
		
		importCSS("KB_CSS_"+ this.index, this.cssFile);  
	
		// put together HTML part
		var badgeHTML = "";
		if (this.layout == "horizontal") {
			badgeHTML += '	<div id="KB_'+ this.index +'" class="'+ this.cssClass +' kyteBadge_horizontal" style="width: '+ (this.showsPerPage*dominantWidth+(this.showsPerPage+1)*this.padding) +'px; height: '+ (3*this.padding+this.thumbHeight+this.metaHeight+this.headerHeight+this.footerHeight) +'px;">';
		} else {
			badgeHTML += '	<div id="KB_'+ this.index +'" class="'+ this.cssClass +' kyteBadge_vertical" style="width: '+ (this.metaWidth+this.thumbWidth+3*this.padding) +'px; height: '+ (this.footerHeight+this.headerHeight+this.showsPerPage*dominantHeight+(this.showsPerPage+1)*this.padding) +'px;">';
		}
		badgeHTML += '			<div class="header" style="height:'+ this.headerHeight +'px;"></div>';
		badgeHTML += '			<div class="footer" style="height:'+ this.footerHeight +'px;"></div>';
		var extraClass = "";	
		if (this.filterJustProduced || this.filterMostWatched || this.filterMostCommented || this.filterSearch || this.filterBestRated) {
			badgeHTML += '		<div class="sorting" style="height: '+ this.headerHeight +'px;">';
			if (this.filterJustProduced) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "createdTime-d")?' active': '') +'"><a href="#content" onclick="KyteBadge.instances['+ this.index +'].Browse(false, \'createdTime-d\', false);">Just Produced</a></span>';
			}			
			if (this.filterMostWatched) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "totalWatches-d")?' active': '') +'"><a href="#content" onclick="KyteBadge.instances['+ this.index +'].Browse(false, \'totalWatches-d\', false);">Most Watched</a></span>';
			}	
			if (this.filterBestRated) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "averageTenths-d")?' active': '') +'"><a href="#content" onclick="KyteBadge.instances['+ this.index +'].Browse(false, \'averageTenths-d\', false);">Best Rated</a></span>';
			}									
			if (this.filterMostCommented) {
				badgeHTML += '		<span class="sortingMode'+ ((this.defaultSortMode == "totalMessageCount-d")?' active': '') +'"><a href="#content" onclick="KyteBadge.instances['+ this.index +'].Browse(false, \'totalMessageCount-d\', false);">Most Commented</a></span>';
			}
			badgeHTML += '		</div>';
		}				
		badgeHTML += '			<div class="badgeTitle" style="height: '+ this.headerHeight +'px; padding: '+ this.padding +'px;">'+ this.badgeTitle +'</div>';   
		if (this.pagingControl) {  	
			badgeHTML += '		<div class="pager">';
			if (page > 1) {
				badgeHTML += '		<a href="#content" onclick="KyteBadge.instances['+ this.index +'].Browse(\'prev\');">'+ prevAct +'</a>';
			} else {
				badgeHTML += 			prevDeact;
			}
			badgeHTML += '			Page '+ (page) +' of '+ totalPages;
			if (page < totalPages) {
				badgeHTML += '		<a href="#content" onclick="KyteBadge.instances['+ this.index +'].Browse(\'next\');">'+ nextAct +'</a>';
			} else {
				badgeHTML +=			nextDeact;
			}
			badgeHTML += '		</div>';
		}
		if (this.filterSearch) {
			badgeHTML += '		<div class="finder" style="height: '+ this.headerHeight +'px;">';
			badgeHTML += '			Find: <input type="text" id="KB_'+ this.index +'_sk" value="'+ this.filterSearchKeyword +'" class="text" /><input type="button" value="Search this Channel" class="button" onclick="KyteBadge.instances['+ this.index +'].Browse(false, \''+ this.defaultSortMode +'\', true);" />';
			badgeHTML += '		</div>';
		} 
		if (this.layout == "horizontal") {
			
		} else {
			badgeHTML += '		<div class="showList" style="top: '+ this.headerHeight +'px; left: 0px; width: 100%; height: '+ (this.showsPerPage*dominantHeight+(this.showsPerPage+1)*this.padding) +'px;">';
		}
		if (showCount > 0) {   	
			for (var i=0; i < showCount; i++) {
				if (this.layout == "horizontal") {
					badgeHTML += '<div class="cell" style="top: '+ this.headerHeight +'px; left: '+ ((i*dominantWidth)+(i*this.padding)) +'px; height: '+ (this.thumbHeight+this.metaHeight+3*this.padding) +'px; width: '+ (dominantWidth+2*this.padding) +'px;">';
					badgeHTML += '	<div class="subCell thumb" style="top: '+ this.padding +'px; left: '+ this.padding +'px; height: '+ this.thumbHeight +'px; width: '+ dominantWidth +'px;">'+ createHyperLink(items[i], this) +'<img src="'+ items[i]["thumb120x90Url"] +'" style="width: '+ this.thumbWidth +'px; height: '+ this.thumbHeight +'px;" /></a></div>';
				} else {
					badgeHTML += '<div class="cell" style="top: '+ (i*dominantHeight+i*this.padding) +'px; height: '+ (dominantHeight+2*this.padding) +'px; width: 100%;">';
					badgeHTML += '	<div class="subCell thumb" style="left: '+ this.padding +'px; top: '+ this.padding +'px; width:'+ this.thumbWidth +'px; height: '+ dominantHeight +'px;">'+ createHyperLink(items[i], this) +'<img src="'+ items[i]["thumb120x90Url"] +'" style="width: '+ this.thumbWidth +'px; height: '+ this.thumbHeight +'px;" /></a></div>';					
				}
				if (this.metaTitle || this.metaDescription || this.metaProducer || this.metaTime || this.metaViews || this.metaRating || this.metaComments) {
					if (this.layout == "horizontal") {
						badgeHTML += '<div class="subCell meta" style="top: '+ ((this.padding*2)+this.thumbHeight) +'px; left: '+ this.padding +'px; height: '+ this.metaHeight +'px; width: '+ this.metaWidth +'px;">';
					} else {
						badgeHTML += '<div class="subCell meta" style="left: '+ (this.padding*2+ this.thumbWidth) +'px; top: '+ this.padding +'px; width:'+ this.metaWidth +'px; height: '+ dominantHeight +'px;">';	
					}
					if (this.metaTitle) badgeHTML 			+= '<div class="metaTitle">'+ createHyperLink(items[i], this) + truncate(items[i]["title"], this.metaTitleLength) +'</a></div>';
					if (this.metaDescription) badgeHTML	+= '<div class="metaDescription">'+ truncate(items[i]["synopsis"], this.metaDescriptionLength) +'</div>';
					if (this.metaProducer) badgeHTML 		+= '<div class="metaProducer">By '+ truncate(items[i]["ownerName"], this.metaProducerLength) +'</div>';
					if (this.metaTime) badgeHTML 				+= '<div class="metaTime">'+ (timeCalculator(items[i]["createdTime"])) +'</div>';
					if (this.metaViews) badgeHTML 			+= '<div class="metaViews">Views: '+ ((items[i]["totalWatches"])? items[i]["totalWatches"]:0) +'</div>';
					if (this.metaRating) badgeHTML    += '<div class="metaRating">Ratings: '+ ((items[i]["rateSum"])? truncate(items[i]["rateSum"]/items[i]["rateCount"],this.metaRatingLength, true):0) +'</div>';
					//if (this.metaComments) badgeHTML 		+= '<div class="metaComments">Comments: '+ ((items[i]["totalMessageCount"])? items[i]["totalMessageCount"]:0) +'</div>'; 				
					badgeHTML += '	</div>';
				}
				badgeHTML += '	</div>';
      }
     } else {
      	if (this.layout == "horizontal") {	 
      		badgeHTML += '	<div class="infoMessage" style="top: '+ Math.round((3*this.padding+this.thumbHeight+this.metaHeight)/2) +'px;">'+ ((this.filterSearchKeyword != "")? 'No matching shows!':'No shows available!') + errMsg +'</div>';
     		} else {
      		badgeHTML += '	<div class="infoMessage" style="top: '+ Math.round((this.showsPerPage*dominantHeight+(this.showsPerPage+1)*this.padding)/2) +'px;">'+ ((this.filterSearchKeyword != "")? 'No matching shows!':'No shows available!') + errMsg +'</div>';
     		}
     } 
    badgeHTML += '		</div>';
    badgeHTML += '	</div>';	
  	if (this.domId != undefined) document.getElementById(this.domId).innerHTML = badgeHTML;
  	else { }
  }
  
//};

    
