//----------------------------------
// CALL TAKEOUT
//----------------------------------


var path;
var playlistId;   

var maxItem    = "12";
//var idPlayer   = "11";

var properties = "?Unit=Item&Attributes=id,playlistId,title,description,thumbnailMedium,published,ratingScore,programmingTotalRows,ratingViews";
var criteria   = "period=LastSevenDays";

//absolutePath
function BoxContainer(boxId,contentId,pagerId,pager,cols){
	this.name        	= "boxContainer"
	this.response    	= this.createThumbList;
	this.responseError 	= delegate(this,this.showError);
	this.loading    	= this.showLoading;
	this.callNewPage 	= this.newContent;
	this.type        	= "";
	this.resource    	= "";
	this.Highlight   	= ""
	this.cols 		 	= cols      || 4;
	this.boxId       	= boxId     || "box";
	this.contentId   	= contentId || "content";
	this.pagerId     	= pagerId   || "index";
	this.pagerObject 	= pager     || new Pager(this.boxId);		
	this.pagerObject.setCallFunction(this.callNewPage);
	this.absolutePath = "";
	this.urlTakeOut = "http://takeout.dmmotion.com/content/programming"
}
	
	BoxContainer.prototype.showError = function(){
		showError(this.contentId);
	}
	
	BoxContainer.prototype.setIdPlayer = function(idPlayer){
		this.urlTakeOut +=  "/"+idPlayer ;
	}
	
	BoxContainer.prototype.setPager = function(value){	
		this.pagerObject = value;
		this.pagerObject.setCallFunction(this);
	}

	BoxContainer.prototype.changeType = function(value,resetPage){	
		this.type = value;
		if(resetPage)this.pagerObject.setCurrentPage(page);
		this.callNewPage();
	}

	BoxContainer.prototype.newContent = function(){	
		this.loading();		
		var url 		 = "";
		var responseCall = "box.response";
		
		switch(String(this.type)){			
			case "1":
			url  = this.urlTakeOut+this.resource+"/mostvoted"+properties+getPaging()+this.Highlight;
			break;
			case "2":
			url  = this.urlTakeOut+this.resource+"/mostviewed"+properties+getPaging()+this.Highlight;
			break;
			default:url = this.urlTakeOut+this.resource+properties+getPaging()+this.Highlight;break;
		}
		
		callTakeOut(url,responseCall)
	}

	BoxContainer.prototype.changeView = function(source){	
		this.response    = this.response == this.createThumbList ? this.createTextList : this.createThumbList;
		this.changeType(this.type,false);
	}
	
	BoxContainer.prototype.createTextList = function(source){			
		
		
		var item;
		var data = source;
		if(typeof(data) == "string")data = eval(source);
		var published;
		var total     = data.length;	
		var container = document.getElementById(this.contentId);	
			container.innerHTML = ""
		
		var fv_vot = {};
		
		var today = new Date()
		var time = today.getTime()
		for(var i=0; i < total;i++){	
			
			
		var divContainer  = document.createElement("div");
		var div 		  = document.createElement("div");
		var link		  = document.createElement("a");
		var title		  = document.createElement("h4");
		var desc		  = document.createElement("p");
		var info		  = document.createElement("div");
		var separator1	  = document.createElement("div");
		var separator2	  = document.createElement("div");
		var clasificacion = document.createElement("div");
		var stars 		  = document.createElement("div");
		var starsCont	  = document.createElement("div");
		var texto	      = document.createElement("p");
		var avaible		  = document.createElement("p");
		var reprod		  = document.createElement("p");
			
			item  	    			= data[i];					
			published    			= new Date(item.published);				
			divContainer.className  = "textList";
			div.className 	  		= ((i)%this.cols == 0?  'item-first' : 'item');			
			title.innerHTML   	 	= item.title;
			desc.innerHTML   		= item.description;
			info.className   		= "rating"
			//avaible.innerHTML     	= 'Agregado: <b>'+published.getDate()+'/'+(published.getMonth()+1)+'/'+published.getFullYear()+'</b>';			
			avaible.innerHTML     	= 'Agregado: <b> hace '+(Math.round(((((time-item.published)/1000)/60)/60)/24))+' días</b>';			
			clasificacion.className = "clasificacion"; 
			separator1.className 	= "separator-line";
			separator2.className 	= "separator-line";
			texto.innerHTML 		= "Calificaci&oacute;n:"; 
			reprod.innerHTML 		= "Reproducciones <b>"+item.ratingViews+" vistas</b>";
			stars.id			    = "startHolder"+i;
			//starsCont.className     = "stars-mask";
			//link.setAttribute("href",this.absolutePath+"videoPlayer.php?itid="+item.id);		
			link.setAttribute("href",this.absolutePath+"item/"+item.id+"/"+urlFormat(item.title));		
			
			clasificacion.appendChild(texto);			
		
			info.appendChild(avaible);
			info.appendChild(reprod);
			info.appendChild(clasificacion);	
			starsCont.appendChild(stars);
			info.appendChild(starsCont);
			

			link.appendChild(title);
			link.appendChild(desc);	
			link.appendChild(separator1);
			link.appendChild(info);
			link.appendChild(separator2); 
			div.appendChild(link);
			
			divContainer.appendChild(div);
			container.appendChild(divContainer);
				
			fv_vot.value 		 = item.ratingScore/2;
			fv_vot.selectedColor = selectedStarColor;
			fv_vot.normalColor 	 = normalStarColor;
			swfobject.embedSWF(path+"image/startVote.swf", "startHolder"+i,  "70",  "12", "8", null,fv_vot,	{wmode: 'transparent',allowScriptAccess:'always'  })
			
		}
		
		var totalItems = data[0].programmingTotalRows || 0;
		this.pagerObject.setTotalPages(Math.ceil(totalItems/maxItem));

		var indexPage 			= document.getElementById(this.pagerId);
			indexPage.innerHTML = this.pagerObject.render();
		//reSizeBox(this.boxId);
	}
	
	BoxContainer.prototype.createThumbList = function(source){			
		var item;
		var data = source;
		if(typeof(data) == "string")data = eval(source);
			
		var published;
		var total        = data.length;	
		var container    = document.getElementById(this.contentId);		
		var thumbs       = "";	
		var disponible   = "";
		var customLayout = "";
		
		for(var i=0; i < total;i++){		
			item  	     = data[i];			
			published    = new Date(item.published);	
			customLayout = item.customLayout;
			disponible   = "";
			if(customLayout){				
				disponible  += customLayout.hd && customLayout.hd.length ? "HD " : "";			
				disponible  += customLayout.bazuca && customLayout.bazuca.length ? "BAZUCA " : "";			
				disponible  += customLayout.tvc && customLayout.tvc.length ? "TVC " : "";			
				disponible  += customLayout.vod && customLayout.vod.length ? "VOD " : "";			
			}
			
			thumbs 		+= '<div class="'+((i)%this.cols == 0?  'item-first' : 'item')+'" >';	
			thumbs      += '<div>';
			thumbs 		+= '<a class="item-tooltip" href="'+this.absolutePath +'item/'+item.id+'"/"'+urlFormat(item.title)+'">';	
			thumbs 		+= '<img src="'+item.thumbnailMedium+'" width="116" height="76"/>';	
			thumbs 		+= '<h4>'+item.title+'</h4>';	
			thumbs 		+= '<p class="parrafo">'+item.description+'</p>';	
			thumbs		+= '</a>';	
			thumbs		+= '<div class="tooltip noDisplay">';	
			thumbs		+= '<div class="content">'
			thumbs		+= '<h4>'+item.title+'</h4>';	
			thumbs 		+= '<p>Agregado:'+published.getDate()+'/'+(published.getMonth()+1)+'/'+published.getFullYear()+'</p>';
			thumbs		+= '<p><span class="left">Calificaci&oacute;n:</span><span id="startHolder'+i+'"></span></p>'
			
			thumbs 		+= '<div class="separator-line"></div>';
			thumbs 		+= '<p class="desc">'+item.description+'</p>';
			thumbs 		+= '<div class="separator-line"></div>';
			if(disponible.length)thumbs 		+= '<p>Disponible: <span class="disponible">'+disponible+'</span></p>';
			thumbs 		+= '</div>';
			thumbs 		+= '</div>';
			thumbs 		+= '</div>';	
			thumbs 		+= '</div>';
			thumbs 		+= '</div>';			

		}
			
		var totalItems = data[0].programmingTotalRows || 0;
		this.pagerObject.setTotalPages(Math.ceil(totalItems/maxItem));

		container.innerHTML 	= thumbs;
		var indexPage 			= document.getElementById(this.pagerId);
			indexPage.innerHTML = this.pagerObject.render();

		for(var zz=0; zz < total;zz++){		
				item  	     = data[zz];				
			var fv_vot = {};
				fv_vot.value 		 = item.ratingScore/2;
				fv_vot.selectedColor = selectedStarColor;
				fv_vot.normalColor 	 = normalStarColor;
				
			swfobject.embedSWF(path+"image/startVote.swf", "startHolder"+zz,  "70",  "12", "8", null,fv_vot,	{wmode: 'transparent',allowScriptAccess:'always'  })
		}
			
		createToolTips();
		//reSizeBox(this.boxId);
		
	}

	BoxContainer.prototype.showLoading = function(){
		var container 			= document.getElementById(this.contentId);
			container.innerHTML = "<p class='loading'>cargando informaci&oacute;n</p>";
		var indexPage 			= document.getElementById(this.pagerId);
			indexPage.innerHTML = "";
			//reSizeBox("#"+this.boxId);
	}
	
	BoxContainer.prototype.setPath = function(p){
		this.absolutePath = p;
	}
