var CONFIG_XML 	= '/res/xml/config.xml';
var FROM = 'iene';
var idboxapertura = 1;


/* ~~~~~~~~~~~~Utils functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function tokenReplace(str, tokens) {
	for ( var t in tokens ) {
		str = str.replace('{' + t + '}', tokens[t]);
	}
	return str;
}

function trimDot(str, len) {
	return ( str.length > len ? str.substring(0, len - 3) + '...' : str );
}

function ShowHide(){
	$("#menuall").animate({"height": "toggle"}, { duration: 700 });
}

var _GET = (function() {
				var get = {};
				var vars = window.location.search.substring(1).split('&');
				for ( var v in vars ) {
					var pair = vars[v].split('=');
					get[ pair[0] ] = pair[1];
				}
				return get;
})();
function getVars() {
	return _GET;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
$(function() {
	var config = {};
	$.ajax({
		url: 		CONFIG_XML,
		dataType: 	'xml',
		error: 		function() {
		},
		success: 	function(xml) {
				$('param', xml).each(function() {
					config[ $(this).attr('key') ] = $(this).text();
				});



				/*
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Disegna la data nell'header
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/
				if ($('.dataora').length > 0){
						var param = $('.dataora').attr('id').split("-");
						var divid = '#'+$('.dataora').attr('id');
						var dayweek = DayWeek(param[0]);
						var day = param[1];
						day = (day.substr(0,1) == 0)? day.substr(1,1) : day;
						var month = Month(param[2]);
						var year = param[3];
						var hour = param[4];
						var minute = param[5];
						$(divid)
							.append( $(	'<span>'+dayweek+', '+day+'  '+month+'</span>'));
						
				}
				/*
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Usate nella homepage:
					carica i contenuti video nell'oggetto tab
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/
				//Video più visti LE IENE
				if ($('#tabvtv_2').length > 0){$(document).trigger('loadTabContentVisti',['#tabvtv_2'])
				if ($('#tabvtv_3').length > 0) $(document).trigger('loadTabContent',['#tabvtv_3','speciali']);
				if ($('#tabvtv_4').length > 0) $(document).trigger('loadTabContent',['#tabvtv_4','interviste']);
				}
				/* 
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Attive le voci del Sottomenu
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
				if ($('#cont-left').length > 0){
					$(document).trigger('activeSubMenu');
				}
				/*
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Invia ad un amico
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/
				if($('#artinvia').length > 0){
					$(document).trigger('inviaAmico');
				}
				/*	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Stampa Articolo
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/				
				if($('#artstampa').length > 0){
					$(document).trigger('stampaArticolo');
				}
				/*	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Setta il font dell'articolo
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/
				if($('#header_articolo').length > 0){
					setFontSize();
				}
				if ($('#apertura').length > 0){
					setInterval("refreshApertura(idboxapertura++)", 5000);
				}
				/*	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Disegna randomicamente le foto nel widget
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/
				if($('#widget').length > 0){
					$(document).trigger('drawImgWidget');
					if ($('.ajaxwidget').length > 0){
						$('.ajaxwidget').each(function(i) {
							var widget = $(this).attr('id').split("-");
							var id_li = '#'+$(this).attr('id');
							var widgetarray = widget[0]+'_widget';
							var widgetnum = widget[1];
							var widgetsite = widget[2];
							$(document).trigger('drawWidgetItem',[id_li,widgetarray,widgetnum,widgetsite]);
						})
					}
					/* Gestione del widget automatico */
					$('.widget_button').each(function(i) {
						$(this).bind('click', function(e) {
							var itemid = '#'+$(this).parent().attr('id');
							if($(this).hasClass('piu')){
								
								$('.meno').each(function(j){
										$(this).removeClass('meno');
										$(this).addClass('piu');
										var itemidall = '#'+$(this).parent().attr('id');
										$(itemidall+' p').css('display','none');
								})
								$(this).removeClass('widget_button piu');
								$(this).addClass('widget_button meno');
								$(itemid+' p').css('display','block');
							}
							else{
								$(itemid+' p').css('display','none');
								$(this).removeClass('widget_button meno');
								$(this).addClass('widget_button piu');
							}
						});
					});
				}

				$('div.videoThumbnail').hover(function() {$('div', this).css('display', 'block');}, function() {$('div', this).css('display', '');});

				/*
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/					
		}
	});


	function makeRequest(type, data, callback, err) {
		var url = tokenReplace( ( config[ type ] == undefined ? type : config[ type ] ), data);
		$.ajax({
			cache: 		false,
			url: 		url,
			dataType: 	'xml',
			data: 		data,
			success: 	callback,
			error: 		$.isFunction(err) ? err : function(XMLHttpRequest, textStatus, errorThrown) {
				//alert('Ajax Error: [' + textStatus + '], [' + errorThrown + ']');
			}
		});
	}
	function getVideoURL(videoId, category, from) {
		var p = videoId.split('/');
		var data = {
			sito: 		p[0],
			data: 		p[1] + '/' + p[2] + '/' + p[3],
			id: 		p[4],
			'category': category,
			'from': 	from
		};
		return tokenReplace( config['url_video'], data );
	}	 

	$(document)		
		.bind('loadTabContentVisti',  function(evt, tabname) {
			makeRequest('url_xml', '', function(xml) {
			var videos 	= $('result > record', xml);
			var videonum = videos.length;			
			videos
				.each(function(i) {
					var id = $('> ID', this).text();
					var title = $('> TITOLO', this).text();
					var date = $('> DATA', this).text();
					var description = $('> DESC_BREVE', this).text();
					var image = $('> THUMBNAIL', this).text();
					var link = $('> URL', this).text();

					$(tabname)
						.append( $('<div class="box90x130">' +
							'<div class="boxplay80x60">' +
								'<div class="videoThumbnail">' +
									'<a href="http://www.video.mediaset.it' + link + '.html">' +
										'<img src="http://www.video.mediaset.it/images/318' + image + '" width="120" height="90"/>' +	
										'<div class="videoOverlay" style="">' +description + '</div>' +
									'</a>' +
								'</div>' +
							'</div>' +
							'<h4>' +
								'<a href="http://www.video.mediaset.it' + link + '.html">' + title + '</a>' +
							'</h4>' +
							'<p>' + date + '</p>' +
						'</div>'));
				});
				$(tabname)
					.append( $('<div id="altrivideo">' +
						'<a class="link_ReadOther" href="http://www.video.mediaset.it/programma/iene/le-iene.html">Tutti i video</a>' +
					'</div>'));
			});
		})
		.bind('loadTabContent', function(evt, tabname, category) {
			makeRequest('url_xmlvideo', { 'category': category} , function(xml) {
			var videos 	= $('category-content > video-summary', xml);
			var videonum = videos.length;
			videos
				.each(function(i) {
					var link = $(this).attr('url');
					var title = $('> title', this).text();
					var date = $('> date', this).text();
					var description = $('> description', this).text();
					var image = $('> image', this).text();
					$(tabname)
						.append( $('<div class="box90x130">' +
							'<div class="boxplay80x60">' +
								'<div class="videoThumbnail">' +
									'<a href="' + link + '">' +
										'<img src="http://www.video.mediaset.it/' + image + '" width="120" height="90"/>' +	
										'<div class="videoOverlay" style="">' +description + '</div>' +
									'</a>' +
								'</div>' +
							'</div>' +
							'<h4>' +
								'<a href="' + link + '">' + title + '</a>' +
							'</h4>' +
							'<p>' + date + '</p>' +
						'</div>'));
				});
				$(tabname)
					.append( $('<div id="altrivideo">' +
						'<a class="link_ReadOther" href="http://www.video.mediaset.it/programma/iene/le-iene.html">Tutti i video</a>' +
					'</div>'));
			});
		})
		.bind('drawImgWidget', function() {
			var src_foto1 = mondo_tv_widget['img1'];
			var src_foto2 = mondo_tv_widget['img2'];
			var src_foto3 = mondo_tv_widget['img3'];

			var round1 = Math.round(Math.random() * 100) % 3;
			var round2 = Math.round(Math.random() * 100) % 2;
			var src_foto = '';

			if ( (src_foto1 != '/') && (src_foto2 != '/') && (src_foto3 != '/') )
			{
				if (round1 == 0) 		src_foto=src_foto1;
				else if (round1 == 1)	src_foto=src_foto2;
				else if (round1 == 2)	src_foto=src_foto3;
			}
			else if ( (src_foto1 != '/') && (src_foto2 != '/') && (src_foto3 = '/'))
			{
				if (round2 == 0)		src_foto=src_foto1;
				else if (round2 == 1)	src_foto=src_foto2;
			}
			else	src_foto=src_foto1;

			$('#wmain > div > div > a')
				.append( $(	'<img width="195" height="147" src="'+src_foto+'"></img>'))
		})
		.bind('drawWidgetItem', function(evt, id_li, widgetarray, widgetnum, widgetsite) {
			var logo = (widgetsite=='tgcom'||widgetsite=='sportmediaset')? 'news' : 'video';
			var news = 'news'+widgetnum;
			var occhiello = (widgetsite=='tgcom'||widgetsite=='sportmediaset')? widgetsite+' - '+eval(widgetarray)[news]['sezione'] : eval(widgetarray)[news]['sezione'];
			$(id_li)
				.append( $('<div class=\'widget_button piu\'><span>widget_button</span></div><h4 class=\'uppercase\'>'+occhiello+'</h4><h3 class=\''+logo+'\'><a href="'+eval(widgetarray)[news]['link']+'">'+eval(widgetarray)[news]['titolo']+'</a></h3><p>'+eval(widgetarray)[news]['catenaccio']+'</p>'))
		})
		.bind('inviaAmico', function() {
			//var tit = $('#txtspace > h1').text();
			var tit = document.title;
			var domaininvia='www.grandefratello.mediaset.it';
			var urlinvia=document.location.href;
			var subjPrefix="Articolo su "+domaininvia+": ";
			var bodyPrefix="\n\n Puoi trovare questo articolo all'indirizzo:\n";
			var subj=escape(tit);
			//var subj=escape(subjPrefix+tit);
			var body=escape('Da Grande Fratello '+urlinvia);
			//var body=escape('Articolo su www.tv.mediaset.it: "'+tit+'"'+bodyPrefix+urlinvia);
			//alert($('#artinvia > a').attr('href'))
			var mail =  'mailto:?subject='+subj+'&body='+body;
			$('#artinvia > a')
				.attr('href', mail);
		})
		.bind('stampaArticolo', function() {
			var id = $('#container').attr('class');
			var urlstampa = 'javascript:anteprima(\''+id+'\')';
			$('#artstampa > a')
				.attr('href', urlstampa);

		})
		
		.bind('activeSubMenu', function() {
			var submenu = $('#cont-left').attr('class');
			var contentmenu = submenu.substr(4);
			//alert(contentmenu);
			var divsubmenu = '#containersm > ul > li > a.menu-'+contentmenu;
			var submenuclass = $(divsubmenu).attr('class')+' active';
				$(divsubmenu)
					.attr('class', submenuclass);	
			
			/*if(submenu == 'sub_news'){
				var submenuclass = $('#containersm > ul > li > a.menu-news').attr('class')+' active';
				$('#containersm > ul > li > a.menu-news')
					.attr('class', submenuclass);	
			}
			else if(submenu == 'sub_sondaggi'){
				var submenuclass = $('#containersm > ul > li > a.menu-sondaggi').attr('class')+' active';
				$('#containersm > ul > li > a.menu-sondaggi')
					.attr('class', submenuclass);	
			}
			else if(submenu == 'sub_personaggi'){
				var submenuclass = $('#containersm > ul > li > a.menu-personaggi').attr('class')+' active';
				$('#containersm > ul > li > a.menu-personaggi')
					.attr('class', submenuclass);	
			}			
			else if(submenu == 'sub_protagonisti'){
				var submenuclass = $('#containersm > ul > li > a.menu-protagonisti').attr('class')+' active';
				$('#containersm > ul > li > a.menu-protagonisti')
					.attr('class', submenuclass);	
			}*/
		})
	
});

