/*
 * DISTRIBUCION
 */

function showHabitacion(valor, tipo) {
    if (valor == '3') {
        document.getElementById('hab_distriH1_' + tipo).className = 'show_distri hab_distri1';
        document.getElementById('hab_distriH2_' + tipo).className = 'show_distri hab_distri2';
        document.getElementById('hab_distriH3_' + tipo).className = 'show_distri hab_distri2';
    } else if (valor == '2') {
        document.getElementById('hab_distriH1_' + tipo).className = 'show_distri hab_distri1';
        document.getElementById('hab_distriH2_' + tipo).className = 'show_distri hab_distri2';
        if (document.getElementById('hab_distriH3_' + tipo) != null) {
			document.getElementById('hab_distriH3_' + tipo).className = 'hidden_distri hab_distri2';
			showEdad('numnin_3', '0', tipo);
		}
    } else if (valor == '1') {
        document.getElementById('hab_distriH1_' + tipo).className = 'show_distri hab_distri1';
        if (document.getElementById('hab_distriH2_' + tipo) != null) {
			document.getElementById('hab_distriH2_' + tipo).className = 'hidden_distri hab_distri2';
			showEdad('numnin_2', '0', tipo);
		}
        if (document.getElementById('hab_distriH3_' + tipo) != null) {
			document.getElementById('hab_distriH3_' + tipo).className = 'hidden_distri hab_distri2';
			showEdad('numnin_3', '0', tipo);
		}  
    } else {
        return;
    }
}

function showEdad(numNinId, valor, tipo) {
    var id = 'seled_' + numNinId.split('_')[1];
    if (valor == '2') {
        document.getElementById(id + '0_' + tipo).className = 'show_edad';
        document.getElementById(id + '1_' + tipo).className = 'show_edad';
        document.getElementById(id + '_' + tipo).className = 'gris_10 show_edad';
    } else if (valor == '1') {
        document.getElementById(id + '0_' + tipo).className = 'show_edad';
        document.getElementById(id + '1_' + tipo).className = 'hidden_edad';
        document.getElementById(id + '_' + tipo).className = 'gris_10 show_edad';
    } else if (valor == '0') {
        document.getElementById(id + '0_' + tipo).className = 'hidden_edad';
        document.getElementById(id + '1_' + tipo).className = 'hidden_edad';
        document.getElementById(id + '_' + tipo).className = 'hidden_edad';
       /* document.getElementById(numNinId + '_' + tipo).options[0].selected = true;*/
    } else {
        return;
    }
}

/* proceso que establece la distribucion de la ocupacion de pasajerosque se pasa al refdistri*/
function referdistri(tipo)
{
    var distri = '';
    var novadistri = '';
    var sep = "A";
    //individual,doble,tiple,cuadruple
    var tiphab = new Array(0, 0, 0, 0);

    var nhabi = document.getElementById('numhab_' + tipo).value;
    if (parseInt(nhabi) == 1) {
        distri = '1' + sep + getNumAdu(nhabi, tipo) + getNumNin(nhabi, tipo);
    } else {
        var cont = parseInt(nhabi) + 1;
        for (var i = 1; i < cont; i++) {
            if (getNumNin(i, tipo) == '')
                tiphab[getNumAdu(i, tipo) - 1] ++;
            else {
                if (novadistri != '')
                    novadistri += 'D';
                novadistri += '1' + sep + getNumAdu(i, tipo) + getNumNin(i, tipo);
            }
        }
        //montamos distri
        for (var j = 0; j < tiphab.length; j++) {
            if (tiphab[j] != 0) {
                if (distri != '')
                    distri += 'D';
                distri += tiphab[j] + sep + (j + 1);

            }
        }
        if (novadistri != '')
            distri += 'D' + novadistri;
    }
    return distri;
}

function referdistri2(tipo){
    var distri = new Array();
    var group = new Array();
    var result = '';
    var nhabi = document.getElementById('numhab_' + tipo).value;
    /* Contamos cuantas habitaciones hay de una misma distri con una hash*/
    for (var i=1; i<=nhabi; i++){
        var d = getNumAdu(i, tipo) + getNumNin(i, tipo);
        if (!group[d]){
            group[d] = 1;
        } else {
            group[d]++;
        }
    }
    /* Formamos la distri con el numero de habitaciones */
    for (var j in group){
        distri.push(group[j].toString() + 'A' + j.toString());
    }
    /* Las habitaciones se separan con una D */
    return distri.join('D');
}

