var GuidaProgrammi = function() {

	var sPath = window.location.pathname;
	//var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	this.guidaProgrammi = false;
	if(sPage == "guidaProgrammi.html") {
		this.guidaProgrammi = true;
	}
	this.nielsen_click_guidaprogrammi_spalla = false;
	
	this.startDate = '2008/12/29';
	this.defaultChan = 'RaiTre'; // Rai Tre
	var a = getServerDateTime();
	this.todayDate = a[0];
	
	if (DEBUG) { this.todayDate = '2009/01/02'; }
	
	this.serverTime = a[1];
	// 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   = "#calendarioGuida .btnPrev";
GuidaProgrammi.prototype.selectorBtnNext   = "#calendarioGuida .btnNext";
GuidaProgrammi.prototype.selectorUlWrapper = "#calendarioGuida .giorni";
GuidaProgrammi.prototype.selectorUl        = "ul.elencoGiorni";
GuidaProgrammi.prototype.selectorContainer = ".Programmazione";
GuidaProgrammi.prototype.selectorDate      = ".titolo h3";
GuidaProgrammi.prototype.selectorMenu      = "#Container .fasciaOraria";
// 2009-09-16 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 = elementi.filter(function() {
		var r = false;
		r |= $(this).is('.liMattina');
		r |= $(this).is('.liPomeriggio');
		r |= $(this).is('.liSera');
		r |= $(this).is('.liNotte');
		return !r;
	});
	elementi.removeClass('passato');
	elementi.removeClass('corrente');
	elementi.removeClass('futuro');
	
	/* modifiche temporanee, in attesa dell'xsl buono */
	var headersAdded = {mattina: false, pomeriggio: false, sera: false, notte: false};
	var orari = {mattina: '12:00', pomeriggio: '18:00', sera: '23:00'};
	var liste = {mattina: $('<ul class="ulMattina"></ul>'), pomeriggio: $('<ul class="ulPomeriggio"></ul>'), sera: $('<ul class="ulSera"></ul>'), notte: $('<ul class="ulNotte"></ul>')};
	var appendToNotte = false;

	elementi.each(function(i) {
		if ($('div', $(this)).length===0) {
			$(this).wrapInner('<div class="liContainer"></div>');
		}
		var h = $('span.ora', $(this)).text();
		if (h <= orari.mattina) {
			if (appendToNotte) {
				liste.notte.append($(this));
			} else {
				liste.mattina.append($(this));
			}
			if ( !headersAdded.mattina ) {
				headersAdded.mattina = true;
				//$(this).before('<li><h4>Mattina</h4></li>');
			}
		} else if (h <= orari.pomeriggio) {
			liste.pomeriggio.append($(this));
			appendToNotte = true;
			if ( !headersAdded.pomeriggio ) {
				headersAdded.pomeriggio = true;
				//$(this).before('<li><h4>Pomeriggio</h4></li>');
			}
		} else if (h <= orari.sera) {
			appendToNotte = true;
			liste.sera.append($(this));
			if ( !headersAdded.sera ) {
				headersAdded.sera = true;
				//$(this).before('<li><h4>Sera</h4></li>');
			}
		} else {
			liste.notte.append($(this));
			appendToNotte = true;
			if ( !headersAdded.notte ) {
				headersAdded.notte = true;
				//$(this).before('<li><h4>Notte</h4></li>');
			}
		}
	});
	cont.empty();
	cont.append($('<li class="liMattina"></li').append(liste.mattina));
	cont.append($('<li class="liPomeriggio"></li').append(liste.pomeriggio));
	cont.append($('<li class="liSera"></li').append(liste.sera));
	cont.append($('<li class="liNotte"></li').append(liste.notte));
	/* fine modifiche temporanee, in attesa dell'xsl buono */
	var corrente = null;
	var hScroll = 0;
	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;
		});
		
		var passati = elementi.slice(0, thresholdIndex);
		passati.addClass('passato');
		var futuri = elementi.slice(thresholdIndex);
		corrente = futuri.slice(0,1).addClass('corrente');
		
		var indexFasciaOraria = $(".Programmazione>li").index(futuri.slice(0,1).parent().parent());
		$('.fasciaOraria>li:eq('+indexFasciaOraria+') a').addClass('selected');
		futuri.slice(0,1).prevAll('li').each(function(){hScroll+=$(this).outerHeight()});
		
		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;
	}
	
	$('.fasciaOraria li a.selected').data('skipNielsen', true).click().data('skipNielsen', false);
	if(!this.guidaProgrammi && $('#panePalinsesto')[0].scrollTo) {
		$('#panePalinsesto')[0].scrollTo(hScroll);
	}
	
	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;
	}	

	/*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 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';

	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;
				//debug('cont: '+cont);
				//debug('c: '+c);
				//this.wrapFunction(this.applyDateTimeStyles, null)
				if(this.nielsen_click_guidaprogrammi_spalla) {
					setNielsen(location.href+"?data="+o.selectedDate);
				}
				this.nielsen_click_guidaprogrammi_spalla = true;
				
				return function(htmlText) {
					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: '+args);
	
	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() {

	$('.fasciaOraria li a').click(function(){
		$('.fasciaOraria li a').removeClass('selected');
		$(this).addClass('selected');
		var timeToShow = $(this).text()
		$('ul.Programmazione>li').hide();
		
		$('ul.Programmazione>.li'+timeToShow+'').show();
		if (!$(this).data('skipNielsen') ) {
			setNielsen(location.href+"?fasciaOraria="+timeToShow);
		}
		//alert(bho);
		if(!this.guidaProgrammi) {
			$('#panePalinsesto').jScrollPane({showArrows:false, scrollbarWidth:16 });
		}
		
		return false;
	});
	
	
	
	// 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="#">';
		if(this.guidaProgrammi) {
			s += '<h4>'+weekDays[w]+'</h4>';
			s += '<h5>'+d+'&nbsp;'+months[m]+'</h5>';
		} else {
			s += '<h4>'+d+'</h4>';
			s += '<h5>'+months[m]+'</h5>';
		}
		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 = 6; // 10 elementi per pagina
		if(this.guidaProgrammi) {
			v = 8;
		}
		//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() {
	// TODO
};
