﻿//manejar popups ej calendarios 
var isIE = (window.navigator.userAgent.indexOf("MSIE")> 0);  
function ninosybebes(callback) {

	if(callback){
		hidepop();
	} else {
		combo('none');
		load('includes/ninosybebes.aspx', 'formspop');
	}
}
function formSel(targ) {
	$('#hotelF').removeClass('f1Sel');
	$('#paqueteF').removeClass('f2Sel');
	css = (targ =='paqueteF'? 'f2Sel' : 'f1Sel');
	eval("$('#' + targ).addClass('" + css + "');");
	$('#formspop').hide();
}
function combo(disp) {
    //apagar o mostrar combos (en ie no puedes flotar elementos encima de un combo)
    for (var f = 0; f < document.forms.length; f++){
        for (var e = 0; e < document.forms[f].length; e++) {
			if(disp =="none") {
				if (document.forms[f].elements[e].options) document.forms[f].elements[e].style.visibility = "hidden";
			} else {
				if (document.forms[f].elements[e].options) document.forms[f].elements[e].style.visibility = "visible";
			}
        }
    }
}
function hidepop() {
    combo('');
        document.getElementById("formspop").style.visibility="hidden";
}
function loadAeropuertos(callback) {
    combo('none');
    params = "callback=" + callback;
    load('includes/aeropuertos.aspx?' + params, 'formspop');
}
function loadCal(callback, quefecha, habdesde, habhasta) {
    //ver calendario.aspx para variables
    combo('none');
    var fechasel = $("#" + quefecha).attr("value");
    var fArr = fechasel.split("/");
    var d = mLength(fArr[0]);
    var m = mLength(fArr[1]);
    var y = yLength(fArr[2]);
    fechasel = y+"-"+m+"-"+d;
    params = "callback=" + callback + "&fechasel=" + fechasel + "&habdesde=" + habdesde + "&habhasta=" + habhasta;
    load('includes/calendario.aspx?' + params, 'formspop');
}
function aeroSalidaCB(aeropuerto) {
    if(aeropuerto){$('#origen').attr({ value: aeropuerto})};
    hidepop();
    submitCheck()
}
function aeroRegresoCB(aeropuerto) {
    if(aeropuerto){$('#destino').attr({ value: aeropuerto})};
    hidepop();
    submitCheck()
}
function fechaHotelCB(fecha) {
    if(fecha){
    
        document.getElementById("fechaEntrada").value= fecha;
        resetCombos();
            if (! isIE){  
                    document.getElementById("fechaEntradaMos").textContent=fecha + ", " + GetDiaNombre(fecha);

 
}
else
{
        document.getElementById("fechaEntradaMos").innerText=fecha + ", " + GetDiaNombre(fecha);
}

        
        fechaHotelVuelta();
    };
    //hidepop();
submitCheck();

}
function fechaHotelVuelta() {
    fecha =document.getElementById("fechaEntrada").value;
    n = parseInt(document.getElementById("noches").value);
    var fArr = fecha.split("/");
    var d = fArr[0];
    var m = fArr[1]-1;
    var y = fArr[2];
    var fVuelta=new Date();
    fVuelta.setFullYear(y,m,d);
    fVuelta.setDate(fVuelta.getDate()+n);
    fVuelta = fVuelta.getDate() + "/" + (fVuelta.getMonth()+1) + "/" + fVuelta.getFullYear();
    if (! isIE){  
    document.getElementById("fechaVuelta").textContent= fVuelta + ", "+ GetDiaNombre(fVuelta);
 
}
else
{
	document.getElementById("fechaVuelta").innerText=fVuelta + ", "+ GetDiaNombre(fVuelta);
}

    
}
function fechaIdaCB(fecha) {
    if(fecha){
        $("#fechaIda").attr("value", fecha);
        $("#fechaIdaMos").html(fecha + ", "+ GetDiaNombre(fecha));
        $("#fechaVuelta").attr("value", fecha);
        $("#fechaVueltaMos").html(fecha + ", "+ GetDiaNombre(fecha));
        var col =(compariridavuelta()? "#333" : "#f60")
        $("#fechaVueltaMos").css("color",col);
    };
    hidepop();
}
function fechaVueltaCB(fecha) {
    if(fecha){
        $("#fechaVuelta").attr("value", fecha);
        $("#fechaVueltaMos").html(fecha + ", "+ GetDiaNombre(fecha));
        var col =(compariridavuelta()? "#333" : "#f60")
        $("#fechaVueltaMos").css("color",col);
    };
    hidepop();
}
//funciones para probar si el formulario puede submit o no
function hotel_combo_check() {
	probarFecha = document.getElementById("entradaD").value + "/" + document.getElementById("entradaM").value + "/" + document.getElementById("entradaY").value;
	var reg = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
    if (probarFecha.match(reg)) {
		//probar fecha es mas que ayer y menos que hoy+334
		f =  new Date(document.getElementById("entradaM").value + "/" +document.getElementById("entradaD").value + "/" + document.getElementById("entradaY").value);
		var fArr = document.getElementById("fechaHoy").value.split("/");
		hoy = new Date(fArr[1] + "/" + fArr[0] + "/" + fArr[2]);
	    diferenciaDias = Math.round((f - hoy)/(24*60*60*1000));
		if(diferenciaDias < -1 ) {
			return false;
		} else {
			return true
        }
    } 
    else 
    {
        return false;
    } 
}
function fechaCombo() {
	if (hotel_combo_check()) {
	
        fecha1="";
        if (document.getElementById("entradaD").value!='' && document.getElementById("entradaD").value!=undefined)
		{
            if (document.getElementById("entradaM").value!='' && document.getElementById("entradaM").value!=undefined)
		    {
                if (document.getElementById("entradaY").value!='' && document.getElementById("entradaY").value!=undefined)
		        {
  
    	            fecha1 = document.getElementById("entradaD").value + "/" + document.getElementById("entradaM").value + "/" + document.getElementById("entradaY").value;
    	            fecha2 = document.getElementById("entradaY").value + "/" + document.getElementById("entradaM").value + "/" + document.getElementById("entradaD").value;
//		            fecha2 = $("#entradaM").attr("value") + "/" + $("#entradaD").attr("value") + "/" + $("#entradaY").attr("value");
		        }
		    }
		}
				var f = new Date(fecha2 );
	   		 BuscadorHoteles1_calendarioCtrl.SetSelectedDate(f,true);

     
	document.getElementById("fechaEntrada").value= fecha1;
if (! isIE){  	
document.getElementById("fechaEntradaMos").textContent= fecha1 + ", " + GetDiaNombre(fecha1);
 		    //document.getElementById("BuscadorHoteles1_calendarioCtrl").VisibleDate="30-07-09";


}
else
{
	document.getElementById("fechaEntradaMos").innerText= fecha1 + ", " + GetDiaNombre(fecha1);
}
	fechaHotelVuelta();
//        f =  new Date(fecha2);
		//calendarioCtrl.SetSelectedDate(f,true)
	} else {
		alert('Fecha no valida');
	}

	submitCheck();
}

