var CONFIG_XML 	= '/res/xml/config.xml';
var config = {};
var FROM = 'mediaset';
var idbox = 1;
var idboxvideo = 1;
var elencoVisualizzato;
var TIMEOUTAPERTURAHP = 7000;
var timerAperturaHP;

/* ~~~~~~~~~~~~Utils functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
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) {
		}
	});
}

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 );
}

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 initApertura() {
	$.ajax({
		url: 		CONFIG_XML,
		dataType: 	'xml',
		error: 		function() {
		},
		success: 	function(xml) {
				$('param', xml).each(function() {
					config[ $(this).attr('key') ] = $(this).text();
				});
				/*
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
					Carica i contenuti video
					~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				*/
				if ($('#apertura').length > 0) {
					$(document).trigger('loadStart');
				}
		}
	});

	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('loadStart', function(evt) {
			makeRequest('url_xml', '', function(xml) {
				var videos = $('category-content', xml).children();
				var videonum = videos.length;
				videos
					.each(function(i) {
						var isvideo = $(this).is('video-summary');
						var id = isvideo ? $(this).attr('id') : '';
						var title = $('> title', this).text();
						var program = $('> program', this).text();
						var program_id = isvideo ? $('> program', this).attr('category-id') : '';
						var description = $('> description', this).text();
						var imagebig = tokenReplace( config['url_foto'] , { foto: $('> imagebig', this).text() } );
						var image = tokenReplace( config['url_foto'] , { foto: $('> image', this).text() } );
						var link = isvideo ? getVideoURL(id, program_id, FROM) : $('> link', this).text();;
						var style1 = (i == 0) ?	'display:block;' : 'display:none;';
						var style2 = (i == 0) ? 'videoApp over' :'videoApp';

						$('#apertura')
							.append( $('<div id="start' + (i+1) + '" style="' + style1 + '">' +
								'<div id="fotoContent">' +
									'<a href="' + link + '">' +
										'<img src="' + imagebig + '"/>' +
									'</a>' +
								'</div>' +
								'<div id="videoDetailBack">' +
								'</div>' +
								'<div id="videoDetail">' +
								'<a href="' + link + '">' +
									'<h3>' + title + '</h3>' +
									'<h3 class="program">' + program + '</h3>' +
									'<p>' + description + '</p>' +
								'</a>' +
								'</div>' +
							'</div>'));
						$('#areaTreVideo')
							.append( $('<div class="' + style2 + '" id="briciola' + (i+1) + '" onmouseover="javascript:refreshApertura(' + (i+1) + ')">' +
								'<div class="videoContent over">' +
								'<a href="' + link + '">' +
								'<img src="' + image + '" width="94" height="70">' +
								'</a>' +
								'<h2>' +
								'<a href="' + link + '">' + trimDot(title, 17) +
								'</a>' +
								'</h2>' +
								'<p>' + trimDot(description, 50) + '</p>' +
								(isvideo ? '<a href="' + link + '">' : '') +
								'<span>&nbsp;</span>' +
								'</a>' +
								'</div>' +
								'</div>'));
					});
				setInterval("refreshApertura(idboxvideo++)", 7000);
			});
		});
		
}

