// Fechas iniciales (HOY) y final (HOY MAS 1 AÑOS) del calendario

var v_info = false; //nos indica si hemos de cargar las fechas del info page o no
var info_from = ""  //para guardar las fechas del info page en el caso de que esten en el xml
var info_to = ""
var info_nigths = ""
var fechaActual = new Date();
var initAnyo = fechaActual.getFullYear();
var initMes_aux = fechaActual.getMonth() + 1;
var initMes = "";
    initMes = initMes_aux;
/*le ponemos un cero al mes en el caso de que sea necesario es decire meses menor de */
if (initMes_aux < 10){
    initMes = '0'+initMes;
}

var sigAnyo = initAnyo + 1;
var finMes = initMes;
var finAnyo = initAnyo + 2;

var anyoAnt =  initAnyo - 1;

if (document.getElementById('divcalendar') != null) {
    var cal1 = new CalendarPopup('divcalendar');
    var cal2 = new CalendarPopup('divcalendar');
}

// Calcula los días que tiene el mes.
// Pasamos el año para calcular los días de febrero (años bisiestos).
function diasMes (mes, ano) {
    var dias = 31;

    if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 )  dias = 30;
    else if  ( mes == 2 ) {
        if ( (ano % 4 == 0) && ( (ano % 100 != 0) || (ano % 400 == 0) ) )
            dias = 29;
        else
            dias = 28;
    }

    return dias;
}

function pintaNoches (id, max, init) {
    var act;

    if (init) act = 1;
    else
        act = document.getElementById(id).options[document.getElementById(id).options.selectedIndex].value;

   for (i = 1; i <= max; i++) {
    if (act == i) {
            document.getElementById(id).options[i] = new Option(i, i);
            document.getElementById(id).options[i].selected = true;
        }
        else
            document.getElementById(id).options[i] = new Option(i, i);
   }
}

function pintaDias (id, mes, ano, init, margen) {
//    alert('lo que recive '+mes);
    var dias = diasMes(mes, ano);
    var param = parseInt(margen);
    var dia_actual = fechaActual.getDate();
    var dia_aux = '';
    var index = 1;
    if (init == 0){
        dia_actual = document.getElementById(id).options[document.getElementById(id).options.selectedIndex].value;
    }
    else {
        if (dia_actual + param > dias){
            dia_actual = (dia_actual + param) % dias;
        }
        else {
            dia_actual = dia_actual + param;
        }

    }
    document.getElementById(id).disabled = false;
    document.getElementById(id).options.length = 0;

    for (i = 1; i <= dias; i++) {
        if (i < 10) dia_aux = '0'+i;
        else dia_aux = i;

        if ((id=='s_day1') || (id=='s_day3')){  
            if (dia_actual == i) {
                document.getElementById(id).options[i-1] = new Option(dia_aux, dia_aux);
                document.getElementById(id).options[i-1].selected = true;
            }else{
                document.getElementById(id).options[i-1] = new Option(dia_aux, dia_aux);
            }
        }else{
            if (dia_actual == i) {
                document.getElementById(id).options[i] = new Option(dia_aux, dia_aux);
                document.getElementById(id).options[i].selected = true;
            }else{
                document.getElementById(id).options[i] = new Option(dia_aux, dia_aux);
            }
        }
    }
    
     if (( id=='s_day2') && (page.indexOf("bol_motorTraslados2.jsp") != -1)){
        document.getElementById(id).options[0] = new Option('no','-1');
        document.getElementById(id).options[0].selected = true;
    }
}

// ----- Formato mes-anyo (xx-xxxx) -----
function getMes (id) {
    var mes = document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
    var aux = mes.toString();
    var aux2 = aux.split('-');
    return (aux2[0]);
}

function getAnyo (id) {
    var mes = document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
    var aux = mes.toString();
    var aux2 = aux.split('-');
    return (aux2[1]);
}

function setMesAnyo (id, mes, anyo) {
    var mes_anyo = mes + '-' + anyo;
    for (i = 0; i < document.getElementById(id).options.length; i++) {
        if (mes + '-' + anyo == document.getElementById(id).options[i].value)
            document.getElementById(id).options[i].selected = true;
    }
}

