
/* funzioni di debug:
 * se e' possibile scrive nella console
 * (sempre disponibile in chrome, disponibile in firefox
 * solo se firebug e' aperto gia' al caricamento della pagina),
 * altrimenti esegue gli alert (solo se DEBUG e' true). */
if (typeof(DEBUG)=='undefined') {
	DEBUG = false;
	(function() {
		var d = getParam('debug'); // cerca nella query o nell'hash (in quest'ordine)
		if (d === true || d == 'true' || d == 'debug') {
			DEBUG = true;
		}
	})();
}
if (typeof(console) == 'undefined') {
	console = {};
}
if (typeof(console.log) == 'undefined') {
	console.log = function(msg) {
		if (DEBUG || DEBUGRAITV) {
			alert(msg);
		}
	};
}
debug = function(msg) {
	try {
		console.log(msg);
	} catch (e) {
		if (DEBUG || DEBUGRAITV) {
			alert(msg);
		}
	}
	return true;
}



	function setNielsen(url) {
		if (url == undefined) url = location.href;
		var servizio = $('.tendinaOpzioni').text();
		
		url = url + '&tipo='+servizio;
		
		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+'?tipo='+servizio);
	}
var GuidaProgrammi = function() {
	this.startDate = '2008/12/29';
	this.defaultChan = 'RaiUno'; // Rai Uno
	
	this.todayDate = ServerDate;
	
	if (DEBUG) { this.todayDate = '2009/01/02'; } 
	
	this.serverTime = ServerTime;
	// determino la differenza tra l'ora del server e l'ora del client (per calcolare correttamente l'ora in onda)
	var serverDateTime = new Date(this.todayDate);
	var hh = this.serverTime.match(/([0-9]{2}):([0-9]{2}):([0-9]{2})/);
	var mm = hh[2];
	var ss = hh[3];
	hh = hh[1];
	
	serverDateTime.setHours(hh);
	serverDateTime.setMinutes(mm);
	serverDateTime.setSeconds(ss);
	var localDateTime = new Date();
	
	this.clientOffsetMillis = serverDateTime - localDateTime; // add this.clientOffsetMillis to local time to get server time
	
	// preload img loading
	this.loadingImg = $('<div style="width: 400px; display: none; text-align: center;"><img src="/dl/portale/image/loading.gif" alt="Caricamento" /></div>');
};

GuidaProgrammi.prototype.daysAfterCurrent  = 5;

GuidaProgrammi.prototype.selectorBtnPrev   = ".calendario .btn_sinistra";
GuidaProgrammi.prototype.selectorBtnNext   = ".calendario .btn_destra";
GuidaProgrammi.prototype.selectorUlWrapper = ".calendario .progdaysWrapper";
GuidaProgrammi.prototype.selectorUl        = "ul.progdays";
GuidaProgrammi.prototype.selectorContainer = "#DatiPalinsesto";
GuidaProgrammi.prototype.selectorDate      = "#Container .BoxLarge .fasciamid h4:first";
GuidaProgrammi.prototype.selectorMenu      = "#Container .BoxLarge .fasciamid .menu_rai";
// 2009-09-11 Update nuova gestione palinsesti: cambio del path da cui caricare i file. E' cambiato anche il formato della data.
GuidaProgrammi.prototype.dataPath          = "/dl/portale/html/palinsesti/guidatv/static/";

GuidaProgrammi.prototype.selectedDate = null;
GuidaProgrammi.prototype.selectedChan = null;

GuidaProgrammi.prototype.wrapFunction = function(func, arg) {
	var obj = this;
	return function(){ return func.call(obj, arg); };
};

