//--------------------------------------------------------------------------------
// Objeto selector de fecha de salida/llegada
//--------------------------------------------------------------------------------
function Selector ( locale ){
    
    /**************/
    /* propietats */
    /**************/
    
    //data actual (de referència)
    this.fechaActual = new Date();
	this.fechaActual.setHours(0,0,0,0);
    
    //numero de calendaris, per defecte 3
    this.numCalendarios=3;	
	this.calendarios = new Array();
    
    //guarda el dia seleccionat (obj Date), per defecte el dia d'avui
    this.fechaSeleccionada = new Date(this.fechaActual);
    
    //referencia al id del selector, selector dia, selector mes-any, id boto retrocede i id boto avanza
    this.idDivSelector = '';
    this.objDivSelector;    
	this.idSelectorDia = '';
    this.idSelectorMesAnyo = '';
    this.idRetrocede='';
    this.idAvanza='';
	this.idInicio='';
    
    //dates limits (inicial i final), per defecte el dia actual + 12 mesos
    this.fechaInicial = new Date( this.fechaActual );
    this.fechaFinal = new Date( this.fechaInicial );
    this.fechaFinal.setMonth(this.fechaInicial.getMonth()+12);	
	
	// Array de id's con los dias marcados.
	this.diasMarcados=new Array();
	this.diasMarcadosIDX= new Array();
	// Fecha del primer dia que se puede realizar reserva.
	this.fechaIniReserva=null;
	
	if( locale ){
		this.locale = locale;
	}else{
		this.locale=new Array();
		this.locale["hoy"]="Hoy";
		this.locale["inicio"]="Inicio";
	}
    
    /***********/
    /* mètodes *
    /***********/
    
    //identificadors
    this.setIdDivSelector     = setIdDivSelector;
    this.setIdSelectorDia     = setIdSelectorDia;
    this.setIdSelectorMesAnyo = setIdSelectorMesAnyo;
    this.setIdRetrocede       = setIdRetrocede;
    this.setIdAvanza          = setIdAvanza;
	this.setIdInicio	  	  = setIdInicio;
    
    //parametres
    this.setFechaInicial      = setFechaInicial;
    this.setFechaFinal        = setFechaFinal;
    this.setNumCalendarios    = setNumCalendarios;
    this.isInicio             = isInicio;
    this.isFinal              = isFinal;
    
    //interns
    this.desplaza             = desplaza;
    this.getFecha             = getFecha;
    
    //comandes
	this.setLocale			  = setLocale;
	this.getLocale			  = getLocale;	
    this.setDia               = setDia;
    this.retrocede            = retrocede;
    this.avanza               = avanza;
    this.updateSelector       = updateSelector;
    this.updateCalendario     = updateCalendario;
    this.init                 = init;
	this.addDisponible		  = addDisponible;	
	this.addReservado		  = addReservado;
	this.selecInicio 		  = selecInicio;
	this.llenarSelectDia	  = llenarSelectDia;
	this.llenarSelectMesAnyo  = llenarSelectMesAnyo;
    this.borrarSelect		  = borrarSelect;
	this.cambiaDia			  = cambiaDia;
	this.cambiaMes			  = cambiaMes;
	this.actualizaBotones	  = actualizaBotones;
	
    /*****************/
	/* final objecte */
    /*****************/
    
    // Método para sobreescribir en caso de querer realizar acciones cuando se cambie la fecha del selector.
    this.diaActualizado = function(){};
}	

/****************************/
/* INICI DESCRIPCIÓ MÈTODES */
/****************************/

function init(){
	var fechaTemp;
	var index;
	
    //cream els calendaris
    for( var i=0; i<this.numCalendarios; i++){
    
        fechaTemp = new Date(this.fechaInicial);
        fechaTemp.setDate(1);
		fechaTemp.setMonth( fechaTemp.getMonth()+i );
        
        index = this.calendarios.length;		
        
        this.calendarios[index] = new Calendario( this.objDivSelector, this );
		
        this.calendarios[index].setMesAnyo( fechaTemp.getMonth(), fechaTemp.getFullYear() ); 
		
		if( i+1 < this.numCalendarios){
            //cream el separador vertical entre calendaris
			var espacioH=document.createElement("div");
			espacioH.className="espacioH";
			this.objDivSelector.appendChild(espacioH);
		}        
	}
	
	if( this.fechaIniReserva != null ){
		this.fechaSeleccionada = this.fechaIniReserva;
	}
	
	if( this.idInicio != '' && this.fechaIniReserva!=null ){
		botonInicio = document.getElementById( this.idInicio );
		if( this.fechaActual.compareTo( this.fechaIniReserva ) == 0 ){			
			botonInicio.innerHTML=this.locale["hoy"];
		}else{
			botonInicio.innerHTML=this.locale["inicio"];
		}
	}
		
    //omplim els selectors del dia i del mes/any i marcam el dia actual    
 	this.llenarSelectMesAnyo();
	this.llenarSelectDia();	
 	this.updateSelector();
}