/* Miramos el nº de adultos que hay seleccionados*/
function getNumAdu(valor, tipo) {
    var nadu = parseInt(document.getElementById('numadu_' + valor + '_' + tipo).value) ;
    return nadu;
}

/* Miramos el nº de niños/bebes que hay seleccionados*/
function getNumNin(valor, tipo) {
    var dis = '';
    var ind = document.getElementById('numnin_' + valor + '_' + tipo).value;
    if (ind != 0) {
        for (var i = 0; i < ind; i++){
            var edad = document.getElementById('seled_' + valor + i + '_' + tipo).value;
            if (edad == 0) {
                dis += 'A1';
            } else {
                dis += 'A' + edad;
            }

        }
            
    }
    return dis;
}

function cambiaNNoches(formId, Value, calendar, numInput) {
    var form = document.getElementById(formId);
    var campoE = numInput ? document.getElementById('fecha_orig' + numInput) : document.getElementById('fecha_orig0');
    var campoR = numInput ? document.getElementById('fecha_dest' + numInput) : document.getElementById('fecha_dest0');


    var String1 = campoE.value;
    var String3 = campoR.value;
    var Data1_arr = String1.split('/');
    var Data3_arr = String3.split('/');
    var current_date;

    current_date = new Date(Data1_arr[2], (Data1_arr[1]) - 1, Data1_arr[0]);
    var new_years_date = new Date(Data3_arr[2], (Data3_arr[1]) - 1, Data3_arr[0]);
    var Dias = days_between(new_years_date, current_date);

    if ((Value == ' ') || (Value == '0') || (Value == '')) {
        cambiaNNoches(1, 0, null, numInput);
    }
    if (calendar == 0) {
        if (Dias < 0) {
            form.numnoc.value = 0;
        } else if (!isNaN(Dias)) {
            form.numnoc.value = Dias;
            // modifica el campo de días cuando el valor es numérico y positivo
        }
    }
    if (calendar == 1) {
        var DateFec = Number(form.numnoc.value);
        DateFec = campoE.value;
        for (var i = 0; i < form.numnoc.value; i++) {
            DateFec = incDate(DateFec);
        }
        if (DateFec.indexOf("NaN") == -1)
            campoR.value = DateFec;
    }
}

//Envio de datos
function enviarFormHotel(nivel, formId) {
    var form = document.getElementById(formId);
    var msg;

        error = checkformHotel(form);
        if (error != '')
        {
            if (error == 'numadu==0') {
                alert('El número de adultos no puede ser 0. ');
                return;
            } else {
                alert(error);
                return;
            }
        }
        //miramos si tambien se encuentra marcado 'vuelo'

        form.codtse.value = 'HT';
        form.conpgr.value = 'HT';
        form.filtra.value = 'impbas##[*]codzge##[*]codsca##[*]codral##';
        form.codzge.value = form.autht.value;
        if (document.getElementById('HT.codzge'))
            document.getElementById('HT.codzge').value = form.autht.value;
        //rellenamos el multid por si es multidisponibilidad
        form.multid.value = 'HT';
        form.codtou.value = 'THO#HTS#GLO';
        form.codcam.value = 1;
        if (form.medloc)
            form.medloc.value = 'KM';
        if (form.valloc)
            form.valloc.value = 25;

    if (form.eventId){
        form.eventId.value = completaParametroTradeDoubler(form);
    }


    var ruta = 'forward.do';
    //var ruta = 'http://www.solytravel.com/forward.do';
    if (nivel != null)
        ruta = nivel;
    form.action = ruta;
    form.target = '_parent';
    //form.target = '_top';
    form.submit();
}

function checkformHotel(form) {
    var error = '';

    form.codele.value = 'impbas';
    form.chkasc.value = 'S';
    form.numrst.value = '10';

    error = validarHotel(form);

        if (error == '')
        {
            form.distri.value = referdistri(form.id == 'buscadorHotel'? 'HT': 'MU');
            error = validateDate(form,'hotel');
            if (error == '')
            {
                if (form.id != 'buscadorVueloHotel') {
                    if (form.fecini.value == '')
                        form.fecini.value = form.fecha_orig0.value;
                    if (form.fecfin.value == '')
                        form.fecfin.value = form.fecha_dest0.value;
                }

                    /* else {
}
                    document.getElementById('HT.fecini').value = form.fecini.value;
                    document.getElementById('HT.fecfin').value = form.fecfin.value
                } */
                /*si es combinada con vuelo, hay que adjuntar la hora*/

                /*if (form.id == 'buscadorVueloHotel'){
                    error = validatePassengersNum('MU'); 
                } else {
                    error = validatePassengersNum('HT');
                }

                if (error == '')
                {
                    //Cuando se usa el autocompletar
                    if (form.id != 'buscadorVueloHotel'){
                        var ht = form.autht.value;
                        if (ht != '')
                            form.codzge.value = ht;

                        if ((form.numnoc.value == '' ) || isNaN(form.numnoc.value))
                            return 'Número de Noches Incorrecto.';
                    }
                } else {
                    return error;
                }*/
            }
        }
    return error;
}

