// Calendar class
var Data = ViewDate( new Date() );
var CalendarPopup = new Array();
var CalendarCount = 0;



function ShowCalendar( id_text )
{
	CalendarCount++;	
	
	id_text = id_text || '';
	
	if (!id_text )
	{
		alert("Impostare id_text")
		return false;
	}
	else if ( typeof(oID(id_text))!="object" )
	{
		alert("'"+id_text+"' non è un oggetto valido");
		return false;
	} 

	// creazione della nuova istanza calendar
	CalendarPopup[CalendarCount] = new Calendar( CalendarCount, id_text );
	CalendarPopup[CalendarCount].setDateSelected();
	CalendarPopup[CalendarCount].Init();
	// ---------------------------------------
}



function Calendar( ID, id_text )
{	
	
	this.ID = ID;
	this.Popup_name = 'CalendarPopup'; //css
	this.Head_name = 'CalendarHead'; //css
	this.TextMonth_name = 'TextMonth'; //css
	this.SelectMonth_name = 'SelectMonth'; //css
	this.TextYear_name = 'TextYear'; //css
	this.TableDay_name = 'TableDay'; //css
	this.Close_name = 'CalendarClose'; //css
	this.Reset_name = 'ResetAndClose'; //css
	this.Control_name = 'CalendarControl'; //css
	this.Popup = this.Popup_name+'_'+id_text;
	this.obj = this.Popup_name+'['+this.ID+']';
	this.TextMonth = this.Popup+'_'+this.TextMonth_name;
	this.SelectMonth = this.Popup+'_'+this.SelectMonth_name;
	this.TextYear = this.Popup+'_'+this.TextYear_name;
	this.TableDay = this.Popup+'_'+this.TableDay_name;
	this.Prev_ico = '../images/calendar_prev.gif';
	this.Next_ico = '../images/calendar_next.gif';
	this.MonthStart = '';
	this.YearStart = '';
	this.TextDate = id_text;
	this.DateSelected = Date();
	this.Months = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
	this.Days = ['Do','Lu','Ma','Me','Gi','Ve','Sa'];
	this.Days_name = ['Domenica','Luned&iacute;','Marted&igrave;','Mercoled&igrave;','Gioved&igrave;','Venerd&igrave;','Sabato'];
	this.YearLimit = [1901,2078];
	
	
	
	
	
	// Imposta la Data scritta nella text come data selezionata
	this.setDateSelected = function()
	{	
		text_date = oID(this.TextDate);
		var str_date = text_date.value;
		// Se il testo data è presente ed è una data valida
		if (str_date!='' && IsDate(str_date))
		{	// Imposta la data di partenza con un oggetto Date ottenuto dalla stringa data
			this.DateSelected = StrDate(str_date);
		}
		// Data inesistente o non valida
		else
		{
			if (str_date!="" && !IsDate(str_date))
				alert('Attenzione, la data inserita non è valida, verrà considerata la data odierna');
			// Imposta data di partenza ad oggi (Data è una var ricevuta da PHP tramite il bridge)
			this.DateSelected = StrDate(Data);
			// Visualizza la data nel formato standard per la text
			text_date.value = ViewDate( this.DateSelected );
		}
		// Memorizzo il mese e l'hanno attuali per la visualizzazione
		this.MonthStart = this.DateSelected.getMonth();
		this.YearStart = this.DateSelected.getFullYear();
	}
	
	
	
	// Imposta la nuova data selezionata nella text
	this.SetDate = function( str_date )
	{
		str_date = str_date || '';
		if ( str_date=="" )
		{
			oID(this.TextDate).value = '';
			this.PopupClose();
		}
		else if ( IsDate(str_date) )
		{
			oID(this.TextDate).value = ViewDate( StrDate(str_date) );
			// Fissa la nuova data nell'oggetto
			this.setDateSelected();
			// Chiude il Popup
			this.PopupClose();
		}
		else
		{
			alert("Data non corretta: "+ str_date);
		}
	}
	
	
	
	// Inizializzo il Calendar
	this.Init = function() 
	{
		if (oID(this.Popup)==null)
		{
			var myBody = document.getElementsByTagName('body')[0];		
			var oPopup = document.createElement('div');
			oPopup.setAttribute('id',this.Popup);
			oPopup.style.position = 'absolute';
			myBody.appendChild(oPopup);
			oPopup.className = this.Popup_name;
		}
		else
		{
			oPopup=oID(this.Popup);
		}
		// visualizzo il popup ed imposto il contenuto
		oPopup.style.display = 'block';
		oPopup.style.top = (GetObjectPosition(oID(this.TextDate),true)+19) + (isMSIE&!isMSIE7?2:0) + 'px';
		oPopup.style.left = GetObjectPosition(oID(this.TextDate),false)  + (isMSIE&!isMSIE7?2:0) + 'px';
		// Scrivo il contenuto del Popup
		this.Write();
	}
	
	
	
	// Stampa il calendario nel Div Target
	this.Write = function()
	{	// Mese e Anno da Visualizzare
		var m = this.MonthStart;
		var y = this.YearStart;	
		// Link 
		var link_m_prev = '<a href="javascript:'+this.obj+'.PrevMonth()" title="Mese Precedente" class="'+this.Control_name+'"><img src="'+this.Prev_ico+'" alt="Prev" align="absmiddle" /></a>';
		var link_m_next = '<a href="javascript:'+this.obj+'.NextMonth()" title="Mese Successivo" class="'+this.Control_name+'"><img src="'+this.Next_ico+'" alt="Next" align="absmiddle" /></a>';
		var link_close = '<a href="javascript:'+this.obj+'.PopupClose()" title="Chiudi" class="'+this.Close_name+'">Chiudi</a>';
		var link_reset = '<a href="javascript:'+this.obj+'.SetDate()" title="Nessuna Data" class="'+this.Reset_name+'">Nessuna Data</a>';
		// Variabile on l'output
		var o = '';
		o+=link_reset;
		o+='<div class="'+this.Head_name+'">';
		o+=link_m_prev;
		o+=this.WriteYear(y);
		o+=this.WriteMonth(m);
		o+=link_m_next;
		o+='</div>';
		// Head Giorni
		o+='<table class="'+this.TableDay_name+'" id="'+this.TableDay+'"><tbody>';
		o+='<tr>';
		o+='<th>'+this.Days[1]+'</th>';
		o+='<th>'+this.Days[2]+'</th>';
		o+='<th>'+this.Days[3]+'</th>';
		o+='<th>'+this.Days[4]+'</th>';
		o+='<th>'+this.Days[5]+'</th>';
		o+='<th>'+this.Days[6]+'</th>';
		o+='<th>'+this.Days[0]+'</th>';
		o+='</tr>';
		// Giorni
		var w_d = '';
		for (d=1; d<=31; d++)
		{	// Crea Stringa ipotetica data
			d_date = d+'/'+(m+1)+'/'+y ;
			//alert( _date );
			// Se la data è esistente
			if ( IsDate(d_date) )
			{	// La converto in oggetto
				obj_date = StrDate(d_date);
				n_day = obj_date.getDay();
				day = d;
				if ( this.CheckDateSelected(obj_date) ) day='<strong>'+d+'</strong>';	
				date = '<a href="javascript:'+this.obj+'.SetDate(\''+d_date+'\')" title="" alt="" class="">'+day+'</a>';
				// Primo giorno e primo giorno della settimana apro un tr
				if (w_d=='' || w_d==0) o+='<tr>';
				// Nel caso il primo giorno sia domenica(0) devo forzare il n.ro di giorni precedenti su 7
				d_after = n_day ? n_day : 7;
				// Se Primo giorno Stampo n td vuoti per raggiungere il week_day corretto
				if (w_d=='') for(i=1;i<d_after;i++) o+='<td><br /></td>';
				o+= '<td>'+ date + '</td>';
				// Se è l'ultimo giorno della settima chiudo il tr
				if (w_d==6) o+='</tr>';
				// Imposta il valore del week_day per il prossimo passaggio
				w_d=n_day;
			}
		}
		// Giorni residui alla chiusura della settimana
		if (w_d>0)
		{
			d_rest = 7-w_d;
			for(i=0;i<d_rest;i++) o+='<td><br /></td>';
			o+='</tr>';
		}
		o+='</tbody></table>';
		// Link di chiusura Popup
		o+=link_close;
		// Scrittura nel popup
		oID(this.Popup).innerHTML = o ;
	}
	
	
	
	
	this.CheckDateSelected = function( obj_date )
	{
		if ( ViewDate(obj_date) == ViewDate(this.DateSelected) )
			return true;
		else
			return false;
	}
	
	// Stampa la select mesi
	this.WriteMonth = function( m )
	{	
		var o = '';
		o+='<input title="Clicca per Cambiare il mese" type="text" name="'+this.TextMonth+'" id="'+this.TextMonth+'" class="'+this.TextMonth_name+'" value="'+this.Months[m]+'" onfocus="'+this.obj+'.ChangeMonth()" />';
		o+='<select name="'+this.SelectMonth+'" id="'+this.SelectMonth+'" class="'+this.SelectMonth_name+'" onchange="this.blur()" onblur="'+this.obj+'.SetMonth(this.value)">';
		for( i=0; i<12; i++ )
		{
			o+='<option value="'+i+'" '+((i==m)?'selected="selected"':'')+'>'+this.Months[i]+'</option>';
		}
		o+='</select>';
		return o;
	}
	// Visualizza la select per cambiare mese
	this.ChangeMonth = function()
	{
  		oID(this.TextMonth).style.display = 'none';
		oID(this.SelectMonth).style.display = 'inline';
		oID(this.SelectMonth).focus();
	}
	// Cambia mese
	this.SetMonth = function( m )
	{
		m = parseInt(m) || 0;
		this.MonthStart = parseInt(m);
		// Rigenero il Calendario
		this.Write();
	}
	// Mese precedente
	this.PrevMonth = function()
	{	
		// Valori di partenza
		var m = this.MonthStart;
		var y = this.YearStart;	
		// Valori mese precedente
		m_prev = m-1;
		if (m_prev<0) {
			m_prev = 11;
			y_prev = y-1;
			this.SetYear(y_prev);
		}	
		// Imposto i nuovi valori della classe
		this.SetMonth(m_prev);
	}
	// Mese successivo
	this.NextMonth = function()
	{	
		// Valori di partenza
		var m = this.MonthStart;
		var y = this.YearStart;	
		// Valori mese successivo 
		m_next = m+1;
		if (m_next>11) {
			m_next = 0;
			y_next = y+1;
			this.SetYear(y_next);
		}
		// Imposto i nuovi valori della classe
		this.SetMonth(m_next);
	}
	
	
	
	
	
	
	// Stampa input text anno
	this.WriteYear = function( y ) 
	{
		var o = '';
		o+='<input name="'+this.TextYear+'" id="'+this.TextYear+'" type="text" class="'+this.TextYear_name+'" value="'+y+'" onchange="'+this.obj+'.SetYear(this.value)" onkeydown="return ForceKey(event,\'numeri\');" maxlength="4" size="4" />';
		return o;
	}
	// Cambia anno
	this.SetYear = function( y )
	{
		y = parseInt(y) || this.YearStart;
		// Se l'anno è fuori limite
		if ( y<this.YearLimit[0] || y>this.YearLimit[1] )
		{
			alert('Inserire un anno compreso fra il '+ this.YearLimit[0] +' ed il '+ this.YearLimit[1] );
		}
		// Se rientra nel limite
		else
		{
			this.YearStart = y;
		}
		// Rigenero il Calendario
		this.Write();
	}
	
	
	
	
	
	// Chusura del Popup
	this.PopupClose = function()
	{
		if (oID(this.Popup)!=null)
		{
			oID(this.Popup).style.display = 'none';
			oID(this.Popup).innerHTML = '';
		}
	}
	
}
