/////////////////////////////////////////////////////////////////
//	Autor: Tomeu
//	Ultima revision: 07/03/2003
//	Ultimo en revisar: Joan Fullana
//	Descripcion:1.He anyadido la posibilidad de tener opcion null para 
//				 dias y meses. He anyadido la posibilidad de especificar
//				 funciones para el evento onChange del listbox de dia y mes
//				2.Opcion de de manipular anyos.
//				3.Incorporar mètode per retornar dia de sa 7mana.
/////////////////////////////////////////////////////////////////


function dateObject(name)
{
	this.name = name;
	this.day = null;
	this.month = null;
	this.year = null;

	this.daysObject = null;
	this.monthsObject = null;
	this.yearsObject = null;
	
	this.dayNullAble = false;
	this.dayNullText;
	this.dayNullValue;
	
	this.monthNullAble = false;
	this.monthNullText;
	this.monthNullValue;
	
	this.listaFechas = null;
	this.listaMeses = null;
	
	this.changed = false;
	
	//idioma
    this.idioma = "es";
    this.appendFullYearToMonth = false;
	
	//*tipo dia = 1 [1,2,3,4...] tipo dia 2 [lun1,mar2,mie3,jue4]
	this.tipoDia = 1;
	this.inicioMes = 1
	this.inicioDia = 1
	this.hastaMes=12
	
	// Metodos
	this.load = dte_load;
	this.add = dte_add;
	this.monthText = dte_monthText;
	this.takeDate = dte_takeDate;
	this.dayOfWeek = dte_dayOfWeek;
	this.getDate = dte_getDate;
	this.getNombreMes = dte_getNombreMes;
	this.getMaxDaysMonth = dte_getMaxDaysMonth;
	this.fechaPermitida = dte_fechaPermitida;
	this.mesPermitido = dte_mesPermitido;
	this.anyadirMes = dte_anyadirMes;

	this.onChangeDay = null;
	this.onChangeMonth = null;
	this.onChangeFunction = null;
	
	// Inicializacion
	var today = new Date();
	this.tday = today.getDate();
	this.tmonth = today.getMonth()+1;
	this.tyear = today.getFullYear();
	this.yearsFrom = today.getFullYear();
	this.yearsTo = today.getFullYear()+2;
	
    this.monthNames = new Array(6,12);
    this.monthNames[0] = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
    this.monthNames[1] = ["Janeiro", "Fevereiro", "Marco", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
    this.monthNames[2] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    this.monthNames[3] = ["Janvier", "Fevrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre"];    
    this.monthNames[4] = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
    this.monthNames[5] = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
    
    this.nombreDias = new Array(6,7);
    this.nombreDias[0] = ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"];    
    this.nombreDias[1] = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"];    
    this.nombreDias[2] = ["Sun", "Mon", "Tue", "Mie", "Thu", "Fri", "Sat"];    
    this.nombreDias[3] = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"];
    this.nombreDias[4] = ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"];
    this.nombreDias[5] = ["So.", "Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa."];

	return;	
}

function dte_load(){	

	if (this.monthsObject!=null){
		var indice = 0;
		
		if (this.monthNullAble)
			this.monthsObject.options[indice++] = new Option(this.monthNullText, this.monthNullValue);
		
		if (this.inicioMes>this.hastaMes)
		{
		
			 for (var i=this.inicioMes;i<=12;i++){
				this.anyadirMes(i, indice++);
			 }
			 for (var i=1;i<=this.hastaMes;i++){
				 this.anyadirMes(i, indice++);
			 }
		}
		else 
		{
			for (var i=this.inicioMes;i<=this.hastaMes;i++){
				this.anyadirMes(i, indice++);
			 }
		}
		for(var i=0; i<this.monthsObject.length;i++)
		{
			//alert(this.monthsObject[i].value); 
			if (this.monthsObject[i].value==this.month)
				 this.monthsObject.selectedIndex=i;
		}
	/*	if (this.monthNullAble)
			this.monthsObject.selectedIndex = this.month;
		else
			this.monthsObject.selectedIndex = this.month-1;
		*/
		if (this.onChangeFunction==null)
			 this.monthsObject.onchange = new Function("dte_changeMonth('" + this.name + "');");
		else
			 this.monthsObject.onchange = new Function("dte_changeMonth('" + this.name + "');" + this.onChangeFunction + ";"); 
	}
	
	if (this.daysObject!=null){
		var indice = 0;
		var maxDays = dte_getMaxDaysMonth(this.month, this.year);
		this.daysObject.options.length = 0;
		if (this.dayNullAble)
			this.daysObject.options[indice++] = new Option(this.dayNullText, this.dayNullValue);

        var diaInicioMes = 1;
        if ((this.month == this.inicioMes) && (this.inicioDia > 1)) {
            diaInicioMes = this.inicioDia
        }
        for (var i = diaInicioMes; i <= maxDays; i++) {	  
			var nombreDia = "";
			var fechaAuxiliar = new Date(this.year, this.month-1, i);
			
			if(this.tipoDia == 2){
                nombreDia = dte_getNombreDia(fechaAuxiliar.getDay(),this.nombreDias) + " ";
			}
			
			if(this.fechaPermitida(fechaAuxiliar)){
				this.daysObject.options[indice++] = new Option(nombreDia + ((i<10) ? "0"+i: i),i);	
			}
		}
		

		if (this.dayNullAble && this.daysObject.options.length>this.day)
			this.daysObject.selectedIndex=this.day;
		else{
			for(i=0;i<this.daysObject.options.length;i++){
				if (this.daysObject.options[i].value == this.day){
					this.daysObject.selectedIndex=i;
				}
			}
		}	
		if (this.onChangeFunction==null)
			this.daysObject.onchange = new Function("dte_changeDay('" + this.name + "');");
		else
			this.daysObject.onchange = new Function("dte_changeDay('" + this.name + "');" + this.onChangeFunction + ";");				
	}
	
	if (this.yearsObject!=null){
		for (var i=0;i<=(this.yearsTo-this.yearsFrom);i++){
			this.yearsObject.options[i] = new Option(this.yearsFrom+i,this.yearsFrom+i);
			
			if ((this.yearsFrom+i)==this.year)
				this.yearsObject.selectedIndex=i
		}
		this.yearsObject.onchange = new Function("dte_changeYear('" + this.name + "')");
	}
		
	return;
}


function dte_changeMonth(nameObject){
	thisObject = eval(nameObject)
	thisObject.month = thisObject.monthsObject.options[thisObject.monthsObject.selectedIndex].value;
	thisObject.changed=true;

	dte_changeYear(nameObject);
	
	if (thisObject.daysObject!=null){
		var maxDays = dte_getMaxDaysMonth(thisObject.month, thisObject.year);
	
		if (thisObject.dayNullAble){
			var tope = 29;
			var indice = 28;
		}else{
			var tope = 28;
			var indice = 27;
		}	
		
		indice = 0;
        thisObject.daysObject.options.length = 0;			    
	    if (thisObject.dayNullAble)
		    thisObject.daysObject.options[indice++] = new Option(thisObject.dayNullText, thisObject.dayNullValue);

		var diaInicioMes = 1;
		if ((thisObject.month == thisObject.inicioMes) && (thisObject.inicioDia > 1)) {
		    diaInicioMes = thisObject.inicioDia		    
		}

		for (var i = diaInicioMes; i <= maxDays; i++) { 
			var nombreDia = ""
			var fechaAuxiliar = new Date(thisObject.year, thisObject.month -1, i);
			
			if (thisObject.tipoDia == 2){
				nombreDia = dte_getNombreDia(fechaAuxiliar.getDay(),thisObject.nombreDias) + " ";
			}
			
			if(thisObject.fechaPermitida(fechaAuxiliar)){
				thisObject.daysObject.options[indice++] = new Option(nombreDia + ((i<10) ? "0" + i: i), i);
			}
		}
				
		if (thisObject.dayNullAble){
            if (thisObject.day != null){
			    if (thisObject.day > maxDays){
				    thisObject.daysObject.selectedIndex = maxDays;
				    thisObject.day = thisObject.daysObject.options[thisObject.daysObject.selectedIndex].value;
			    }else 
                    thisObject.daysObject.selectedIndex = thisObject.day;
            }
        } else {
            if (diaInicioMes > 1) {   
                var seleccionDia = thisObject.day             
                if (thisObject.day < thisObject.daysObject.options[0].value) {
                    seleccionDia = thisObject.daysObject.options[0].value;
                }
                if (thisObject.day > thisObject.daysObject.options[maxDays - diaInicioMes].value) {
                    seleccionDia = thisObject.daysObject.options[maxDays - diaInicioMes].value;
                }
                thisObject.daysObject.selectedIndex = seleccionDia - diaInicioMes;            
            }
            else {            
			    if (thisObject.day > thisObject.daysObject.options.length){
				    thisObject.daysObject.selectedIndex=thisObject.daysObject.options.length-1;
			    }else{
				    thisObject.daysObject.selectedIndex=thisObject.day-1;
			    }
            }
			thisObject.day = thisObject.daysObject.options[thisObject.daysObject.selectedIndex].value;
		}
	}
	
	if (thisObject.onChangeMonth != null)
		thisObject.onChangeMonth();
	
	return;
}
	
	
function dte_changeDay(nameObject)
{
	thisObject = eval(nameObject)
	thisObject.day = thisObject.daysObject.options[thisObject.daysObject.selectedIndex].value;
	thisObject.changed=true;
	dte_changeYear(nameObject);

	if (thisObject.onChangeDay != null)
		thisObject.onChangeDay();

	return;
}


function dte_changeYear(nameObject)
{
	var Obj = eval(nameObject)
	if (Obj.yearsObject==null){
		if ((Obj.month < Obj.tmonth)){
				if ((Obj.month == Obj.tmonth) && (Obj.day > Obj.tday))
					Obj.year = Obj.tyear;
				else
					Obj.year = Obj.tyear + 1;
		}else
			Obj.year = Obj.tyear;	
	}else
		Obj.year = Obj.yearsObject.options[Obj.yearsObject.selectedIndex].value;
	return;
}


function dte_add(numDays){
	this.day = parseInt(this.day,10) + numDays;
	var maxDays = dte_getMaxDaysMonth(this.month, this.year);
	
	if (this.day>maxDays){
		this.month = parseInt(this.month,10) + 1;
		this.day = parseInt(this.day,10) - parseInt(maxDays,10);
		
		if (this.month==13){
			this.month = 1;
			this.year = parseInt(this.year,10) + 1;
		}
	}
	return;
}

	
function dte_takeDate(format){
	//Modificat: J.Fullana (09/02/2004)
	//format --> (1) dd/mm/yyyy  
	//format --> (2) yyyymmdd  
	//format --> (3) dd-mmm-yyy

	var str = "";

    if ((this.day != null)&&(this.month != null)&&(this.year != null)){
	    switch (format){
	    case 1:
		    str = dosDigits(this.day) +"/"+ dosDigits(this.month) +"/"+ this.year;
		    break;
	    case 2:
		    str = this.year + dosDigits(this.month) + dosDigits(this.day);
		    break;
	    case 3:
		    str = dosDigits(this.day) +"-"+ this.getNombreMes(parseInt(this.month,10),2) +"-"+ this.year;
		    break;
	    }
    }
	return str;
}

function dte_monthText(){
	return this.getNombreMes(this.month, 1)
}

function dte_dayOfWeek(){
	//***********
	// modifiat: 07/02/2003 - J. Fullana
	// retorna: DG -> 1
	//			DL -> 2
	//			DM -> 3
	//			DX -> 4
	//			DJ -> 5
	//			DV -> 6
	//			DS -> 7
	//***********
	
	var data = new Date(this.year,(this.month-1)%12,this.day)
	return data.getDay() + 1;
}

function dte_getDate(){
	return new Date(this.year, this.month-1, this.day)
}

//retorna el nom del mes en diferents formats
//creat: J.Fullana (09/02/2004)
function dte_getNombreMes(mes, format){
	//format --> (1) "Enero, Febrero, ..."
	//format --> (2) "Jan, Feb, ..."
	var nomMes;
	
	switch(this.idioma){
	case "br":
	case "pt":
	    nomMes = this.monthNames[1][mes-1];
	    break;
	case "en":
	    nomMes = this.monthNames[2][mes-1];
	    break;
	case "fr":
	    nomMes = this.monthNames[3][mes-1];
	    break;
    case "it":
	    nomMes = this.monthNames[4][mes-1];
	    break;
	case "de":
		nomMes = this.monthNames[5][mes-1];
		break;
	default:
	    nomMes = this.monthNames[0][mes-1];
	    break;
	}	
	switch(format){
	case 1:
	    return nomMes;
	case 2:
        return nomMes.substring(0,3);
	}
}


function dte_getNombreDia(dia,llista)
{
	//format --> (1) "Enero, Febrero, ..."
	//format --> (2) "Jan, Feb, ..."
	var nomDia = "";	
	switch(this.idioma){
		case "br":
	    case "pt":
	        nomDia = llista[1][dia];
	        break;
	    case "en":
	        nomDia = llista[2][dia];
	        break;
	    case "fr":
	        nomDia = llista[3][dia];
	        break;
        case "it":
	        nomDia = llista[4][dia];
	        break;
	    case "de":
			nomDia = llista[5][dia];
			break;
	    default:
	        nomDia = llista[0][dia];
	        break;
	}	
	return nomDia;		
}
// Funcion que retorna el numero maxim de dies del mes
function dte_getMaxDaysMonth(month, year){
    month = parseInt(month,10);
    year = parseInt(year,10);
    
    switch (month){
		case 2: 
		    if (((year % 4) != 0) || (((year % 100) == 0) && ((year % 400) != 0)))
		        return 28;
		    else
		        return 29;
		    break;
		case 4: case 6: case 9: case 11: 
		    return 30;
		default:
		    return 31;
	}
}

//function que retorna un String de 2 digits
function dosDigits(num){
	var str = num.toString();
	switch (str.length){
	case 1: return "0"+ str;
	case 2: return str;
	default: return str.substring(0,2);
	}
}

function dte_fechaPermitida(fecha)
{
	if(this.listaFechas!=null){
		var key = fecha.getDate() + "/" + (parseInt(fecha.getMonth(), 10)+1) + "/" + fecha.getFullYear();
		return (this.listaFechas[key]!=null);
	}
	return true;
}

function dte_mesPermitido(mes, anyo)
{
	if(this.listaMeses!=null){
		var key = mes.toString() + "/" + anyo.toString();
		return (this.listaMeses[key]!=null);
	}
	return true;
}

function dte_anyadirMes(mes, indice)
{
	var name = this.getNombreMes(mes,1);
	var anyo = (mes >= this.tmonth)?(this.tyear):(this.tyear + 1);
	if (this.appendFullYearToMonth){
		name += " " + String(anyo);//.substring(2); Tiene que aparecer el anyo completo en el select de mes.
	}
	
	if(this.mesPermitido(mes, anyo)){
		this.monthsObject.options[indice] = new Option(name,mes);
	}
}
