var isIpad = (navigator.userAgent.match(/iPad/i));
var isIphone = (navigator.userAgent.match(/iPhone/i));
var isAndroid = (navigator.userAgent.match(/android/i));

var skipNielsen = true;
function applyPngFix ()
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])

	if ((version >= 5.5) && (version < 7) && (document.body.filters))
	{
	   for(var i=0; i<document.images.length; i++)
	   {
		  var img = document.images[i]
		  var imgName = img.src.toUpperCase()
		  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		  {
			 var imgID = (img.id) ? "id='" + img.id + "' " : ""
			 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			 var imgStyle = "display:inline-block;" + img.style.cssText
			 if (img.align == "left") imgStyle = "float:left;" + imgStyle
			 if (img.align == "right") imgStyle = "float:right;" + imgStyle
			 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			 var strNewHTML = "<span " + imgID + imgClass + imgTitle
			 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
			 img.outerHTML = strNewHTML
			 i = i-1
		  }
	   }
	}
};


var isIpad = (navigator.userAgent.match(/iPad/i));
var isIphone = (navigator.userAgent.match(/iPhone/i));
if (isIpad || isIphone) {
	$(function(){$('.banner_sottile, .banner_quad, .mini_banner, .mini_banner2').remove();});
}


function loadContents(url,elHTML) {
	$.ajax({
	  url: url,
	  cache: false,
	  success: function(html){
		if (html.indexOf('<title>')<0) {
			$(elHTML).html(html);
			applyPngFix();
			if (!isIpad && !isIphone && !isAndroid) {
				$(".box_scroll a[title]").tooltip('#videotip');
			}
		} else {
			// stessa cosa di onError
		}
	  }/*,
	  error: function(html){
		if (DEBUGRAITV) {alert("ERRORE");}
		$.ajax({
		  url: PATH_NO_CONTENT,
		  cache: false,
		  success: function(html){
			$(elHTML).html(html);
			setView();
			$("#mediaList").fadeIn("slow", function () {
				setReflection(".reflect");
			});
		  }
		});
	  }*/
	});
	return false;
};

function setNielsen(url) {
		if (url == undefined){url = location.href};
		if (url.match("^/dl")){url = "http://www.tg3.rai.it"+url};
		url = encodeURIComponent(url);
		//Zozzata richiesta da nielsen
		url = url.replace(/%2F/g,'/');
		$("#nielsen img").attr("src","//secure-it.imrworldwide.com/cgi-bin/m?ci=rainet-it&cg=0&si="+url);
};
function playMeNow (urlHtml){
	var urlXml = urlHtml.replace('.html','.xml');
	var dataP = new Date();
	var ggP, mmP, aaaaP;
	  ggP = dataP.getDate() + "-";
	  mmP = dataP.getMonth() + 1 + "-";
	  aaaaP = 1900+dataP.getYear();

	$.ajax({
		url: urlXml,
		cache: false,
		dataType : 'xml',
		success: function(xml){
			var videoUrl = $.trim($("url", $(xml)).text());
			var videoUrlH264 = $.trim($("videoUnit attributes attribute", $(xml)).filter(function(){return /h264/i.test($('key', this).text());}).find('value').text());
			playMe(videoUrl, false, videoUrlH264);
			setNielsen(location.href+'&video='+urlHtml+'&data='+ggP+mmP+aaaaP+'');
		}
	});
}

