/* Refresh della sessione */
function refreshSession() {
  var request="http://aa.cubovision.it/aa/refreshSession?1=1";
  aObj = new JSONscriptRequest(request);
  aObj.buildScriptTag();
 	aObj.addScriptTag();
 	setTimeout("refreshSession()",600000);
}
/* Refresh della sessione ogni 10 minuti */
setTimeout("refreshSession()",10000);

var enabledComment=false;
var videoTv=false;

jQuery.fn.truncatitle = function(options) {
	//set default options  
	var defaults = {
		limit: 50
	};
	
	//call in the default otions
	var options = jQuery.extend(defaults, options);
	
	//act upon the element that is passed into the design    
	return this.each(function(i) {
		//check length of text to what out maximum is
		if(jQuery(this).text().length > defaults.limit) {
	var val0=jQuery(this).html().lastIndexOf(" ",defaults.limit);
			var val1=jQuery(this).html().lastIndexOf(",",defaults.limit);
			var val2=jQuery(this).html().lastIndexOf(";",defaults.limit);
			var val3=jQuery(this).html().lastIndexOf(":",defaults.limit);		
var endTruncate=Math.max(val0,val1,val2,val3);
			var splitText = jQuery(this).html().substr(endTruncate);
			var hiddenText = '<span style="display:none">'+splitText+'</span>'
			jQuery(this).html($(this).text().substr(0,endTruncate)).append('&nbsp;<span>&#8230;<span/>'+hiddenText);
			/*var splitText = $(this).html().substr(defaults.limit);
			var hiddenText = '<span style="display:none">'+splitText+'</span>'
			$(this).html($(this).text().substr(0,defaults.limit)).append('<span>&#8230;<span/>'+hiddenText);
			*/
		}
	});
};


jQuery(document).ready(function (){
		/* menu utente registrato*/
		jQuery('#h_log').click(function () {jQuery('#h_mnu').slideToggle("slow");jQuery('#h_log').toggleClass('on');return false;});
		jQuery("#h_mnu li:last").css('border-bottom','none');
		jQuery("#h_mnu li:first").css('border-top','none');
		/*footer*/
		jQuery('#footer dl:last').css('margin-right','0');
		jQuery('#f_wtv dl dd:gt(6)').css('width','280px');
		//gestione grafica voto attivo
		/*if (jQuery('DIV').is('.rating')) {
			var pos = jQuery('.rating .voto').css('backgroundPosition'); //posizione in cui e' il bkg
			var votato = false;
			jQuery('.voto LI A').mouseover(function(){
				var ulbg = jQuery(this).parent().parent(); //UL in cui cambiare il background
				var lk = jQuery(this); //link
				grafVoto(lk,ulbg);
			}).mouseout(function(){
				var ulbg = jQuery(this).parent().parent(); //UL in cui cambiare il background
				ulbg.attr('style','background-position:'+pos+';');
			}).click(function(){
				var ulbg = jQuery(this).parent().parent(); //UL in cui cambiare il background
				var lk = jQuery(this); //link
				grafVoto(lk,ulbg);
				if (votato===false) {
					jQuery('.rating .info01').html('Grazie per aver votato');
					votato = true;
				} else {
					jQuery('.rating .info01').html('<b>Hai gi&agrave; votato</b>');
				}
			});
		} */
		
		if (jQuery('DIV').is('.rating')) {
			var pos = jQuery('.rating .voto').css('backgroundPosition'); //posizione in cui e' il bkg
			
			jQuery('.voto LI A').mouseover(function(){
				var ulbg = jQuery(this).parent().parent(); //UL in cui cambiare il background
				var lk = jQuery(this); //link
				grafVoto(lk,ulbg);
			}).mouseout(function(){
				var ulbg = jQuery(this).parent().parent(); //UL in cui cambiare il background
				ulbg.attr('style','background-position:'+pos+';');
			}).click(function(){
				var ulbg = jQuery(this).parent().parent(); //UL in cui cambiare il background
				var lk = jQuery(this); //link
				grafVoto(lk,ulbg);
				
				var boxInfo = $(this).parent().parent().parent().children(".info01");
				if (boxInfo.html() != 'Grazie per aver votato' &&
              boxInfo.html() != '<b>Hai gi&agrave; votato</b>') {
				  boxInfo.html('Grazie per aver votato');
				} else {
					boxInfo.html('<b>Hai gi&agrave; votato</b>');
				}
			});
		}
        
  /*jQuery(function() {
		var zIndexNumber = 1000;
		jQuery('div').each(function() {
			jQuery(this).css('zIndex', zIndexNumber);
			zIndexNumber -= 10;
		});
	});*/ 
	
	//gestione msg overlay
	if (jQuery('A').is('.aol1')) {
		jQuery('.aol1').colorbox({transition:'none',title:true,initialWidth:'0',initialHeight:'0'});
	}
	//gestione msg overlay LOGIN
	if (jQuery('A').is('.ax1')) {
		jQuery(".ax1").colorbox({transition:'none',title:true,initialWidth:'0',initialHeight:'0'});
	}
	
	//chiusura footer federato//
	var ftf = '';
	jQuery('.ti-tab a').click(function(){
		jQuery('.ti-collapsable ul').slideToggle();
		if(ftf == ''){
		$(this).html('Aprire');
		$(this).addClass('ti-closed');
		ftf = 'chiuso';
		}else {
			jQuery(this).html('Chiudere');
			jQuery(this).removeClass('ti-closed');
			ftf = '';
		}
		return false;	
	});
});

	//equlizza colonne
	function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
	}
	
	//fx grafica voto
	function grafVoto(lk,ulbg) {
		if (lk.is('.lk01')) {
			ulbg.attr('style','background-position:-166px -125px;');
		} 
		if (lk.is('.lk02')) {
			ulbg.attr('style','background-position:-166px -136px;');
		}
		if (lk.is('.lk03')) {
			ulbg.attr('style','background-position:-166px -147px;');
		}
		if (lk.is('.lk04')) {
			ulbg.attr('style','background-position:-166px -158px;');
		}
		if (lk.is('.lk05')) {
			ulbg.attr('style','background-position:-166px -169px;');
		}
	}