function validarHotel(form){
    var error='';
    if (form.multid.value != 'AE#HT' && form.inputArbol.value == ''){
        error = 'Debe introducir la ciudad en la que desea buscar su hotel';
    }
    return error;
}

function getPassengers(distri){
    var hab = distri.split('D');
    var numadu = 0;
    var numnin = 0;
    var numbeb = 0;

    for (var i=0; i<hab.length; i++){
        var numhab = 0;
        if (hab[i]){
            var pas = hab[i].split('A');
            if (pas[0] && parseInt(pas[0]) > 0){
                numhab = parseInt(pas[0]);

                if (pas[1]){
                    numadu += (parseInt(pas[1]) * numhab);
                }
                for (var j=2; j<=3; j++){
                    if (pas[j]){
                        if (parseInt(pas[j]) < 2){
                            numbeb += (1 * numhab);
                        } else {
                            numnin += (1 * numhab);
                        }
                    }
                }
            }
        }
    }
    return {"numadu": numadu, "numnin": numnin, "numbeb": numbeb};
    
}

/* Calcula num de niños permitidos segun el num de adultos seleccionados */
function recalculaNinyos(id_select_adultos, numero_adultos, funcion) {
	id_select_ninyos = 'numnin_' + id_select_adultos.split('_')[1] + '_' + id_select_adultos.split('_')[2];
	var select_ninyos = document.getElementById(id_select_ninyos);
	if (numero_adultos < 3 && + select_ninyos.length == 3) return;
	while (select_ninyos.length > 0) select_ninyos.remove(0);
	// Maximo 4 personas; Maximo 2 niños
	for (i = 0; i <= 4 - numero_adultos && select_ninyos.length <= 2; i++) {
		var y = document.createElement('option');
		y.text = i;
		y.value = i;
		try {
			select_ninyos.add(y,null); // standards
		} catch(ex) {
			select_ninyos.add(y); // IE
		}
	}
	if (funcion == 'mostrarSelNinMini') mostrarSelNinMini(select_ninyos.id, id_select_adultos.split('_')[2]);
	else if (funcion == 'showEdad') showEdad(select_ninyos.id, select_ninyos.value, id_select_adultos.split('_')[2]);
	else showEdad(select_ninyos.id, select_ninyos.value, id_select_adultos.split('_')[2]);
}

/*function validatePassengersNum(tipo){
    var error = '';
    var numadu = parseInt(document.getElementById('numadu_' + tipo).value);
    var numbeb = parseInt(document.getElementById('numbeb_' + tipo).value);
    var numnin = parseInt(document.getElementById('numnin_' + tipo).value);

    var numhab = parseInt(document.getElementById('numhab_' + tipo).value);
    var totadu = 0;
    var totnin = 0;
    if (numhab >= 1){
        if (parseInt(document.getElementById('numadu_1_' + tipo).value) == 0){
            error += 'numadu==0';
            return error;
        }
         totadu += parseInt(document.getElementById('numadu_1_' + tipo).value);
         totnin += parseInt(document.getElementById('numnin_1_' + tipo).value);

        if (numhab >= 2){
            if (parseInt(document.getElementById('numadu_2_' + tipo).value) == 0){
                error += 'numadu==0';
                return error;
            }
            totadu += parseInt(document.getElementById('numadu_2_' + tipo).value);
            totnin += parseInt(document.getElementById('numnin_2_' + tipo).value);

            if (numhab == 3){
                if (parseInt(document.getElementById('numadu_3_' + tipo).value) == 0){
                    error += 'numadu==0';
                    return error;
                }
                totadu += parseInt(document.getElementById('numadu_3_' + tipo).value);
                totnin += parseInt(document.getElementById('numnin_3_' + tipo).value);
            }
        }
    }
    if (tipo == 'MU'){
        if (numadu != totadu){
            error += 'numaduVH';
        }else
            if ((numnin + numbeb) != totnin){
                error += 'numninVH';
            }
        return error;
    } else {
        return error;
    }     
    return error;
}*/