function setDia (id, dia) {
    document.getElementById(id).options[document.getElementById(id).selectedIndex].value = dia;
}

function setNoches (id, num) {
    for (i = 0; i < document.getElementById(id).options.length; i++) {
        if (num == document.getElementById(id).options[i].value)
            document.getElementById(id).options[i].selected = true;
    }
}

// --------------------------------------------------------------------------

function rePintaDias (idMes, idDias, init, margen) {
    var mes = getMes(idMes)
    var anyo = getAnyo(idMes);
    pintaDias(idDias, mes, anyo, init, margen);
}

function pintaMesAnyo (id, init,all_days, ano, margen) {
    var v_nomMeses = new Array(comb_key1,comb_key2,comb_key3,comb_key4,comb_key5,comb_key6,comb_key7,comb_key8,comb_key9,comb_key10,comb_key11,comb_key12);
    var v_numMeses = new Array('01','02','03','04','05','06','07','08','09','10','11','12');
    var year = '';
    var numyears = 0;
    var index = 1;
    if ((id =='s_mes1') || (id == 's_mes3')) index = 0;
    var mes_act =  Math.abs(0 - initMes);

    var dias = diasMes(mes_act, ano);
    var param = parseInt(margen);
    var dia_actual = fechaActual.getDate();

    if (init == 1 && (dia_actual + param > dias)){
        mes_act = mes_act + 1;
    }

    if (all_days=='true') numyears = 4;
    else numyears = 3;
    for (j=0; j<numyears; j++ ){
        if (all_days=='true'){
           if (j == 0) year = anyoAnt.toString();
           else if(j == 1)  year = initAnyo.toString();
           else if(j == 2)  year = sigAnyo.toString();
           else year = finAnyo.toString();
        }else{
           if (j == 0) year = initAnyo.toString();
           else if (j == 1) year = sigAnyo.toString();
           else year = finAnyo.toString();
        }
       /*escogemos el año en funcion de los que queramos cargar en la combo*/
       for(i=1; i<=12; i++) { /*reyenamos las combos contemplando varias cosas:*/
         if ((year==initAnyo.toString()) && (all_days!='true')){ /*si el año es el actual i no se carga los meses del año pasado*/
            if ( i >= mes_act) { /*escribimos solo los meses de hoy en adelante*/
               // alert('dentro ' + v_numMeses[i]+' indice '+i);
                document.getElementById(id).options[index] = new Option(v_nomMeses[i-1] + ' ' + year.substring(2, 4), v_numMeses[i-1] +'-' + year);
                index ++;
            }
         }else{/*si queremos el año pasado en la combo se escriben todos los meses*/
            document.getElementById(id).options[index] = new Option(v_nomMeses[i-1] + ' ' + year.substring(2, 4), v_numMeses[i-1] +'-' + year);
            index ++;
         }
      }
    }
    if (init) {
        for (i = 0; i < document.getElementById(id).options.length; i++) {
            if (dia_actual + param > dias){
                if ((initMes+1) + '-' + initAnyo == document.getElementById(id).options[i].value){
                    document.getElementById(id).options[i].selected = true;
                }
            }
            else {
                if (initMes + '-' + initAnyo == document.getElementById(id).options[i].value){
                    document.getElementById(id).options[i].selected = true;
                }
            }
        }
    }
    
    if (( id=='s_mes2') && (page.indexOf("bol_motorTraslados2.jsp") != -1)){
        document.getElementById(id).options[0] = new Option(comb_key13,'-1');
        document.getElementById(id).options[0].selected = true;
    }
}

function pintaSelectMesAnyo (id, m, y) {

    document.getElementById(id).disabled = false;

    for (i = 0; i < document.getElementById(id).options.length; i++) {
        if (document.getElementById(id).options[i].value == m + '-' + y)
            document.getElementById(id).options[i].selected = true;
    }
}

function pintaSelectDia (id, d) {
    for (i = 0; i < document.getElementById(id).options.length; i++) {
        if (document.getElementById(id).options[i].value == d)
            document.getElementById(id).options[i].selected = true;
    }
}