function showParentalControl(){
	if (isParentalControl()) {
	 jQuery('#h_pr_cntrl').addClass('pct_on');
	 jQuery('#statuspc').html("ON");
	} else {
   jQuery('#h_pr_cntrl').removeClass('pct_on');
   jQuery('#statuspc').html("OFF");
  }	
}
	
function headerLogin(){
	if (isLogged()){
	  var nick = getCookie('nick');
	  
 		jQuery("#head_utn_log").show();
 		jQuery("#head_utn_nlog").hide();
 		jQuery('.logName').html("Benvenuto " + nick);
 		jQuery('.logName').show();
 	} else {
 	  var urlReg = "http://registrazioni.alice.it/cubo/registra/form.do?entryPoint=cubo&urlRitorno=";
			  urlReg += encodeURIComponent("https://buy.cubovision.it/registration/createprofile?urlRegOk=http://"+getBaseUrl()+"&urlRegKo=http://"+getBaseUrl());
 	  
    jQuery('.logName').hide();
 		jQuery("#head_utn_nlog").show();//attr('style','visibility:inline');
 		jQuery("#head_utn_log").hide();
 		jQuery('#h_reg').attr('href',urlReg);
 	}
 	
 	if (isLogged()){
  	loadHeaderMessagesCount();
	}
	showParentalControl();
}

function loadHeaderMessagesCount() { //aggiorna i messaggi e richiama showPrivateMessage
  var url = "http://comment.cubovision.it/json_pm.php";
  callJson(url);
}
function showPrivateMessage(response){
	 var headMsgCount = document.getElementById("headMsgCount").value;
	 if (headMsgCount != null && headMsgCount != undefined)
  		jQuery('#headMsgCount').html(response.inbox);
}

//Paginazione galleri
var pag_counter = 1;
	function numeri(selec,chi,container){
			var MMX = $(selec).length -1;
			$(selec).removeClass('on');
			$(selec).eq(chi).addClass('on');
			pag_counter = $(selec).eq(chi).text();
			if(pag_counter == 1 ){
				$(''+container+' .gal_left').css('display','none');
			}else {
				$(''+container+' .gal_left').css('display','block');
			}
			if( pag_counter >MMX ){
				$(''+container+' .gal_right').css('display','none');
			}else{
				$(''+container+' .gal_right').css('display','block');
			}
}

	function precedente(selec,container){
		$(selec).removeClass('on');
		$(selec).eq(pag_counter - 2).addClass('on');
		$(''+container+' .gal_right').css('display','block');
			if(pag_counter == 2){
				$(''+container+' .gal_left').css('display','none');
			}else{
				$(''+container+' .gal_left').css('display','block');
			}
		pag_counter--
}

	function successiva(selec,container){
		var MMX = $(selec).length -1;
		$(selec).removeClass('on');
		$(selec).eq(pag_counter).addClass('on')
		$(''+container+' .gal_left').css('display','block');
		if(pag_counter == MMX){
			$(''+container+' .gal_right').css('display','none');
		}else{
			$(''+container+' .gal_right').css('display','block');
		}
		pag_counter++
}

function isParentalControl(){
	 return isCookiePresent("CubovisionFF3");
}

function isValidParentalProcess(){
	 return isCookiePresent("CubovisionFF1");
}
function isValidParentalUser(){
	 return isCookiePresent("CubovisionFF");
}

function isLogged() {
  return isCookiePresent("authen");
}

function getBaseUrl() {
  var baseurl; 
  var txt=document.URL;//'http://blog.cubovision.it/pippo.html?jsdhgf=asjkdhg';

  var re1='.*?';	// Non-greedy match on filler
  var re2='((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])';	// Fully Qualified Domain Name 1

  var p = new RegExp(re1+re2,["i"]);
  var m = p.exec(txt);
  if (m !== null)
  {
      var tempbaseurl=m[1];
      baseurl = tempbaseurl.replace(/</,"&lt;");
  }
  
  return baseurl;
}

function inPageLogin() {
  var baseurl = getBaseUrl();

  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  
  if (username.indexOf('@') == -1) {
    username += "@alice.it";
  }
  
  var url = "https://aaacsc.alice.it/piattaformaAAA/aapm/amI";
  url += "?a3l=" + encodeURIComponent(username) + "&a3p=" + encodeURIComponent(password)+"&channel=1&totop=false&nototopa3ep=true";
  url += "&a3ep="+encodeURIComponent("https://aaacsc.alice.it/idema/aapm/Forward?serviceid=cubo&channel=1&urlOk=http://"+baseurl+"/logOk.html&urlKo=http://"+baseurl+"/logKo.html&isAjax=1");
  url += "&a3afep="+encodeURIComponent("https://aaacsc.alice.it/idema/aapm/Forward?serviceid=cubo&urlKo=http://"+baseurl+"/logKo.html&urlOk=http://"+baseurl+"/logOk.html&channel=1&isAjax=1");
  
  var theIframe = document.createElement("iframe");
  theIframe.style.visibility = "hidden";
  theIframe.setAttribute('id', 'asynchIF');
  document.body.appendChild(theIframe);
  
  theIframe.src = url;
}

function loginOk() {
  jQuery.fn.colorbox.close();
  var theIframe = document.getElementById("asynchIF");
  document.body.removeChild(theIframe);
  jQuery("#head_utn_nlog").hide();
  //$("#head_utn_log").show();
  headerLogin();
}

function loginKo() {
  var theIframe = document.getElementById("asynchIF");
  document.body.removeChild(theIframe);
  
  //alert("Login Ko");
  jQuery(".alert").show();
  jQuery("#head_utn_nlog").show();
  jQuery("#head_utn_log").hide();
}


function viewLogin() {
//alert("common view login");
  var urlLogin="/common/alert/template_Wlogin.html";
  var urlReg = "http://registrazioni.alice.it/cubo/registra/form.do?entryPoint=cubo&urlRitorno=";
			urlReg += encodeURIComponent("https://buy.cubovision.it/registration/createprofile?urlRegOk=http://"+getBaseUrl()+"&urlRegKo=http://"+getBaseUrl());

	jQuery.fn.colorbox({href:""+urlLogin});
	jQuery(document).bind('cbox_complete', function(){
	  jQuery(".alert").hide();
	  jQuery("#reglink").attr("href", urlReg);
	  jQuery('#lostpwdlink').attr('href', "http://gest.virgilio.it/ryalp/lostpassword");
	});
}