GuidaProgrammi.prototype.applyDateTimeStyles = function() {
	if (this.updateStyleTimer !== null) {
		clearTimeout(this.updateStyleTimer);
		this.updateStyleTimer = null;
	}
	var cont = $(this.selectorContainer);
	
	var d = this.selectedDate.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})/);
	var m = d[2];
	var y = d[3];
	d = d[1];
	var dat = new Date(y+'/'+m+'/'+d);
	
	var weekDaysLong = ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'];
	var monthsLong = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
					  'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'];
	
	if (DEBUG) {
	
		var dbgTime = new Date();
		dbgTime = new Date(dbgTime.getTime() + this.clientOffsetMillis);
		dbgTime = (dbgTime.getHours()<10?'0':'')+dbgTime.getHours() + ':' + (dbgTime.getMinutes()<10?'0':'') +dbgTime.getMinutes()+':'+(dbgTime.getSeconds()<10?'0':'')+dbgTime.getSeconds();
		$(this.selectorDate).html(weekDaysLong[dat.getDay()] + ' ' + d + ' ' + monthsLong[m-1]+ ' <acronym title="Debug: server time">'+dbgTime+'</acronym>');
	} else {
		$(this.selectorDate).html(weekDaysLong[dat.getDay()] + ' ' + d + ' ' + monthsLong[m-1]);
	}
	var dateString = (dat.getFullYear())+'/'+(dat.getMonth()<9?'0':'')+(dat.getMonth()+1)+'/'+(dat.getDate()<10?'0':'')+dat.getDate();
	
	var elementi = $('li', cont).filter(function(){return $('span.ora', $(this)).length > 0;}); // li prendo tutti: anche se appartengono a UL diversi.
	elementi.removeClass('passato');
	elementi.removeClass('corrente');
	elementi.removeClass('futuro');
	
	/* modifiche temporanee, in attesa dell'xsl buono */
	if ($('ul', cont).length===0) {
		cont.wrapInner('<ul></ul>');
	}
	var headersAdded = $('ul', cont).data('headers');
	if (!headersAdded) {
		headersAdded = {mattina: false, pomeriggio: false, sera: false, notte: false};
	}
	var orari = {mattina: '12:00', pomeriggio: '18:00', sera: '23:00'};
	elementi.each(function(i) {
		$(this).find('>h5').remove();
		if ($('div', $(this)).length===0) {
			$(this).wrapInner('<div class="liContainer"></div>');
		}
		var h = $('span.ora', $(this)).text();
		if (h <= orari.mattina) {
			if ( !headersAdded.mattina ) {
				headersAdded.mattina = true;
				$(this).before('<li><h4>Mattina</h4></li>');
			}
		} else if (h <= orari.pomeriggio) {
			if ( !headersAdded.pomeriggio ) {
				headersAdded.pomeriggio = true;
				$(this).before('<li><h4>Pomeriggio</h4></li>');
			}
		} else if (h <= orari.sera) {
			if ( !headersAdded.sera ) {
				headersAdded.sera = true;
				$(this).before('<li><h4>Sera</h4></li>');
			}
		} else {
			if ( !headersAdded.notte ) {
				headersAdded.notte = true;
				$(this).before('<li><h4>Notte</h4></li>');
			}
		}
	});
	$('ul', cont).data('headers', headersAdded);
	/* fine modifiche temporanee, in attesa dell'xsl buono */
	
	if ( dateString < this.todayDate) { // giorno passato
		elementi.addClass('passato');
	} else if (dateString == this.todayDate) { // oggi
		var thresholdTime = new Date();
		thresholdTime = new Date(thresholdTime.getTime() + this.clientOffsetMillis);
		thresholdTime = (thresholdTime.getHours()<10?'0':'')+thresholdTime.getHours() + ':' + (thresholdTime.getMinutes()<10?'0':'') +thresholdTime.getMinutes();
		
		//debug(thresholdTime);
		
		var thresholdIndex = -1;
		
		elementi.each(function(i){
			var h = $('span.ora', $(this)).text();
			if (thresholdIndex < 0 && h > thresholdTime) {
				thresholdIndex = i-1;
				return false;
			}
			return true;
		});
		
		if (thresholdIndex < 0) {
			// nessun elemento iniziato nel passato (nemmeno il corrente)
			elementi.addClass('futuro');
		} else {
			var passati = elementi.slice(0, thresholdIndex);
			passati.addClass('passato');
			var futuri = elementi.slice(thresholdIndex);
			futuri.slice(0,1).addClass('corrente');
			futuri.slice(1).addClass('futuro');
		}
	} else { //giorno futuro
		elementi.addClass('futuro');
	}

/* disegno dello sfondo per l'elemento corrente */
this.drawCurrentItemBackground();
/* fine disegno sfondo */
	
	cont.slideDown('slow');
	this.loadingImg.css('display', 'block');
	
	if (this.updateStyleTimer !== null) {
		clearTimeout(this.updateStyleTimer);
		this.updateStyleTimer = null;
	}
	this.updateStyleTimes = setTimeout(this.wrapFunction(this.applyDateTimeStyles, null), (DEBUG?1:60)*1000);
};