function retrocede(){

    var fechaMin=new Date( this.fechaInicial.getFullYear(), this.fechaInicial.getMonth(), 1 );
    var fechaAnt=new Date( this.calendarios[0].anyo, this.calendarios[0].mes, 1 );
    
    //restem 2 mesos 
    fechaAnt.setMonth(fechaAnt.getMonth()-2);
    
    if (fechaMin.compareTo(fechaAnt) > 0 ) {
        //excedim el limit inferior restant 2 mesos
    
        fechaAnt.setMonth( fechaAnt.getMonth()+1 );
        
        if (fechaMin.compareTo(fechaAnt) <= 0 ) {
        
            //no excedim el limit inferior restant 1 mes
            this.desplaza(-1);
        
        }
        
    }else{    
        //no excedim el limit inferior
        this.desplaza(-2);
        
    }
    
}
function avanza(){
	numCal = this.calendarios.length;
	
    var fechaMax=new Date( this.fechaFinal.getFullYear(), this.fechaFinal.getMonth(), 1 );
    var fechaAnt=new Date( this.calendarios[ numCal-1 ].anyo, this.calendarios[ numCal-1 ].mes, 1 );
    
    //sumem 2 mesos
    fechaAnt.setMonth(fechaAnt.getMonth()+2);
    
    if (fechaAnt.compareTo(fechaMax) > 0 ) {
        //excedim el limit superior sumant 2 mesos    
        fechaAnt.setMonth( fechaAnt.getMonth()-1 );                
        
        if (fechaAnt.compareTo(fechaMax) <= 0 ) {                                
			//no excedim el limit superior sumant 1 mes
            this.desplaza(1);        
        }
        
    }else{    
        //no excedim el limit superior
        this.desplaza(2);        
    }   
}

function desplaza(numMeses){

    var fecha=new Date( this.calendarios[0].anyo,this.calendarios[0].mes, 1 );
    fecha.setMonth(fecha.getMonth()+numMeses);
    
    for(var i=0; i<this.numCalendarios; i++) {
        this.calendarios[i].setMesAnyo( fecha.getMonth(), fecha.getFullYear() );
        fecha.setMonth( fecha.getMonth()+1 );
    }	    
}

function setLocale( locale ){
	this.locale = locale;
}
function getLocale(){
	return this.locale;
}

function updateSelector(){	
	
    var nuevoSelectDia=false;
	
	//marca mes i any
    objSelMesAny = document.getElementById(this.idSelectorMesAnyo);
    for (i=0; i<objSelMesAny.options.length; i++){
        opc = objSelMesAny.options[i];
        if ( opc.value == (this.fechaSeleccionada.getMonth())+'/'+this.fechaSeleccionada.getFullYear() ){
            opc.selected = true;
			nuevoSelectDia=true;
        }else{
            opc.selected = false;
        }
    }
	
	if( nuevoSelectDia ){		
		this.llenarSelectDia( this.fechaSeleccionada );
	}
    
	//marca dia
    objSelDia = document.getElementById(this.idSelectorDia);
    for (i=0;i<objSelDia.options.length;i++){
        opc = objSelDia.options[i];
        if ( parseInt(opc.value,10) == parseInt(this.fechaSeleccionada.getDate(),10) ){
            opc.selected = true;
        }else{
            opc.selected = false;
        }
    }
	    
}

function updateCalendario(anyo,mes,dia){
    objDia = document.getElementById(dia+'/'+mes+'/'+anyo)
    objDia.className+=' seleccionado';
}