function checkLogin() {
    if (!isLogged()){
        viewLogin();
        return false;
    }
    return true;
}

//array contenente le richieste JSON da stoppare
var arrayBlockCall = new Array();

function callJson(request,callBack) {

        if(arrayBlockCall[request]!='STOP'){
          arrayBlockCall[request] = 'STOP';
          setTimeout(function(){arrayBlockCall[request]=null;}, 250);
          
          if(request.indexOf("?")==-1){
               request += "?";
          }else{
              request += "&";
          }
  	    	request = request + "OUTPUT=json"; 
  	    	request = request + "&view=json"; 
  	    	request = request + "&CALLBACK="+callBack;
  	    	request = request + "&callback="+callBack;
  	    	
  				aObj = new JSONscriptRequest(request);
  				aObj.buildScriptTag();
  		 		aObj.addScriptTag();
		 		}
}

function getLinkAllCat(categorizationCubo){
		var link_array = new Array();
		var link=categorizationCubo;
		link=link.toLowerCase();
		link=link.replace(/ /g,"_");		
		link_array=link.split(";");		
		link=link_array[0]+"/"+link_array[1] +"/"; 				
		return link;
}	

function getLinkAllVodByCat(categorizationCubo){
		var link_array = new Array();
		var link=categorizationCubo;
		link=link.toLowerCase();
		link=link.replace(/ /g,"_");		
		link_array=link.split(";");		
		link=link_array[0]+"/"+link_array[1] +"/"+link_array[2]+"/";				
		return link;
}

function getLinkVod(categorizationCubo){
		var link_array = new Array();
		var link=categorizationCubo;
		link=link.toLowerCase();
		link=link.replace(/ /g,"_");		
		link_array=link.split(";");		
		link=link_array[0]+"/"+link_array[1] +"/"+link_array[2]+"/"+getCntId()+".html";				
		return link;
}

  
	function getCntAssetid(){
	  return _contentBean.assetId;
	}
  
	function getCntId(){
		var cntid = _contentBean.contentId;
		if(cntid == 0){
			cntid = getContentIdFromUrl();
		}
		return cntid;
	}

	function getContentIdFromUrl(){
		try{
			var sPath = window.location.pathname;
			var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
			var sContentId = sPage.substring(0, sPage.indexOf('.'));

			return sContentId;
		}catch(e){
			return "";
		}
	}
	function getCntType(){
			var contentType = null;
			if(_contentBean.contentType == undefined){
           contentType = 'VOD';
      }else{
           contentType = _contentBean.contentType;
      }
			return contentType;
	}
	
	function getCntTitle(){
	  return _contentBean.title;
	}
  
	function getCntDescription(){
		_contentBean.longDescription;
	}
  
	function getCntLink(){
		//return "http://www.google.it";
		return getHrefContenuto(_contentBean);
	}
	
	function getCntVideoFileUrl(){
		return _contentBean.videoFileUrl;
	}
	
	function getCntTrailerFileUrl(){
		return _contentBean.trailerFileUrl;
	}
	
	function getCntTrailerDuration(){
		return _contentBean.trailerDuration;
	}
	
	function getCntDuration(){
		return _contentBean.duration;
	}
	
	function getCntImg(){
		return _contentBean.imageFilePath;
	}
	
	function getCntCat(){
		return _contentBean.categorization;
	}
  
	function getCntCategorizationCubo(){
		return _contentBean.categorizationra;
	}
	
	function getCntProviderName(){
		return _contentBean.providerName;
	}
	
 //funzione che torna i minuti a partire dai secondi
	function getMinutesBySeconds(time){

		time=parseInt(time);
		var minute = time / 60;
		var hour = 0;
		var k = 60;
		var str = "";
		if(minute > 0){
				str= Math.round(minute)+" min";

		}else{ 
			str=time+" sec";

		}
	return str;
}

function printStatistic(num){
	if (num == null || num == undefined || num == 0){
		return 'Mai';
	}
	if (num == 1){
		return '1 volta';
	}
	else{
		return num+' volte';
	}
}

function trunkDate(date){
	var dataF=date.substring(8,10)+"-"+date.substring(5,7)+"-"+date.substring(0,4);
	return dataF;
}
	
function formatSeconds(seconds){
	var minTotali = Math.floor(seconds / 60);
	var s = seconds % 60;
	var h = Math.floor(minTotali / 60);
	var m = minTotali % 60; 
	return h+"h "+m+"m "+s+"s";
}
  
  
 function getNavigator(categorization) {
   return categorization; 
 }
 
 function splitCategorization(categorizationCubo){
/*
il categorizationCubo contiene site;subsite;sezione
la funzione restituisce un oggetto json con lo split del categorizationracubo in subsite e sezione, ('genr' di default se mancano subsite o sezione)
*/	
	var cat_array = new Array();
	var cat=categorizationCubo;
	var subsite='';
	var sezione='';
	cat=cat.toLowerCase();
	cat=cat.replace(/ /g,"_");		
	cat_array=cat.split(";");	
	
	if (cat_array[1]==undefined)
		subsite = 'genr';
	else
		subsite =  cat_array[1];
		
	if (cat_array[2]==undefined)
		sezione = 'genr';
	else
		sezione =  cat_array[2];
		
	var path = { 
						"subsite":subsite, 
						"sezione":sezione 	
			};				
	return path;
	

 }
 
 function loadVideo() {
 	var streamingServer="";
 		if (videoTv){
 			streamingServer='rtmpt://yalplive.alice.cdn.interbusiness.it:80/live/';
 		} else {
			streamingServer="rtmpt://yalpvod.alice.cdn.interbusiness.it/vod/";
		}
	
	var path = getPathName();
	var applicazione = path[1];
	
	var path = splitCategorization(getCntCategorizationCubo());
	
	var subsite = path.subsite;
	
	//var sezione = path.sezione;
	var sezione = "genr";
	var cp = getCntProviderName();
	cp = "noprovider";
	
	
		if(applicazione == 'contenutipay'){
			playVideo(getCntTrailerFileUrl(), 'true', streamingServer, getCntTrailerDuration(),'0','0','0','0');
		}else{		
			//playVideo(getCntVideoFileUrl(), 'true', streamingServer, getCntDuration(),'0','0','0','0');
			playVideo(getCntVideoFileUrl(), 'true', streamingServer, getCntDuration(),subsite,sezione,cp,'898');
		}
		
 }
 
 
 var loadHtmlScheda=false;
 function loadScheda() {
		//alert("loadScheda _contentBean.contentId "+_contentBean.contentId);
 		/*if(_contentBean.contentId==0){
 			loadHtmlScheda=true;
 		}
		*/
 		//TODO getCntId
		//alert("loadScheda "+getCntId());
		enabledComment=true;
 		doCall_GetData(getCntId(), "viewVoteResponse");

		//doCall_GetData(getCntId(), "caricaValori","getValueScheda()");
 }
 
  function loadSchedaFruizione() {
		//alert("loadScheda _contentBean.contentId "+_contentBean.contentId);
 		/*if(_contentBean.contentId==0){
 			loadHtmlScheda=true;
 		}
		*/
 		//TODO getCntId
		//alert("loadScheda "+getCntId());
		enabledComment=true;
 		doCall_GetData(getCntId(), "setSchedaContentFruizione");

		//doCall_GetData(getCntId(), "caricaValori","getValueScheda()");
 }