GuidaProgrammi.prototype.drawCurrentItemBackground = function() {
	if (this.canvas == null) {
		this.canvas = $('#CurrentItemBackgroundCanvas');
	}
	var c = this.canvas;
	
	var minHeight = 12;
	var current = $('li.corrente');
	if (current.length == 0) {
		$('li canvas').remove();
		$('#LabelOraInOnda').remove();
		return true;
	}
	if ($('canvas', current).length != 0) {
		return true;
	}
	var h = parseInt(current.height());
	if (h<minHeight) {
		h = minHeight;
	}
	var addedHeight = 2;
	//var c = $('<canvas id="CurrentItemBackgroundCanvas" width="400" height="'+(h+addedHeight)+'"></canvas');
	
	//alert('1) c.get(0).getContext: '+c.get(0).getContext);
	
	if (c.get(0).getContext == null)  {
		G_vmlCanvasManager.initElement.call(G_vmlCanvasManager, c.get(0));
	}
	//alert('2) c.get(0).getContext: '+c.get(0).getContext);
	
	if (typeof(c.get(0).getContext)=='undefined') {
		return false;
	}
	var ctx = c.get(0).getContext('2d');
	//var ctx = document.getElementById('CurrentItemBackgroundCanvas').getContext('2d');

	
	$('li canvas').remove();
	$('#LabelOraInOnda').remove();
	$('>div', current).css( {position: 'relative', height: 'auto', background: 'transparent'});
	$('*', current).css( {position: 'relative'});
	
	h = parseInt(current.height());
	if (h<minHeight) {
		h = minHeight;
	}
	c.attr('height', ''+(h+addedHeight));
	c.css({
		padding: '0px'
		,margin: '0px'
		,width: '400px'
		,height: (h+addedHeight)+'px'
		,marginBottom: '-'+(h+addedHeight)+'px'
		,float: 'left'
	});
	current.prepend('<div id="LabelOraInOnda" style="float: right; width: 70px; height: '+(h+addedHeight)+'px; margin: 0px 5px -'+(h+addedHeight)+'px -70px; color: #fff; font-size: 10px; font-family: Arial; position: relative; text-align: right;">Ora in onda</div>');
	$('#LabelOraInOnda').css({
		paddingTop: Math.floor((h+addedHeight)/2 - 7)+'px'
		, marginBottom: '-'+(h+addedHeight  + Math.floor((h+addedHeight)/2 - 7) )+'px'
	});
	current.prepend(c);
	c.show();
	
	/* gradiente sinistro */
	var gradient1 = ctx.createLinearGradient(0, 1, 0, h);
	gradient1.addColorStop(0, '#fefffc');
	gradient1.addColorStop(1, '#ecebe2');
	ctx.fillStyle = gradient1;
	ctx.fillRect(1, 4, 1, h-6);
	ctx.fillRect(2, 3, 1, h-4);
	ctx.fillRect(3, 2, 1, h-2);
	ctx.fillRect(4, 1, 331, h);

	/* gradiente destro */
	var gradient2 = ctx.createLinearGradient(335, 1, 335, h);
	gradient2.addColorStop(0, '#d2d4d1');
	gradient2.addColorStop(1, '#babcb9');
	ctx.fillStyle = gradient2;
	ctx.fillRect(335, 1, 62, h);
	ctx.fillRect(397, 2, 1, h-2);
	ctx.fillRect(398, 3, 1, h-4);
	ctx.fillRect(399, 4, 1, h-6);

	/* bordo */
	var radius = 6;
	var maxH = h+addedHeight-1;
	var maxW = 400;
	ctx.strokeStyle = '#d9dbd7';
	ctx.lineWidth = 1;
	
	ctx.beginPath();
	ctx.moveTo(0, radius);
	ctx.arc(radius, radius, radius, Math.PI, 3*Math.PI/2, false);

	ctx.moveTo(radius, 0);
	ctx.lineTo(maxW-radius, 0);

	ctx.arc(maxW-radius, radius, radius, -Math.PI/2, 0, false);

	ctx.moveTo(maxW, radius);
	ctx.lineTo(maxW, maxH-radius);

	ctx.arc(maxW-radius, maxH-radius, radius, 0, Math.PI/2, false);

	ctx.moveTo(maxW-radius, maxH);
	ctx.lineTo(radius, maxH);

	ctx.arc(radius, maxH-radius, radius, Math.PI/2, Math.PI, false);

	ctx.moveTo(0, maxH-radius);
	ctx.lineTo(0, radius);

	ctx.stroke();
};

