/**
setta tutte le funzioni del box MyRaiTV dalla login al recupera password
**/
function loginControlPanel() {
	$("#myraitvusername").focus(function() {
		$("#myraitvusername").val("");
		return false;
	});
	$("#myraitvpass").focus(function() {
		$("#myraitvpass").val("");
		return false;
	});
	// $(".lostPass").click(function() {
	// 	$(".loginMyraitv").hide();
	// 	$(".recuperaPwdMyraitv").show();
	// 	return false;
	// });
	$(".backLogin").click(function() {
		$(".recuperaPwdMyraitv").hide();
		$(".loginMyraitv").show();
		return false;
	});
	$("#myraitvemail").focus(function() {
		$("#myraitvemail").val("");
		return false;
	});
	$("#myraitvsubmitemail").click(function() {
		var optionShadowbox = {};
		if($("#myraitvemail").val()!="E-mail" && /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($("#myraitvemail").val()))
		{
			$.post(PATH_RETRIEVE_LOGIN_DATA, {email:$("#myraitvemail").val()},
			  function(data){
				if(data == "ok")
				{
					optionShadowbox = {
								title : "Recupero Login",
								content:'<div id="msg">'+messages["retrieveEmailOK"]+'</div>',
								player : "html",
								height :100,
								width: 300,
								options :{ animate:false}
					};
				} else {
					optionShadowbox = {
								title : "Recupero Login",
								content:'<div id="msg">'+messages["retrieveEmailKO"]+'</div>',
								player : "html",
								height :100,
								width: 300,
								options :{ animate:false}
					};
				}
				messageShadowbox(optionShadowbox);
			});
		} else {
			optionShadowbox = {
					title : "Recupero Login",
					content:'<div id="msg">'+messages["retrieveEmailERROR"]+'</div>',
					player : "html",
					height :100,
					width: 300,
					options :{ animate:false}
			};
			messageShadowbox(optionShadowbox);
		}
		return false;
	});
	$("#myraitvsubmit").click(function() {
		var myUsername = $("#myraitvusername").val();
		if(myUsername!="Utente" && $("#myraitvpass").val() != "Pass") {
			$.post(PATH_LOGIN, {username:$("#myraitvusername").val(),password :$("#myraitvpass").val() },
			  function(data){
				var result = $.trim(data).split("-");
				var esito = 0;
				if (result.length > 1) {
					result = [result[0], result.slice(1).join('-')];
				}
				// try {console.log({array: result});}catch(e){}
				if (result.length > 1 && /\({.*}\);/.test(result[1])) {

					var json = result[1].replace(/\(({.*})\);/, '$1');
					// try {console.log({string: json});}catch(e){}
					try {
						eval('json = '+json+';');
					} catch (e) {
						json = {"error": "error"};
					}
					try {console.log(json);}catch(e){}
					if (!!json.redirect) {
						var text = "";
						var u = decodeURIComponent(json.redirect);
						u += (/[\?#]/.test(u))?'&':'?';
						u += 'ref='+encodeURIComponent(''+document.location);
						if (!!json.message && !!messages["userAlteredMessages"][json.message]) {
							text += "<p>"+messages["userAlteredMessages"][json.message].replace("#url#", u)+"</p>";
						} else {
							text += "<p>"+messages["userAlteredDuringImport"].replace("#url#", u)+"</p>";
						}
						var msgStyle = '<style type="text/css">#msg p {text-align: left; font-size: 16px;} #msg a, #msg a:link, #msg a:visited {color:#fff; text-decoration: underline;} #msg a:hover, #msg a:active {color: #ccc;}</style>';
						var optionShadowbox = {
							title   : "Login",
							content : msgStyle+'<div id="msg">'+text+'</div>',
							player  : "html",
							height  : 250,
							width   : 640,
							options : {animate:false}
						};
						messageShadowbox(optionShadowbox);
						return;
					} else if (!!json.token) {
						var t = json.token;
						var d = t+'-'+myUsername;

						utils.cookie.set("MyRaiTvUser",d,"",'/',HOST,'');
						utils.cookie.set("token",t,"",'/',HOST,'');
						utils.cookie.set("tokenExt",t,"",'/',HOST,'');

						$('iframe#MyRaiTvLogin,iframe#MyRaiTvLogin2,iframe#MyRaiTvLogin3,iframe#MyRaiTvLogin4').remove();
						var domain = 'www.rai.tv';
						if (/rai.tv/i.test(''+document.location)) {
							domain = 'www.rai.it';
						}
						$('<iframe id="MyRaiTvLogin" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=MyRaiTvUser&amp;c='+d+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
						$('<iframe id="MyRaiTvLogin2" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=token&amp;c='+t+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
						$('<iframe id="MyRaiTvLogin4" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=tokenExt&amp;c='+t+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
						domain = '212.162.68.150';
						$('<iframe id="MyRaiTvLogin3" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=token&amp;c='+t+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));

						esito = 1;
						login(esito);

					} else {
						esito = 3;
						login(esito);
					}
				} else if (result.length > 1) {
					var t = data.split('-');
					t = t[0];
					utils.cookie.set("MyRaiTvUser",data,"",'/',HOST,'');
					utils.cookie.set("token",t,"",'/',HOST,'');
					utils.cookie.set("tokenExt",t,"",'/',HOST,'');

					$('iframe#MyRaiTvLogin,iframe#MyRaiTvLogin2,iframe#MyRaiTvLogin3,iframe#MyRaiTvLogin4').remove();
					var domain = 'www.rai.tv';
					if (/rai.tv/i.test(''+document.location)) {
						domain = 'www.rai.it';
					}
					$('<iframe id="MyRaiTvLogin" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=MyRaiTvUser&amp;c='+data+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
					$('<iframe id="MyRaiTvLogin2" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=token&amp;c='+t+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
					$('<iframe id="MyRaiTvLogin4" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=tokenExt&amp;c='+t+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
					domain = '212.162.68.150';
					$('<iframe id="MyRaiTvLogin3" src="http://'+domain+'/dl/js/cookieUtils.html?m=s&amp;n=token&amp;c='+t+'" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));

					esito = 1;
					login(esito);
				}  else if (result[0] == "nonvalido"){
					esito = 2;
					login(esito);
				} else {
					esito = 3;
					login(esito);
				}
				// Segnalo che e' stato fatto il login a myraitv.
				// Per ricevere l'evento: $(document).bind('myRaiTv.loggedIn', function(){alert('boo! :P'});
				// es: gestione commenti
				$(document).trigger('myRaiTv.loggedIn');
			});
		} else {
			var optionShadowbox = {
							title : "Login",
							content:'<div id="msg">'+messages["loginERROR"]+'</div>',
							player : "html",
							height :100,
							width: 300,
							options :{ animate:false}
							};
			messageShadowbox(optionShadowbox);
		}
		return false;
	});
};

/**
Logout e ricarica la pagina in cui si e'
**/
function logout(){
	$.getScript('http://sso.widget.rai.it/smartLogout.php?callback=(function(){})');

	$('iframe#MyRaiTvLogin,iframe#MyRaiTvLogin2,iframe#MyRaiTvLogin3,iframe#MyRaiTvLogin4').remove();
	var domain = 'www.rai.tv';
	if (/rai.tv/i.test(''+document.location)) {
		domain = 'www.rai.it';
	}
	$('<iframe id="MyRaiTvLogin" src="http://'+domain+'/dl/js/cookieUtils.html?m=r&amp;n=MyRaiTvUser" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
	$('<iframe id="MyRaiTvLogin2" src="http://'+domain+'/dl/js/cookieUtils.html?m=r&amp;n=token" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
	$('<iframe id="MyRaiTvLogin2" src="http://'+domain+'/dl/js/cookieUtils.html?m=r&amp;n=tokenExt" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));
	domain = '212.162.68.150';
	$('<iframe id="MyRaiTvLogin3" src="http://'+domain+'/dl/js/cookieUtils.html?m=r&amp;n=token" frameborder="0" style="width: 1px; height: 1px; position: absolute; left: -100px; top: -100px; overflow: hidden;"></iframe>').appendTo($('body'));


	window.setTimeout(function(){
		// spero di dare il tempo all'iframe di cancellare il cookie :)

		utils.cookie.remove("MyRaiTvUser",'/',HOST);
		utils.cookie.remove("token",'/',HOST);
		utils.cookie.remove("tokenExt",'/',HOST);

		window.location.reload();
	}, 2500);
	return false;
};

/**
effettua i controlli sulla login
**/
function login(data){
	try {
		loadWidget();
	} catch(e) {}
	var indexAccordion = 0;
	setAccordion(indexAccordion);
	var html ="";
	if (utils.cookie.get("MyRaiTvUser")) {
		MyRaiTvUserCodeComplete = utils.cookie.get("MyRaiTvUser");
		MyRaiTvUserCode = utils.cookie.get("MyRaiTvUser").split("-")[0];
		MyRaiTvNickname = utils.cookie.get("MyRaiTvUser").split("-")[1];
		data = 1;
	}
	if (utils.cookie.get("MyRaiTvPlaylistTemp")) {
		$("H2.drawer-handle:eq(1)").click();
	}
	switch(data) {
		case 1:
			if(!menu) {
				drawMyRaiTvMenu();
				$(".loginMyraitv").html("");
				html = '<ul class="opzioniCP"><li><a href="/dl/community/articolo/ContentItem-6ae96bc9-4570-431c-a6fd-0155a45eb1d4.html" class="modCP">Modifica i tuoi dati</a></li><li><a href="#" onclick="logout(); return false;" class="logout">Esci da MyRai.tv</a></li></ul>';
				$(".loginMyraitv").html(html);
				menu = true;
			}
			$(".tastiOpzioni>.Fave,.vodOpzioni>.Fave").html('<a href="#" class="btnFave" title="Aggiungi ai preferiti"></a>');
			$("A.btnFave").click(function() {
					var idItem = $(this).parents(".tastiOpzioni").parent("LI").attr("id");
					if(idItem == undefined) {
						idItem = $("#uniquename").text();
					}
					addFavourites(idItem);
				return false;
			});
			break;
		case 2:
			var optionShadowbox = {
							title : "Login",
							content:'<div id="msg">'+messages["loginUserNotValid"]+'</div>',
							player : "html",
							height :100,
							width: 300,
							options :{ animate:false}
							};
			messageShadowbox(optionShadowbox);
			break;
		case 3:
			var optionShadowbox = {
							title : "Login",
							content:'<div id="msg">'+messages["loginErrorUserPassword"]+'</div>',
							player : "html",
							height :100,
							width: 300,
							options :{ animate:false}
							};
			messageShadowbox(optionShadowbox);
			break;
	}
	$(".tastiOpzioni>LI,.vodOpzioni>LI").click(function() {
		if ($(this).find('a').length == 0) {
			var message = "";
			if($(this).is('.Fave')) {
				message = messages["alertButtonOptionsFave"];
			} else if($(this).is('.Download')) {
				message = messages["alertButtonOptionsPodcast"];
			} else if($(this).is('.Feed')) {
				message = messages["alertButtonOptionsFeed"];
			} else if($(this).is('.Playlist')) {
				message = messages["alertButtonOptionsPlaylist"];
			}
			var optionShadowbox = {
							title : "Avviso",
							content:'<div id="msg">'+message+'</div>',
							player : "html",
							height :100,
							width: 300,
							options :{ animate:false}
							};
			messageShadowbox(optionShadowbox);

			return false;
		} else {
			return true;
		}

		if($(this).text() == "") {
			var message = "";
			if($(this).is('.Fave')) {
				message = messages["alertButtonOptionsFave"];
			} else if($(this).is('.Download')) {
				message = messages["alertButtonOptionsPodcast"];
			} else if($(this).is('.Feed')) {
				message = messages["alertButtonOptionsFeed"];
			} else if($(this).is('.Playlist')) {
				message = messages["alertButtonOptionsPlaylist"];
			}
			var optionShadowbox = {
							title : "Avviso",
							content:'<div id="msg">'+message+'</div>',
							player : "html",
							height :100,
							width: 300,
							options :{ animate:false}
							};
			messageShadowbox(optionShadowbox);
		}
		return false;
	});
};

/**
Accordion del box MyRaiTV presente in tutte le pagine di RaiTV
**/
function setAccordion(val){
	$("UL.drawers>LI.drawer>div.drawer-container:not(:eq("+val+"))").slideUp("fast");
	$("UL.drawers>LI.drawer>H2:eq("+val+")").addClass("open");
	$("H2.drawer-handle").click(function() {
		if ($(this).next().css('display') == 'none') {
			$(this).parents(".drawers").children(".drawer").children("h2").removeClass("open").next().slideUp("slow");
			$(this).addClass('open').next().slideDown("slow");
		}
	});
};

/**
Aggiunge un ContentItem alla playlist temporanea se un utente non e' loggato
**/
function addPlaylistTemp(){
	if(vodOpzioni == false) {
		$("OL.vodOpzioni A.btnPlaylist").click(function() {
			if (!utils.cookie.get("MyRaiTvUser")) {
				setCookiePlaylistTemp($(this).attr("rel"));
			}
			return false;
		});
		vodOpzioni = true;
	}
	$("OL.tastiOpzioni A.btnPlaylist").click(function() {
		if (!utils.cookie.get("MyRaiTvUser")) {
			setCookiePlaylistTemp($(this).attr("rel"));
		}
		return false;
	});
	return false;
};


/**
Aggiunge un ContentItem alla playlist temporanea se un utente non e' loggato
**/
function addPlaylist(idItem){
	if (utils.cookie.get("MyRaiTvUser")) {
			var optionShadowbox = {
							title : "Aggiungi il media alla playlist",
							content:PATH_ADD_PLAYLIST+idItem,
							player : "iframe",
							width: 520,
							height: 250,
							options :{ animate:false}
						};
			Shadowbox.init({
			skipSetup: true // skip the automatic setup
			});
			Shadowbox.open(optionShadowbox);
	} else {
		setCookiePlaylistTemp(idItem);
	}
	return false;
};


/**
Svuota la playlist temporanea
**/
function cleanPlaylistTemp(){
	utils.cookie.remove("MyRaiTvPlaylistTemp",'/',HOST);
	$("UL.playlistTemp > *").fadeOut(1000, function () {
		$("UL.playlistTemp").html("");
	});
	$("#savePlaylistTempMessaggio").fadeOut(1000);
	$('#paneTempPlayList').empty().append($('<ul class="playlistTemp"><li><h4>'+messages["playlistTempEmpty"]+'</h4></li></ul>'));

	var isIpad = (navigator.userAgent.match(/iPad/i));
	var isIphone = (navigator.userAgent.match(/iPhone/i));
	// jScrollPane inutilizzabile con il touch di safari
	if (!isIpad && !isIphone) {
		$('#paneTempPlayList').jScrollPane({showArrows:false, scrollbarWidth:16,animateTo:true });
	}
	return false;
};

/**
Setta i valori della playlist temporanea in un cookie
**/
function setCookiePlaylistTemp(contentItem){
	var playlistCookie = {};
	var title = $("#"+contentItem + " .Desc H2").text();
	if(title == "" || title == null) {
		title = $("#idMedia").text();
	}

	var imgpath = $("#"+contentItem + " .reflected , #"+contentItem + " .reflect").attr("src");
	if(imgpath == undefined) {
		imgpath = $("#pathImgStat").text();
	}

	var programName = $("DIV.logoDescr").children("H2").text();
	if(programName == "" || title == programName) {
		programName = $("#"+contentItem + ">.Desc>.Lancio>H5").text();
	}

	if (utils.cookie.get("MyRaiTvPlaylistTemp")) {
		try {
			playlistCookie = $.evalJSON($.base64Decode(utils.cookie.get("MyRaiTvPlaylistTemp")));
		} catch(e) {}
	}

	if(typeof(playlistCookie[contentItem]) == 'undefined') {
		playlistCookie[contentItem] = {title: title, imgpath: imgpath,programName:programName };
		utils.cookie.set("MyRaiTvPlaylistTemp",$.base64Encode($.toJSON(playlistCookie)),"",'/',HOST,'');
		$('html,body').animate( {scrollTop: $(".boxMyRaitv").offset().top-90});
		drawPlaylistTemp();
	} else {
		var optionShadowbox = {
						title : "Playlist",
						content:'<div id="msg">'+messages["playlistTempAlreadyExist"]+'</div>',
						player : "html",
						height :150,
						width: 300,
						options :{ animate:false}
						};
		messageShadowbox(optionShadowbox);
	}
};

/**
Crea l'html della playlist temporanea
**/
function drawPlaylistTemp(){
	var playlistCookie = {};
	if (utils.cookie.get("MyRaiTvPlaylistTemp")) {
		$("H2.drawer-handle:eq(1)").click();
		$('#paneTempPlayList').empty().append($('<ul class="playlistTemp"></ul>'));

		try {
			var isIpad = (navigator.userAgent.match(/iPad/i));
			var isIphone = (navigator.userAgent.match(/iPhone/i));
			// jScrollPane inutilizzabile con il touch di safari
			if (!isIpad && !isIphone) {
				$('#paneTempPlayList').jScrollPane({showArrows:false, scrollbarWidth:16,animateTo:true });
			}
		} catch(e) {return false;}
		try {
			playlistCookie = $.evalJSON($.base64Decode(utils.cookie.get("MyRaiTvPlaylistTemp")));
		} catch(e) {}
		var j = false;
		for (j in playlistCookie) {
			var id = j,title= playlistCookie[j].title, imgpath = playlistCookie[j].imgpath,programName = playlistCookie[j].programName;
			var html = '<li><a href="#" class="screenShot"><div class="mask"></div><img src="'+imgpath+'" width="69" class="reflect" /></a><a href="/dl/RaiTV/programmi/media/'+j+'.html#p=0" class="Lancio"><h2>'+title+'</h2><h3>'+programName+'</h3><!--h5><span>Durata</span> 01:05:23</h5--></a><a href="#"  onclick="javascript:removeItemPlaylistTemp(\''+j+'\');return false;" title="Elimina" class="Elimina"><span class="solotesto">Elimina</span></a></li>';
			$("UL.playlistTemp").append(html);
		}
		if(j === false) {
			cleanPlaylistTemp();
		}
		try {
			var isIpad = (navigator.userAgent.match(/iPad/i));
			var isIphone = (navigator.userAgent.match(/iPhone/i));
			// jScrollPane inutilizzabile con il touch di safari
			if (!isIpad && !isIphone) {
				$('#paneTempPlayList').jScrollPane({showArrows:false, scrollbarWidth:16,animateTo:true });
			}
		} catch(e) {}
	    /*if($("UL.playlistTemp>li").length > 3)
			$('#paneTempPlayList')[0].scrollTo("UL.playlistTemp>li:last");*/
		setReflection(".reflect");
	}
};

/**
Rimuove un ContentItem dalla playlist temporanea
**/
function removeItemPlaylistTemp(Item){
	var playlistCookie = {};
	if (utils.cookie.get("MyRaiTvPlaylistTemp")) {
		try {
			playlistCookie = $.evalJSON($.base64Decode(utils.cookie.get("MyRaiTvPlaylistTemp")));
			delete playlistCookie[Item];
			utils.cookie.set("MyRaiTvPlaylistTemp",$.base64Encode($.toJSON(playlistCookie)),"",'/',HOST,'');
		} catch(e) {}
		$("H2.drawer-handle:eq(1)").click();
	}
	drawPlaylistTemp();
};

function addFavourites(item){
	var valori = {"username" : MyRaiTvNickname, "confirmKey":MyRaiTvUserCode,"domain" : "RaiTv", "localId" :item};
	var optionShadowbox = {};
	$.ajax({
	   url: PATH_SAVE_FAVOURITE,
	   type: "POST",
	   dataType: "text",
	   data: valori,
	   success: function(result){
			if(result == "ok") {
				optionShadowbox = {
								title : "Preferiti",
								content:'<div id="msg">'+messages["favouriteAddItemOK"]+'</div>',
								player : "html",
								height :100,
								width: 300,
								options :{ animate:false}
								};
				messageShadowbox(optionShadowbox);
			} else {
				var mex = messages["favouriteAddItemKO"];
				if(result == "esistente") {
					mex = messages["favouriteAddItemExist"];
				}
				optionShadowbox = {
								title : "Preferiti",
								content:'<div id="msg">'+mex+'</div>',
								player : "html",
								height :100,
								width: 300,
								options :{ animate:false}
								};
				messageShadowbox(optionShadowbox);
			}
	   },
	   error : function(result){
			optionShadowbox = {
						title : "Preferiti",
						content:'<div id="msg">'+messages["favouriteAddItemKO"]+'</div>',
						player : "html",
						height :100,
						width: 300,
						options :{ animate:false}
						};
			messageShadowbox(optionShadowbox);
	   }
	});
};
function removeFavoutites(item){
	var optionShadowbox = {};
	var valori = {"username" : MyRaiTvNickname, "confirmKey":MyRaiTvUserCode,"domain" : "RaiTv", "localId" :item};
	$.ajax({
	   url: PATH_REMOVE_FAVOURITE,
	   type: "POST",
	   dataType: "text",
	   data: valori,
	   success: function(result){
			if(result == "ok") {
				optionShadowbox = {
								title	:	"Preferiti",
								content	:'<div id="msg">'+messages["favouriteRemoveItemOK"]+'</div>',
								player	: "html",
								height	:100,
								width	:	300,
								options	:{	animate:false,
											onFinish : $("#"+item).remove()
										}
								};
				messageShadowbox(optionShadowbox);
				pagintionFavourite();
				showHTMLFavourite(0);
			} else {
				optionShadowbox = {
								title : "Preferiti",
								content:'<div id="msg">'+messages["favouriteRemoveItemKO"]+'</div>',
								player : "html",
								height :100,
								width: 300,
								options :{ animate:false}
								};
				messageShadowbox(optionShadowbox);
			}
	   },
	   error : function(result){
			optionShadowbox = {
							title : "Preferiti",
							content:'<div id="msg">'+messages["favouriteRemoveItemKO"]+'</div>',
							player : "html",
							height :100,
							width: 300,
							options :{ animate:false}
							};
			messageShadowbox(optionShadowbox);
	   }
	});
};
function sendPlaylistTemp(){
	var playlistCookie = {};
	var playlistTempString = "";
	try {
		playlistCookie = $.evalJSON($.base64Decode(utils.cookie.get("MyRaiTvPlaylistTemp")));
	} catch(e) {}

	for (j in playlistCookie) {
		playlistTempString += j+"^";
	}
	playlistTempString = playlistTempString.substring(0,playlistTempString.length-1);

	var valori = {"username" : MyRaiTvNickname, "confirmKey":MyRaiTvUserCode,"domain" : "RaiTv", "playlistName" :$("#nomePlaylistTemp").val(), "contents":playlistTempString};
	$.ajax({
	   type: "POST",
	   url: PATH_SAVE_PLAYLIST_TEMP,
	   data: valori,
	   dataType: "text",
	   success: function(result){
			if(result == "ok") {
				$("#savePlaylistTempMessaggio").fadeIn(800, function () {
					$(this).html(messages["playlistSaveOK"]).fadeOut(3000, function () {
						$("H2.drawer-handle:eq(0)").click();
						cleanPlaylistTemp();
					});
				});
			} else {
				$("#savePlaylistTempMessaggio").fadeIn(800, function () {
					$(this).html(messages["playlistSaveKO"]);
				});
			}
	   },
	   error : function(result){
			$("#savePlaylistTempMessaggio").fadeIn(800, function () {
				$(this).html(messages["playlistSaveKO"]);
			});
	   }
	 });
}
function savePlaylistTemp(){
	if (utils.cookie.get("MyRaiTvUser")) {
		$("#savePlaylistTempMessaggio").html('<div class="nuovaPlaylist"><input type="text" value="Nome Playlist" id="nomePlaylistTemp"/><input type="image" id="myraitvsavesubmit" value="Salva" class="submit" src="/dl/portale/image/trasparent.png" /></div>').show("slow", function () {
			$("#nomePlaylistTemp").focus(function() {
				$("#nomePlaylistTemp").val("");
				return false;
			});
			$("#myraitvsavesubmit").click(function() {
				sendPlaylistTemp();
				return false;
			});
		});
	} else {
		$("#savePlaylistTempMessaggio").fadeIn(500, function () {
			$(this).html(messages["playlistSaveNoLogin"]).fadeOut(3500, function () {
				$("H2.drawer-handle:eq(0)").click();
			});
		});
	}
};

/**
Crea l'html del menu MyRaiTV
**/
function drawMyRaiTvMenu(){
	var html  = "";
	html = '<div id="myraitvHeader"><ul class="Opzioni"><li>Ciao '+MyRaiTvNickname+'</li><li><a href="/dl/community/articolo/ContentItem-6ae96bc9-4570-431c-a6fd-0155a45eb1d4.html">Modifica i tuoi dati</a></li><li><a href="http://www.community.rai.it/dl/community/articolo/ContentItem-6ae96bc9-4570-431c-a6fd-0155a45eb1d4.html#ajax_profile_embed=%2Fembed%2Fletters%2Findex%2Fmailto%3Aadmin_rai_community">Contatta il moderatore</a></li><li><a href="#" onclick="logout(); return false;">Esci da MyRai.tv</a></li></ul><a href="#" class="logoMyRaitv"><h2 class="solotesto">MyRai.tv</h2></a><ul class="Menu"><li><a href="/dl/RaiTV/MyRaiTV/homeMyRaiTv.html">My home</a></li><li><a href="/dl/RaiTV/MyRaiTV/myPlaylists.html">Le mie Playlist</a></li><li><a href="/dl/RaiTV/MyRaiTV/myPrograms.html">I miei programmi</a></li><li><a href="/dl/RaiTV/MyRaiTV/myFavourites.html">Preferiti</a></li></ul></div>';
	$(".Main").prepend(html);
};

function messageShadowbox(optionOpen){
	Shadowbox.init({
        skipSetup: true // skip the automatic setup
    });
	var closeBtn = '<a title="Chiudi" class="Close" onclick="Shadowbox.close(); return false;" href="#" style="display: block; width: 15px; height: 15px; position: absolute; top: 2px; right: 2px; background: transparent url(/dl/RaiTV/images/btn_close_comm.gif) no-repeat scroll 0 0"><span class="solotesto">Chiudi</span></a>';
	if (optionOpen.content.indexOf('class="Close"')<0 && optionOpen.content.indexOf('Shadowbox.close')<0) {
		optionOpen.content = closeBtn + optionOpen.content;
	}
	Shadowbox.open(optionOpen);
}
var MyRaiTvUserCodeComplete = "";
var MyRaiTvUserCode = "";
var MyRaiTvNickname = "";
var vodOpzioni = false;
var menu = false;
var myRaiTvDomain = document.domain;
if (myRaiTvDomain == '10.99.40.40') {
	myRaiTvDomain = '10.99.40.40:5852';
}
var PATH_LOGIN = "http://"+myRaiTvDomain+"/MyRaiTv/login.do";
var PATH_RETRIEVE_LOGIN_DATA = "http://"+myRaiTvDomain+"/MyRaiTv/retrieveLoginData.do";
var PATH_SAVE_PLAYLIST_TEMP = "http://"+myRaiTvDomain+"/MyRaiTv/savePlaylist.do";
var PATH_ADD_PLAYLIST = "http://"+document.domain+"/dl/RaiTV/MyRaiTV/addItemToPlaylist.html?contentItem=";
var PATH_SAVE_FAVOURITE = "http://"+myRaiTvDomain+"/MyRaiTv/addFavouriteContent.do";
var PATH_REMOVE_FAVOURITE = "http://"+myRaiTvDomain+"/MyRaiTv/deleteFavouriteContent.do";
$(function(){
	 $(".loadingAjax").bind("ajaxSend", function(){
	   $(this).show();
	 }).bind("ajaxComplete", function(){
	   $(this).hide();
	 });
	loginControlPanel();
	drawPlaylistTemp();
	login();
});