function setIdDivSelector(nomSelector) {
    this.idDivSelector = nomSelector;
    this.objDivSelector = document.getElementById(this.idDivSelector);
}
function setIdSelectorDia(nombre){
    this.idSelectorDia = nombre;
}
function setIdSelectorMesAnyo(nombre){
    this.idSelectorMesAnyo = nombre;
}
function setIdRetrocede(nombre){
    this.idRetrocede = nombre;
}
function setIdAvanza(nombre){
    this.idAvanza = nombre;
}
function setIdInicio(nombre){
	this.idInicio=nombre;
}
function setFechaInicial(any,mes,dia){
    this.fechaInicial = new Date(any,mes,dia,0,0,0,0);
}
function setFechaFinal(any,mes,dia){
    this.fechaFinal = new Date(any,mes,dia,0,0,0,0);
}
function setNumCalendarios(numCal){
    this.numCalendarios = numCal;
}
function isInicio(){
    strIni = this.fechaInicial.getFullYear()+'-'+this.fechaInicial.getMonth();
    strAct = this.calendarios[0].anyo+'-'+this.calendarios[0].mes;
    return (strIni==strAct);
}
function isFinal(){
	numCal = this.calendarios.length;	
	
	var fechaUltimoCal=new Date( this.calendarios[numCal-1].anyo, this.calendarios[numCal-1].mes,1 );	
	//fecha.setMonth( fecha.getMonth()+1 );	
	
	var fechaLimite = new Date( this.fechaFinal );
	fechaLimite.setDate(1);
	    
	/*strAct = fecha.getFullYear()+'-'+fecha.getMonth();    
	strFin = this.fechaFinal.getFullYear()+'-'+this.fechaFinal.getMonth();
    return (strFin==strAct);
	*/    
	
	return fechaUltimoCal.compareTo( fechaLimite ) == 0;
}

function setDia(strDia){
    aux = strDia.split('/'); 
    dia= parseInt(aux[0],10);
    mes= parseInt(aux[1],10);
    any= parseInt(aux[2],10);
    
	if( (a = document.getElementById( this.fechaSeleccionada.toDMA() )) ){
		a.className="diaDisponible"	;
	}
	
    //actualitzem la data dins l'objecte
    this.fechaSeleccionada = new Date(any,mes,dia,0,0,0,0);
	
	if( (a = document.getElementById( this.fechaSeleccionada.toDMA() )) ){
		a.className="diaSeleccionado"	;
	}		        
	
	var fechaTemp=new Date( this.fechaSeleccionada );
	fechaTemp.setDate(1);
	var fechaCal0=new Date( this.calendarios[0].anyo, this.calendarios[0].mes, 1, 0,0,0,0 );
	var fechaCal2=new Date( this.calendarios[ this.calendarios.length-1 ].anyo, this.calendarios[ this.calendarios.length-1 ].mes, 1, 0,0,0,0 );
	
	dist=0;			
	if( fechaTemp.compareTo( fechaCal0) < 0 ){				
		while( fechaTemp.compareTo( fechaCal0 ) < 0 ){
			fechaTemp.setMonth( fechaTemp.getMonth()+1 );
			dist++;
		}
		this.desplaza( -dist );
	}else if( fechaTemp.compareTo( fechaCal2 ) > 0 ){		
		while( fechaTemp.compareTo( fechaCal2 ) > 0 ){
			fechaCal2.setMonth( fechaCal2.getMonth()+1 );
			dist++;
		}		
		this.desplaza( dist );
	}
	
	//actualitzem el selector
    this.updateSelector();
	this.actualizaBotones();
	
	this.diaActualizado();
}

function selecInicio(){	
	if( this.fechaIniReserva ){
		this.setDia( this.fechaIniReserva.toDMA() );
	}
}

function addDisponible( fecha ){
	if( !this.fechaIniReserva ){
		this.fechaIniReserva=new Date( fecha );
	}
	this.diasMarcados[ fecha.toDMA() ] = "disponible";
	
	//avallbona
	arrAux = fecha.toDMA().split('/');
	
	//clau any-mes
	clau = arrAux[2]+'-'+arrAux[1];
	if (!this.diasMarcadosIDX[clau]){
	    this.diasMarcadosIDX[clau] = new Array();
	}
	
	//afegim un objecte option per cada dia disponible
	ind = this.diasMarcadosIDX[clau].length;
	this.diasMarcadosIDX[clau][ind] = new Option(arrAux[0],arrAux[0]);
	
}

function addReservado( fecha ){
	this.diasMarcados[ fecha.toDMA() ] = "reservado";
}

//--------------------------------------------------------------------------------
    
