$(document).ready(function(){
	var cookie = $.cookie("style");
	if(cookie!= null){
		setActiveStyleSheet(cookie);
	} else {
		setActiveStyleSheet("small");
	}

	//print page
	if (document.location.href.indexOf("print") > -1) {
		window.print();
	}

	$(window).unload( function(){ 
		var title = getActiveStyleSheet();
		$.cookie("style", title,{expires: 365});
	});
	
	
	if ($('#page_ita').length > 0){
		var pageurl = ''+document.location;
		if( pageurl.indexOf("_en.") >= 0){
			var newpageurl = pageurl.replace('_en','_it');
			$('#page_ita a').attr('href',newpageurl);
		}			
		else
			$('#page_ita a').attr('href',document.location);	
		
	};
	
	if ($('#page_eng').length > 0){
		var pageurl = ''+document.location;
		if( pageurl.indexOf("_it.") >= 0){
			var newpageurl = pageurl.replace('_it','_en');
			$('#page_eng a').attr('href',newpageurl);		
		}			
		else
			$('#page_eng a').attr('href',document.location);	
		
	};	
	
	

	if ($('#tickerTgcom').length > 0){
		
		$(document).trigger('loadUltimissimeTgcom');
		
	};


	if ($('#tickerMediaset').length > 0){
		
		$.ajax({
	    		type: "GET",
	    		url: "/investor/dati/quotazione_flash.xml",
	    		dataType: "xml",
	    		success: function(xml) {
	    		
	    			$(xml).find("DATO").each(function(){
	    				var pageurl = ''+document.location;
					if( pageurl.indexOf("_en.") >= 0)
    						$("ul#ticker02").append($('<li><p class="news">'+$(this).attr("EN")+' '+' '+$(this).attr("VALUE")+' </p></li>'));
    					else
    						$("ul#ticker02").append($('<li><p class="news">'+$(this).attr("IT")+' '+' '+$(this).attr("VALUE")+' </p></li>'));
  				});
  				
  				//$("ul#ticker02").liScroll();
  				$(function(){$("ul#ticker02").liScroll();
				});
	    		}
	  	});

	};


	if ($('#datepickerEvents').length > 0){
		initCalendary(lang);
	};

	if ($('.tabs').length > 0){
		var tabContainers = $('div.tabs > div');
		tabContainers.hide().filter(':first').show();
                        
		$('div.tabs ul.tabNavigation a').click(function () {
			tabContainers.hide();
			tabContainers.filter(this.hash).show();
			$('div.tabs ul.tabNavigation a').removeClass('selected');
			$(this).addClass('selected');
			return false;
		}).filter(':first').click();
	};
	

	
	
	if ($('.searchyear').length > 0){
		var pageurl = ''+document.location;
		var currentyear = pageurl.substr((pageurl.indexOf("/salastampa/")+12),4)
		$('#combo-year option').each(function(i) {
			if($(this).attr('value')!=''){
				$('#combo-year').change(function(e) {
					var newyear = $(this).attr('value');
		
					var newpageurl = pageurl.replace(currentyear,newyear);
					
					if(newpageurl.indexOf("?") >= 0){
						newpageurl = newpageurl.substring(0,newpageurl.indexOf("?"))
					}
					document.location = newpageurl
				});	
			}
		})
	
	};
});


$(document)
	.bind('loadUltimissimeTgcom', function(evt) {	
		
		
			$.getJSON("http://www.tgcom24.mediaset.it/ultimissima/ultimissime.sjson?callback=?", function(data)        
		        {
		        	var numnews = 3;
		        	try
		          	{
					$.each(data.RECORD,function(i,news) {
				
					if (i >= numnews) return;		
		        		var title = news.TITOLO;
					var data = news.DATA;
					var ora = news.ORA;
					var sezione = news.SEZIONE;
					var idarticolo = news.IDARTICOLO;
					var link = 'http://www.tgcom24.mediaset.it/'+sezione+'/articoli/articolo'+idarticolo+'.shtml';
				
					$("ul#ticker01").append($('<li><p class="news"><strong>'+ora+' - '+sezione+'</strong> <a href="'+link+'" target="_blank">'+title+'</a></p></li>'));
					
					
				});
				//$("ul#ticker01").liScroll();
$(function(){$("ul#ticker01").liScroll();
});
				}
				catch(er){
	                		alert(er.message);
	  	  		}
			})	
	})

	