GuidaProgrammi.prototype.loadData = function() {
	if (this.updateStyleTimer !== null) {
		clearTimeout(this.updateStyleTimer);
		this.updateStyleTimer = null;
	}
	
	if (this.selectedDate === null) {
		this.selectedDate = this.todayDate.replace(/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/, "$3-$2-$1");
	}
	
	if (this.selectedChan === null) {
		this.selectedChan = this.defaultChan;
	}
	
	
	$(this.selectorMenu+' a').removeClass('currentChan');
	$(this.selectorMenu+' a').css('backgroundColor', 'transparent');
	var btnId = '#btn_'+this.selectedChan.replace(/-/g, '_');
	// if ($(this.selectorMenu+' '+btnId).length==0) {
	// 	btnId = '#bnt_'+this.selectedChan.replace(/-/g, '_');
	// }
	$(this.selectorMenu+' '+btnId).addClass('currentChan');
	$(this.selectorMenu+' '+btnId).css('backgroundColor', '#2375C8');
	
	var channelName = $(this.selectorMenu+' a').attr('title');
	var cont = $(this.selectorContainer);

	// 2009-09-11 Update nuova gestione palinsesti: la data ora segue il pattern yyyy_mm_dd invece di dd-mm-yyyy
	var d = this.selectedDate.replace(/([0-9]{2})-([0-9]{2})-([0-9]{4})/, "$3_$2_$1");
	var path = this.dataPath + this.selectedChan + '_' + d + '.html';
	
	var nielsenUrl = document.location + '#?chan='+ this.selectedChan + '&day=' + d ;
	
	cont.hide();
	
	cont.empty();
	
	//cont.append('<img src="/dl/portale/image/loading.gif" alt="Caricamento..." style="display: block; margin: 0px auto;" />');
	cont.append(this.loadingImg);
	this.loadingImg.css('display', 'block');
	this.loadingImg.css('margin', '0px auto');
	
	cont.show();
	
	// TODO chiamata a nielsen
	
	//debug('Loading data from url:\n'+path);
	
	//cont.load(path, null, this.wrapFunction(this.applyDateTimeStyles, null));
	var obj = this;
	$.ajax(
		{
			async: true,
			url: path,
			success: (function(){
				//debug('obj: '+obj);
				var o = obj;
				//debug('o: '+o)
				var c = cont;
				var domPath = 'http://www.rai.it'+path;
				//debug('cont: '+cont);
				//debug('c: '+c);
				//this.wrapFunction(this.applyDateTimeStyles, null)
				return function(htmlText) {
					// setNielsen(domPath);
					setNielsen(nielsenUrl);
					
					c.html(htmlText);
					o.applyDateTimeStyles.call(o);
				}
			})()
		}
	);

	//debug('Async load called...');
};

GuidaProgrammi.prototype.selectChan = function(chanId) {
	this.selectedChan = chanId;
	this.loadData();
	return false;
};

GuidaProgrammi.prototype.dateClicked = function(args) {
	//alert('startDate on this: '+this.startDate);
	//alert('arg: '+arg);
	
	var cal = $(this.selectorUlWrapper);
	var ul = $(this.selectorUl, cal);
	$('li', ul).removeClass('current');
	$(args[1]).addClass('current');
	this.selectedDate = args[0];
	this.loadData();
	return false;
};

GuidaProgrammi.prototype.checkBtnDisabled = function() {
	return false;
	/*
	var n = $(this.selectorBtnNext);
	var p = $(this.selectorBtnPrev);
	if (n.hasClass('disabled')) {
		n.css('background', 'url(/dl/portale/image/btn_destra.gif) top no-repeat');
	} else {
		n.css('background', '');
	}
	if (p.hasClass('disabled')) {
		p.css('background', 'url(/dl/portale/image/btn_sinistra.gif) top no-repeat');
	} else {
		p.css('background', '');
	}*/
};