function setSchedaContentFruizione(contentBean){
	
		//Gestisco categoria != null, ma  = object
		var categoria = contentBean.categorization;
		try{
			if(categoria.toString()=='[object Object]'){
				categoria = " ";
			}
		}catch(ex){
			categoria = " ";
		}	
		document.getElementById("id_categorization").innerHTML=categoria;
		//
		document.getElementById("id_title1").innerHTML='<img src="http://images.cubovision.it/'+contentBean.imageFilePath+'"/> '+ contentBean.title;
		document.getElementById("id_title2").innerHTML=contentBean.title;
		document.getElementById("id_provider").innerHTML='da '+contentBean.providerName;
		document.getElementById("id_longdescription").innerHTML=contentBean.longDescription;
		document.getElementById("id_aggiunto").innerHTML=trunkDate(contentBean.startDate);
		document.getElementById("id_durata").innerHTML=getMinutesBySeconds(contentBean.duration);
		document.getElementById("id_visto").innerHTML=contentBean.viewCounter;
		document.getElementById("id_commentato").innerHTML=printStatistic(contentBean.commentCounter);
		document.getElementById("id_fonte").innerHTML=contentBean.providerName;
		document.getElementById("id_categoria2").innerHTML=categoria;
		document.getElementById("id_lingua").innerHTML=contentBean.language;
		
		//Gestisco che keywords sia null, e se non lo fosse replico il tag <p>
		var keywords = contentBean.keywords;
		try{
			if(keywords.toString()!='[object Object]'){
				keywords = replaceAll(keywords,"<p>"," ");
				keywords = replaceAll(keywords,"</p>","");
			}else{
				keywords = "";
			}
		}catch(ex){
			keywords = "";
		}	
		
		if(keywords != ""){
			var keys = keywords.split(',');
			var id_key="";
			for(i=0;i<keys.length;i++){
				id_key = id_key+'<li>'+keys[i];+'</li>';			
			}
			document.getElementById("id_key").innerHTML=id_key;
		}else{
			document.getElementById("id_key").innerHTML=keywords;	
		}		
													
		//try{										
																
		//}catch(Exception){}
		
		var path = getPathName();
		var applicazione = path[1];
		var lnk="http://webtv.cubovision.it/"+path[1]+"/"+path[2]+"/"+path[3]+"/aa/"+contentBean.contentId+".html";
		document.getElementById("id_disponibilita").innerHTML='<span>Disponibile fino al </span>'+trunkDate(contentBean.stopDate);						
		
		//Gestisco regia != null, ma  = object
		var regia = contentBean.directorList;
		try{
			if(regia.toString()=='[object Object]'){
				regia = " ";
			}
		}catch(ex){
			regia = " ";
		}	
		
		document.getElementById("id_regia").innerHTML=regia;
		//
		
		//Gestisco actor != null, ma  = object
		var actor = contentBean.actorList;
		try{
			if(actor.toString()!='[object Object]'){
				actor = replaceAll(actor,"<p>"," ");
				actor = replaceAll(actor,"</p>","");
				actor = replaceAll(actor,"#"," ");
			}else{
				actor = "&nbsp;";
			}
		}catch(ex){
			actor = "&nbsp;";
		}	
		
		document.getElementById("id_cast").innerHTML=actor;
		document.getElementById("id_anno").innerHTML=contentBean.year;
		//Gestisco genre != null, ma  = object
		var genre = contentBean.genre;
		try{
			if(genre.toString()=='[object Object]'){
				genre = "&nbsp;";
			}
		}catch(ex){
			genre = "&nbsp;";
		}		
		document.getElementById("id_genre").innerHTML=genre;
		//
		
		/*playVideo(contentBean.videoFileUrl, 'true', 'rtmpt://yalpvod.alice.cdn.interbusiness.it/vod/', contentBean.duration,'0','0','0','0');
		getRatingVoto("vote_"+contentBean.contentId, contentBean.voteTotal,contentBean.voteCountet);
		loadCommenti(getCntId(),0,contentBean.title,contentBean.longDescription,getCntLink());
		*/
		equalHeight($("dl.video_info_ele"));
		_contentBean=contentBean;
				//loadVideo();
				if (enabledComment){
					LivestatsClient.sendView(getCntId());
					loadCommenti(getCntId(),0,getCntTitle(),getCntDescription(),getCntLink());		
				}

			getRatingVoto("vote_"+contentBean.contentId, contentBean.voteTotal,contentBean.voteCounter);
			try {
					document.getElementById("n_voti_scheda").innerHTML="("+contentBean.voteCounter+")";
					document.getElementById("n_mipiace_scheda").innerHTML=contentBean.likeCounter;
					document.getElementById("n_commenti_scheda").innerHTML=contentBean.commentCounter;
			} catch(ex){}	

			params.mediaUrl="http://videotecahttp.alice.cdn.interbusiness.it/DAM"+contentBean.videoFileUrl;
			createSilverlight(params);	
			
	}
	 
	function viewVoteResponse(contentBean){
			
		if (_contentBean.contentId==0){
			//alert("viewVoteResponse: "+contentBean);
			setSchedaContent(contentBean);
		}
			var videoFileUrl;
			if (videoTv){
				contentBean.videoFileUrl=_contentBean.videoFileUrl
				//alert(_contentBean.videoFileUrl);
			}
		_contentBean=contentBean;
		if(contentBean.videoFileFormat != 'wmv'){
		loadVideo();
		}
			
			if (enabledComment){
				LivestatsClient.sendView(getCntId());
				loadCommenti(getCntId(),0,getCntTitle(),getCntDescription(),getCntLink());		
			}

		getRatingVoto("vote_"+contentBean.contentId, contentBean.voteTotal,contentBean.voteCounter);
		try {
				document.getElementById("n_voti_scheda").innerHTML="("+contentBean.voteCounter+")";
				document.getElementById("n_mipiace_scheda").innerHTML=contentBean.likeCounter;
				//document.getElementById("n_commenti_scheda").innerHTML=contentBean.commentCounter;
		} catch(ex){}
}