//accessibility
/*window.onload = function(e) {
	var cookie = readCookie("style");
	if (cookie && cookie != "null") {
		setActiveStyleSheet(cookie);
	} else {
		setActiveStyleSheet("small");
	}
	//print page
	if (document.location.href.indexOf("print") > -1) {
		window.print();
	}
}*/

/*window.onunload = function(e) {
	var title = getActiveStyleSheet();
	createCookie("style", title, 365);
}*/


function setActiveStyleSheet(title) {
	var i, a, main;
	for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
		if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if (a.getAttribute("title") == title) a.disabled = false;
		}
	}
}

function getActiveStyleSheet() {
	var i, a;
	for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
		if (a.getAttribute("rel").indexOf("style") != -1
			&& a.getAttribute("title") && !a.disabled
		) return a.getAttribute("title");
	}
	return null;
}

function getPreferredStyleSheet() {
	var i, a;
	for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
		if (a.getAttribute("rel").indexOf("style") != -1
			&& a.getAttribute("rel").indexOf("alt") == -1
			&& a.getAttribute("title")
		) return a.getAttribute("title");
	}
	return null;
}

/*function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else expires = "";
	document.cookie = name+ "=" + value + expires + "; path=/";
}*/

/*function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}*/

//menu hiligtht
function litMenu(menuId) {
	itemLi = document.getElementById("m" + menuId);
	if (itemLi != null) itemLi.className = "menuon";
}

//home flash
function homeFlash() {
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="792" height="312">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="movie" value="res/swf/homeco.swf" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="FlashVars" value="&xml_url=res/xml/imghome.xml&" />');
	document.write('<embed allowScriptAccess="sameDomain" src="res/swf/homeco.swf" Flashvars="&xml_url=res/xml/imghome.xml&" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="792" height="312"></embed>');
	document.write('</object>');
}

/* service */
function readUrl(param){
	var theurl=window.location.toString()+"&";
	var posparam=theurl.indexOf(param+"=");
	if(posparam==-1)return"";
	var sottostringa=theurl.substring(posparam);
	var start=sottostringa.indexOf("=");
	var end=sottostringa.indexOf("&");
	var val=sottostringa.substring(start+1,end);
	return val;

}


/* start ricerca mediaset */
function checkKeywordES() {
  var theObj = document.ricerca_mediaset.q;
  if (tokES(theObj)) document.forms['ricerca_mediaset'].submit(); 	
}

function checkKeywordES_c() {
  var theObj = document.ricerca_comunicati.q;
  if (tokES(theObj)) document.forms['ricerca_comunicati'].submit(); 
}
 
function tokES(theObj){
 	var ALPHANUMERICS = "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890אטילעש";
 	var text=theObj.value+" ";
 	var pos,pos1=0;
 	var finale,word,ch=" ";
 	var find=true;
 	var fword=false;
 	for(var i=0;i<text.length;i++){
 		ch=text.charAt(i);
 		if(ch==" "){
 			if(find!=true){
 				find=true;
 				pos1=i;
 				word=text.substring(pos,pos1);
 				if(word.substring(0,1)==" ")word=word.substring(1,word.length);
 				var wU=word.toUpperCase();
 				if(wU=="AND"||wU=="OR"||wU=="NOT"){
 						alert("La parola ' "+wU+" ' non ט ammessa");
 					theObj.focus();
 					return false;
 				}
 				pos=pos1;
 				if(fword==false){
 					finale=word;
 					fword=true;
 				}else
 					finale=finale+" "+word;
 			}else
 				pos=i+1;
 			}else{
 				if(ALPHANUMERICS.indexOf(ch)==-1){
 					alert("Il carattere ' "+ch+" ' non ט ammesso");
 				theObj.focus();
 				return false;
 			}
 			find=false;
 			}//end if
 	}//end for
 	if(fword==false){ 	
 		alert("Inserisci la/e parola/e che vuoi ricercare!");
 		theObj.value="";
 		theObj.focus();
 		return false;
 	}
 	theObj.value=finale;
 	return true;
}
/* end ricerca mediaset */


