var mensajeMaximo = "Solamente valores permitidos entre {0} y {1}";
var mensajeSeleccionPais = "Indique un Pais";
var mensajeSeleccionDias = "Indique un número de días";
var mensajeSeleccionPersonas = "Indique un número de Personas";
var textoUnidades="N&ordm; Unidades:";
var caracterMiles = ".";

var rutaXML = "xml/xmlCalculadoraGastos.xml";
var xmlDoc;
var xmlPais;
var ddlPais;
var tblAlojamiento;
var tblManutencion;
var tblTransporte;
var tblExcursion;
var tblRegalo;
var rbtnTasaSi;
var txtPersonas;
var txtDias;
var lblMoneda;
var dolar;
var euro;
var imgDerechaPrecios;
var imgConsejos;
function ReiniciarFormulario() {
    ddlPais.val("");
//    txtDias.val("");
//    txtPersonas.val("");
    $("input:checked").attr("checked", false);
    $("input:text").val("");
    ReiniciarAccordion();
    
}

function AlIniciar() {
    ddlPais = $("#ddlPais");
    tblAlojamiento = $("#tblAlojamiento");
    tblTransporte = $("#tblTransporte");
    tblManutencion = $("#tblManutencion");
    tblExcursion = $("#tblExcursion");
    tblRegalo= $("#tblRegalo");
    rbtnTasaSi=$("#rbtnTasaSi");
    txtPersonas=$("#txtPersonas");
    txtDias = $("#txtDias");
    imgDerechaPrecios = $("#imgDerechaPrecios");
    imgConsejos = $("#imgConsejos");
    lblMoneda = $("#lblMoneda");
    
    ddlPais[0].onchange = SeleccionPais;
    $("#txtPersonas").blur(function() {
        return Limite(this, 1, 10);
    });

    $("#txtDias").blur(function() {
        return Limite(this, 1, 30);
    });
    
    CreateAccordion()


}

function Limite(obj, min, max) {
    var cantidad = parseInt($(obj).val());
    if (isNaN(cantidad))
    {
        cantidad = min;
        $(obj).val("");
        return false;
    }
    if ((cantidad>max) || (cantidad<min)){
        alert(mensajeMaximo.replace("{0}",min).replace("{1}",max))
        obj.focus();
        obj.select();
        return false;
    }
    return true;
}

function SeleccionPais() {

    jQuery.ajax({
        type: "GET",
        url: rutaXML,
        dataType: "xml",
        success: function(xml) {
            xmlDoc = $(xml);
            xmlPais = xmlDoc.find('pais[codigo="' + ddlPais.val() + '"]');
            tblAlojamiento.html("");
            lblMoneda.html(xmlPais.attr("moneda"));
            
            xmlPais.find('hotel').each(function() {
                var h = $(this);
                tblAlojamiento.append('<tr><td width="20"><input name="rbtnAlojamiento" type="radio" value="' + h.text() + '" /></td><td height="25">' + h.attr("text") + '</td></tr>');
            }
            );

            tblManutencion.html("");
            xmlPais.find('comida').each(function() {
                var h = $(this);
                tblManutencion.append('<tr><td width="20"><input name="rbtnComida" type="radio"  value="' + h.text() + '"/></td><td height="25">' + h.attr("text") + '</td></tr>');
            }
            );

            tblTransporte.html("");
            xmlPais.find('transporte').each(function() {
                var h = $(this);
                tblTransporte.append('<tr><td width="20"><input name="rbtnTransporte" type="radio"  value="' + h.text() + '" /></td><td height="25">' + h.attr("text") + '</td></tr>');
            }
            );
            tblExcursion.html("");
            xmlPais.find('excursion').each(function() {
                var h = $(this);
                tblExcursion.append('<tr><td><label><input type="checkbox" name="checkbox3"  value="' + h.text() + '"/></label></span>' + h.attr("text") + '<span class="Estilo32"> </td></tr>');
            }
            );
            tblRegalo.html("");
            tblRegalo.append("<tr></tr>");
            var trRegalo = tblRegalo.find("tr");

            xmlPais.find('regalo').each(function() {
                var h = $(this);
                trRegalo.append('<td><table><tr><td>' + h.attr("text") + '</td></tr>' +
                '<tr><td><img src="' + h.attr("imagen") + '" width="100" height="81" /></td></tr>' +
                '<tr><td>' + textoUnidades + '<label><input name="txtUnidades" class="txtUnidades" type="text" size="2" maxlength="2" onBlur="javascript: return Limite(this,0, 10);"/><input class="txtUnidadesValue" type="hidden" value="' + h.text() + '"/></label></td></tr>' +
                '</table></td>');
            }
            );
            var impuesto = parseFloat(xmlPais.find('impuesto').eq(0).text());
            if (isNaN(impuesto))
                impuesto = 0;
            rbtnTasaSi.val(impuesto);
            dolar = parseFloat(xmlPais.find('dolar').text());
            if (isNaN(dolar))
                dolar = 1;
            euro = parseFloat(xmlPais.find('euro').text());
            if (isNaN(euro))
                euro = 1;

        }
    });
    //close $.ajax(
    
    var codigoPais = ddlPais.val();
    imgDerechaPrecios.attr("src", "imagenes/calculadora/IMG_Derecha_Precios_" + codigoPais + ".jpg");
    imgConsejos.attr("src", "imagenes/calculadora/consejos_" + codigoPais + ".jpg");
	
    
}