function getPathName() {
	var url = window.location;
	var urlparts = url.pathname.split('/');
	return urlparts;
	//alert(urlparts[1] +url.pathname);
	//var host = url.host;
	//alert(host);
}


function setSchedaContent(contentBean){
	
	//Gestisco categoria != null, ma  = object
	var categoria = contentBean.categorization;
	try{
		if(categoria.toString()=='[object Object]'){
			categoria = "&nbsp;";
		}
	}catch(ex){
		categoria = "&nbsp;";
	}	
	document.getElementById("id_categorization").innerHTML=categoria;
	//
	
	document.getElementById("id_title2").innerHTML=contentBean.title;
	document.getElementById("id_provider").innerHTML='da '+contentBean.providerName;
	document.getElementById("id_longdescription").innerHTML=contentBean.longDescription;
	document.getElementById("id_aggiunto").innerHTML=trunkDate(contentBean.startDate);
	document.getElementById("id_durata").innerHTML=getMinutesBySeconds(contentBean.duration);
	document.getElementById("id_visto").innerHTML=contentBean.viewCounter;
	document.getElementById("id_commentato").innerHTML=printStatistic(contentBean.commentCounter);
	document.getElementById("id_fonte").innerHTML=contentBean.providerName;
	document.getElementById("id_categoria2").innerHTML=categoria;
	document.getElementById("id_lingua").innerHTML=contentBean.language;
	
	//Gestisco che keywords sia null, e se non lo fosse replico il tag <p>
	var keywords = contentBean.keywords;
	try{
		if(keywords.toString()!='[object Object]'){
			keywords = replaceAll(keywords,"<p>"," ");
			keywords = replaceAll(keywords,"</p>","");
		}else{
			keywords = "&nbsp;";
		}
	}catch(ex){
		keywords = "&nbsp;";
	}	
	
	if(keywords != ""){
		var keys = keywords.split(',');
		var id_key="";
		for(i=0;i<keys.length;i++){
			id_key = id_key+'<li>'+keys[i];+'</li>';			
		}
		document.getElementById("id_key").innerHTML=id_key;
	}else{
		document.getElementById("id_key").innerHTML=keywords;	
	}		
	//try{										
													
	//}catch(Exception){}
	
	var path = getPathName();
	var applicazione = path[1];
	//alert(applicazione);
	document.getElementById("id_title1").innerHTML='<img src="http://images.cubovision.it/'+contentBean.imageFilePath+'"/> '+ contentBean.title;
	
	if(applicazione == 'contenutipay'){
	
		var lnk="";
		if (path[3]==""){
			lnk="http://webtv.cubovision.it/"+path[1]+"/"+path[2]+"/aa/"+contentBean.contentId+".html";
		} else {
			lnk="http://webtv.cubovision.it/"+path[1]+"/"+path[2]+"/"+path[3]+"/aa/"+contentBean.contentId+".html";
		}
		var fornitore_stat = '<a href="#" title="Nome Utente">';
		fornitore_stat = fornitore_stat + '<span class="foto"></span><img src="http://images.yalp.alice.it/'+contentBean.imageFilePath+'"/>';
		fornitore_stat = fornitore_stat + '<span>'+contentBean.major+'</script></a> <span>'+contentBean.categorization+'</span>';
		fornitore_stat = fornitore_stat + '<a href="#" title="www.urlcanale.com" class="urlc"></a> <p>Scritta Scritta Scritta Scritta Scritta</p>';
		fornitore_stat = fornitore_stat + '<div class="isc"><a href="'+lnk+'" class="pulsante" title="Compra"><span>Compra</span></a><strong>&euro; '+Math.abs(contentBean.defaultPrice)+'</strong> PAY PER VIEW</div>'; 
		
		//document.getElementById("fornitore_stat").innerHTML=fornitore_stat;
		document.getElementById("id_disponibilita").innerHTML='<span>Disponibile fino al </span>'+trunkDate(contentBean.stopDate);						
		document.getElementById("id_video_prezzo").innerHTML='&euro; '+Math.abs(contentBean.defaultPrice)+'<b>PAY PER VIEW</b><a href="'+lnk+'" class="pulsante" title="Compra"><span>Compra</span></a>';

		//Gestisco actor != null, ma  = object
		var actor = contentBean.actorList;
		try{
			if(actor.toString()!='[object Object]'){
				actor = replaceAll(actor,"<p>"," ");
				actor = replaceAll(actor,"</p>","");
				actor = replaceAll(actor,"#"," ");
			}else{
				actor = "&nbsp;";
			}
		}catch(ex){
			actor = "&nbsp;";
		}	
		
		//Gestisco regia != null, ma  = object
		var regia = contentBean.directorList;
		try{
			if(regia.toString()=='[object Object]'){
				regia = " ";
			}
		}catch(ex){
			regia = " ";
		}		
	
		document.getElementById("id_regia").innerHTML=regia;
		//

		document.getElementById("id_cast").innerHTML=actor;
		document.getElementById("id_anno").innerHTML=contentBean.year;
		//Gestisco genre != null, ma  = object
		var genre = contentBean.genre;
		try{
			if(genre.toString()=='[object Object]'){
				genre = "&nbsp;";
			}
		}catch(ex){
			genre = "&nbsp;";
		}		
		document.getElementById("id_genre").innerHTML=genre;
		//
		
		//var plugin = document.getElementById("pluginSL");
		//alert("http://videotecahttp.cdn.interbusiness.alice.it/DAM"+contentBean.videoFileUrl);
		//plugin.Content.slObject.SetVideo("http://videotecahttp.alice.cdn.interbusiness.it/DAM"+contentBean.trailerFileUrl, 'aa');
		//alert("http://videotecahttp.cdn.interbusiness.alice.it/DAM"+contentBean.videoFileUrl);
		//params.mediaUrl="http://yalpvod.alice.cdn.interbusiness.it/vod/"+contentBean.trailerFileUrl;
		params.mediaUrl="http://videotecahttp.alice.cdn.interbusiness.it/DAM"+contentBean.trailerFileUrl;
		//params.mediaUrl="http://videotecahttp.alice.cdn.interbusiness.it/DAM"+contentBean.videoFileUrl;
		//alert("ok "+params.mediaUrl);
		//params.mediaUrl="http://videotecahttp.alice.cdn.interbusiness.it/DAM/Film/2010/07/RA3_TSTREAM_50183946.wmv";
		//alert("ok "+params.mediaUrl);
		createSilverlight(params);
		//alert("ok "+params.mediaUrl);
		equalHeight($("dl.video_info_ele"));		
	}else{
		/*
		document.getElementById("id_title1").innerHTML=contentBean.title;
		var id_utente_stat = 	'<a href="#" onclick=javascript:document.location.href="http://webtv.cubovision.it/'+getLinkVod(contentBean.categorizationra)+'" title="Nome Utente">';
			id_utente_stat = id_utente_stat + '<span class="foto"></span><img src="http://images.yalp.alice.it/'+contentBean.imageFilePath+'"/>';
			id_utente_stat = id_utente_stat + '<span>'+contentBean.title+'</script></a><span>'+contentBean.categorization+'</span>';
			id_utente_stat = id_utente_stat + '<a href="#" title="www.urlcanale.com" class="urlc"></a> <p></p>';
			id_utente_stat = id_utente_stat + '<div class="isc"><a href="#" class="pulsante" title="Iscriviti"><span>Iscriviti</span></a><strong>1234567 Iscritti</strong></div>'; 
			document.getElementById("utente_stat").innerHTML=id_utente_stat;						
			*/
	}
	
	/*playVideo(contentBean.videoFileUrl, 'true', 'rtmpt://yalpvod.alice.cdn.interbusiness.it/vod/', contentBean.duration,'0','0','0','0');
	getRatingVoto("vote_"+contentBean.contentId, contentBean.voteTotal,contentBean.voteCountet);
	loadCommenti(getCntId(),0,contentBean.title,contentBean.longDescription,getCntLink());
	*/
	equalHeight($("dl.video_info_ele"));
}