function pintaHoras (id) {

    document.getElementById(id).disabled = false;
    document.getElementById(id).options[0] = new Option('hh','-1');
    for (i = 1; i <= 24; i++) {
        if (i < 11){

           document.getElementById(id).options[i] = new Option('0' + (i-1), '0' + (i-1));
                       }
        else
            document.getElementById(id).options[i] = new Option(i-1, (i-1));
    }
     document.getElementById(id).selectedIndex = 0;
     
}

function pintaMinutos (id) {

    document.getElementById(id).disabled = false;
    document.getElementById(id).options[0] = new Option("mm", '-1');

    var i = 0;
    var j = 1;

    while (i <= 55) {
        if ((i == 0) || (i == 5))
            document.getElementById(id).options[j] = new Option('0' + i, '0' + i);
        else
            document.getElementById(id).options[j] = new Option(i, i);

        i = i + 5;
        j = j + 1;
    }
    document.getElementById(id).selectedIndex = 0;
}

// Obtenemos el Julian Day Number para poder restar las fechas con mayor facilidad.
// Podemos encontrar la explicación del calendario Juliano y el algoritmo en Internet.
// Ref: http://www.sizes.com/time/dayJulianr.htm
// Date format YYYYMMDD
function getJulianDate (yyyymmdd) {
      ymd = yyyymmdd;

      var iyear = ymd - (ymd % 10000);
      var imonth = (ymd - iyear);

      imonth = (imonth - (imonth % 100)) / 100;
      iyear = iyear / 10000;

      var iday = ymd % 100;

      if (imonth < 3) { imonth += 12; iyear --;}
      imonth++;

      var ia = (iyear - (iyear % 100)) / 100;
      var ib = (ia - (ia % 4)) / 4;
      var ic = 2 - ia + ib;
      var ie = (iyear + 4716) * 1461;

      ie = (ie - (ie % 4)) / 4;

      var ig = imonth * 306001;
      ig = (ig - (ig % 10000)) / 10000;

      var ijd = ic + iday + ie + ig - 1524;
      return ijd;
}

function sumaNoches (id, idDiaIni, idMesIni, idDiaFin, idMesFin) {
    var mes = getMes(idMesIni)
    var anyo = getAnyo(idMesIni);

    var num_noches = document.getElementById(id).value;

    var fecha = new Date();
    fecha.setDate(document.getElementById(idDiaIni).value);
    // Los meses empiezan por 0.
    fecha.setMonth(mes-1);
    fecha.setFullYear(anyo);

    var time = fecha.getTime();
    time = time + num_noches * 24 * 60 * 60 * 1000;
    time = new Date(time);

    setMesAnyo(idMesFin, (time.getMonth() + 1), time.getFullYear());
    setDia(idDiaFin, time.getDate());
    rePintaDias(idMesFin, idDiaFin, 0);
}     

function calculaNoches (id, idDiaIni, idMesIni, idDiaFin, idMesFin) {
    var mes1 = getMes(idMesIni);
    var anyo1 = getAnyo(idMesIni);
    var mes2 = getMes(idMesFin);
    var anyo2 = getAnyo(idMesFin);

    var fecha1 = new Date();
    fecha1.setDate(document.getElementById(idDiaIni).value);
    fecha1.setMonth(mes1-1);
    fecha1.setFullYear(anyo1);

    var fecha2 = new Date();
    fecha2.setDate(document.getElementById(idDiaFin).value);
    fecha2.setMonth(mes2-1);
    fecha2.setFullYear(anyo2);

    var dif_dias = parseInt((fecha2 - fecha1) / (1000 * 60 * 60 * 24));
    setNoches(id, dif_dias);
}

function cargaFecCombos(date,tipo,margen){
    var fecha = date.split('/');
    var id ='1';
    if (tipo=='to'){
         id ='2';
    }
    if (tipo=='from2'){
        id = '3';
    }
    document.getElementById("s_mes"+id).value = fecha[1]+'-'+fecha[2];
    rePintaDias("s_mes"+id, "s_day"+id, 0,margen)
    document.getElementById("s_day"+id).value = fecha[0];
}