function submitCheck() {
    if($("#hotelform").attr("name")) {
        (hotel_poblacion_check() && hotel_o_paquete_edad_check() && hotel_combo_check() ? submitshowhide(true) : submitshowhide(false))
    }
    if($("#paqueteform").attr("name")) {
        (paquete_origen_y_destino_check() && hotel_o_paquete_edad_check() ? submitshowhide(true) : submitshowhide(false))
    }
}
function submitshowhide(val) {
    if(val) {
            document.getElementById("buscarDis").style.visibility="hidden";
            document.getElementById("buscar").style.visibility="visible";
            document.getElementById("buscar").style.display="";
    } else {
            document.getElementById("buscar").style.visibility="hidden";
            document.getElementById("buscarDis").style.visibility="visible";
            document.getElementById("buscarDis").style.display="";
    }
}
function hotel_poblacion_check() {

    //segurar que poblacion no es igual a "poblacion" o con valor blanco
    p = trim($("#poblacion").attr("value") ? $("#poblacion").attr("value") : " ")
    return (p == 'Poblacion' || p =='' || p.charCodeAt(0) == 32 ? false : true)
}

function hotel_o_paquete_edad_check() {
    //segurar que los edades estan rellenados
    var allgood = true;
    for(var i=1;i<=$("#habitaciones").attr("value");i++) {
				n = $("#habitacion-" + i).attr("value").split("-")
				n= (n[1]? n[1] : 0);
				for(var j=1;j<=n;j++) {
					if(document.getElementById("edad" + i + "-" + j).selectedIndex == 0) { allgood = false; }
				}
            }
    return allgood;
}
function paquete_origen_y_destino_check() {

    //segurar que destino y origen no son igual o con valor blanco
    if ($("#destino").fieldValue() == $("#origen").fieldValue()) {
        $("#destino")[0].selectedIndex = 0; //set destino back to "destino" if its = to origen
    }
    return ($("#origen").fieldValue() == 'Origen' || $("#destino").fieldValue() == 'Destino' ? false : true)
}