function cambiaMes( obj ){			
	/*var fecha=getFecha( this.idSelectorDia, this.idSelectorMesAnyo );
	fecha.setDate(1);
	this.llenarSelectDia( fecha );
	fecha=getFecha( this.idSelectorDia, this.idSelectorMesAnyo );	
	this.setDia( fecha.toDMA() );*/
	
	var sel = document.getElementById( this.idSelectorMesAnyo );	
	var mes = sel.options[ sel.selectedIndex ].value.split("/")[0];
	var anyo = sel.options[ sel.selectedIndex ].value.split("/")[1];
	
	var fecha = new Date( anyo, mes, 1, 0, 0, 0, 0);
	
	this.llenarSelectDia( fecha );
	
	sel = document.getElementById( this.idSelectorDia );
	var dia = sel.options[ sel.selectedIndex ].value;
	fecha.setDate( dia );
	this.setDia( fecha.toDMA() );
}
	
//--------------------------------------------------------------------------------
	
function actualizaBotones(){
	var a;
	
	var fechaAnt=new Date( this.calendarios[0].anyo, this.calendarios[0].mes, 1 );			
	var fechaSig=new Date( this.calendarios[ this.calendarios.length-1 ].anyo, this.calendarios[ this.calendarios.length-1 ].mes, 1 );
	
	fechaAnt.setMonth( fechaAnt.getMonth()-1 );
	fechaSig.setMonth( fechaSig.getMonth()+1 );						
		
	a=document.getElementById( this.idRetrocede );
	a.innerHTML=this.locale["meses"][ fechaAnt.getMonth() ] +' '+ fechaAnt.getFullYear();
	a.style.display = oSel.isInicio() ? "none" : "inline";			
	
	a=document.getElementById( this.idAvanza );
	a.innerHTML=this.locale["meses"][ fechaSig.getMonth() ] +' '+ fechaSig.getFullYear();
	a.style.display = oSel.isFinal() ? "none" : "inline";			
}

//--------------------------------------------------------------------------------

function cambiaDia(){
	var selDia=document.getElementById( this.idSelectorDia );
	var selMesAny=document.getElementById( this.idSelectorMesAnyo );
	
	var fecha=this.getFecha( this.idSelectorDia, this.idSelectorMesAnyo );
	oSel.setDia( fecha.toDMA() );
}		
//--------------------------------------------------------------------------------

function llenarSelectDia( fecha ){
	var objSel=document.getElementById(this.idSelectorDia);
    var fechaTemp, i, mes;
    
    this.borrarSelect( objSel );
	
	if( !fecha ){
		fecha =  this.fechaInicial;		
	}
	
    /*	
	fechaTemp = new Date( fecha );
	fechaTemp.setDate(1);
    mes=fecha.getMonth();		 
    while( ( fechaTemp.getMonth() == mes ) ){
        if( fechaTemp.compareTo( this.fechaInicial ) >= 0 ){	
            i=objSel.options.length;
            objSel.options[i]=new Option( fechaTemp.getDate(), fechaTemp.getDate() );
        }
        fechaTemp.setDate( fechaTemp.getDate()+1 );
    }
    */
    
    //objecte de data temporal que ens serveix per a la verificació de l'hora limit de reserves del dia actual
    var fechaTmp = new Date(fecha);
    var diaPassat = false;
	
	llistaDies = this.diasMarcadosIDX[fecha.getFullYear()+'-'+fecha.getMonth()];
	for(i=0;i<llistaDies.length;i++){
	    
	    fechaTmp.setDate(llistaDies[i].value);
	    
	    //si esteim al dia actual, verifiquem l'hora límit per fer reserves
		if (fechaTmp.getDate()==this.fechaActual.getDate() && fechaTmp.getMonth()==this.fechaActual.getMonth() && fechaTmp.getFullYear()==this.fechaActual.getFullYear()){
		    
		    //data auxiliar per agafar l'hora actual
            var horaActual = new Date();
            fechaTmp.setHours(horaActual.getHours(),horaActual.getMinutes(),horaActual.getSeconds(),horaActual.getMilliseconds());
            
            //fixem la data limit al dia actual
            this.fechaActual.setHours(14,0,0,0);                
            
            //si el l'hora és major que l'hora limit el dia ja ha passat
            diaPassat = fechaTmp.getTime()>=this.fechaActual.getTime();
		    
		    //tornem a fixar les hores a 0
		    fechaTmp.setHours(0,0,0,0);
		    this.fechaActual.setHours(0,0,0,0);
		    
		}else{
		    
		    diaPassat = false;
		    
		}
					
	    if (!diaPassat){
            objSel.options[objSel.options.length] = new Option(llistaDies[i].text,llistaDies[i].value);
	    }
	    
	}
	
}

//--------------------------------------------------------------------------------