function loadSchedaTV() {
		//alert(getCntVideoFileUrl());
		//playVideo(getCntVideoFileUrl(), 'true', 'rtmpt://yalplive.alice.cdn.interbusiness.it:80/live/', '0','0','0','0','0');
		videoTv=true;
		loadVideoHP();
		if (_contentBean.enabledComment){
			loadCommenti(getCntId(),0,getCntTitle(),getCntDescription(),getCntLink());
		}
 }
 
 function loadVideoHP() {
		loadVideo();
		doCall_GetData(getCntId(), "viewVoteResponse",getCntId());
 }
 
var fullPlaylist;
function loadVideoHPCommunity() {
		try{
			var lenCnt=cntCommunity.length;
			//alert(cntCommunity);
			for (var iCnt = 0; iCnt < lenCnt; iCnt++){
				if (iCnt==0){
					doCall_GetData(cntCommunity[iCnt], "viewCommunityResponse");
				} else {
					doCall_GetData(cntCommunity[iCnt], "viewCommunityResponseThumb");
				}
			}
		} catch(ex){}
		//loadVideo();
		//doCall_GetData(getCntId(), "viewVoteResponse",getCntId());
 }
 
function viewCommunityResponseThumb(contentBean) {
	document.getElementById("titolo_"+contentBean.contentId).innerHTML=contentBean.title;
	document.getElementById("categoria_"+contentBean.contentId).innerHTML=contentBean.categorization;
	document.getElementById("img_"+contentBean.contentId).src="http://images.yalp.alice.it"+contentBean.imageFilePath;
	getRatingVoto("vote_"+contentBean.contentId, contentBean.voteTotal,contentBean.voteCountet);
	//if (fullPlaylist){
 	//	
 	//}
}

function viewCommunityResponse(contentBean){
 	document.getElementById("titolo_"+contentBean.contentId).innerHTML=contentBean.title;
 	try {
 		document.getElementById("descrizione_"+contentBean.contentId).innerHTML=contentBean.longDescription;
		$('#descrizione_'+contentBean.contentId).truncatitle({limit:90});
 	} catch(ex){}
 	//document.getElementById("n_mipiace_"+contentBean.contentId).innerHTML=contentBean.likeCounter;
 	document.getElementById("n_mipiace_scheda").innerHTML=contentBean.likeCounter;
 	//document.getElementById("n_voti_"+contentBean.contentId).innerHTML="(" +contentBean.voteTotal +")";
 	document.getElementById("n_voti_scheda").innerHTML="(" +contentBean.voteCounter +")";
 	getRatingVoto("vote_"+contentBean.contentId, contentBean.voteTotal,contentBean.voteCountet);

 	playVideo(contentBean.videoFileUrl, 'true', 'rtmpt://yalpvod.alice.cdn.interbusiness.it/vod/', contentBean.duration,'0','0','0','0');
 	if (fullPlaylist){
		 document.getElementById("duration").innerHTML=getMinutesBySeconds(contentBean.duration);
		 document.getElementById("viewCounter").innerHTML=contentBean.viewCounter;
		 document.getElementById("commentCounter").innerHTML=contentBean.commentCounter;
		 document.getElementById("categorization").innerHTML=contentBean.categorization;
		 document.getElementById("providerName").innerHTML=contentBean.providerName;
		 document.getElementById("keywords").innerHTML=contentBean.keywords;
		 document.getElementById("language").innerHTML=contentBean.language;
		 document.getElementById("startDate").innerHTML=trunkDate(contentBean.startDate);
		 document.getElementById("img_"+contentBean.contentId).src="http://images.yalp.alice.it"+contentBean.imageFilePath;
		 document.getElementById("categoria_"+contentBean.contentId).innerHTML=contentBean.categorization;
		 document.getElementById("titolo").innerHTML=contentBean.title;
 	} else {
 		document.getElementById("comment_"+contentBean.contentId).innerHTML="("+contentBean.commentCounter+")";
 	}
}

