
/* Estrae i parametri da una stringa, dalla query o dall'hash dell'url.
 * I parametri devono essere codificati come nella query delle url: nome1=valore1&nome2=valore2
 * Se un parametro non ha valore, nell'array viene impostato come valore true.
 */
function getParams(s) {
	if (s == null) {
		s = document.location.search;
		if (s == null || s == '') {
			s = document.location.hash;
		}
	}
	if (s.match(/^\?/) || s.match(/^#/)) {
		s = s.substring(1);
	}
	var strParams = s.split('&');
	var params = {};
	var i = 0;
	for (i in strParams) {
		var name = strParams[i];
		var value = true;
		var pos = name.indexOf('=');
		if (pos>0) {
			value = decodeURIComponent(name.substring(pos+1));
			name = name.substring(0, pos);
		}
		params[name] = value;
	}
	return params;
};
function getParam(name, string) {
	var params = getParams(string);
	return params[name] || false;
}
function setHashParams(params) {
	var arr = '';
	
}
function setHashParam() {
}

/* funzioni di debug:
 * se e' possibile scrive nella console
 * (sempre disponibile in chrome, disponibile in firefox
 * solo se firebug e' aperto gia' al caricamento della pagina),
 * altrimenti esegue gli alert (solo se DEBUG e' true). */
if (typeof(DEBUG)=='undefined') {
	DEBUG = false;
	(function() {
		var d = getParam('debug'); // cerca nella query o nell'hash (in quest'ordine)
		if (d === true || d == 'true' || d == 'debug') {
			DEBUG = true;
		}
	})();
}
if (typeof(console) == 'undefined') {
	console = {};
}
if (typeof(console.log) == 'undefined') {
	console.log = function(msg) {
		if (DEBUG || DEBUGRAITV) {
			alert(msg);
		}
	};
}
debug = function(msg) {
	try {
		console.log(msg);
	} catch (e) {
		if (DEBUG || DEBUGRAITV) {
			alert(msg);
		}
	}
	return true;
}
if (DEBUG) {
	DEBUGRAITV = true;
}



/* gestione fallback per SL 1.0 */
var videoURL = null;
var SLPlayerController = null;
function playerLoaded(pController) {
	SLPlayerController = pController;
}
function SLPlayVideo(video, titolo) {
	SLPlayerController.Play.call(SLPlayerController, video, titolo);
	return false;
}
function createSilverlight() {
	// controllo se e' presente SL 2.0...
	// if (Silverlight.isInstalled("2.0")) {
	// 	var slHtml = getSLHtml();
	// 	$('#silverlightControlHost').html(slHtml);
	// 	return false;
	// }
	
	var scene = new Video_Messaggi.Page();

	$('<div></div>').load(channelXmlPath,
		null,
		function(a, b, c){
			var xml = null;
			if (c.responseXML) {
				xml = $(c.responseXML);
			} else {
				xml = $(a);
			}
			var url = $('set[@uniquename=\''+cid+'\'] videoUnit[@type=\'RaiTv videoWall Video\'] url:eq(0)', xml);
			if (url.length == 0) {
				url = $('set[@uniquename=\''+cid+'\'] videoUnit url:eq(0)', xml);
			}
			url = url.text();
			videoURL = url;

			/* costruisce l'elenco dirette */
			var ul = $('<ul id="menuDiretteVideo"></ul>');
			var dirette = $("videoUnit[@type='RaiTv Diretta Full Video']", xml);
			dirette.each(function(){
				var cset = $(this).parents('set').attr('uniquename');
				var title = $("textUnit[@type='Title']", $(this).parents('item')).text();
				title = title.replace(/[\n\W]*(.*)[\n\W]*/, "$1");
				var url = $('url', $(this)).text();
				var li = $('<li></li>');
				var anchor = $('<a href="?cid='+cset+'">'+title+'</a>');
				anchor.click(
					(function(){
						var u = url;
						var t = title;
						return function(){
							return SLPlayVideo(u, t);
						};
					})()
				);
				li.append(anchor);
				ul.append(li);
			});

	Silverlight.createObjectEx({
		source: "/dl/RaiTV/silverlight1.0/Page.xaml",
		parentElement: document.getElementById("silverlightControlHost"),
		id: "SilverlightControl",
		properties: {
			width: "384",
			height: "352",
			version: "1.0",
			autoUpgrade: "true"}
			,
		events: {
			onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
			onError: function(sender, args) {
				var errorDiv = document.getElementById("errorLocation");
				if (errorDiv != null) {
					var errorText = args.errorType + "- " + args.errorMessage;

					if (args.ErrorType == "ParserError") {
						errorText += "<br>File: " + args.xamlFile;
						errorText += ", line " + args.lineNumber;
						errorText += " character " + args.charPosition;
					}
					else if (args.ErrorType == "RuntimeError") {
						errorText += "<br>line " + args.lineNumber;
						errorText += " character " +  args.charPosition;
					}
					errorDiv.innerHTML = errorText;
				}
			}
		}
	});

			$('#silverlightControlHost').prepend(ul);
			$('#silverlightControlHost').wrapInner('<div id="containerLinux"></div>');
		});
}


/* gestione banner */

function createCallback(func) {
	var baseName = 'bannerCallback';
	var fname = baseName + Math.round(Math.random()*1000000);
	while (typeof(window[fname]) != 'undefined') {
		debug('BannerLoader: creating callback, '+fname+' already exists');
		var r = Math.round(Math.random()*1000000);
		fname = baseName + r;
	}
	var f = (function(fun, funcName) {
		return function() {
			window[funcName] = function(){};
			return fun.call(window, arguments);
		}
	})(func, fname);
	window[fname] = f;
	return fname;
};
bannercode = '';
function reloadBanner300x100(banner300x100, banner300x250) {
	var f = (function(banner300x100, banner300x250) {
		return function() {
			//debug('loaded banner 300x100:\n'+bannercode);
			$(".spallaDx .banner300x100").empty();
			if (bannercode!="") {
				$(bannercode).appendTo(".spallaDx .banner300x100");
			}
			reloadBanner300x250(banner300x100, banner300x250);
		}
	})(banner300x100, banner300x250);
	if (banner300x100 == null) {
		bannercode='';
		f();
	} else {
		var fname = createCallback(f);
		var url = getAdagioURL(banner300x100, '', fname+'();', fname+'();', '', '');
		debug('loading banner 300x100 from url:\n'+url);
		$.getScript(url);
	}
	return true;
}
function reloadBanner300x250(banner300x100, banner300x250) {
	var f = (function(banner300x100, banner300x250) {
		return function() {
			//debug('loaded banner 300x250:\n'+bannercode);
			$(".spallaDx .banner300x250").empty();
			if (bannercode!="") {
				$(bannercode).appendTo(".spallaDx .banner300x250");
			}
		}
	})(banner300x100, banner300x250);
	if (banner300x250 == null) {
		bannercode='';
		f();
	} else {
		var fname = createCallback(f);
		var url = getAdagioURL(banner300x250, '', fname+'();', fname+'();', '', '');
		debug('loading banner 300x250 from url:\n'+url);
		$.getScript(url);
	}
	return true;
}

var lastBannerVars = {};
function reloadAdvertisement() {
	debug('reloadAdvertisement called:\n');
	debug(arguments);
	
	// l'ordine dei parametri e' quasi sicuramente sballato: indoviniamo i parametri corretti... -.-;
	var bannerspot = null;
	var banner300x100 = null;
	var banner300x250 = null;
	var chanId = 'null';
	
	for (var i = 0; i<arguments.length; i++) {
		var v = arguments[i];
		if (/(PublishingBlock|ContentSet)/i.test(v)) {
			chanId = v;
		} else if (/300x250/i.test(v)) {
			banner300x250 = v;
		} else if (/300x100/i.test(v)) {
			banner300x100 = v;
		} else if (/rtv_streaming/i.test(v)) {
			bannerspot = v;
		}
	}
	lastBannerVars['300x250'] = banner300x250;
	lastBannerVars['300x100'] = banner300x100;
			
	// var re = /(PublishingBlock|ContentSet)/i;
	// if (re.test(bannerspot)) {
	// 	chanId = bannerspot;
	// 	bannerspot = undefined;
	// }
	// if (re.test(banner300x100)) {
	// 	chanId = banner300x100;
	// 	banner300x100 = undefined;
	// }
	// if (re.test(banner300x250)) {
	// 	chanId = banner300x250;
	// 	banner300x250 = undefined;
	// }
	
	debug('reloadAdvertisement filtered vars:\n'+bannerspot+'\n'+banner300x100+'\n'+banner300x250+'\n'+chanId);
	
	reloadBanner300x100(banner300x100, banner300x250);
	// il caricamento del banner 300x250 viene chiamato *dopo*, all'interno della callback di reloadBanner300x100
	debug("chanId is: "+chanId);
	if (chanId != null) {
		// mostra i contenuti corretti: se e' una webtv, mostra l'archivio, altrimenti mostra i piu' recenti
		showArchivio(chanId);
	}
}

function isWebTvChannel(chanId) {
	var res = false;
	if (typeof(getBlockBySet) != 'undefined' && typeof(getWebTvBlockIds) != 'undefined') {
		debug('Checking if '+chanId+' is a webTv');
		var webTvBlocks = getWebTvBlockIds(); // contiene gli id dei blocchi delle webtv
		var parentBlock = getBlockBySet(chanId); // sara' false nel caso in cui il cid sia un block invece di un set
		//console.log(webTvBlocks);
		if (webTvBlocks[chanId]) {
			debug('Yes, it is!');
			isWebTv = true;
			res = true;
		} else {
			debug("No, it isn't.");
			isWebTv = false;
			res = false;
		}
	} else {
		debug('getBlockBySet or getWebTvBlockIds not set...');
	}
	return res;
}
function showArchivio(webTvBlock) {
	// fa in modo di mostrare l'archivio invece de "i piu' recenti"
	$(function() {
		var n = $('ul#dirette li:eq(0) a');
		var o = $('ul#dirette li:gt(0)');
		if (!n.data('origRel')) {
			n.data('origRel', n.attr('rel'));
			n.data('origText', n.text());
		}
		n.css('color', ''); // viene sovrascritto in setTabStyle, chiamato nel block dela playlist
		if (isWebTvChannel(webTvBlock)) {
			n.attr('rel', '/dl/RaiTV/VideoWall/PlayList/'+webTvBlock+'.html');
			n.text('Altri video');
			$('ul#dirette li:eq(0)').addClass('canaleWebTv');
			o.hide();
		} else {
			n.attr('rel', n.data('origRel'));
			n.text(n.data('origText'));
			$('ul#dirette li:eq(0)').removeClass('canaleWebTv');
			o.show();
		}
		
		// evito la chiamata Nielsen: viene gia' fatta dal player SL al cambio di canale.
		var f = window.setNielsen;
		window.setNielsen = function() {return false;};
		
		n.parent('li').click();
		
		window.setNielsen = f;
	});
}
function setTabStyle(channelInfo) {
	var n = $('ul#dirette li:eq(0) a');
	n.text(channelInfo.title);
	n.css('color', channelInfo.color);
}


var cid = null;
cid = getParam('cid'); // da parametri della query o nell'hash
if (typeof(getValidIds) != 'undefined') {
	var validIds = getValidIds();
	if (!validIds[cid]) {
		// try to decode set to block...
		var set2block = getSet2BlockMap();
		if (!set2block[cid]) {
			debug('Invalid id: '+cid);
			cid = null;
		} else {
			debug('Mapping ContentSet to PublishingBlock');
			cid = set2block[cid];
		}
	}
}
if (cid == null || cid == '' || cid == 'null') {
	// cid = 'ContentSet-37f0f5d4-af33-48df-9281-2d46214c1b5d'; // Diretta Raiuno
	cid = 'PublishingBlock-64203784-70f7-4b53-9d21-b14693850195'; // Diretta Raiuno
}

//var channelXmlPath = '/dl/RaiTV/videoWall/PublishingBlock-5566288c-3d21-48dc-b3e2-af7fbe3b2af8.xml';
var channelXmlPath = 'http://www.objects.rai.it/dl/objects/xml/raitv/Page-905f9415-7875-4087-a647-7ecfe784614f.html';

var isWebTv = isWebTvChannel(cid);
//showArchivio(cid);

// non so dove vengano usate queste variabili, ne' perche' esistano o.o'
var videoTitolo = "Test1";
var logoIMG = "/dl/RaiTV/silverlight1.0/logo_rai.png";
var liveMode = "1";


/* creazione del player silverlight */
var _myplayerObject;
//alert("TOGLIERE /test/ dal src di SL! ;)");
var installExperienceHTML = '';
var installExperienceHTMLLX = '';
//var advIntervalSec = 5; // TEST: in produzione va messo a 60
var advIntervalSec = 60;

function getSLHtml() {
	installExperienceHTML = '';
	installExperienceHTML += '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">';
	installExperienceHTML += '<param name="source" value="/dl/objects/silverlight/raitv/Lettore_Rai_Diretta.xap"/>';
	//installExperienceHTML += '<param name="source" value="/dl/test/objects/silverlight/raitv/Lettore_Rai_Diretta.xap"/>';
	installExperienceHTML += '<param name="onerror" value="onSilverlightError" />';
	installExperienceHTML += '<param name="background" value="#0a0a0a" />';
	installExperienceHTML += '<param name="minRuntimeVersion" value="2.0.31005.0" />';
	installExperienceHTML += '<param name="autoUpgrade" value="true" />';
	installExperienceHTML += '<param name="initparams" value="advIntervalSec='+advIntervalSec+',channelXmlPath='+channelXmlPath+',channelId='+encodeURIComponent(cid)+',pathbanner=http://ad2.neodatagroup.com/ad/load_ndgruler.jsp?sid=49&bt=n&wt=n&jsvar=&rnd='+rnd+'&loc=BANNERSPOT,nScriptUrl=http://server-it.imrworldwide.com/cgi-bin/count" />';
	// initparams per vod
	//installExperienceHTML += '<param name="initparams" value="videoPath=' + videoURL + ',auto=false" />';
	installExperienceHTML +='<center style="color:#fff;" ><a>Se vuoi visualizzare il video installa Microsoft Silverlight</a></center><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">';
	installExperienceHTML += '<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Installa Microsoft Silverlight" style="border-style: none"/>';
	installExperienceHTML +='</a></center>';
	installExperienceHTML +='</object>';
	
	return installExperienceHTML;
}

function getSLHtmlLX() {
	installExperienceHTMLLX = '';
	installExperienceHTMLLX += '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">';
	installExperienceHTMLLX += '<param name="source" value="/dl/objects/silverlight/raitv/Lettore_Rai_Diretta.xap"/>';
	installExperienceHTMLLX += '<param name="onerror" value="onSilverlightError" />';
	installExperienceHTMLLX += '<param name="background" value="#0a0a0a" />';
	installExperienceHTMLLX += '<param name="minRuntimeVersion" value="2.0.31005.0" />';
	installExperienceHTMLLX += '<param name="autoUpgrade" value="true" />';
	installExperienceHTMLLX += '<param name="initparams" value="advIntervalSec='+advIntervalSec+',channelXmlPath='+channelXmlPath+',channelId='+encodeURIComponent(cid)+',pathbanner=http://ad2.neodatagroup.com/ad/load_ndgruler.jsp?sid=49&bt=n&wt=n&jsvar=&rnd='+rnd+'&loc=BANNERSPOT,nScriptUrl=http://server-it.imrworldwide.com/cgi-bin/count" />';
	// initparams per vod
	//installExperienceHTMLLX += '<param name="initparams" value="videoPath=' + videoURL + ',auto=false" />';
	installExperienceHTMLLX += '<center style="color:#fff;" ><a>Per visualizzare il contenuto video installa Moonlight <a href="http://www.go-mono.com/moonlight/">da questo sito</a> e poi torna sulla pagina.</a></center>';
	installExperienceHTMLLX +='</object>';
	
	return installExperienceHTMLLX;
}

function buildSilverlightDirette() {

	var rnd = parseInt((Math.random()*(Date.parse(new Date()))));

	installExperienceHTML = getSLHtml();
	installExperienceHTMLLX = getSLHtmlLX();

	// Silverlight.InstallAndCreateSilverlight(
		// '1.0',
		// document.getElementById('silverlightControlHost'),
		// installExperienceHTML,
		// installExperienceHTMLLX,
		// 'InstallPromptDiv',
		// createSilverlight);
	
	// questo qui sotto dovrebbe mostrare il player serio anche su linux...
	Silverlight.InstallAndCreateSilverlight(
		'2.0',
		document.getElementById('silverlightControlHost'),
		installExperienceHTML,
		installExperienceHTMLLX,
		'InstallPromptDiv',
		createSilverlight);
}
$(buildSilverlightDirette);


function initArchivioPlaylist() {
	$("UL.elencoTematiche LI>A").click(function() {
		$("UL.elencoTematiche LI").attr("id","");
		var setUrl = $(this).attr("id");
		if (DEBUGRAITV) {alert("cont 0");}
		if($(this).next(".sottoTematica").length!=0) {
			if (DEBUGRAITV) {alert("cont 1");}
			$("UL.sottoTematica").hide();
			$(this).next().show();
			if($(this).parent().attr("class") == "") {
				if (DEBUGRAITV) {alert("cont 1.1");}
				$(this).parent().attr("id","unselectedDown");
				$(this).next().children("LI:visible:first").attr("id","selected");
				setUrl = $(this).next().children("LI:visible:first").children().attr("id").toString();
			} else {
				if (DEBUGRAITV) {alert("cont 1.2");}
				$(this).parent().attr("id","selected");
				$(this).parents(".sottoTematica").parent().attr("id","unselectedDown");
			}
		} else {
			if (DEBUGRAITV) {alert("cont 2");}
			if($(this).parents(".sottoTematica").length == 0) {
				if (DEBUGRAITV) {alert("cont 3");}
				$("UL.sottoTematica").hide();
				$(this).parent().attr("id","selected");
			} else {
				if (DEBUGRAITV) {alert("cont 4");}
				$(this).parents(".sottoTematica").parent().attr("id","unselectedDown");
				$(this).parent().attr("id","selected");
			}
		}
		var url = "/dl/RaiTV/programmi/liste/"+setUrl+".html";
		if(pageVisited == "page") {
			url = "/dl/RaiTV/programmi/liste/"+setUrl+"-"+__TAB+"-0.html";
		}		
		
		setView();
		$("#mediaList").fadeIn("slow", function () {
			setReflection(".reflect");
			pagination();
			applyPngFix();
			login();				
		});
		$("#mediaList>div>ul>li").slice(12).hide();

	  return false;
	});
}

setNielsen = (function() {
	
	var f = setNielsen;
	
	return function(u) {
		try {
			f(u);
		} catch(e) {
			try {
				console.log('exception catched', e);
			} catch(g) {
			}
		}
		
		try {
			reloadBanner300x100(lastBannerVars['300x100'], lastBannerVars['300x250']);
		} catch(e) {
			try {
				console.log('exception catched', e);
			} catch(g) {
			}
		}
	}
})();