function llenarSelectMesAnyo( fecha ){
	var fechaTemp;
    var objSel = document.getElementById(this.idSelectorMesAnyo);
		
    this.borrarSelect(objSel);
    
	// Si no le pasamos la fecha por parámetro utilizamos la fecha actual.
	if( !fecha ){
	    //obtenim la data inicial
	 	fechaTemp = new Date(this.fechaInicial);
	}else{
		fechaTemp = fecha;
	}
	   
    //anem creant els options
    
    /*
    while ( fechaTemp.compareTo(this.fechaFinal) < 0 ){
    
        nom = this.calendarios[0].locale["meses"][fechaTemp.getMonth()]+' '+fechaTemp.getFullYear();
        val = (fechaTemp.getMonth())+'/'+fechaTemp.getFullYear();
        
        objSel.options[objSel.options.length] = new Option(nom,val);
        
        fechaTemp.setMonth(fechaTemp.getMonth()+1);        
    }    
    */
    
    for (clau in this.diasMarcadosIDX){
        aux=clau.split('-');
        nom = this.calendarios[0].locale["meses"][aux[1]]+' '+aux[0];
        val = (aux[1])+'/'+aux[0];
        objSel.options[objSel.options.length] = new Option(nom,val);
    }
    
}

// Borra un select
function borrarSelect( sel ){						
	while( sel.options.length > 0 ){
		sel.options[0] = null;
	}				
}				

// Obtiene la fecha almacenada en dos selectores.
function getFecha( idSelDia, idSelMesAny ){
	var selDia=document.getElementById( idSelDia );
	var selMesAny=document.getElementById( idSelMesAny );

	var dia=parseInt(selDia.options[ selDia.selectedIndex ].value,10);
	var mes=parseInt(selMesAny.options[ selMesAny.selectedIndex ].value.split('/')[0],10);
	var any=parseInt(selMesAny.options[ selMesAny.selectedIndex ].value.split('/')[1],10);
	
	return new Date( any, mes, dia );
}


/****************************/
/* FINAL DESCRIPCIÓ MÈTODES */
/****************************/

/*****************/
/* Extensió DATE */
/*****************/
Date.prototype.toIso=function(inicial){
    if (typeof(inicial)=='undefined'){
        inicial=0;
    }
    //var dia = this.getDate()<10 ? '0'+this.getDate() : this.getDate();
    var dia = this.getDate();
    var mes = this.getMonth()+inicial;
    var any = this.getFullYear();
    //mes = mes <10 ? '0' + mes : mes;
    return (any+'-'+mes+'-'+dia);
}
Date.prototype.toDMA=function(inicial){
    //controlem si el més de gener volem que sigui zero o 1, per defecte 1
    if (typeof(inicial)=='undefined'){
        inicial=0;
    }
    //var dia = this.getDate()<10 ? '0'+this.getDate() : this.getDate();
    var dia = this.getDate();
    var mes = this.getMonth()+inicial;
    var any = this.getFullYear();
    //mes = (mes) <10 ? '0' + mes : mes;
    return (dia+'/'+mes+'/'+any);
}
Date.prototype.toAMD=function(inicial){
    //controlem si el més de gener volem que sigui zero o 1, per defecte 1
    if (typeof(inicial)=='undefined'){
        inicial=0;
    }
    //var dia = this.getDate()<10 ? '0'+this.getDate() : this.getDate();
    var dia = this.getDate();
    var mes = this.getMonth()+inicial;
    var any = this.getFullYear();
    //mes = (mes) <10 ? '0' + mes : mes;
    return (any+'/'+mes+'/'+dia);
}

Date.prototype.toParam=function(inicial){
    if (typeof(inicial)=='undefined'){
        inicial=0;
    }
    return (this.getFullYear()+','+(this.getMonth()+inicial)+','+this.getDate());
}

//comparem dues dates
// retorna 0 si són iguals
// retorna 1 si la data de l'objecte es major que la data que ens pasen
// retorna -1 si la data de l'objecte es menor que la data que ens pasen
Date.prototype.compareTo=function (objFecha){
    if ( this.getTime() == objFecha.getTime() ){
        return 0;
    }else if (this.getTime() > objFecha.getTime() ){
        return 1;
    }else{
        return -1;
    }
}

// Mirar si una fecha se encuentra en un rango
// retorna 1 sin la fecha se encuentra dentro del rango y 0 en caso contrario.
Date.prototype.between=function(objFechaIni, objFechaFin ){
	return ( this.compareTo( objFechaIni ) >= 0 && this.compareTo( objFechaFin ) <=0 );
}

/********************/
/* Fi extensió DATE */
/********************/