function cambiarOcupacion(which, val) {
	var n = val.split('-')[1]; //cuantos nios
    n = (!n ? 0 : parseInt(n));
    if (n == 0) {
		$("#edades" + which).hide();
    } else {
		$("#edades" + which).show();
		for(var i =1;i<4;i++) { $("#edad" + which + "-" + i).hide(); }
		for(i=1;i<=n;i++) { $("#edad" + which + "-" + i).show(); }
	} 
	submitCheck()
}
function cambiarHabitaciones(val) {
	for(var i =1;i<5;i++) {
		$("#hab" + i).hide();
	}
	for(i =1;i<=val;i++) {
		$("#hab" + i).show();
	}
	submitCheck()
}

//funciones generals para manejar fechas etc
function resetCombos() {
	fecha = document.getElementById("fechaEntrada").value;
    var fArr = fecha.split("/");
    var d = fArr[0]-1;
    var m = fArr[1]-1;
    //var y = fArr[2]-2008;
    
    var fechaHoy =document.getElementById("fechaHoy").value.split("/");
	var hoy = new Date(fechaHoy[1] + "/" + fechaHoy[0] + "/" + fechaHoy[2]);
	
	//alert(hoy.getFullYear());
    
    var y = fArr[2]-hoy.getFullYear();
    select('entradaD', d);
    select('entradaM', m);
    select('entradaY', y);
}
function select(id, indice) {
	document.getElementById(id).selectedIndex=indice;
}
function prepDest(cual) {
    v = cual.value
    if (v == "Origen" || v=="Poblacin" || v=="Destino") {
		cual.value="";
		submitshowhide(false);
    }
}
function compariridavuelta() {
    //comparir ida vs vuelta para avisar si vuelta antes que ida
    fIda = $("#fechaIda").attr("value");
    fVuelta = $("#fechaVuelta").attr("value");
    iArr = fIda.split('/');
	vArr = fVuelta.split('/');
	i = yLength(iArr[2])+mLength(iArr[1])+mLength(iArr[0]);
	v = yLength(vArr[2])+mLength(vArr[1])+mLength(vArr[0]);
	return ((Number(i))<=(Number(v)) ? true : false);
}
function contarPersonas(str){
    if(!str){str = "";}
    n= str.split("-");
    n[0] = (parseInt(n[0])? n[0] : 0);
    n[1] = (parseInt(n[1])? n[1] : 0);
    return parseInt(n[0]) + parseInt(n[1]);
}
function GetDiaNombre(fecha) {
	//fecha tiene que estar en formato dd/mm/yy o d/m/yy o yyyy
	m = fecha.match(/^(\d*)(\/?)(\d*)(\2)(\d\d)?(\d\d)$/);
	m[1] = mLength(m[1]); // 6 -> 06 dia
	m[3] = mLength(m[3]); // 6 -> 06 mes
	m[5] = yLength(m[5]); // 07 -> 2007 anio
	d =["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo"];
	return d[new Date(m[5] + m[6] + "/" + m[3] + "/" + m[1]).getDay()];
}
function yLength(y) {
	y = (parseInt(y) < 100 ? "20" + y : y);
	return y;
}
function mLength(m) {
	m = (m.length == 1 ? "0" + m : m);
	return m;
}
function cambiarFechaHotel(fecha) {
	iArr = fecha.split('/');
	y = yLength(iArr[2]);
	m = mLength(iArr[1]);
	d = mLength(iArr[0]);
	fecha = y + '-' + m + '-' + d;
	return fecha;
}
function quitarTilde(str) {
	rep ={"á":"-aacute","é":"-eacute","í":"-iacute","ó":"-oacute","ú":"-uacute","Á":"-Aacute","É":"-Eacute","Í":"-Iacute","Ó":"-Oacute","Ú":"-Uacute","ñ":"-ntilde","Ñ":"-Ntilde"};
	for(var p in rep) {
		str=str.replace(p,rep[p]);
	}
	return str;
}
function loading() {
    document.getElementById("global").style.visibility="hidden";
    document.getElementById("global").style.display="none";
 	document.getElementById("Espera").style.visibility="visible";
    document.getElementById("Espera").style.display="inline";

}