//----------------------------------
//----------------------------------

function Pager(id,instanceName){
	this.name          = "pager"
	this.instanceName  = instanceName || "pager";
	this._id           = id || "pager";
	this._countPages   = 10;
	this._current      = 1;
	this._totalPages   = 1;
	this._minPage      = 1;
	this._objCaller    = null;
}

	Pager.prototype.setName = function(value){
		this.instanceName = value;
	}
	
	Pager.prototype.setCallFunction = function(callFunction){
		this._objCaller = callFunction;
	}

	Pager.prototype.setCountPages = function(value){
		this._countPages = value;
	}
	
	Pager.prototype.getCurrentPage = function(){
		return this._current;
	}	

	Pager.prototype.setCurrentPage = function(current){
		this._current = current;
	}

	Pager.prototype.setTotalPages = function(total){
		this._totalPages = total;
	}

	Pager.prototype.nextPage = function(){
		this._current++;		
		if(this._current <= this._totalPages){
			this.getNewRecentPage(this._current);
		}
	}

	Pager.prototype.prevPage = function(){
		this._current--;
		if(this._current >= this._minPage){
			this.getNewRecentPage(this._current);
		}
	}

	Pager.prototype.getNewRecentPage = function(page){
		this.setCurrentPage(page);
		this._objCaller.callNewPage();
	}
		
	Pager.prototype.render = function (instanceName) {		
		prevClass    = (this._current > 1) ? "showElement":"hideElement";
		nextClass    = (this._current < this._totalPages) ? "showElement":"hideElement";		
		html  		 = "";

		if(this._totalPages > 1){		
			html 		+= '<div class="separator-line"></div>';
			html 		+= '<div class="pages">' ;
			html 		+= '<span class="prevContainer" ><a href="#'+this._id+'" onclick="javascript:'+this.instanceName+'.prevPage();"><span id="prevPagesButton" class="'+prevClass+'">&nbsp;</span></a></span>';
			html 		+= '<span class="pagesContainer">';
			html 		+=  this.createPages(this.instanceName);
			html 		+= '</span>';
			html		+= '<span class="nextContainer" ><a href="#'+this._id+'" onclick="javascript:'+this.instanceName+'.nextPage();"><span id="nextPagesButton" class="'+nextClass+'">&nbsp;</span></a></span>';

			html 		+= '</div>';
		}
		
		return html;
	}
	
	Pager.prototype.createPages = function() {	
		var tags   = "";
		var min    = Math.ceil(this._current / this._countPages) ;
		var max    = min * this._countPages;
		var total  = max > this._totalPages ? this._totalPages : max;
		var start  = min * this._countPages - this._countPages + 1;
	
		for (var i = start; i <= total; i++) {		
			tags += i != this._current ? '<span><a href="#'+this._id+'" onclick="javascript:'+this.instanceName+'.getNewRecentPage('+(i)+');" class="indexer">'+i+'</a></span>' : '<span class="selected"><span class="paging-bg-right">'+i+'</span></span>';			
		}
		
		return tags;
	}