function playMe (videoUrl, useUniplayer, videoUrlH264){
	useUniplayer = !!useUniplayer;
	useUniplayer = true;

	var dataP = new Date();
	var ggP, mmP, aaaaP;
	  ggP = dataP.getDate() + "-";
	  mmP = dataP.getMonth() + 1 + "-";
	  aaaaP = 1900+dataP.getYear();
	var videoTit = $(".btn_attivo a p").text();

	if ( (isIpad || isIphone || isAndroid) ) {
		if (!!videoUrlH264) {
			if (false && $('#silverlightControlHost video').length > 0) {
				$('#silverlightControlHost video').attr('src', videoUrlH264);
			} else {
				$('#silverlightControlHost').html('');
				var altHtml = '<video width="320" height="260" src="'+videoUrlH264+'" controls autobuffer>';
				altHtml += '<source src="'+videoUrlH264+'" type="video/mp4" />';
				altHtml += '<h3>Video non ancora disponibile per dispositivi mobili</h3>';
				altHtml += '</video>';
				$('#silverlightControlHost').html(altHtml);
			}
		} else {
			altHtml = '<h3>Video non ancora disponibile per dispositivi mobili</h3>';
			$('#silverlightControlHost').html(altHtml);
		}
	} else {
		if (useUniplayer) {
			$('#silverlightControlHost').html('<object height="260" width="320" id="SilverlightControl" '+
					'data="data:application/x-silverlight," '+
					'type="application/x-silverlight">'+
					'<param value="transparent" name="background" />'+
					'<param value="true" name="windowless" />'+
					'<param value="/dl/objects/silverlight/uniplayer/Rai.UniPlayer.xap" name="source" />'+
					'<param value="configUri=/dl/objects/silverlight/uniplayer/Config.standard.xml,mediaUri='+videoUrl+',advertisingUri=,overrideConfig=type$Startup;autoPlay$true" name="initParams" />'+
					'<param value="25" name="maxFramerate" />'+
					'</object>');
		} else {
			//$('.titolo_edizioni p').text('Edizione '+videoTit);
			$('#silverlightControlHost').html('<object height="260" width="320" name="plugin" id="plugin" data="data:application/x-silverlight-2," type="application/x-silverlight-2"><param name="source" value="/dl/objects/silverlight/raitv/Lettore_Rai_VOD.xap"><param name="background" value="#0a0a0a"><param name="windowless" value="false"><param name="minRuntimeVersion" value="2.0.31005.0"><param name="autoUpgrade" value="true"><param name="enableHtmlAccess" value="true"><param name="initparams" value="videoPath='+videoUrl+',pathbanner=,auto=true,stlPath="><center style="color: black;"><a>Se vuoi visualizzare il video installa Microsoft Silverlight</a></center><a style="text-decoration: none;" href="http://go.microsoft.com/fwlink/?LinkID=124807"><img style="border-style: none;" alt="Installa Microsoft Silverlight" src="http://go.microsoft.com/fwlink/?LinkId=108181"></a></object>');
		}
	}


	setNielsen(location.href+'&video='+videoTit+'&data='+ggP+mmP+aaaaP+'');
}

function popMeNow(urlContent) {
	var urlPop = urlContent.replace('.html','-popup.html');
	setNielsen(location.href+'&video='+urlPop);
	var wid = window.open(urlPop,'tg3pop','top=40,left=40,toolbar=0,directories=0,menubar=0,status=0,resizable=0,statusbar=0,scrollbars=0,width=449,height=400');
	wid.focus();
}

function login() {}

function setCarouselVideo() {
	$.getScript("/dl/js/jquery/plugin/jcarousellite.pack.js", function(){
		$.getScript("/dl/js/jquery/plugin/jquery.easing.js", function(){
		var numberItem = $(".videoLista ul li").length;
		if(numberItem > 1) {
			$(".scroll_visti .videoLista").jCarouselLite({
				 auto: false,
				 btnNext: ".scroll_visti .next_video",
				 btnPrev: ".scroll_visti .prev_video",
				 speed: 1000,
				 visible: 4,
				 scroll: 1,
				 easing: "easeOutBack"
			});
		} else {
			$(".scroll_visti .next_video").css("visibility","hidden");
			$(".scroll_visti .prev_video").css("visibility","hidden");
			$(".scroll_visti .videoLista").css("visibility","visible");
		}
		});
	});
	if (!isIpad && !isIphone) {
		$(".box_scroll a[title]").tooltip('#videotip');
	}
}
function setTitoli() {
	$(".videobox_schede_titoli>DIV>a").click(function() {
		var idContente = $(this).attr('rel');
		var namecontent = $(this).text();
		$('.videobox_schede_titoli div a').removeClass('selected');
		$(this).addClass('selected');
		$('.elenco_titoli').hide();
	//	$('.elenco_titoli').attr('rel',''+idContente+'').show();
		$('div[rel='+idContente+']').show();
		/* SKIPPARE PRIMA ESECUZIONE NIELSEN*/
		if(skipNielsen != true) {
			setNielsen(location.href+'&sez='+namecontent);
		}
		skipNielsen = false;
		return false;
	});
}