//VALIDAR HOTELES...................................................................

//VALIDAR HOTELES...................................................................

function validarHoteles() {
    var msg='';
       var poblacion = quitarTilde(document.getElementById("BuscadorHoteles1_poblacion").value)
    if (poblacion=="")
    {
        alert('Debe seleccionar al menos un destino.')
	return false;
    }
	//var poblacion = quitarTilde($("#poblacion").attr("value"))
	var fechahotel = cambiarFechaHotel(document.getElementById("fechaEntrada").value)
	var noches = parseInt(document.getElementById("noches").value)
	var categoria = document.getElementById("categoria").value
	var regimen = document.getElementById("regimen").value
	var habitaciones = document.getElementById("habitaciones").value
    var ocupacion='';
	var edades='';

	for(var i=1;i<=habitaciones;i++) {
		//obtener ocupaciones y edades
		ocupacion += document.getElementById("habitacion-" + i).value + "/";
		var n = document.getElementById("habitacion-" + i).value.split("-")[1]; //cuantos ninos
		n = (!n ? 0 : parseInt(n));
		var ed=(n == 0 ? "--" : "");
		for(var j=1;j<=n;j++) {
			//ed += $("#edad"+i+"-"+j ).attr("value") + "-";
			ed += document.getElementById("edad" + i + "-" + j).selectedIndex + "-";
		}
		ed = ed.substring(0,ed.length-1);
		edades += ed + "/";
	}

	ocupacion = ocupacion.substring(0,ocupacion.length-1);
	loading();
	var url='http://hoteles.muchoviaje.com/hoteles/Buscador/ResultadosHoteles.aspx?pob=' + poblacion + '&cat=' + categoria + '&ocupa=' + ocupacion + '&edades=' + edades + '&numhab=' + habitaciones + '&ureg=' + regimen + '&fent=' + fechahotel + '&n=' + noches;
	document.location.href=url;
	return false;
}

//VALIDAR PAQUETES...................................................................

function validarPaquetes() {
	var dest=4
	var origen = $("#origen").fieldValue()
	var destino = $("#destino").fieldValue()
	var fechabusqueda = cambiarFechaHotel($("#fechaEntrada").attr("value"))
	var bebes = $("#bebes").fieldValue()
	var noches = $("#noches").fieldValue()
	var categoria = '1' //todas las estrellas por defecto (sort luego)
	var categoria = $("#categoria").attr("value")
	var habitaciones = $("#habitaciones").attr("value")
    var ocupacion='';
	var edades='';
	for(var i=1;i<=habitaciones;i++) {
		//obtener ocupaciones y edades
		ocupacion += $("#habitacion-" + i).attr("value") + "/";
		var n = $("#habitacion-" + i).attr("value").split("-")[1]; //cuantos ninos
		n = (!n ? 0 : parseInt(n));
		var ed=(n == 0 ? "--" : "");
		for(var j=1;j<=n;j++) {
			ed += $("#edad"+i+"-"+j ).attr("value") + "-";
		}
		ed = ed.substring(0,ed.length-1);
		edades += ed + "/";
	}
	ocupacion = ocupacion.substring(0,ocupacion.length-1);
	loading()
	url='http://islas.muchoviaje.com/Vuelos-Hoteles/aspx/Buscador.aspx?codorg=' + origen + '&coddst=' + destino + '&fechs=' + fechabusqueda + '&noches=' + noches + '&bebes=' + bebes + '&ocup=' + ocupacion +  '&edad=' + edades + '&dest=' + dest;
	document.location.href=url;
	return false;
}