GuidaProgrammi.prototype.initProgDays = function() {
	// Calcola le date da visualizzare:
	// Arriva fino a 5 giorni dopo oggi (this.daysAfterCurrent)
	// partendo da 14 giorni prima di oggi (daysBeforeCurrent).
	// Sono quindi visibili 2 pagine da 10 giorni.
	var daysBeforeCurrent = 20-this.daysAfterCurrent-1;

	//var currDate = new Date(this.startDate); // data di partenza
	var currDate = new Date(this.todayDate); // data di partenza
	var todayDate = new Date(this.todayDate);
	currDate.setDate(todayDate.getDate()-daysBeforeCurrent);
	
	var maxDate = new Date(this.todayDate);
	var offsetDays = Math.floor((todayDate - currDate)/(24*60*60*1000));
	maxDate.setDate(maxDate.getDate()+this.daysAfterCurrent);
	
	var cal = $(this.selectorUlWrapper);
	var ul = $(this.selectorUl, cal);
	ul.empty();
	
	var months = ['GEN', 'FEB', 'MAR', 'APR', 'MAG', 'GIU',
				  'LUG', 'AGO', 'SET', 'OTT', 'NOV', 'DIC'];
	var weekDays = ['DOM', 'LUN', 'MAR', 'MER', 'GIO', 'VEN', 'SAB'];
	
	for ( ; currDate <= maxDate; currDate.setDate(currDate.getDate()+1) ) {
		var d = currDate.getDate();
		var m = currDate.getMonth();
		var y = currDate.getFullYear();
		var w = currDate.getDay();
		var dateString = ((d<10)?'0'+d:''+d)+'-'+((m<9)?'0'+(m+1):''+(m+1))+'-'+y;
		var s = '<li';
		if (currDate.getTime() == todayDate.getTime()) {
			s+= ' class="current"';
		}
		s += '><a href="#">';
		s += '<span class="giorni">'+weekDays[w]+'</span><br />';
		s += '<span class="mesi">'+d+'&nbsp;'+months[m]+'</span>';
		s += '</a></li>';
		var l = $(s);
		var a = $('a', l);
		a.click(this.wrapFunction.call(this, this.dateClicked, [dateString, l]));
		ul.append(l);
	}
	if ($('li', ul).length>1) {
		var v = 8; // 10 elementi per pagina
		//var scroll = Math.ceil(this.daysAfterCurrent/2);
		var scroll = v; // scrolla di 10 elementi alla volta
		//var offset = offsetDays - Math.floor(this.daysAfterCurrent/2);
		// posiziono il carousel sull'ultima pagina disponibile
		var offset = offsetDays + this.daysAfterCurrent - v + 1;
		$(cal).jCarouselLite({
			speed: 0
			, scroll: scroll
			, visible: v
			, start: offset
			, circular: false
			, btnNext: this.selectorBtnNext
			, btnPrev: this.selectorBtnPrev
			//, afterEnd: this.checkBtnDisabled
		});
	}
	$(this.selectorBtnNext).addClass('disabled');
	//this.checkBtnDisabled();
	//list.show();
};

GuidaProgrammi.prototype.initMenuRai = function() {
	$('.Tendine').mouseover(function(){
		$('#seltendinaOpzioni').show();
	}).mouseout(function(){
		$('#seltendinaOpzioni').hide();
	});

	$("#seltendinaOpzioni .Mid ul>LI").click(function() {
		if(!$(this).is('.selected')) {
			var elenco = $('a.choice',this).attr('rel');
			if (elenco == 'tivu') {
				$('.btn_generico').hide();
				$('.btn_generico[rel=tivu]').show();
				$('.btn_generico[rel=sat]').show();
				$('.btn_generico[rel=dtt]').show();
				$('.menu_rai a:visible').slice(0,1).click();
			} else if (elenco != 'tutti') {
				$('.btn_generico').hide();
				//$('.btn_generico').filter('[rel='+elenco+'""]').show();
				//$('.menu_rai a[rel='+elenco+']').show();
				$('.btn_generico').hide().filter('[rel="'+elenco+'"]').show();
				$('.menu_rai a[rel='+elenco+']:eq(0)').click();
			} else {
				$('.btn_generico').hide().show();
				$('.menu_rai a:eq(0)').click();
			}
			$("#seltendinaOpzioni .Mid ul>LI").removeClass("selected");
			$(this).addClass("selected");
			var choice = $('a.choice',this).text();
			$('.tendinaOpzioni').text(choice);
		}
		return false;
	});
};

