//manejar popups ej calendarios 
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('');
    $('#formspop').fadeOut();
}
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('/hotel/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){
        $("#fechaEntrada").attr("value", fecha);
        resetCombos();
        $("#fechaEntradaMos").html(fecha + ", "+ GetDiaNombre(fecha));
        fechaHotelVuelta();
    };
    hidepop();
	submitCheck();
}
function fechaHotelVuelta() {
    fecha = $("#fechaEntrada").attr("value");
    n = parseInt($("#noches").attr("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();
    $("#fechaVuelta").html(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 = ($("#entradaD").attr("value") + "/" + $("#entradaM").attr("value") + "/" + $("#entradaY").attr("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($("#entradaM").attr("value") + "/" + $("#entradaD").attr("value") + "/" + $("#entradaY").attr("value"));		
		var fArr = $("#fechaHoy").attr("value").split("/");
		hoy = new Date(fArr[1] + "/" + fArr[0] + "/" + fArr[2]);
		diferenciaDias = Math.round((f - hoy)/(24*60*60*1000));
		//if(diferenciaDias < -1  || diferenciaDias > 334) {
		if(diferenciaDias < -1) {
			return false;
		} else {
			return true
        }
    } else {
        return false;
    } 
}
function fechaCombo() {
	if (hotel_combo_check()) {
		fecha1 = $("#entradaD").attr("value") + "/" + $("#entradaM").attr("value") + "/" + $("#entradaY").attr("value");
		fecha2 = $("#entradaM").attr("value") + "/" + $("#entradaD").attr("value") + "/" + $("#entradaY").attr("value");
		$("#fechaEntrada").attr("value", fecha1);
		$("#fechaEntradaMos").html(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) {
        $("#buscar").show();
        $("#buscarDis").hide();
    } else {
        $("#buscar").hide()
        $("#buscarDis").show()
    }
}
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 niños
    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 = $("#fechaEntrada").attr("value");
    var fArr = fecha.split("/");
    var d = fArr[0]-1;
    var m = fArr[1]-1;
    //var y = fArr[2]-2008;
    
    var fechaHoy = $("#fechaHoy").attr("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=="Población" || 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() {
    $("#cont").hide();
    $("#capaPieHomeAlternativo").hide();
    $("#espera").show("slow");
}


//VALIDAR HOTELES...................................................................

function validarHoteles() {
	
    var msg='';
	var poblacion = quitarTilde($("#poblacion").attr("value"));	
	
	var fechahotel = cambiarFechaHotel($("#fechaEntrada").attr("value"));
	var noches = $("#noches").attr("value");
		
	var categoria = $("#categoria").attr("value");
	var regimen = $("#regimen").attr("value");
	var habitaciones = $("#habitaciones").attr("value");
    var ocupacion='';
	var edades='';
	var edadTempAux = "";
	
	var isBancotel = false;
	var isDebug = false;
	
	if($("#flagBancotel").attr("value")) {
		isBancotel = true;
	}
	if($("#flagDebug").attr("value")) {
		isDebug = true;
	}
	
	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++) {
			edadTempAux = $("#edad"+i+"-"+j).attr("value") + "-";
			//Si peta al cogerlo por JQuery, lo intentamos coger por el metodo tradicional que nunca falla
			if(edadTempAux == "undefined-") {
			
				edadTempAux = document.getElementById("edad" + i + "-" + j)[document.getElementById("edad" + i + "-" + j).selectedIndex].text + "-";
				alert(edadTempAux);
			}
			ed += edadTempAux;
		}
		ed = ed.substring(0,ed.length-1);
		edades += ed + "/";
	}
	
	

	ocupacion = ocupacion.substring(0,ocupacion.length-1);

	loading();

	var url='/hoteles/Buscador/ResultadosHoteles.aspx?pob=' + poblacion + '&cat=' + categoria + '&ocupa=' + ocupacion + '&edades=' + edades + '&numhab=' + habitaciones + '&ureg=' + regimen + '&fent=' + fechahotel + '&n=' + noches;
	
	if(isBancotel) {
		if(!isDebug) {
			url = "http://hoteles.muchoviaje.com" + url;
		}
		url += "&bancotel=true";
	}

	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;
}