/* ~~~~~~~~~~~~Gestione della data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function DayWeek(dayweek){
  switch (dayweek) {
  case 'Monday': 	return 'luned&igrave;';
  case 'Tuesday': 	return 'marted&igrave;';
  case 'Wednesday': return 'mercoled&igrave;';
  case 'Thursday':	return 'gioved&igrave;';
  case 'Friday': 	return 'venerd&igrave;';
  case 'Saturday': 	return 'sabato';
  case 'Sunday': 	return 'domenica';
  }
}
function Month(month){
  switch (month) {
  case '01': return 'gennaio';
  case '02': return 'febbraio';
  case '03': return 'marzo';
  case '04': return 'aprile';
  case '05': return 'maggio';
  case '06': return 'giugno';
  case '07': return 'luglio';
  case '08': return 'agosto';
  case '09': return 'settembre';
  case '10': return 'ottobre';
  case '11': return 'novembre';
  case '12': return 'dicembre';
  }
}
/* ~~~~~~~~~Anteprima di stampa~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function anteprima(id){
	var w=705;
	var h=530;
	var parts = id.split("-");
	var contentid = parts[0];
	var contenttype = parts[1];
	var settings = 'location=no,directories=no,menubar=no,toolbar=no,status=no,scrollbars=yes,resizable=no,fullscreen=no,top=10,left=10,width='+w+',height='+h;
	var url = document.location.href;
	if (contenttype=='personaggio') {
		var popup=window.open('/res/html/stampapopup.shtml?/personaggio/stampa/personaggio-stampa-'+contentid+'.shtml','stampa',settings);
	} else  {
		var popup=window.open('/res/html/stampapopup.shtml?/articoli/stampa/'+contentid+'.shtml','stampa',settings);
	}
	if(popup != null) popup.focus();
}
/* ~~~~~~~~~Stampa~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function stampa(){
	print();
	window.close ();
}
/* ~~~~~~~~~Ricerca di yahoo: controllo del testo da cercare~~~~~~~~~~~*/