function CalcularPrecio() {
    
    var numPersonas=parseInt(txtPersonas.val());
    var numDias = parseInt(txtDias.val());
    
    if (isNaN(numPersonas))
        numPersonas = parseFloat(0);
    if (isNaN(numDias))
        numDias = parseFloat(0);
    var numDecimales=2
    var total=parseFloat(0);
    tblAlojamiento.find("input:checked").each(function() {
        total += parseFloat($(this).val()) * numPersonas * numDias;
    });
			//alert("Alojamiento: " + total);
    
    tblManutencion.find("input:checked").each(function(){
        total+=parseFloat($(this).val()) * numPersonas * numDias;
    });
    			//alert("Manutencion: " + total);
    tblTransporte.find("input:checked").each(function(){
        total+=parseFloat($(this).val()) * numPersonas;
    });
    			//alert("transporte: " + total);
    tblExcursion.find("input:checked").each(function(){
        total+=parseFloat($(this).val()) * numPersonas;
    });
    			//alert("Excursion: " + total);
    var txtUnidades = $(".txtUnidades");
    var txtUnidadesValue = $(".txtUnidadesValue");
    var i=0;
    while (txtUnidades[i]) {
        var num = parseInt(txtUnidades.eq(i).val());
        
        if (isNaN(num)) {
            num = 0;
        }
        var val = parseFloat(txtUnidadesValue.eq(i).val());
        
        total += parseFloat(val * num);
        i++;
    }
    			//alert("Regalos: " + total);
    if (rbtnTasaSi.attr("checked")==true)
        total += parseFloat(rbtnTasaSi.val())* numPersonas;
			//alert("Tasa: " + total);
    var totalLocal = total
    var totalDolares = total * dolar;
    var totalEuros = total * euro;

    $("#divTotal").val(FormateaMiles(parseInt(totalLocal.toFixed(numDecimales))));
    $("#divTotalDolares").val(FormateaMiles(parseInt(totalDolares.toFixed(numDecimales))));
    $("#divTotalEuros").val(FormateaMiles(parseInt(totalEuros.toFixed(numDecimales))));

	if(ddlPais.val()=="ESP")
	{
    $("#trTotalEuros").css("display", "none");
    }else
	{
		$("#trTotalEuros").css("display","block");
		}
		
		
}