var getTime = (function() {
        if (typeof(getServerTime) == 'function') {
            // debug('getTime returns SERVER time');
            return getServerTime;
        } else {
            // debug('getTime returns LOCAL time');
            return function() {
                return new Date();
            }
        }
    })();
var TG3IsLive = (function() {
    var forceLive = false;
    var dirette = [
        {from: '11:55', to: '12:35'},
        {from: '14:15', to: '14:50'},
        {from: '18:55', to: '19:35'}
    ];
    // eseguo il controllo solo la prima volta: se non esiste la funzione getServerTime, ritorno sempre l'ora locale


    return function() {
        if (forceLive === true) return true;
        var l = false;
        var d = getTime();
        var h = d.getHours();
        var m = d.getMinutes();
        var s = ((h<10)?'0':'')+h+':'+((m<10)?'0':'')+m;
	//	alert('s: '+s);
        for (var i=0; i<dirette.length; i++) {
            d = dirette[i];
		//	alert('d: '+d.from+'  --- dto:'+d.to);
            if ( s >= d.from && s < d.to) {
			//	alert('d: '+d.from+'  --- dto:'+d.to);
                l = true;
                break;
            }
        }
        return l;
    };
})(jQuery);

// la chiamata alla funzione TG3IsLive() restituisce ora true o false, in base all'ora corrente
// TG3IsLive()

var tg3_functions_loaded = false;
$(function() {

	if (tg3_functions_loaded) return;

$('.box_HeaderInterno #Data').html(formatDate(new Date(getDateFromFormat(jQuery.trim($('.box_HeaderInterno #Data').text()),"dd/MM/yyyy")),"EE dd MMM yyyy")).show();
var skipNielsen = true;
	$(".box_schede>div>a").click(function() {
		$(".box_schede>div").removeClass("videoSelected");
		$(this).parent().addClass("videoSelected");
		var uniqueName = $(this).attr("rel");
		if (uniqueName != 'stats'){
			var url = '/dl/tg3/multimedia/'+uniqueName+'.html';
		}
		else {
			var url = '/dl/tg3/statistiche/PiuVisti.html';
		}
		loadContents(url,".visti_votati");
		setNielsen(url);
		setCarouselVideo();
		return false;
	});
	$("UL.vis>LI").click(function() {
		if(!$(this).is('.selected')) {
			$("UL.vis>LI").removeClass("selected");
			$(this).addClass("selected");

			if($(".listaVideoLista, .listaVideo").is('.listaVideoLista')) {
				if($(".listaVideoLista, .listaVideo").is(".listaStretta"))
				{
					$(".listaVideoLista").attr("class", "listaVideo iconeStrette");
				} else {
					$(".listaVideoLista").attr("class", "listaVideo");
				}

			} else {
				if($(".listaVideoLista, .listaVideo").is(".iconeStrette")){
					$(".listaVideo").attr("class", "listaVideoLista listaStretta");
				} else {
					$(".listaVideo").attr("class", "listaVideoLista");
				}
			}
		}
		return false;
	});

	$(".pulsanti_player>div>a").click(function() {
		$(".pulsanti_player .btn_attivo").removeClass("btn_attivo").addClass("btn_inattivo");
		$(this).parent().addClass("btn_attivo").removeClass("btn_inattivo");
		/*
		var videoTit = $(".btn_attivo a p").text();
		$('.titolo_edizioni p').text('Edizione '+videoTit);
		*/
		return false;
	});

	setCarouselVideo();
	setTitoli();
	if (!isIpad && !isIphone) {
		$("div.video_boxino a[title]").tooltip('#dailytip');
	}
	try {
		checkLive();
	} catch (pincoPallino) {
	}
	$(".videobox_schede_titoli>DIV>a:eq(0)").click();

	/*sciopero*/
	var sio = getTime();
	var scioStart = new Date(2010, 6, 9, 06, 00, 00, 00);
	var scioStop = new Date(2010, 6, 10, 06, 00, 00, 00);

	if((sio>scioStart) && (sio<scioStop)){
		$('#tlvdNews').hide();
	}
		/*sciopero*/

	//$('#pane').jScrollPane({showArrows:false, scrollbarWidth:16 });
	//$('#paneVideo').jScrollPane({showArrows:false, scrollbarWidth:16 });
});