// Pone la fecha correcta en el calendario con el valor de los combos y carga la fecha en los imputs.
function putDateCal (combom, combod,input_date) {

        var dias = document.getElementById(combod).value;
	var mes = getMes(combom);
	var anyo = getAnyo(combom);

	var fecha = new Date();
	fecha.setDate(dias);
	fecha.setMonth(mes - 1);
	fecha.setFullYear(anyo);
	cal.currentDate = fecha;

	//le ponemos el valor al input de la fecha
        if (dias == '-1'|| mes == '-1' || anyo == '-1') {
            document.getElementById(input_date).value='dd/mm/yyyy';
        }else {
            document.getElementById(input_date).value=dias+'/'+mes+'/'+anyo;
        }
	
    
	
}

/*funcion que se llama cuando se cambia las combos from*/
function changeDatefrom(from_name,all_days){
   putDateCal('s_mes1', 's_day1','i_from');
   returnFrom(from_name,'i_from','i_to','s_nights',all_days);
}

/*funcion que se llama cuando se cambia las combos from*/
function changeDatefrom2(from_name,all_days){
   putDateCal('s_mes3', 's_day3','i_from2');
   returnFrom(from_name,'i_from2','','s_nights',all_days);
}

function changeDateTo(from_name,all_days){
   putDateCal('s_mes2', 's_day2','i_to');
   returnTo(from_name,'i_from','i_to','s_nights',all_days);
}

function changeDateToCar(){
   putDateCal('s_mes2', 's_day2','i_to');
   //returnTo(from_name,'i_from','i_to','s_nights',all_days);
}


/*funcin que se llama desde el calendar2.js cuando se produce un error
 con las fechas y lo que hace es inicialicar las fechas al dia de hoy
function errorAction(){
   if (v_info){
        loadInfoDates()
   }else{
        pintaDias("s_day1", initMes, initAnyo, 1);
        pintaMesAnyo("s_mes1", 1);
        pintaDias("s_day2", initMes, initAnyo, 1);
        pintaMesAnyo("s_mes2", 1);
        //sumaNoches('comboNoches', 's_day1', 's_mes1', 's_day2', 's_mes2');
        putDateCal('s_mes1', 's_day1','i_from');
        putDateCal('s_mes2', 's_day2','i_to');
        dateFrom =  document.getElementById("i_from").value;
        dateTo =  document.getElementById("i_to").value;
        cal2.enableAllDates();
        cal2.addDisabledDates(null,calculateFinalDate(dateFrom,-1),dFormat);
   }

}                                                */

function loadComboDates(idmesAnyo,iddia,idinput){
    var date = document.getElementById(idinput).value;
    date = date.replace('/','-').replace('/','-');
    var dia = date.substring(0,2);
    var mesAnyo = date.substring(3);
    var options = document.getElementById(idmesAnyo).getElementsByTagName('option');
    for (i=0;i<options.length;i++) {
        if (document.getElementById(idmesAnyo).options[i].value == mesAnyo) document.getElementById(idmesAnyo).options[i].selected = true;
       // if (document.getElementById(iddia).options[i].value == dia) document.getElementById(iddia).options[i].selected = true; 
    }
    var options2 = document.getElementById(iddia).getElementsByTagName('option');
    for (i=0;i<options2.length;i++) {
        //if (document.getElementById(idmesAnyo).options[i].value == mesAnyo) document.getElementById(idmesAnyo).options[i].selected = true;
        if (document.getElementById(iddia).options[i].value == dia) document.getElementById(iddia).options[i].selected = true; 
    }
}

function returnComboIndex(id,code){
    var options = document.getElementById(id).getElementsByTagName('option');
    for (i=1;i<options.length;i++) {
        if (document.getElementById(id).options[i].value == code) return i;
    }
    return 0;
}


/*guarda los valores de las fechas del info page en variables glovales*/
function loadInfoVars(v_from,v_to,v_nights){
       // alert('infovars');
        v_info = true;
        info_from = v_from
        info_to = v_to;
        info_nigths = v_nights;
}

/*carga las fechas del impopage en las combos*/
function loadInfoDates(){
        document.getElementById('i_from').value = info_from;
        document.getElementById('i_to').value = info_to;
        if (info_nigths != 0 ){
            document.getElementById('comboNoches').value = info_nigths;
        } else {
            document.getElementById('comboNoches').value = 1;
        }
        

        dateFrom = document.getElementById('i_from').value;
        dateTo = document.getElementById('i_to').value;

        cargaFecCombos(info_from,"from",0);
        cargaFecCombos(info_to,"to",0);
}