function FormateaMiles(numero) {
    var sNumero = numero.toString();
    var sFormato = "";
    var i = 0;
    while (i < sNumero.length) {
        if ((i>0) && (parseInt(i % 3) == 0)) {
            sFormato = caracterMiles + sFormato;
        }

        sFormato = sNumero.charAt(sNumero.length - 1 - i) + sFormato;
        
        i++;
    }
    return sFormato   
}

function CreateAccordion() {
    
    var accordion = $("#basic-accordian");
    var headers = accordion.find(".accordion_headings");
    var childs = accordion.find(".accordion_child").parent();
    var checkboxes = accordion.find("input:checkbox");
    var i = 0;
    while (headers[i]) {
        headers.eq(i).attr("idchild", i);
        checkboxes.eq(i).attr("idchild", i);
        i++;
    }
    accordion.click(function() {
        checkboxes.each(function() {
        var child = childs.eq($(this).attr("idchild"));
        this.checked = child.find(":checked").length > 0
        });
    }
    );

    checkboxes.click(function() {
        var child = childs.eq($(this).attr("idchild"));
        if (!this.checked) {
            child.find("input:checked").attr("checked", false);
        }
        
    });
    
    i = 0;
    while (childs[i]) {
        childs.eq(i).attr("idchild", i);
        i++;
    }
    childs.css("display", "none");
    childs.css("overflow", "hidden");
    childs.height(0);
    var childOpen = null;

    headers.click(function() {
        childs.attr("open", "false");
        var child = childs.eq($(this).attr("idchild"));
        child.attr("open", "true");

        var alto = 0;
        if (child.height() != 100)
            alto = 100;
        if (childOpen) {
            childOpen.animate({ height: 0 }, 500, function() {
                var o = $(this);
                o.css("display", "none");
                childOpen = null;
            });
        }
        
        if ((childOpen==null) || (child.attr("idchild") != childOpen.attr("idchild"))) {
            child.animate({ height: alto }, 500, function() {
                var o = $(this);
                o.css("display", "block");
                childOpen = o;

            });
        }
        
    });

}

function ReiniciarAccordion() {
    var accordion = $("#basic-accordian");
    var childs = accordion.find(".accordion_child").parent();
    childs.css("display", "none");
    childs.height(0);
}

function Visualizar(pasoSiguiente, pasoActual) {

    //realizamos las validaciones
    if ((pasoActual == 1) && (pasoSiguiente == 2)) {
        if (ddlPais.val() == "") {
            alert(mensajeSeleccionPais);
            return;
        }
        var personas = parseInt(txtPersonas.val());
        if (isNaN(personas)) {
            alert(mensajeSeleccionPersonas);
            return;
        }
        var dias = parseInt(txtDias.val());
        if (isNaN(dias)) {
            alert(mensajeSeleccionDias);
            return;
        }

    }
    var tblpaso1 = document.getElementById("paso1");
    var tblpaso2 = document.getElementById("paso2");
    var tblpaso3 = document.getElementById("paso3");
    var tblpaso4 = document.getElementById("paso4");
    var tblpasoActual = document.getElementById("paso" + pasoActual);
    tblpaso1.style.display = "none";
    tblpaso2.style.display = "none";
    tblpaso3.style.display = "none";
    tblpaso4.style.display = "none";
    switch (pasoSiguiente) {
        case 1: 
            {
                tblpaso1.style.display = "block";
                if (pasoActual == 4)
                    ReiniciarFormulario();

                break;
            }
        case 2:
            {
                if (pasoActual == 1) {
                    var personas = parseInt(txtPersonas.val());
                    if (isNaN(personas)) {
                        alert(mensajeSeleccionPersonas);
                    }
                    var dias = parseInt(txtDias.val());
                    if (isNaN(dias)) {
                        alert(mensajeSeleccionDias);
                    }
                    
                }
                tblpaso2.style.display = "block";
                break;
            }
        case 3: 
            {
                tblpaso3.style.display = "block";
                break;
            }
        case 4: 
            {
                CalcularPrecio();
                tblpaso4.style.display = "block";
                break;
            }

    }

}


$(document).ready(AlIniciar);