function loadVideoContenuto(){
    for(var i=0; i<cntCommunity.length; i++){
        var contentId = cntCommunity[i];
        doCall_GetData(contentId, "viewVideoContenuto");
    }
}

function viewVideoContenuto(contentBean){
     $("#titolo_"+contentBean.contentId).each(function(){  
          $(this).html(contentBean.title);
     });
     
     $("#duration_"+contentBean.contentId).each(function(){  
          $(this).html(formatOra(contentBean.duration));
     });
     
     $("#lastmodtime_"+contentBean.contentId).each(function(){  
          $(this).html(formatDate(contentBean.lastModTime));
     });
     
     $("#img_src_"+contentBean.contentId+" img").each(function(){
          $(this).attr("src","http://images.cubovision.it"+contentBean.imageFilePath); 
          $(this).attr("alt",contentBean.title); 
     });
     
     $("#img_src_"+contentBean.contentId+" > a").each(function(){ 
          //$(this).attr("href","http://webtv.cubovision.it/video/informazione/news/"+contentBean.contentId+".html");
          var href = getHrefContenuto(contentBean);
          $(this).attr("href",href);
     });
     
     $("#voto_"+contentBean.contentId).each(function(){ 
          getRatingVoto("voto_"+contentBean.contentId,contentBean.voteTotal,contentBean.voteCounter);
     });
     
    
     $("#titolo_sort_"+contentBean.contentId).each(function(){  
          $(this).val(contentBean.title);
     });
     
     $("#duration_sort_"+contentBean.contentId).each(function(){  
          var duration = contentBean.duration;
          while(duration.length<6){
              duration = "0"+duration;
          }
          $(this).val(duration);
     });
     
     $("#lastmodtime_sort_"+contentBean.contentId).each(function(){  
          $(this).val(contentBean.lastModTime);
     });
     
     $("#href_"+contentBean.contentId).each(function(){ 
          var href = getHrefContenuto(contentBean);
          $(this).attr("href",href);                                       
     });
     
     $("#da_"+contentBean.contentId).each(function(){  
     
          var index = contentBean.categorizationra.lastIndexOf(";");   
          var tempCategorizationra = contentBean.categorizationra.substring(0,index -1);
          
          index = tempCategorizationra.lastIndexOf(";"); 
          //alert(tempCategorizationra.substring(index +1)); 
          $(this).html("da "+tempCategorizationra.substring(index +1));
     });
     
     $(".categoria_"+contentBean.contentId).each(function(){ 
          var index = contentBean.categorizationra.lastIndexOf(";");   
          var tempCategorizationra = contentBean.categorizationra.substring(0,index -1);
          
          index = tempCategorizationra.lastIndexOf(";"); 
          //alert(tempCategorizationra.substring(index +1)); 
          $(this).html(tempCategorizationra.substring(index +1));
     });
     
}

///////////////////////////////////////////////////////
//chiamata da BUY per recuperare l'href dei contenuti 
//a partire da una stringa di ricerca sulla search
function urlByRicercaCnt(ricerca, idNode, isAcquistato){
     doCall_GetRicercaData(ricerca,"cbUrlByRicercaCnt",idNode,isAcquistato);
}

function cbUrlByRicercaCnt(contentBean,idNode,isAcquistato){
     var responseContentBean = setContentBean(contentBean); 
     
     if(responseContentBean.categorizationra == ""){
          
          $("."+idNode).each(function(){
               var insideText = $(this).html();
               $(this).replaceWith(insideText);
               //var parentNode = $(this).parent();
               //parentNode.html(insideText);
          });
          
     }else{
          var href = getHrefContenuto(responseContentBean,isAcquistato);
          $("."+idNode).attr("href",href);
     }
}
///////////////////////////////////////////////////////
function srcByRicercaCnt(ricerca, idNode){
     doCall_GetRicercaData(ricerca,"cbSrcByRicercaCnt",idNode);
}

function cbSrcByRicercaCnt(contentBean,idNode){
     var responseContentBean = setContentBean(contentBean); 
     var src = "http://images.cubovision.it"+responseContentBean.imageFilePath;

     $("#"+idNode).attr("src",src);
     
     //var href = getHrefContenuto(responseContentBean);
     //$("#"+idNode).parent().attr("href",href);
}
///////////////////////////////////////////////////////

function getHrefContenuto(contentBean,isAcquistato){
    var href = "http://webtv.cubovision.it/" 
          
    var hrefDirArray = contentBean.categorizationra.split(";", 3);
    
    var hrefDir = ""; 
    for(var i=0; i<hrefDirArray.length; i++){
          hrefDir += hrefDirArray[i]+"/";
    }
    
    hrefDir = hrefDir.replace(/ /g,"_");  
    
    if(hrefDir.indexOf("hannahmontana") != -1){
        hrefDir = "/hannahmontana/aa/";
    }else if(hrefDir.indexOf("videopay") != -1){
        hrefDir = hrefDir.replace("videopay", "contenutipay");
        hrefDir += "scheda/";
    }else{
        hrefDir += "scheda/";
    }
    
    if(isAcquistato != undefined){
       if(isAcquistato.toLowerCase() == "true"){
			hrefDir = hrefDir.replace("scheda", "aa");
		}
    }
	
    href += hrefDir+contentBean.contentId+".html";
    
    href = href.toLowerCase();

    return href;
}
 
var mapMesi = new Array();
mapMesi["01"] = "Gennaio";
mapMesi["02"] = "Febbraio";
mapMesi["03"] = "Marzo";
mapMesi["04"] = "Aprile";
mapMesi["05"] = "Maggio";
mapMesi["06"] = "Giugno";
mapMesi["07"] = "Luglio";
mapMesi["08"] = "Agosto";
mapMesi["09"] = "Settembre";
mapMesi["10"] = "Ottobre";
mapMesi["11"] = "Novembre";
mapMesi["12"] = "Dicembre";

function formatOra(stringOra){
    var ore = Math.floor(stringOra/60);      
    var minuti = stringOra%60;
    if(minuti < 10){
        minuti = "0"+minuti;
    }
    return ore+":"+minuti+" min";
}

