
    /**    
    * hide all the rooms divs
    * and shows only for the num of rooms selected in the combo
    * @param num int with the number of comboRooms to show
    * @return nothing
    */
    function jsEngineInc__mostrarHabitaciones(num)
    {
        core__hideDiv("div_habita2");
        core__hideDiv("div_habita3");
        core__hideDiv("div_habita4");
        core__hideDiv("div_habita5");

        for (i=1; i<=num; i++)
        {
            core__showDiv('div_habita'+i);
        } 
    }

    /**    
    * hide all ages combos and show only the indicates
    * @param iEdad
    * @return nothing
    */
    function jsEngineInc__mostrarEdades(iEdad)
    {
        var edad = iEdad.split('-');
    
        // First, hide all combo ages
        for (i=1; i<=4; i++)
        {
            core__hideDiv('divEdad_'+edad[0]+'_'+i);
        }     
        // Show indicated
        for (i=1; i<=edad[2]; i++)
        {
            core__showDiv('divEdad_'+edad[0]+'_'+i);
        } 
    }

    /**
    * shows or hides the services div for the contract
    * @param string sObject
    * @param string sImagen
    */
    function jsEngineInc__ocultarMostrarDivServicios()
    {
        if(document.getElementById("divRelacionServicios").style.visibility == 'hidden')
        {        
            core__showDiv("divRelacionServicios");  
            document.getElementById('divBotonesServicios').innerHTML = '&nbsp;&#9658;&nbsp;<a href="#null" class="enlaceServicios" onclick=jsEngineInc__ocultarMostrarDivServicios("divRelacionServicios") >'+core__lang_t('Ocultar servicios')+'</a> &nbsp;&#9668;&nbsp;';
        }
        else
        {                                        
            core__hideDiv("divRelacionServicios");
            document.getElementById('divBotonesServicios').innerHTML = '&nbsp;&#9658;&nbsp;<a href="#null" class="enlaceServicios" onclick=jsEngineInc__ocultarMostrarDivServicios("divRelacionServicios")>'+core__lang_t('Mostrar servicios')+'</a> &nbsp;&#9668;&nbsp;';
        }
    }
    
    /**    
    * This function verify adding data and validate before jump to second step (summary)    
    */     
    function jsEngineInc__VerificaDatos()
    {             
        with(document.frm_DatosTitularReservaPaso1)
        { 
            
            if(!core__validateBlank("txtNombres",core__lang_t("Ingrese su nombre")))
            {
                return false;
            }
            
            if(!core__validateBlank("txtApellidos",core__lang_t("Ingrese sus apellidos")))
            {
                return false;
            }
            if(!core__validateEmail("txtEmail",core__lang_t("Ingrese su e-mail")))
            {
                return false;
            }
            if(!core__validateBlank("txtDNICIF",core__lang_t("Ingrese sus datos de identificación personal")))
            {
                return false;
            }
            if(!core__validateBlank("txtTelefono",core__lang_t("Ingrese su Teléfono o su móvil")))
            {
                return false;
            }            
            if(!core__validateCheckBox("chk_DatosPrivacidad",core__lang_t("Debe aceptar las condiciones de privacidad")))
            {
                return false;    
            } 
            if(!core__validateCheckBox("chk_CancelacionesHotel",core__lang_t("Debe aceptar las políticas del hotel")))
            {
                return false;    
            }                       
            if(!core__validateCheckBox("chk_CancelacionesSistema",core__lang_t("Debe aceptar las condiciones del sistema de reservas")))
            {
                return false;    
            }            

            submit();
        }
    }

    function jsEngineInc__VerificaDatosTarjetaCredito(directPayment)
    {
        with(document.frm_DatosTitularReserva)
        { 
            if(directPayment==1)
            {
                if(!core__validateBlank("txtNombresTC",core__lang_t("Ingrese el nombre del titular de la tarjeta de crédito")))
                {
                    return false;
                } 
                
                if(!core__validateBlank("txtApellidosTC",core__lang_t("Ingrese los apellidos del titular de la tarjeta de crédito")))
                {
                    return false;
                } 
                
                if(!core__validateBlank("txtNumeroTC",core__lang_t("Ingrese el numero de la tarjeta de crédito")))
                {
                    return false;
                }

                if(!core__validateBlank("txtCVV",core__lang_t("Ingrese el código de verificación")))
                {
                    return false;
                }

                if(sltMes.value==0)
                {
                   alert(core__lang_t("Ingrese el mes de caducidad de la tarjeta"));
                   return(false);
                } 
                if(sltAny.value==0)
                {
                   alert(core__lang_t("Ingrese el Año de caducidad de la tarjeta"));
                   return(false);
                }
                
                var sTipoTarjeta = document.getElementById('CardType').value;
                var iNumeroTarjeta = document.getElementById('txtNumeroTC').value;
                
                if (!core__checkCreditCard(iNumeroTarjeta,sTipoTarjeta)) 
                {
                    alert(core__lang_t("Error con el número de tarjeta"));
                    txtNumeroTC.focus();
                    return (false);
                }

            }
            submit();
        }        
    }

    /**    
    * This function allows to convert a number to float
    * @param int amount number to convert to float
    */
    function jsEngineInc__Decimales(amount)
    {
        var val = parseFloat(amount); 
        if (isNaN(val))
        { 
            return "0,00";
        } 
        if (val <= 0)
        { 
            return "0,00"; 
        } 
        val += ""; 
        
        // Next two lines remove anything beyond 2 decimal places 
        if (val.indexOf('.') == -1) 
        { 
            return val+",00"; 
        } 
        else
        { 
            val = val.substring(0,val.indexOf('.')+3); 
        } 
        val = (val == Math.floor(val)) ? val + '.00' : ((val*10 == Math.floor(val*10)) ? val + '0' : val);
        val = val.replace('.',',');
        
        return val;
    }
     
    /**    
    * This function check if value is set for init date and final date
    * 
    * @param string sFechaI
    * @param string sFechaF
    * @return string (false in wrong case, ok in right case)
    */
    function jsEngineInc__checkDatesFirstLast()
    {
        var miFechaI = document.getElementById("txt_fecha_inicial").value;
        var miFechaF = document.getElementById("txt_fecha_final").value;
                                                         
       // If exists value on the cities select field
        if( document.getElementById("sltCiudad") )
        { 
           valor = document.getElementById("sltCiudad").value;
              if (valor == 0)
              {
                  alert(core__lang_t("Seleccione la ciudad"));
                  return (false);
              }
        } 
      
        if(miFechaI == "")
        {
            alert(core__lang_t("La Fecha de entrada debe ser introducida"));
            
            document.getElementById("txt_fecha_inicial").focus();
            document.getElementById("txt_fecha_inicial").style.background = "#FFEAEA"; 

            return(false);
        }
        
        if(miFechaF == "")
        {
            alert(core__lang_t("La Fecha de salida debe ser introducida."));
            
            document.getElementById("txt_fecha_final").focus();
            document.getElementById("txt_fecha_final").style.background = "#FFEAEA"; 

            return(false);
        }

        if(!core__validateFormatDate(document.getElementById("txt_fecha_inicial")))
        {
            return (false);    
        }
        if(!core__validateFormatDate(document.getElementById("txt_fecha_final")))
        {
            return (false);    
        }
        
        fi = new Date(core__formatUsa(miFechaI));
        ff = new Date(core__formatUsa(miFechaF));
        
        if(ff<=fi)
        {
            alert(core__lang_t("La fecha de salida debe ser mayor al día de entrada"));
            return (false);
        }
        
        // If exists DIV of rooms divHabitaciones. This is when quantity of rooms are selected on the SEARCH RESULTS
        // and it's sended paramater of room config (cfg_habitaciones)
        if( document.getElementById("divHabitaciones") )
        { 
            var sCfgHabitaciones    = "";   // Room config
            var sHabitacion         = "";
            var aParametros         = "";
            var iNumAdultos         = 0;
            var iNumNinos           = 0;
            
            numHabitaciones = document.getElementById("slt_habitaciones").value;
            
            for(i=1; i<=numHabitaciones; i++)
            {                
                if(document.getElementById('div_habita'+i))
                {
                    if(document.getElementById('div_habita'+i).style.visibility == "visible")
                    {            
                        // We try rooms
                        sHabitacion    = document.getElementById('slt_habitacion_'+i).value;
                        aParametros    = sHabitacion.split('-');
                        iNumAdultos    = aParametros[1];
                        iNumNinos      = aParametros[2];
                        sCfgHabitaciones += i+'-'+iNumAdultos+'-'+iNumNinos;
                        
                        // Child ages
                        for(j=1; j<=iNumNinos; j++)
                        {
                            if (document.getElementById('slt_edades_'+i+'_'+j).value != '--')
                            {
                                sCfgHabitaciones += '-'+document.getElementById('slt_edades_'+i+'_'+j).value;
                            }
                            else
                            {
                                alert(core__lang_t('Se requiere todas las edades de los menores.'));
                                return;
                            }
                        }
                    }
                }
                else
                {
                    sCfgHabitaciones += i+'-2-0';
                }
                
                sCfgHabitaciones += '|';
            }
            
            document.getElementById("cfg_habitaciones").value = sCfgHabitaciones;
        }
                        
        document.forms["frmAlojaEngine"].submit();        
    }
    
    /**    
    * Set images into a Div for show images of services
    * @param string sArchivo
    */
    function jsEngineInc__ImagenServicio(file)
    {
        document.getElementById('divImagenPrincipal').innerHTML = '<img src= "'+file+'" width="280" height="240" style="border:3px solid #CCC"/>';
    }
    
    /**    
    * This function make control for malicious intent of insert a negative value on
    * a text box of "cantidad de servicios adicionales" for reservation
    * If client do "copy-paste" value with negative vaule, cantidad is set to zero
    */
    function jsEngineInc__serviceCalculate(iPayAllTpv, dComision, bPrecioComisionable, iImporteComision, bDirectPayment,dPorcDescuentoCliente)
    {
        
        valueList = document.getElementsByTagName('input');
         for(f=0; f<valueList.length; f++)
         {
             if(valueList[f].type=='text')
             {
                 value = parseInt(valueList[f].value);
                 
                 if(value<0)
                 {
                     alert(core__lang_t('No se admiten valores negativos'));
                     
                     subName = valueList[f].name.split('_');
                     
                     var txt = 'txtCantidad_'+subName[1]+'_'+subName[2];                     
                     document.getElementById(txt).value = parseInt(0);
                 }

                 jsEngineInc__Recalcular(iPayAllTpv,dComision,bPrecioComisionable,iImporteComision,bDirectPayment,dPorcDescuentoCliente);
             }
         }
     }
    
    /**    
    * This function read all selected checkboxes and his information
    * and do a calculation of all imports of reservation
    */
    function jsEngineInc__Recalcular(iPayAllTpv, dComision, bPrecioComisionable, iImporteComision, bDirectPayment,dPorcDescuentoCliente)
    {
        dHabitaciones       = document.getElementById('divImporteTotalHabitaciones').innerHTML;
        dHabitaciones       = jsEngineInc__floatFormat(dHabitaciones);
        
        dDescuentoCliente   = document.getElementById('divImporteDescuentoCliente').innerHTML;
        dDescuentoRG        = document.getElementById('divImporteTotalDescRG').innerHTML;
        dTotalServicios     = "0.00";
        dHabitaciones = jsEngineInc__roundValue(dHabitaciones,2);
        
        // If hotel don't have policy of RG we need to control posible errors on calculating
        // this is for check if we need to set a value after all and before present values
        existingRG = false;
        
        if(dDescuentoCliente=="")
        {
            dDescuentoCliente = "0.00";
        }
        else
        {
            dDescuentoCliente = jsEngineInc__floatFormat(dDescuentoCliente);
            dDescuentoCliente = jsEngineInc__roundValue(dDescuentoCliente,2);
        }

        var lista = document.getElementsByTagName('input');

        for(f=0;f<lista.length;f++)
        {
            
            if(lista[f].type == 'checkbox')
            {
                //alert(lista[f].name);
                if(lista[f].name == 'chk_ReservaGarantizada')
                {
                    existingRG = true;  // This indicate that we have RG checkbox and can use values of dDescuentoRG
                    // If checkbox is Guaranted Booking...
                    if(lista[f].checked)
                    {
                        dDescuentoRG = parseFloat(dHabitaciones) * parseFloat(lista[f].value)/100;
                        dDescuentoRG = jsEngineInc__roundValue(dDescuentoRG,2);
                    }
                    else
                    {
                        dDescuentoRG = "0.00";     
                    }
                }
            }
            
            if(lista[f].type == 'text')
            {
                subName = lista[f].name.split('_');
                if(subName[0]=='txtCantidad')
                {
                    //value = valueList[f].value; 
                    value = document.getElementById('txtCantidad_'+subName[1]+'_'+subName[2]).value

                    if( value != '')
                    {
                        dPrecioServicio = document.getElementById("divPrecio_"+subName[1]+"_"+subName[2]).innerHTML;
                        dPrecioServicio = jsEngineInc__floatFormat(dPrecioServicio);
                        cantidad = document.getElementById('txtCantidad_'+subName[1]+'_'+subName[2]).value;
                        subTotalServicio = parseFloat(dPrecioServicio) * parseFloat(cantidad);
                        dTotalServicios = parseFloat(dTotalServicios) + parseFloat(subTotalServicio);
                        
                        document.getElementById('divSubTotalServicio_'+subName[1]+'_'+subName[2]).innerHTML = jsEngineInc__moneyFormat(subTotalServicio);
                    }
                    else
                    {
                        document.getElementById('divSubTotalServicio_'+subName[1]+'_'+subName[2]).innerHTML = jsEngineInc__moneyFormat(0);    
                    }
                }
            }
        }
                
        if(existingRG == true)
        {
            if(document.getElementById("chk_ReservaGarantizada").checked == true)
            {
               document.getElementById("divMensajePagoRG").style.visibility = "visible";
               document.getElementById("divMensajePagoRG").style.display = "block";
               document.getElementById("divMensajePagoRG").style.border = "1px solid red";
               document.getElementById("divMensajePagoRG").style.padding = "5px";
               document.getElementById("divMensajePagoRG").style.margin = "0px";

               document.getElementById("divMensajePagoRG").innerHTML = core__lang_t("En el caso de cancelación, son reservas no reembolsables.");
            }
            else
            {
               document.getElementById("divMensajePagoRG").style.visibility = "hidden";
               document.getElementById("divMensajePagoRG").style.display = "none";
               document.getElementById("divMensajePagoRG").style.margin = "0px";           
               document.getElementById("divMensajePagoRG").innerHTML = "";
            }
            
             dDescuentoCliente = (dHabitaciones -  dDescuentoRG)* dPorcDescuentoCliente/100;
        }
        else
        {
            dDescuentoRG = 0.00;
        }

        dReserva = parseFloat(dHabitaciones) - parseFloat(dDescuentoRG) - parseFloat(dDescuentoCliente) + parseFloat(dTotalServicios);
        dReserva = jsEngineInc__roundValue(dReserva,2);
        
        if(dDescuentoRG == 0)
        {
            if(bPrecioComisionable == 1) 
            {
                dPasarela = (parseFloat(dReserva) * parseFloat(dComision))/100;
            }
            else //Precio Neto
            {
                dPasarela = iImporteComision + (parseFloat(dTotalServicios) * parseFloat(dComision))/100;    
            }
        }
        else
        {
            dPasarela = dReserva;
        }

        dHotel = parseFloat(dReserva) - parseFloat(dPasarela);

        dReserva = jsEngineInc__moneyFormat(dReserva);
        
        //Imprimimos los resultados en sus respectivos DIVS
        document.getElementById('divImporteTotalDescRG').innerHTML = jsEngineInc__moneyFormat(dDescuentoRG);
        document.getElementById('divImporteDescuentoCliente').innerHTML = jsEngineInc__moneyFormat(dDescuentoCliente);
        document.getElementById('divImporteTotalServicios').innerHTML= jsEngineInc__moneyFormat(dTotalServicios);
                                                                        //--------------------
        document.getElementById('divImporteTotalReserva').innerHTML = dReserva;
        
        if(iPayAllTpv == 1) //Si el cliente tiene que pagar el 100% de la reserva en la pasarela de pago
        {
            document.getElementById('divImporteTotalPasarela').innerHTML = dReserva;
                                                                            //--------------------    
            document.getElementById('divImporteTotalHotel').innerHTML = jsEngineInc__moneyFormat(0);
        }
        else // Si el cliente solo paga una parte de la reserva (es lo normal)
        {
            if(bDirectPayment==1)
            {
                document.getElementById('divImporteTotalPasarela').innerHTML =  jsEngineInc__moneyFormat(0);   
                document.getElementById('divImporteTotalHotel').innerHTML = jsEngineInc__moneyFormat(dReserva);
            }
            else
            {
                document.getElementById('divImporteTotalPasarela').innerHTML = jsEngineInc__moneyFormat(dPasarela);
                document.getElementById('divImporteTotalHotel').innerHTML = jsEngineInc__moneyFormat(dHotel);
            }
        }
     }
     
     /**     
     * this function give format to value for math operations
     * @param mixed num
     * @return float num with dots as separator of decimals because comas generate errors for math operations
     */
     function jsEngineInc__floatFormat(num)
     {
         num = num.replace(".","");
         num = num.replace(",",".");
         return num;
     }
     
     /**
     * rounds the value to the specified decimals... not truncate
     * @param float num value to round
     * @param int decimals value of number of decimals we want to round
     * @return float
     */
     function jsEngineInc__roundValue(num, decimals)
     {
         if(num!=0)
         {
            value = Math.pow(10, decimals);
            redondeado = Math.round(num*value);
            redondeado = redondeado/value;
            return redondeado;
         }
         return num;
     }
     
     /**     
     * This function give format to a money values
     * @param decimal num
     * @return decimal num (in format xxxx,xx)
     */
     function jsEngineInc__moneyFormat(num)
     {
         valorInt = parseInt(num);
         
         if(valorInt==num)
         {
             num=num.toString()+'.00';
         }
         if(num.toString().indexOf('.')!=-1)
         {
             num = num.toString().replace(/\$|\,/g,'');
             
             if(isNaN(num))
             {
                 num = "0.00";
             }
             
             sign = (num == (num = Math.abs(num)));
             //if have an error try to do num= Math.floor(num*100+0.50000000001)
             num = Math.floor(num*100+0.499999999999999);
             cents = num%100;
             num = Math.floor(num/100).toString();
             
             if(cents<10)
             {
                 cents = "0" + cents;
             }
             
             // Lets get number of thousand units...    if num=    5323,12 ...gets 1 -->      5.323,12
             //                                         if num=     232,23 ...gets 0 -->        232,23
             //                                         if num= 2345632,65 ...gets 2 -->  2.345.632,65
             //num="5658621";
             parts = Math.floor((num.length) / 3);
             longitud = num.length;
             partNum = "";
             testigo = 0;
             posicionIni = 0;
             posicionFin = 0;
             
             for (var i = 0; i < parts; i++)
             {                 
                 // Entering here means that number is at last three-digits and maybe needs a '.'
                 testigo=1;
                 posicionFin = parseFloat(longitud - (i * (3)));
                 posicionIni = parseFloat(longitud - ((i+1) * (3)));
                 partNum = num.substring(posicionIni , posicionFin) + partNum;
                 
                 // Next condition check if number needs a '.' before next part
                 if(posicionIni!=0)
                 {
                     partNum = '.' + partNum;
                 }
             }
             
             if(posicionIni>0)
             {
                 partNum = num.substring(0,posicionIni)+partNum;
             }
             
             if(testigo == 1)
             {
                 num = partNum;
             }
             
             return (((sign)?'':'-') + num + ',' + cents);
         }
         else
         {
             // Else, if we have a ','  we don't want to do anything with value
             return(num);
         }
     }
     
     /**
     * Esta funcion controla los rangos de ingreso y salida al seleccionarlas mediante el calendario de jquery
     */
     function jsEngineInc__onLoadDatesEngine(qtyMonth)
     {

            $("#txt_fecha_inicial").datepicker({
                                        dateFormat: 'dd/mm/yy', 
                                        minDate:0, 
                                        numberOfMonths: qtyMonth,
                                        firstDay: 1,
                                        showOn: 'button', 
                                        buttonImage: './img/calendar.png', 
                                        buttonImageOnly: true, 
                                        buttonText: core__lang_t("Seleccione la fecha de entrada"),
                                        beforeShow: function(input, inst){                                            
                                            
                                            if(qtyMonth == 1){
                                                if ( !($.browser.msie)){
                                                    inst.dpDiv.css({marginTop: '5px', marginLeft: '-35px'});
                                                }
                                                else{
                                                    if( !document.getElementById("engine_container") )
                                                    {
                                                        inst.dpDiv.css({marginTop: '-60px', marginLeft: '-35px'});
                                                    }
                                                }
                                            }
                                            else{
                                                if ( !($.browser.msie)){
                                                    inst.dpDiv.css({marginTop: -input.offsetHeight + 'px', marginLeft: '-5px'});
                                                }
                                            }

                                        }
            });
            
            $("#txt_fecha_final").datepicker({
                                        dateFormat: 'dd/mm/yy', 
                                        numberOfMonths: qtyMonth,
                                        firstDay: 1,
                                        showOn: 'button', 
                                        buttonImage: './img/calendar.png', 
                                        buttonImageOnly: true, 
                                        buttonText: core__lang_t("Seleccione la fecha de salida"),                                        
                                        beforeShow: function(input, inst){
                                                                                    
                                            if(qtyMonth == 1){
                                                if ( !($.browser.msie)){
                                                    inst.dpDiv.css({marginTop: '5px', marginLeft: '-35px'});
                                                }
                                                else{
                                                    if( !document.getElementById("engine_container") )
                                                    {
                                                        inst.dpDiv.css({marginTop: '-110px', marginLeft: '-35px'});
                                                    }

                                                }
                                            }
                                            else{
                                                if ( !($.browser.msie)){
                                                    inst.dpDiv.css({marginTop: -input.offsetHeight + 'px', marginLeft: '-5px'});
                                                };
                                            }
                                            
                                            return {
                                                minDate: (input.id == "txt_fecha_final"   ? $("#txt_fecha_inicial").datepicker("getDate") : null),
                                                maxDate: (input.id == "txt_fecha_inicial" ? $("#txt_fecha_final").datepicker("getDate") : null)
                                            };
                                        }                                        
            });
     }   
     