function sendURLByEmail(lang){
	
	var pTitle = document.title;
	var pUrl = document.location.href;
	var head = (lang == 'en') ? "Please check the page at the following address:\n" : "Ti segnalo la pagina all'indirizzo:\n";
	var foot = (lang == 'en') ? "Mediaset Group - Corporate\nhttp://www.mediaset.it/corporate/home_en.shtml" : "Gruppo Mediaset - L'Azienda\nhttp://www.mediaset.it/corporate/home_it.shtml";
	var subj = escape(pTitle);
	var body = escape(head + pUrl + "\n\n=========================\n" + foot);
	
	window.open("mailto:?subject=" + subj + "&body=" + body, "sendmail");
	
}



/* send page by email */
function sendByEmail(lang){
	/*
	var pTitle = document.title;
	var pUrl = document.location.href;
	var head = (lang == 'en') ? "Please check the page at the following address:\n" : "Ti segnalo la pagina all'indirizzo:\n";
	var foot = (lang == 'en') ? "Mediaset Group - Corporate\nhttp://www.mediaset.it/corporate/home_en.shtml" : "Gruppo Mediaset - L'Azienda\nhttp://www.mediaset.it/corporate/home_it.shtml";
	var subj = escape(pTitle);
	var body = escape(head + pUrl + "\n\n=========================\n" + foot);
	var sendmail = window.open("mailto:?subject=" + subj + "&body=" + body, "sendmail");
	*/
	var sendmail = window.open("mailto:mediaset@mediaset.it", "sendmail");
}

/* print page */
if (document.location.href.indexOf('print') > -1) {
	document.write('<link rel="stylesheet" type="text/css" href="/corporate/res/css/print.css">');
}

function printPage(){
	var pUrl = document.location.href;
	if (pUrl.indexOf('?') > -1) pUrl = pUrl.substring(0, pUrl.indexOf('?'));
	window.open(pUrl + "?print").focus();
}

/* add to favorites */
function addToFavorites(lang) {
	if (document.all) {
			window.external.AddFavorite(document.location.href, document.title); // Internet Explorer
	} else if (window.sidebar) {
			window.sidebar.addPanel(document.title, document.location.href, ""); // Mozilla Firefox
	} else if (navigator.appName == "Netscape") {
		if (lang == 'en') {
			alert("Puoi aggiungere la pagina all\'elenco dei \'Preferiti\' premendo i tasti CTRL+D");
		} else {
			alert("You can add this page to your \'Favorites\' with the key sequence CTRL+D");
		}			
	}
}

/* popup photos */
function imgpopup(foto, w, h){
	var param = foto.href.substr(foto.href.indexOf('/bin/') + 5);
	var settings = 'location=no,directories=no,menubar=no,toolbar=no,status=no,scrollbars=yes,resizable=yes,fullscreen=no';
	//var w = 320; var h = 240;
	var x = (screen.width - w) / 2;
	var y = (screen.Height - h) / 2 - 20;
	if (x < 0) x = 0; if (y < 0) y = 0;
	//if (w > screen.width) w = screen.width;	if (h > screen.height) h = screen.height;
	var psettings = 'top=' + y + ',left=' + x + ',width=' + w + ',height=' + h + ',' + settings;
	window.open('/corporate/res/html/imgpopup.shtml?' + param, 'foto', psettings).focus();
	return false;
}