//----------------
// RENDER
//----------------
var errorFunc
var isFlajaxLoaded = false;
function getPaging(){
 return "&Paging="+String(pager.getCurrentPage())+","+maxItem;
}

function getElement(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function callTakeOut(url,response){
	errorFunc = response+"Error";
	if(isFlajaxLoaded){	
		getElement("flajax")["call"](url, response,"GET", null);
	}else{
		eval(errorFunc)();
	}
}

function flajaxLoad(o) {
	isFlajaxLoaded = true;
}

function flajaxIOError(o) {
	eval(errorFunc)()
}

function showError(id){
	var container 			= document.getElementById(id);
		container.innerHTML = "<p class='loading'>Informaci&oacute;n no disponible</p>";	
}

function flajaxSecurityError(o) {
	flajaxIOError(o)
}

function urlFormat(texto) {
	var text = texto.toLocaleLowerCase();
		text = text.replace(/ /g, "-");				
		text = text.replace(/[á | à | ä | â]/gi, "a");
		text = text.replace(/[é | è | ë | ê]/gi, "e");
		text = text.replace(/[í | ì | ï | î]/gi, "i");
		text = text.replace(/[ó | ò | ö | ô]/gi, "o");
		text = text.replace(/[ú | ù | ü | û]/gi, "u");
		text = text.replace(/[ñ]/gi, "n");
		text = text.replace(/[ç]/gi, "c");
		text = text.replace(/[^a-z0-9\\-]/g, "");	
	
	return text;
}

function delegate(scope, method){
	var params = Array(arguments).splice(2,arguments.length-2);                
	var proxy  = function(){
		method.apply(scope,params);
	}
	return proxy;
}



function StyleSelectObject(){
	var _scope			= this
	var _SelectObject 	= [];
	var seleccion 			= document.getElementsByTagName('select');
	this.onChange	 	= onChange;
	subscribeBody()
	
	this.createDropDown = function(seleccion){
		var li;
		var texto;
		var items;
		var option;
		var opciones 		 		= seleccion.options;
		var total   		 		= opciones.length;
		var container        		= document.createElement("div");
			container.className 	= "styleContainer";
			container.id       	 	= seleccion.id+"Select";
		var selected            	= document.createElement("div");
			selected.className  	= "itemSelected";
			selected.onclick    	= openList;				 
		var list 					 = document.createElement("ul");
			list.className 			 = "dropDown dropDownClose";
			list.style.display 		 = 'none';				
			seleccion.style.display	 = "none";
			_SelectObject[seleccion.id] = {item:"",timeout:0,container:container, label:selected};
		
		for(var i = 0; i < total;i++){
			option		= opciones[i];
			texto  		= document.createTextNode(option.text);
			li     		= document.createElement('li');
			li.seleccion   = seleccion;
			li.selIndex = option.index;
			li.val    = option.value;
			li.text     = option.text;
			li.onclick  = selectItem;
			
			if (option.selected) {
				li.className                 += " selected";
				_SelectObject[seleccion.id].item = li;
				selected.innerHTML 		      = option.text;
			}
			
			li.onmouseover = function() {
				this.className = this.className.replace(new RegExp(" hout\\b"), ' hover');
			}
		
			li.onmouseout = function() {
				this.className = this.className.replace(new RegExp(" hover\\b"), ' hout');
			}
			
			li.onmouseover();
			li.appendChild(texto);
			list.appendChild(li);
		}
		
		container.appendChild(selected);
		container.appendChild(list);
		seleccion.parentNode.appendChild(container);
	};
	
	function openList(){
		showList(this.parentNode.getElementsByTagName("ul")[0]);
	}
	
	function showList(container, closeDrop){
		if(new RegExp(" dropDownOpen\\b").test(container.className) || closeDrop){
			container.className     = container.className.replace(new RegExp(" dropDownOpen\\b"), ' dropDownClose');
			container.style.display = 'none';
		}else{
			container.className     = container.className.replace(new RegExp(" dropDownClose\\b"), ' dropDownOpen');
			container.style.display = '';
		}
	}
	
	function selectItem () {		
		var idSelect = this.seleccion.id;			
		if(_SelectObject[idSelect].item != this){
			_SelectObject[idSelect].item.className = "";
			_scope.onChange(this);			
		}			
		var option 								= _SelectObject[idSelect];
			option.item 						= this;		
			option.item.className 				= 'selected';								
			option.item.seleccion.selectedIndex 	= this.selIndex;
			option.label.innerHTML 				= this.text;
	} 
	
	function subscribeBody(){
		if(document.addEventListener)document.addEventListener("click",onCloseCombos,false);
		else document.attachEvent("onclick",onCloseCombos);
	}
	
	function onCloseCombos(evt){		
		try{
			var item;
			var container;
			var evt  = evt || window.event;
			var target = evt.originalTarget ? evt.originalTarget.parentNode.id : evt.srcElement.parentNode.id;			
			for(var i in  _SelectObject){
				container = _SelectObject[i].container;
				if(target != container.id){
					showList(container.getElementsByTagName("ul")[0], true);
				}
			}
		}catch(error){
			
		}
	}
	
	function onChange(evt){		
	};
	
	for (var i = 0; i < seleccion.length; i++){			
		this.createDropDown(seleccion[i]);
	};
	
}