function checkLive() {
	if(TG3IsLive() && !(isIpad || isIphone)) {
		$('.titolo_edizioni p').text('TG3 LIVE');
		// playMe('http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=986', true);
		playMe('http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=180117', true);
	} else {
		$('.titolo_edizioni p').text('Multimedia');
	}
}
function initRss(){
	var params = {
		src:  "http://www.televideo.rai.it/televideo/pub/rss101.xml",
		utf:  "y",
		targ: "y",
		tz:   "+1",
		date: "y",
		num: "10",
		desc: "1"
	};

	var callback = function() {
		$('li.rss-item').each(function(){
			var tt = $('a.rss-item', this).text();
			var hr = $('a.rss-item', this).attr('href');
			var dt = $('span.rss-date', this).text();
			$(this).html('<a class="rss-item" href="'+hr+'"><span class="rss-date">'+dt+' </span>'+tt+'</a>')
			//$($(">br:eq(1)",this)[0].nextSibling).wrap('<span class="ccissDesc" style="display:none"></span>')
		});
		$("span.rss-date").each(function(){
			$(this).html($(this).html().substring(11)).show();
		});
		$("a.rss-item").each(function(){
			$(this).attr("href","http://www.televideo.rai.it/televideo/pub/"+$(this).attr("href"));
		});
		if ($.browser.msie && $.browser.version < 7) {

		} else {

		}
	};

	function getUniqueName() {
		var t = new Date();
		t = t.getTime();
		var r = Math.floor(Math.random()*997);
		var baseName = 'feed_';
		var fname = baseName+t+r;
		while (typeof(window[fname]) != 'undefined') {
			r = Math.floor(Math.random()*997);;
			fname = baseName+''+t+''+r;
		}
		return fname;
	};

	var uName = getUniqueName();
	var obj = {};
	obj.feed = [];
	obj.render = function() {
		var html = obj.feed.join('');
		try {
			$("div.rss-box").html(html);
		} catch(e) {
			$("div.rss-box").replaceWith(html);
		}
		if (callback) {
			if (typeof(callback) == 'string' && typeof(window[callback]) == 'function') {
				window[callback].apply($("div.rss-box")[0]);
			} else if (typeof(callback) == 'function') {
				callback.apply($("div.rss-box")[0]);
			}
		}
	};
	obj.init = function() {obj.feed = [];};

	window[uName] = obj;


	var myParams = {
		initFunction: uName+'.init();',
		outputFunction: uName+'.feed.push',
		callbackFunction: uName+'.render();'
	}

	params = $.extend({}, params, myParams);

	var p = $.param(params);

	var url = 'http://www.feed.rai.it/async_feed.php?'+p;
	$.getScript(url);
};