function formatDate(stringDate){
    var anno =  stringDate.substr(0 , 4);
    var mese = stringDate.substr(5 , 2);
    var giorno = stringDate.substr(8 , 2);
      
    return giorno+" "+mapMesi[mese]+" "+anno;
}  

function getEventInfo(epgTV) {
            var plugin = document.getElementById("plugin");
            var json=eval("(" + epgTV+ ")");
            document.getElementById("titleVideo").innerHTML=json.Title;
            var desc=json.LongDescription;
            document.getElementById("descVideo").innerHTML=desc;
			$('#descVideo').truncatitle({limit:110});
			try {
			 var urlVideo=json.ChannelLink;
            document.getElementById("urlVideo").innerHTML='<a href="'+urlVideo+'" title="Leggi Tutto">(vai al canale)</a>';
            document.getElementById("social_comm").href=urlVideo;
			} catch(ex){}
          
            
}

//=================== CONDIVIDI CONTENUTO ==================//
jQuery(document).ready(function() {
        bindCondividi();
});

function bindCondividi(){
    if ((jQuery.browser.msie)) { //ie
			jQuery('.intCond LABEL').click(function() {
				var lab = jQuery(this);
				var inp = jQuery(this).children('INPUT');
				if(!inp.is(':checked')){
					lab.css('background-position','-504px -55px');
					inp.attr('checked','checked'); //attivazione checkbox
				} else {
					lab.css('background-position','-504px -75px');
					inp.attr('checked',''); //disattivazione checkbox
				}
				     
					condividiContenuto(	jQuery(this).children('INPUT').val());
			});
		} else { //tutti gli altri browser
			jQuery('.intCond LABEL').click(function() {
				var lab = jQuery(this);
				var inp = jQuery(this).children('INPUT').is(':checked');
				if(inp){
					lab.css('background-position','-504px -55px');
				} else {
					lab.css('background-position','-504px -75px');
				}
				    
					condividiContenuto(	jQuery(this).children('INPUT').val());
			});
		}
}
//=========================================================//
jQuery(document).ready(function (){
  jQuery("body").append('<div class="fdbck" style="left:400px;top:340px;display:none;"><span class="f_sx"></span><span class="f_dx"></span></div>');
});
function showFeedback(msg,callback){

jQuery('.fdbck').center();
    jQuery('.fdbck .f_dx').html(msg);
    jQuery('.fdbck').fadeIn(1000);
    
    setTimeout (function(){
         jQuery('.fdbck').fadeOut(1000)
    }, 2500 ); 
    
    if(callback != undefined){
      setTimeout (function(){
           callback();
      }, 3500 );
    }
}
	
jQuery.fn.center = function () {
	    var ELEMwidth = jQuery(this).width();	
	    var ELEMheight = jQuery(this).height();
	    var SCREENwidth = jQuery(document).width();
	    var SCREENheight = jQuery(window).height();	
	    var SCREENscrolltop = jQuery(window).scrollTop();
	    jQuery(this).css({"position":"absolute","left":(SCREENwidth-ELEMwidth)/2+"px","top":(SCREENheight-ELEMheight)/2+SCREENscrolltop+"px"});
}



function loadSchedaHannahMontana() {
		//alert("loadScheda _contentBean.contentId "+_contentBean.contentId);
 		/*if(_contentBean.contentId==0){
 			loadHtmlScheda=true;
 		}
		*/
 		//TODO getCntId
		//alert("loadScheda "+getCntId());
		enabledComment=true;
 		doCall_GetData(getCntId(), "viewVoteResponseHannahMontana");

		//doCall_GetData(getCntId(), "caricaValori","getValueScheda()");
 }
 
 function viewVoteResponseHannahMontana(contentBean){
			
		if (_contentBean.contentId==0){
			//alert("viewVoteResponse: "+contentBean);
			//setSchedaContent(contentBean);ù
			/*
				document.getElementById("id_categorization").innerHTML=categoria;
	//
	
	document.getElementById("id_title2").innerHTML=contentBean.title;
	document.getElementById("id_provider").innerHTML='da '+contentBean.providerName;
	document.getElementById("id_longdescription").innerHTML=contentBean.longDescription;
	document.getElementById("id_aggiunto").innerHTML=trunkDate(contentBean.startDate);
	document.getElementById("id_durata").innerHTML=getMinutesBySeconds(contentBean.duration);
	document.getElementById("id_visto").innerHTML=contentBean.viewCounter;
	document.getElementById("id_commentato").innerHTML=printStatistic(contentBean.commentCounter);
	document.getElementById("id_fonte").innerHTML=contentBean.providerName;
	document.getElementById("id_categoria2").innerHTML=categoria;
	document.getElementById("id_lingua").innerHTML=contentBean.language;
	*/
	document.getElementById("title").innerHTML=contentBean.title;
	document.getElementById("desc").innerHTML=contentBean.longDescription;
	params.mediaUrl="http://videotecahttp.alice.cdn.interbusiness.it/DAM"+contentBean.videoFileUrl;
			createSilverlight(params);	
		}
			var videoFileUrl;
			if (videoTv){
				contentBean.videoFileUrl=_contentBean.videoFileUrl
				//alert(_contentBean.videoFileUrl);
			}
		_contentBean=contentBean;
		if(contentBean.videoFileFormat != 'wmv'){
		//loadVideo();
		}
		
}

function ricerca(t){
	
    var input=document.getElementById(t).value;				

				if(input != ""){				
				input=encodeURIComponent(escape(input));				
				
				window.location.href="http://webtv.cubovision.it/ricerca/ricerca-"+input;
				return input;
				}else{
				  jQuery.fn.colorbox({href:"http://webtv.cubovision.it/common/alert/template_alert.html"});
        	jQuery(document).bind('cbox_complete', function(){
        	  jQuery(".tit").html("<span class=\"ico\"></span> Ricerca");
        	  jQuery(".quest").html("<strong>Ricerca vuota</strong>");
        	  jQuery('.note').html("Inserire una o pi&ugrave; parole da ricercare.");
        	  jQuery('#btOk').click(function(event){
              event.preventDefault();
              jQuery.fn.colorbox.close();
            });
        	});
				return false;
				}
}