function cerca() {
		obj = document.ricercayahoo;
		var val = obj.p.value;
		if(val.length>0){
			return true;
		} else {
			alert('Inserire il testo da cercare'); 	return false;
		}
}


/* ~~~~~~~~~Dimensione font articoli~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function setFontSize() {	
	setActiveStyleSheet('small');
	/*var q = location.search.split('=');
	if (q.length > 1){
	
		setActiveStyleSheet(q[1]);
	}
	else{
	
		setActiveStyleSheet('small');
	}*/
}

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")) {
			if (a.getAttribute("title") != "style") a.disabled = true;
			if (a.getAttribute("title") == title) a.disabled = false;
		}
	}
	fontSize_= title;
}

/* ~~~~~~~~~Rotazione boxlancio nella index ~~~~~~~~~~~~~~~~*/
function refreshApertura(idboxapertura){
	var id;

	if ($('#start1').length > 0 && $('#start2').length > 0 && $('#start3').length > 0)
	{
		id = (idboxapertura % 3);
		if(id==0) id=3;

		document.getElementById("start1").style.display='none';
		document.getElementById("start2").style.display='none';
		document.getElementById("start3").style.display='none';
	} else if ($('#start1').length > 0 && $('#start2').length > 0 )
		{
			id = (idboxapertura % 2);
			if(id==0) id=2;

			document.getElementById("start1").style.display='none';
			document.getElementById("start2").style.display='none';
		}
		else if ($('#start1').length > 0){
			id=1;
			document.getElementById("start1").style.display='block';
		}
	
	var current = document.getElementById("start"+id);
	current.style.display='block';
}

/* ricerca mediaset */
function checkKeywordES() {
  var theObj = document.ricerca_mediaset.q;
  if (tokES(theObj)) document.ricerca_mediaset.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;
}