$(function() {
	
	$(document)
		.bind('loadOraInOnda', function(evt, divid, network, timestamp) {
			makeRequest('url_palinsesto', '', function(xml) {

			if(network=='C5') network='Canale 5';
			else if(network=='I1') network='Italia 1';
			else if(network=='R4') network='Rete 4';

			var programs = $('programmi > programma', xml);
			var titoloR4 ='';
			var oraR4 = '';
			var titoloI1 ='';
			var oraI1 = '';
			var titoloC5 ='';
			var oraC5 = '';
			var titoloR4next ='';
			var oraR4next = '';
			var titoloI1next ='';
			var oraI1next = '';
			var titoloC5next ='';
			var oraC5next = '';
			programs
				.each(function(i) {
					var time = eval($(this).attr('timestamp'));
						if(timestamp>=time && $(this).attr('idref')=='C5'){
							titoloC5 = $(this).attr('titolo');
							oraC5 = $(this).attr('ora');
						}
						else if($(this).attr('idref')=='C5'){
							titoloC5next = $(this).attr('titolo');
							oraC5next = $(this).attr('ora');
							return false;
						}
				});
			programs
				.each(function(i) {
					var time = eval($(this).attr('timestamp'));
						if(timestamp>=time && $(this).attr('idref')=='I1'){
							titoloI1 = $(this).attr('titolo');
							oraI1 = $(this).attr('ora');
						}
						else if($(this).attr('idref')=='I1'){
							titoloI1next = $(this).attr('titolo');
							oraI1next = $(this).attr('ora');
							return false;
						}
				});
			programs
				.each(function(i) {
					var time = eval($(this).attr('timestamp'));
						if(timestamp>=time && $(this).attr('idref')=='R4'){
							titoloR4 = $(this).attr('titolo');
							oraR4 = $(this).attr('ora');
						}
						else if($(this).attr('idref')=='R4'){
							titoloR4next = $(this).attr('titolo');
							oraR4next = $(this).attr('ora');
							return false;
						}
				});
				$(divid)
					.append( $(	'<div id=\'ultimaora1\'><strong>'+oraC5+' - CANALE 5 -</strong><span>'+titoloC5+'</span></div>'+
								'<div id=\'ultimaora2\'><strong>'+oraI1+' - ITALIA 1 -</strong><span>'+titoloI1+'</span></div>'+
								'<div id=\'ultimaora3\'><strong>'+oraR4+' - RETE 4 -</strong><span>'+titoloR4+'</span></div>'));

				setInterval("rotateUltimaora(idbox++)", 5000);

				if ($('#orainondaC5').length > 0){
					if(titoloC5!=''){
						$('#orainondaC5')
							.append( $(	'<li><span class="txt_Time">Ore '+oraC5+'</span><span class="txt_Title">'+titoloC5+'</span></li>'));
					}
					if(titoloC5next!=''){
						$('#orainondaC5')
							.append( $(	'<li><span class="txt_Time">Ore '+oraC5next+'</span><span class="txt_Title">'+titoloC5next+'</span></li>'));
					}
				}

				if ($('#orainondaI1').length > 0){
					if(titoloI1!=''){
						$('#orainondaI1')
							.append( $(	'<li><span class="txt_Time">Ore '+oraI1+'</span><span class="txt_Title">'+titoloI1+'</span></li>'));
					}
					if(titoloI1next!=''){
						$('#orainondaI1')
							.append( $(	'<li><span class="txt_Time">Ore '+oraI1next+'</span><span class="txt_Title">'+titoloI1next+'</span></li>'));
					}
				}

				if ($('#orainondaR4').length > 0){
					if(titoloR4!=''){
						$('#orainondaR4')
							.append( $(	'<li><span class="txt_Time">Ore '+oraR4+'</span><span class="txt_Title">'+titoloR4+'</span></li>'));
					}
					if(titoloR4next!=''){
						$('#orainondaR4')
							.append( $(	'<li><span class="txt_Time">Ore '+oraR4next+'</span><span class="txt_Title">'+titoloR4next+'</span></li>'));
					}
				}

				if ($('#orainondaTV').length > 0){
					if(titoloC5!=''){
						$('#orainondaTV')
							.append( $(	'<li><span class="txt_Time">Ore '+oraC5+'</span><span class="txt_Title">CANALE 5 - '+titoloC5+'</span></li>'));
					}
					if(titoloI1!=''){
						$('#orainondaTV')
							.append( $(	'<li><span class="txt_Time">Ore '+oraI1+'</span><span class="txt_Title">ITALIA 1 - '+titoloI1+'</span></li>'));
					}
					if(titoloR4!=''){
						$('#orainondaTV')
							.append( $(	'<li><span class="txt_Time">Ore '+oraR4+'</span><span class="txt_Title">RETE 4 - '+titoloR4+'</span></li>'));
					}
				}


			});
		})

		/*
			~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			Carica il contenuto dell'ora in onda nell'header e nelle eventuali box in spalla destra
			~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		*/
		if ($('.ultimaora').length > 0){
			var param = $('.ultimaora').attr('id').split("-");
			var divid = '#'+$('.ultimaora').attr('id');
			var network = param[0];
			var timestamp = param[1];
			$(document).trigger('loadOraInOnda',[divid,network,timestamp]);
		}
		/*
			~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			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>'));
		}
});

/* ~~~~~~~~~~~~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';
  }
}
/* ~~~~~~~~~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;
		}
}

/* ~~~~~~~~~Rotazione della programmazione negli header~~~~~~~~~~~~~~~~*/
function rotateUltimaora(idbox){
	var id = (idbox % 3);
	if(id==0) id=3;

	document.getElementById("ultimaora1").style.display='none';
	document.getElementById("ultimaora2").style.display='none';
	document.getElementById("ultimaora3").style.display='none';
	var current = document.getElementById("ultimaora"+id);
	current.style.display='block';
}
/* ~~~~~~~~~Rotazione delle box video in hp~~~~~~~~~~~~~~~~*/
function refreshApertura(idboxvideo){
	var id = (idboxvideo % 3);
	if (id==0) id=3;

	document.getElementById("start1").style.display='none';
	document.getElementById("start2").style.display='none';
	document.getElementById("start3").style.display='none';

	document.getElementById("briciola1").className='videoApp';
	document.getElementById("briciola2").className='videoApp';
	document.getElementById("briciola3").className='videoApp';

	var apertura = document.getElementById("start"+id);
	apertura.style.display='block';

	apertura = document.getElementById("briciola"+id);
	apertura.className+=' over';
}

/* 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;
}