

if (typeof (HTMLElement) != 'undefined'
            && HTMLElement.prototype.__defineGetter__!='undefined')
    {
        HTMLElement.prototype.__defineGetter__( "innerText", function ()
        {
            var oTextRange = this.ownerDocument.createRange();
            oTextRange.selectNodeContents(this);            
            return oTextRange.toString();
        });
        
        HTMLElement.prototype.__defineSetter__( "innerText", function (s)
        {
            this.innerHTML = s.replace("/\?[]+>","");        
        });                
    }

UltimoError = new Object();

function GetVersion()
{
    alert("Version 9.10(000)");
}
    
function MontarTextoSelecHabs(OnLine)
{
    if (OnLine)return TEXTO_SELEC_HABITACIONES;
    else return TEXTO_NO_CONEXION;
}


function VisualizacionInputSeleccion(Wait,MostrarGifEspera)
{
    GetComponent("Habitaciones").disabled = Wait;

    GetComponent("datosservicios").disabled = Wait; 
    GetComponent("tabsprecios").disabled = Wait;       
    
    GetComponent("ID_Dia_desde").disabled = Wait;
    GetComponent("ID_Mes_desde").disabled = Wait;
    GetComponent("ID_Ano_desde").disabled = Wait;
    GetComponent("ID_Dia_hasta").disabled = Wait;
    GetComponent("ID_Mes_hasta").disabled = Wait;
    GetComponent("ID_Ano_hasta").disabled = Wait;
    GetComponent("ID_CountHab").disabled = Wait;
    GetComponent("ID_Adultos").disabled = Wait;
    GetComponent("ID_Ninos").disabled = Wait;
    GetComponent("ID_Regimen").disabled = Wait;        
    GetComponent("ID_Tarifa").disabled = Wait;
    GetComponent("IMG_Calendario_Hasta").disabled = Wait;
    GetComponent("IMG_Calendario_Desde").disabled = Wait;    
    GetComponent("ID_LoginButton").disabled = Wait || GetComponent("ID_LoginButton").className=="";        
    GetComponent("ID_SearhGif").style.visibility = Wait?"visible":"hidden";      
}

function ImpedirModificaciones()
{        
    GetComponent("Habitaciones").disabled = true;
    GetComponent("ID_Dia_desde").readOnly = true;
    GetComponent("ID_Mes_desde").readOnly = true;
    GetComponent("ID_Ano_desde").readOnly = true;
    GetComponent("ID_Dia_hasta").readOnly = true;
    GetComponent("ID_Mes_hasta").readOnly = true;
    GetComponent("ID_Ano_hasta").readOnly = true;
    GetComponent("ID_CountHab").readOnly = true;
    GetComponent("ID_Adultos").readOnly = true;
    GetComponent("ID_Ninos").readOnly = true;
    GetComponent("ID_Regimen").readOnly = true;
    GetComponent("ID_Tarifa").readOnly = true;
}

function MontarTextoSinDisponibilidad(Resaltar)
{
    var pComponenHelpString =  GetComponent("HelpString");    
    if ((Resaltar && AST_ONLINE) || ( HabsOk==0 && Resaltar))
    {
        pComponenHelpString.style.color = "red";
        pComponenHelpString.style.fontWeight = "bold";                
        return TEXTO_SIN_DISPONIBILIDAD + " " + TEXTO_SELEC_FECHAS;      
    }
    else 
    {                     
        pComponenHelpString.style.color = SaveComponenHelpStringstylefontColor;
        pComponenHelpString.style.fontWeight = SaveComponenHelpStringstylefontWeight;
        if (Resaltar)return TEXTO_SELEC_HABITACIONES;          
    }        
}

function GetValue(HtmlComponentID)
{  

  try
   {
        return GetComponent(HtmlComponentID).value;
  }
  catch(e)
    {
        UltimoError.Object = e;
        UltimoError.Metodo = "GetValue";
        return "";         
    } 
}

function SeleccionaOption(SelectComponent,FindValue)
{
  for (var opcombo=0;opcombo < SelectComponent.length;opcombo++){ 
          if(SelectComponent[opcombo].value==FindValue){ 
          SelectComponent.selectedIndex=opcombo; break;}}

}

function GetSender(evento)
{
    if(window.event && window.event.srcElement != null)return window.event.srcElement;
	else if (evento.target && evento.target != null)return evento.target;
	else return evento;
}

function  BotonReservar_onclick(Component)
{
    if (Validacion(null))
    {
         Component.disabled = true;
         GetComponent("Error_Server_Valor").innerText = TEXTO_PLEASEWAIT;             
         GetComponent("ID_NombreCliente").readOnly = true; 
         GetComponent("ID_Apellidos").readOnly = true;
         GetComponent("ID_Email").readOnly = true;
         GetComponent("ID_Telefono").readOnly = true;
         if (GetComponent("ID_TelefonoMov")!=null)
            GetComponent("ID_TelefonoMov").readOnly = true;                 
         GetComponent("FormPrincipal").submit();
    }
}

function  BotonAtras_onclick(Component)
{
    Component.disabled = true;
    GetComponent("back_CMD").value = "CMD_BACK_OPERATION";
    GetComponent("Error_Server_Valor").innerText = TEXTO_PLEASEWAIT;    
    GetComponent("FormPrincipal").submit();   
}

function GetComponent(HtmlComponent)
{
    if (typeof(document.getElementById) != "undefined")
    {
        return document.getElementById(HtmlComponent);
    }
    else if (typeof(document.all) != "undefined")
    {
        return document.all[HtmlComponent];
    }
    else return null;
}

function GetIntValue(HtmlComponentID , Relleno)
{

    Value = GetValue(HtmlComponentID);
    
    if (Value.length < Relleno)    
    {
        Relleno = Relleno - Value.length;
        for (i = 0; i<Relleno;i++)
            Value = "0" + Value;
    }
    
    return Value;
}

function GetDesde()
{
    return GetIntValue("ID_Dia_desde",2) + GetIntValue("ID_Mes_desde",2) + GetIntValue("ID_Ano_desde",4);
}

function GetHasta()
{
    return GetIntValue("ID_Dia_hasta",2) + GetIntValue("ID_Mes_hasta",2) + GetIntValue("ID_Ano_hasta",4);
}       

var oMethod = null;
var oPrecios = null;
var oDisponibilidad = null;
var oLogined = null;
var oLoginedVIP = null;
var oDiasCerrados = null;
var oServicios = null;
var oRegimenes = null;
var Array_HabitacionesReservables;

var diaAnterior_Calendario_Day="";
var diaAnterior_Calendario_bkgr="rgb(255,255,255)";
var diaSeleccion_Calendario ="";
var StrColorFinDeSemana="rgb(234,228,243)";
var NewWindowVip = null;
var SaveComponenHelpStringstylefontColor = null;
var SaveComponenHelpStringstylefontWeight = null;

var COND_TARIFA_OK = 0;
var COND_TARIFA_ERROR = 1;
var COND_TARIFA_MINDIAS = 2;
var COND_TARIFA_DIASEMCHKIN = 3;
var COND_TARIFA_DIASSEMCHKOUT = 4;
var COND_TARIFA_MAXDIAS = 5;

function AbortarTodo()
{
    try
    {
        if ( oDisponibilidad !=null )   
        {
            oDisponibilidad.CodHabit = null;
            oDisponibilidad.XMLHttpRequest.abort();   
            oDisponibilidad = null;  
            oDisponibilidad = new Object();
        }    
    }
    catch(e)
    {
    
    }        
    
    try
    {
        if (oMethod != null )
        {
            oMethod.Tarifas = null;
            oMethod.XMLHttpRequest.abort();     
            oMethod =  null;            
        }
    }
    catch(e)
    {
                 
    }        
    
    try
    {
        if (oPrecios != null)
        {
            oPrecios.Precios = null;
            oPrecios.XMLHttpRequest.abort();
            oPrecios = null;            
        }
    }
    catch(e)
    {
                  
    }
    
    try
    {
        if (oDiasCerrados != null)
        {
            oDiasCerrados.DiasCerrados = null;
            oDiasCerrados.XMLHttpRequest.abort();
            oDiasCerrados = null;            
            oDiasCerrados = new Object();
        }
    }
    catch(e)
    {

    }

   
    try {
        if (oServicios != null) {
            oServicios.Servicios = null;
            oServicios.IsAbort = true;
            oServicios.XMLHttpRequest.abort();
            oServicios = null;
        }
    }
    catch (e) {

    }

    try {
        if (oRegimenes != null) {
            oRegimenes.PartRegimenes = null;
            oRegimenes.XMLHttpRequest.abort();
            oRegimenes = null;
        }
    }
    catch (e) {

    }               
}

function CerrarSession() 
{
    var EndSession = new Object();
    EndSession.Invoke = "Reservar_AjaxCmd.aspx?Cmd=CerrarSesion";
    EndSession.XMLHttpRequest = null;
    EndSession.OnComplete = function() {
        return 0;
    }
    InvokeMethod(EndSession, true); 
}


function PreguntarDisponbilidad(Desde,Hasta,Cantidad,Personas)
{
    if ( oDisponibilidad==null )oDisponibilidad = new Object();
    else
    {
        AbortarTodo();
    }
    
     
    AST_PRECIOS = false;
    
    oDisponibilidad.Invoke = "Reservar_AjaxCmd.aspx?Cmd=disponib&Desde="+ 
        Desde + "&Hasta=" + Hasta + "&Cantidad=" + Cantidad + "&Personas=" + Personas +
            "&Cacheoff=" + Math.random() + new Date().getTime();
    oDisponibilidad.XMLHttpRequest = null;
    
    oDisponibilidad.OnComplete = function() 
        {                           
            if (oDisponibilidad.XMLHttpRequest.readyState==4 
                && oDisponibilidad.XMLHttpRequest.status == 200)
            {                                                                                                                     
                try
                {
                
                    oDisponibilidad.CodHabit = eval("(" + oDisponibilidad.XMLHttpRequest.responseText+ ")");
                    AST_ONLINE  = oDisponibilidad.CodHabit.OnLine;
                  
                    Array_HabitacionesReservables = null;
                    Array_HabitacionesReservables = new Array();
                    
                    HayDisponib = false;
                    HabsOk = 0; 
                                                        
                    for (a =0 ;a<oDisponibilidad.CodHabit.Habits.length; a++)
                    {
                        Tipo = oDisponibilidad.CodHabit.Habits[a].Id;
                                                     
                        if (parseInt(oDisponibilidad.CodHabit.Habits[a].Cantidad)>0)
                        {                        
                            GetComponent("CodHabit_" + Tipo).disabled =  AST_ONLINE;
                            GetComponent("Help_" + Tipo).innerHTML = oDisponibilidad.CodHabit.Texto;
                            if (AST_ONLINE)                            
                            {
                                Array_HabitacionesReservables.push(Tipo);                                                       
                                HayDisponib = true;
                            } 
                            HabsOk ++;                              
                        }
                        else
                        {            
                            GetComponent("CodHabit_" + Tipo).disabled = true;
                            GetComponent("Help_" + Tipo).innerText = TEXTO_SIN_DISPONIBILIDAD;
                        }        
                        
                         GetComponent("Precios_" + Tipo).innerText = "";
                    }                                                                               
                           
                    if (oDisponibilidad.CodHabit.Habits.length>0 && AST_ONLINE && HayDisponib)
                    {
                        ObtenerTarifas(Desde, Hasta);                       
                    }
                    else 
                    {
                        ModoVisualEsperandoResultado(false);                        
                        GetComponent("HelpString").innerText =  MontarTextoSinDisponibilidad(true);                        
                    }
                                                            
                }
                catch(e)
                {    
                    UltimoError.Object = e;                
                    UltimoError.Metodo = "PreguntarDisponbilidad";                            
                    Inicializar();
                } 
            }                  
            else if (oDisponibilidad.XMLHttpRequest.readyState == 4
                        && oDisponibilidad.XMLHttpRequest.status != 200)
                    {                                      
                    Inicializar();                
                    }
                              
        };
                
    InvokeMethod(oDisponibilidad,true);    
}

function ObtenerTarifas(Desde, Hasta)
{           
    if ( oMethod==null )oMethod = new Object();
    else
    {
      oMethod.Tarifas = null;
      oMethod.XMLHttpRequest.abort();       
    }
    
    oMethod.Invoke = "Reservar_AjaxCmd.aspx?Cmd=Tarifas&Desde=" 
        + Desde + "&Hasta=" + Hasta + "&Cacheoff=" + Math.random() + new Date().getTime(); 
    oMethod.XMLHttpRequest = null;
    oMethod.Tarifas = null;
    oMethod.OnComplete = function() 
        {      
                    
            if (oMethod.XMLHttpRequest.readyState==4 && oMethod.XMLHttpRequest.status == 200)
            {
                               
                try
                {
                    oMethod.Tarifas = eval("(" + oMethod.XMLHttpRequest.responseText+ ")");
                    var Tarifas = oMethod.Tarifas;
                    var cbTarifas = GetComponent("ID_Tarifa");  
                   
                    var TarifaSeleccionada = cbTarifas.value;                  
                    var iSelectedValue = 0;
                   
                    cbTarifas.options.length=0;    
                                   
                    for (var a= 0 ;a<Tarifas.length;a++)
                    {
                        var opt = cbTarifas.appendChild(document.createElement("option"));
                        opt.value = Tarifas[a].Codigo;
                        if ( TarifaSeleccionada!="" && TarifaSeleccionada == opt.value)
                        {
                            opt.selected = true;
                            iSelectedValue = a;                    
                        }
                        opt.appendChild(document.createTextNode(Tarifas[a].NombreTarifa));
                        Tarifas[a].Condiciones = unescapeExtended(Tarifas[a].Condiciones);
                    }                                      
                                        
                    PreguntarPrecios();
                    
                }
                catch(Exception)
                {
                    UltimoError.Object = Exception;
                    UltimoError.Metodo = "ObtenerTarifas";                                        
                    oMethod.Tarifas = null;
                    Inicializar();
                }                                                  
            }                                  
            
            if (oMethod.XMLHttpRequest.readyState == 4
                && oMethod.XMLHttpRequest.status != 200)
            {                
                oMethod.Tarifas = null;                
                Inicializar();                
            }            
        };
                
    InvokeMethod(oMethod,true);    
}


function MontarPrecios(Precios)
{

    HabsOk = 0;
    var ComponentAutoClick = null;  
    
    var desde = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,
            GetValue("ID_Dia_desde"),0,0,0);
    var hasta = new Date(GetValue("ID_Ano_hasta"),GetValue("ID_Mes_hasta")-1,
            GetValue("ID_Dia_hasta"),0,0,0);               
            
    TextoUsuarioCompletado = false;
                 
    for (var a = 0 ; a < Precios.length; a++)
    {                     
        var CondicionesTarifa = CondicionesTarifaOk(desde,hasta);
        
        if (Precios[a].Precio!="0.00" && Precios[a].Precio!="0,00" && CondicionesTarifa == COND_TARIFA_OK)
        {
            GetComponent("Precios_" + Precios[a].Codigo).innerHTML = Precios[a].Precio 
                + " &euro; ";
            GetComponent("CodHabit_" + Precios[a].Codigo).disabled = false;
            GetComponent("Help_" + Precios[a].Codigo).innerText = TEXTO_SELEC_HABITACION;
            ComponentAutoClick = GetComponent("CodHabit_" + Precios[a].Codigo);
            HabsOk++;
                        
            if (Precios[a].PreciosEnBruto == "S")
                GetComponent("ID_Texto_MSJHotel").innerText = TEXTO_CONIVA;
            else
                GetComponent("ID_Texto_MSJHotel").innerText = TEXTO_SINIVA;
                
            GetComponent("ID_Texto_MSJHotel").style.visibility = "visible";                       
        }                                                   
        else if (Precios[a].Codigo!="")
        {            
            // Mostrar errores especificos
            if (CondicionesTarifa == COND_TARIFA_MINDIAS) 
            {
                GetComponent("Precios_" + Precios[a].Codigo).innerText = "";
                    
                Texto = TEXTO_DIASMIN + " " + DameDatosTarifaSel().MinDias + " " + TEXTO_NOCHES;
                GetComponent("Help_" + Precios[a].Codigo).innerText = Texto;            
                
                MontarTextoSinDisponibilidad(true);            
                GetComponent("HelpString").innerText = Texto + "." + TEXTO_SELEC_FECHAS;               
                TextoUsuarioCompletado = true;
            }
            else if (CondicionesTarifa == COND_TARIFA_MAXDIAS) 
            {
                GetComponent("Precios_" + Precios[a].Codigo).innerText = "";

                Texto = TEXTO_DIASMAX + " " + DameDatosTarifaSel().MaxDias + " " + TEXTO_NOCHES;
                GetComponent("Help_" + Precios[a].Codigo).innerText = Texto;

                MontarTextoSinDisponibilidad(true);
                GetComponent("HelpString").innerText = Texto + "." + TEXTO_SELEC_FECHAS;
                TextoUsuarioCompletado = true;
            }                                    
            else if (CondicionesTarifa == COND_TARIFA_DIASEMCHKIN) 
            {
                GetComponent("Precios_" + Precios[a].Codigo).innerText = "";
                
                Texto = TEXTO_DIASSEMCHKIN + " " + GetNombreDiaSem(desde);
                GetComponent("Help_" + Precios[a].Codigo).innerText = Texto;
                
                MontarTextoSinDisponibilidad(true);
                GetComponent("HelpString").innerText = Texto + "." + TEXTO_SELEC_FECHAS;
                TextoUsuarioCompletado = true;
            }                                                    
            else if (CondicionesTarifa == COND_TARIFA_DIASSEMCHKOUT) 
            {
                GetComponent("Precios_" + Precios[a].Codigo).innerText = "";
                
                Texto = TEXTO_DIASSEMCHKOUT + " " + GetNombreDiaSem(hasta);
                GetComponent("Help_" + Precios[a].Codigo).innerText = Texto;
                
                MontarTextoSinDisponibilidad(true);
                GetComponent("HelpString").innerText = Texto + "." + TEXTO_SELEC_FECHAS;                
                TextoUsuarioCompletado = true;                
            }                                                                    
            else /*las condiciones son ok o errores de tarifa*/
            {
                GetComponent("Precios_" + Precios[a].Codigo).innerText = "";
                GetComponent("Help_" + Precios[a].Codigo).innerText = TEXTO_SIN_DISPONIBILIDAD;           
            }                                
        }
        else 
        {
            for (a=0;a<Array_Habitaciones.length; a++)
            {
                GetComponent("Precios_" + Array_Habitaciones[a]).innerText = "";
                GetComponent("Help_" + Array_Habitaciones[a]).innerText = TEXTO_SIN_DISPONIBILIDAD;                            
            }
        }
    }
    
    GetComponent("ID_Regimen").disabled = false;
    if (HabsOk == 0 && GetComponent("ID_Tarifa").options.length<=0)Inicializar();
    else if (HabsOk ==0)
    {    
        if (!TextoUsuarioCompletado)
            GetComponent("HelpString").innerText = MontarTextoSinDisponibilidad(true);                     
    }
    else 
    {
        AST_PRECIOS = true;
        
        if (!TextoUsuarioCompletado)
            GetComponent("HelpString").innerText = MontarTextoSelecHabs(AST_PRECIOS);
        
        if (HabsOk==1 && ComponentAutoClick)ClickHabits(ComponentAutoClick);
    }

    if (oMethod.Tarifas != null && oMethod.Tarifas.length > 1)
        GetComponent("FILA_Tarifa").style.display = "block";
    else GetComponent("FILA_Tarifa").style.display = "none";    
}


function unescapeExtended(Buffer)
{
    return Buffer;
    /*Buffer = unescape(Buffer);    
    return Buffer.replace(/\+/g," ");    */
}

function PreguntarPrecios()
{
    // Estamos OnLine, no tenemos precios y ya tenemos tarifas
    if (AST_ONLINE && !AST_PRECIOS && oMethod != null && oMethod.Tarifas != null)
    {
        GetComponent("ID_SearhGif").style.visibility = "visible";
        
        if ( oPrecios==null )oPrecios = new Object();
        else
        {
            oPrecios.Precios = null;
            oPrecios.XMLHttpRequest.abort();
            oPrecios = new Object();
        }       
        
        CodHabits = "";
        for (i =0;i<Array_HabitacionesReservables.length;i++)
        {
            CodHabits+= Array_HabitacionesReservables[i] + ",";
            CodHabits+= GetValue("ID_CountHab") + ",";
            CodHabits+= GetValue("ID_Adultos") + ",";
            CodHabits+= GetValue("ID_Ninos") + ",|";            
        }
                          
        var TarifaEsc = encodeURIExpand(GetValue("ID_Tarifa"));
                          
        oPrecios.Invoke = "Reservar_AjaxCmd.aspx?Cmd=Precios&Desde="
            + GetDesde() + "&Hasta=" + GetHasta()+ "&CodRegimen=" + GetValue("ID_Regimen") + 
                "&CodTarif=" + TarifaEsc + "&CodHabits=" + CodHabits + 
                    "&Cacheoff=" + Math.random() + new Date().getTime();                   
                
        oPrecios.XMLHttpRequest = null;
        
        oPrecios.OnComplete = function() 
        {                             
            MostrarTarifa = false
            try
            {
                if (oPrecios.XMLHttpRequest.readyState==4 && oPrecios.XMLHttpRequest.status == 200)
                {                
                    try
                    {               
                        oPrecios.Precios = eval("(" + oPrecios.XMLHttpRequest.responseText + ")");                                                            
                        MontarPrecios(oPrecios.Precios);
                        VisualizacionInputSeleccion(false,true);                            
                        return;
                    }
                    catch(e)
                    {
                        UltimoError.Object = e;
                        UltimoError.Metodo = "PreguntarPrecios";
                        for (a=0;a<Array_Habitaciones.length; a++)
                        {
                            GetComponent("Precios_" + Array_Habitaciones[a]).innerText = "";
                            GetComponent("Help_" + Array_Habitaciones[a]).innerText = TEXTO_SIN_DISPONIBILIDAD;                            
                        }
                    }
                }
                
                if (oPrecios.XMLHttpRequest.readyState == 4
                   && oPrecios.XMLHttpRequest.status != 200)
                {                    
                    Inicializar();                
                }                             
            }
            catch(e)
            {
                UltimoError.Object = e;
                UltimoError.Metodo = "PreguntarPrecios";                
                Inicializar();                
            }
            
           ModoVisualEsperandoResultado(false);       
                                
        };
        
    InvokeMethod(oPrecios,true);    
    }
}

function encodeURIExpand(Buffer)
{
    i= Buffer.indexOf("+");
    
    while( i!=-1)
    {           
        Buffer = Buffer.replace ("+","%2B");
        i= Buffer.indexOf("+");
    }
    
    return escape(Buffer);

}

function OnLeerContrato(Owner)
{    
    if ( TEXTO_CONTRATO != null && TEXTO_CONTRATO.length > 0)
    {        
        var pWinCondiciones = CrearVentana(Owner,"Contrato");                                
        pWinCondiciones.style.top = "80px";
        pWinCondiciones.style.left = "120px";
        pWinCondiciones.style.height = "125px";
    
        pWinCondiciones.innerHTML +=
          "<BR><div ID='ID_TEXTO_CONTRATO' style='visibility:visible;'>" + TEXTO_CONTRATO + "</div>";

        
        
        GetComponent("ID_TEXTO_CONTRATO").innerHTML =
            GetComponent("ID_TEXTO_CONTRATO").innerText;        
                            
        pWinCondiciones.Show();   
    }
}

function ConsultarCondicionesTarifa(Owner)
{
    TarifaSel = DameDatosTarifaSel();
    if (TarifaSel != null && TarifaSel.Condiciones.length>0)
    {           
        var pWinCondiciones = CrearVentana(Owner,"Condiciones");                    
            
        pWinCondiciones.style.top = "80px";
        pWinCondiciones.style.left = "120px";
        pWinCondiciones.style.height = "125px";
    
        pWinCondiciones.innerHTML +=
          "<BR><div ID='TEXTO_CONDICIONTARIFA' style='visibility:visible;'>" + TarifaSel.Condiciones + "</div>";
        
        GetComponent("TEXTO_CONDICIONTARIFA").innerHTML =
            GetComponent("TEXTO_CONDICIONTARIFA").innerText;        
                            
        pWinCondiciones.Show();   
    }
}


function ConsultarDiasCerrados(DesdeHasta,FechaConsulta)
{
    if ( oDiasCerrados==null )oDiasCerrados = new Object();
    else
    {
        AbortarTodo();
    }        
    
    oDiasCerrados.Invoke = "Reservar_AjaxCmd.aspx?Cmd=DiasCerrados&Fecha="+ 
        FechaConsulta + "&Cantidad=" + GetValue("ID_CountHab") 
            + "&Cacheoff=" + Math.random() + new Date().getTime();
                
    oDiasCerrados.XMLHttpRequest = null;    
    oDiasCerrados.DesdeHasta = DesdeHasta;
    
    oDiasCerrados.OnComplete = function() 
        {                           
            if (oDiasCerrados.XMLHttpRequest.readyState==4 
                && oDiasCerrados.XMLHttpRequest.status == 200)
            {                                                                                          
                try
                {   
                    var DiasCerrados = eval("(" + oDiasCerrados.XMLHttpRequest.responseText + ")");                    
                    MontarCalendario(oDiasCerrados.DesdeHasta,DiasCerrados);                             
                }
                catch(e)
                {
                    UltimoError.Object = e;
                    UltimoError.Metodo = "ConsultarDiasCerrados";  
                    MontarCalendario(DesdeHasta,null);                                                        
                } 
            }    
            if (oDiasCerrados.XMLHttpRequest.readyState==4 
                 && oDiasCerrados.XMLHttpRequest.status != 200)
            {                
                MontarCalendario(DesdeHasta,null);            
            }
            
        };
                
    InvokeMethod(oDiasCerrados,true);   
}

function UserLogin(Owner)
{
    if ( oLogined==null )oLogined = new Object();
    else
    {
        AbortarTodo();
    }        
    
    oLogined.Invoke = "Reservar_AjaxCmd.aspx?Cmd=login&User="+ encodeURI(EncodeUSERANDPASS(GetValue("user_Login")))
        + "&Pass=" + encodeURI(EncodeUSERANDPASS(GetValue("user_Password"))) + "&Cacheoff=" + Math.random() + new Date().getTime();
    oLogined.XMLHttpRequest = null;
    oLogined.user = GetValue("user_Login");
    oLogined.PassOK = false;
    
    oLogined.OnComplete = function() 
        {                           
            if (oLogined.XMLHttpRequest.readyState==4 
                && oLogined.XMLHttpRequest.status == 200)
            {                                                                                          
                try
                {   
                    var a = eval("(" + oLogined.XMLHttpRequest.responseText + ")");
                    if (a.OK == "")throw ("Error");
                    else 
                        {                            
                            oLogined.PassOK = true;
                            alert(TEXTO_BIENVENIDO + " " + a.OK);
                            GetComponent("ID_LoginButton").innerText = a.OK;
                            GetComponent("ID_LoginButton").disabled = false; 
                            GetComponent("ID_AnulConsulButton").innerText = a.TEXTO_ANUL_CONSUL;
                            
                            CerrarVentanaModal(GetComponent("WinLogon_Cerrar"));                                                       
                            Inicializar();                              
                            ConsultaDisponibilidad(GetComponent("ID_Regimen"));
                        }
                }
                catch(e)
                {
                    UltimoError.Object = e;
                    UltimoError.Metodo = "UserLogin";                    
                    alert(TEXTO_DESCONOCIDO_USER);                
                } 
            }    
            if (oLogined.XMLHttpRequest.readyState==4 
                 && oLogined.XMLHttpRequest.status != 200)
            {
                Inicializar();
                CerrarVentanaModal(GetComponent("WinLogon_Cerrar"));
            }
            
        };
                
    InvokeMethod(oLogined,true);    
}


function AnularReserva(Owner)
{
    if (Owner != null && Owner == GetComponent("ID_AnulConsulButton"))
        location.href = URL_AnularReserva;
}


function LoginUser(Owner)
{
    if (GetComponent("ID_LoginButton").disabled)return;
    if (oLogined!= null && oLogined.PassOK)
    {        
        location.href = URL_ClientesWeb;
    }
    else
    {                        
        var pWinLogon = CrearVentana(Owner,"WinLogon","OnCloseLoginUser");
            
        VisualizacionInputSeleccion(true,false);
        AccionBotonSeguir( false);
            
        pWinLogon.style.top = "80px";
        pWinLogon.style.left = "120px";
        pWinLogon.style.height = "125px";
    
        pWinLogon.innerHTML +=  "<FORM class='Valor'>"+
                            "<span>" + TEXTO_USER +":</span><BR>" + 
                                "<INPUT id ='user_Login' type='text' ></input><BR>" +
                            "<span>PassWord:</span><BR>"+ 
                                "<INPUT id ='user_Password' type='password'</input><BR><BR>" +
                            "<input type='button' value='Login' onClick=' return UserLogin(this);'></input><BR>"+
                            "<input id='DisLogon' name='DisableSubmit' type='text' style='visibility:hidden'/><BR>"+
                            "</FORM>";
                            
        pWinLogon.Show();
    }
}

function OnCloseLoginUser(Owner)
{
    VisualizacionInputSeleccion(false,false);
    AccionBotonSeguir( false);
    CerrarVentanaModal(Owner);
}

function AccionBotonSeguir(Disabled)
{
    if (GetComponent("BotonSeguir") != null)
        GetComponent("BotonSeguir").disabled = Disabled;    
}


function UserLoginVIP(Owner)
{

    GetComponent("BotonOK").disabled = true;
    GetComponent("RESULTADO_LOGIN").innerText = "";
    
    if (oLoginedVIP ==null )oLoginedVIP = new Object();
    else
    {
        try
        {
            if (oLoginedVIP != null )
            {
                oLoginedVIP.Tarifas = null;
                oLoginedVIP.XMLHttpRequest.abort();                     
            }
        }
        catch(e)
        {
                     
        }     
        
        oLoginedVIP =  new Object();
    }    
    
    try
    {
        if (NewWindowVip != null)NewWindowVip.close();
    }
    catch(e)
    {
    
    }    
    
     GetComponent("RESULTADO_LOGIN").innerText = "please wait...";
    
    oLoginedVIP.Invoke = "Reservar_AjaxCmd.aspx?Cmd=loginVIP&User="+ GetValue("USUARIO")
        + "&Pass=" + GetValue("PASS") + "&Cacheoff=" + Math.random() + new Date().getTime();
    oLoginedVIP.XMLHttpRequest = null;
    oLoginedVIP.user = GetValue("user_Login");
    oLoginedVIP.PassOK = false;
        
    
    oLoginedVIP.OnComplete = function() 
        {                           
            if (oLoginedVIP.XMLHttpRequest.readyState==4 
                && oLoginedVIP.XMLHttpRequest.status == 200)
            {                                                                                          
                try
                {   
                    var a = eval("(" + oLoginedVIP.XMLHttpRequest.responseText + ")");
                    if (!a.OK)throw ("Error");
                    else 
                        {                            
                            oLoginedVIP.PassOK = true;                                                  
                            GetComponent("RESULTADO_LOGIN").innerText = "Welcome";
                            NewWindowVip = window.open("SaldoClientesVip.aspx","_blank");
                        }
                }
                catch(e)
                {
                    UltimoError.Object = e;
                    UltimoError.Metodo = "UserLoginVIP";                    
                    GetComponent("RESULTADO_LOGIN").innerText = "User not found";
                    NewWindowVip = null;
                   // alert(TEXTO_DESCONOCIDO_USER);                
                } 
                
                GetComponent("BotonOK").disabled = false;
            }    
            if (oLoginedVIP.XMLHttpRequest.readyState==4 
                 && oLoginedVIP.XMLHttpRequest.status != 200)
            {
                GetComponent("RESULTADO_LOGIN").innerText = "User not found";                
                NewWindowVip = null;
            }
            
        };
                
    InvokeMethod(oLoginedVIP,false);    
}


//****************************************************************************
//
//          AJAX STANDARD METHOD
//
//****************************************************************************
function InvokeMethod(oMethodAjaxProcedure,Async)
{
    
    var Object = CreateAjaxObject();
    if (Object != null)
     {        
       oMethodAjaxProcedure.XMLHttpRequest = Object;
       Object.onreadystatechange = oMethodAjaxProcedure.OnComplete;     
       Object.open("get",oMethodAjaxProcedure.Invoke,Async);
       Object.setRequestHeader("Cache-Control","no-cache");
       Object.setRequestHeader("Pragma","no-cache");
       Object.send(null);
     }
    
}

function CreateAjaxObject()
{
    var xmlObject = null;
    try 
    {
        xmlObject = new XMLHttpRequest();
    }
    catch(e) 
    {                                   
        var Versions = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0",
                        "MSXML2.XMLHttp.3.0",
                        "Microsoft.XMLHTTP","MSXML2.XMLHttp"];
        
        for (var a=0;a<Versions.length;a++)
        try 
        {
            xmlObject = new ActiveXObject(Versions[a]);
            break;
        }
        catch(e) 
        {
           
        }
    }
    
    if (xmlObject == null) alert("You need update Browser or turn on ActiveX to use app");
    
    return xmlObject;
 }    
 //****************************************************************************
     
 //**************************************************************************** 
 
 function CrearVentana(Owner, WindowName, CustomClose)
 {
    if (GetComponent(WindowName) != null && GetComponent(WindowName)!="undefined")        
        GetComponent(WindowName).Close();        
        
    var Ventana = document.createElement("div");    
    Ventana.iframeIE6 = document.createElement("iframe");
    var iframeIE6 = Ventana.iframeIE6;
     
    Ventana.className = "VentanaModal";
    Ventana.id = WindowName;
    Ventana.style.backgroundColor = "white";
    
    iframeIE6.className = "VentanaModal";
    iframeIE6.style.zIndex = 5;        
    iframeIE6.id = "SaveBackground_iframeIE6_" + Ventana.id ;    
    
    if (CustomClose == null || CustomClose=="undefined")CustomClose = "CerrarVentanaModal";
    
    Ventana.innerHTML = "<span id='" + WindowName + "_Cerrar' class ='AnchorSimulator' onclick='return " 
        + CustomClose + "(this);'>" + TEXTO_CERRAR +"</span>";     
   
    GetComponent("MainBody").appendChild(iframeIE6);             
    GetComponent("MainBody").appendChild(Ventana);       
    
    Ventana.Show = function()
        {                        
            this.iframeIE6.style.border = "solid 2px white";
            this.iframeIE6.style.left = this.style.left;
            this.iframeIE6.style.top = this.style.top;   
            this.iframeIE6.style.width =  SetPixelValue(this.style.width,8);
            this.iframeIE6.style.height = SetPixelValue(this.style.height,2);    
            this.iframeIE6.style.visibility = "visible"; 
            this.style.visibility = "visible";             
        }     
        
    Ventana.Close = function()
        {
            BorrarNodo(this.iframeIE6);
            BorrarNodo(this);
        }
    return Ventana;
 }
 
 
 function SetPixelValue(Valor,Incremento)
 {
    if (Valor!="")
    {
        var a = Valor.substring(0,Valor.indexOf("px"));
        return (parseInt(a,10)+Incremento) + "px";
    }
    return "";
 }
 
 function CerrarVentanaModal(e)
 {
    var Sender = GetSender(e);
    Sender.parentNode.Close();    
 }
 
 function BorrarNodo(Nodo)
 {
    if (Nodo.removeNode)Nodo.removeNode(true);
    else Nodo.parentNode.removeChild(Nodo);
 }
 
 function DameDatosTarifaSel()
 {
    var cbTarifas = GetComponent("ID_Tarifa");
    for (var ValorIdx =0 ;oMethod.Tarifas.length; ValorIdx++)
    {
        if (oMethod.Tarifas[ValorIdx].Codigo == cbTarifas.value)
        return oMethod.Tarifas[ValorIdx];
    }
    
    return null;
 }
 
 function SaltaOtroMes(mes,Nombre_ComponenteMes,Nombre_ComponenteAno,WinName)
{               
    SaveMes = GetComponent(Nombre_ComponenteMes).selectedIndex + mes;
    if (SaveMes>12)
    {        
        if(GetComponent(Nombre_ComponenteAno).selectedIndex+1
            < GetComponent(Nombre_ComponenteAno).length )
        {
            SaveMes = 1;
            GetComponent(Nombre_ComponenteAno).selectedIndex = 
                GetComponent(Nombre_ComponenteAno).selectedIndex +1;
        }
        else SaveMes = 12;
    }
    else if (SaveMes<1)
    {
        if (GetComponent(Nombre_ComponenteAno).selectedIndex-1 >0)
        {
            SaveMes = 12;
            GetComponent(Nombre_ComponenteAno).selectedIndex = 
                GetComponent(Nombre_ComponenteAno).selectedIndex -1;            
        }
        else SaveMes = 1;        
    }
    
    GetComponent(Nombre_ComponenteMes).selectedIndex = SaveMes;
    GetComponent(WinName).Close();    
    Calendario_onclick(NameID == "ID_Mes_desde"?0:1);    
}
 
 function SeleccionDia(DesdeOHasta,dia,desde,WinName,Noches)
 {    
    diaSeleccion_Calendario = dia;   
        
    if (Noches==0 && DesdeOHasta ==0)
    {
        GetComponent(WinName).Close(); 
      
        DiaDesdeTmp = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,dia,0,0,0);
        DiaHastaTmp = new Date(GetValue("ID_Ano_hasta"),GetValue("ID_Mes_hasta")-1,
            GetValue("ID_Dia_hasta"),0,0,0);
            
        SeleccionaOption(GetComponent("ID_Dia_desde"),DiaDesdeTmp.getDate());                           
        SeleccionaOption(GetComponent("ID_Mes_desde"),parseInt(DiaDesdeTmp.getMonth())+1);                                             
                
        if (DiaHastaTmp<=DiaDesdeTmp || 
            Math.floor( (DiaHastaTmp.getTime()-DiaDesdeTmp.getTime())/(1000 * 60 * 60 * 24)) >14)
        {
            DiaHastaTmp = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,
                parseInt(GetValue("ID_Dia_desde"))+1,0,0,0);
                
            SeleccionaOption(GetComponent("ID_Dia_hasta"),DiaHastaTmp.getDate());
            SeleccionaOption(GetComponent("ID_Mes_hasta"),parseInt(DiaHastaTmp.getMonth())+1);
            SeleccionaOption(GetComponent("ID_Ano_hasta"),DiaHastaTmp.getFullYear());
        }        
                
        ConsultaDisponibilidad(GetComponent("ID_Mes_desde"));          
    }    
    else if (DesdeOHasta ==0)    
    {                
    
        SaveDia = parseInt(Noches) +  parseInt(dia);
        DiaHastaTmp = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,SaveDia,0,0,0);
     
         if (diaAnterior_Calendario_Day!="" &&  GetComponent("Calendario_dias_"+ diaAnterior_Calendario_Day))
         {
            GetComponent("Calendario_dias_"+ diaAnterior_Calendario_Day).style.backgroundColor=diaAnterior_Calendario_bkgr;
         }
         
         diaAnterior_Calendario_Day=dia;
         if (GetComponent("Calendario_dias_"+ dia) != null)         
            {
                diaAnterior_Calendario_bkgr=GetComponent("Calendario_dias_"+ dia).style.backgroundColor;                                                                
                GetComponent("Calendario_dias_"+ dia).style.backgroundColor="#FAC1CD";   
            }
         else diaAnterior_Calendario_Day ="";                         
         
         GetComponent("Calendario_fsalida_calc").innerText = GetComponent("ID_TEXTO_SALIDA").innerText + 
            DiaHastaTmp.getDate() + "/" +  parseInt(DiaHastaTmp.getMonth()+1) + "/" + DiaHastaTmp.getYear();
                                                                                                        
    }
    else 
    {                  
        GetComponent(WinName).Close(); 
        GetComponent(desde).value = dia;                               
        GetComponent("ID_Dia_hasta").selectedIndex = dia;                       
        ConsultaDisponibilidad(GetComponent(desde));                 
    }
    
 }
 
 function FechaMenorHoy(fecha)
 {
    var hoy = Math.floor(new Date());
    return Math.floor( (hoy-fecha.getTime())/(1000 * 60 * 60 * 24))>0;
 }

 function ComprobarFechas(MaxDiasPorReserva)
 {
        var Retorno = true;
        
        
        var desde = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,
            GetValue("ID_Dia_desde"),0,0,0);
        var hasta = new Date(GetValue("ID_Ano_hasta"),GetValue("ID_Mes_hasta")-1,
            GetValue("ID_Dia_hasta"),0,0,0);                                                  
            
        if (hasta.getMonth() != GetValue("ID_Mes_hasta")-1 
                || desde.getMonth() != GetValue("ID_Mes_desde")-1 
                    || FechaMenorHoy(desde) || FechaMenorHoy(hasta))
            throw ("");
            
        if (hasta <= desde ||
                Math.floor( (hasta.getTime() - desde.getTime())/(1000 * 60 * 60 * 24)) > MaxDiasPorReserva)
        {            
            hasta = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,
                parseInt(GetValue("ID_Dia_desde"))+1,0,0,0);
                
            SeleccionaOption(GetComponent("ID_Dia_hasta"),hasta.getDate());
            SeleccionaOption(GetComponent("ID_Mes_hasta"),parseInt(hasta.getMonth())+1);
            SeleccionaOption(GetComponent("ID_Ano_hasta"),hasta.getFullYear());            
        }
        
        return Retorno;
 }
 
 function CondicionesTarifaOk(desde,hasta)
 {
                    
    var Noches =  Math.floor( (hasta.getTime()-desde.getTime())/(1000 * 60 * 60 * 24));            
    var Tarifa = DameDatosTarifaSel();    
    var TarifaOk = COND_TARIFA_ERROR;
    
    if (Tarifa != null)
    {
        TarifaOk = Noches >= DameDatosTarifaSel().MinDias ? COND_TARIFA_OK : COND_TARIFA_MINDIAS;

        if (TarifaOk == COND_TARIFA_OK && DameDatosTarifaSel().MaxDias != "")
            TarifaOk = Noches < DameDatosTarifaSel().MaxDias ? COND_TARIFA_OK : COND_TARIFA_MAXDIAS;                
            
        if (TarifaOk == COND_TARIFA_OK)
        {
            if (Tarifa.DiaSemEntrada.indexOf(NormalizaLunFirstDay(desde.getDay(),true),0)==-1)
                TarifaOk = COND_TARIFA_DIASEMCHKIN;
            if (Tarifa.DiaSemSalida.indexOf(NormalizaLunFirstDay(hasta.getDay(),true),0)==-1)
                TarifaOk = COND_TARIFA_DIASSEMCHKOUT;       
        }                                      
    }
        
    return TarifaOk;
 }
 
 function Validaciones_Email(ValorEmail)
{
    if (!ValidarEmail(ValorEmail))GetComponent("IMG_WarningEmail").style.visibility="visible";
    else GetComponent("IMG_WarningEmail").style.visibility = "hidden";  
}
 
 function ValidarEmail(Texto)
 {
    if (Texto=="")return true;
    PosArroba = Texto.indexOf("@"); 
    if (PosArroba==-1)return false;
    else if (Texto.indexOf(".")==-1 || Texto.indexOf(".",PosArroba)==-1)return false;
    return true;
 }
 
 function ValidarFecCaduca(Texto)
 {    
    if (Texto=="")return true;
    Posbarra = Texto.indexOf("/"); 
    if (Posbarra==-1 || Posbarra!=2)return false;
    try {   
        Mes = parseInt(Texto.substring(0, 2),10);
        if (Mes == NaN || Mes <= 0 || Mes > 12) return false;

        Anno = parseInt(Texto.substring(3), 10);
        var FechaAct = new Date();
        var AnnoAct = FechaAct.getYear();
        if (Anno == NaN || Anno +2000 < AnnoAct ) return false;
    }
    catch(e)
    {
        UltimoError.Object = e;
        UltimoError.Metodo = "ValidarFecCaduca";        
        return false;
    }
    return true;    
 }
 
 function OnCalendarioAceptar(dia,WinName,Noches)
 {
    GetComponent(WinName).Close(); 
      
    DiaDesdeTmp = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,dia,0,0,0);

    DiaHastaSave = parseInt(Noches) +  parseInt(dia);
    DiaHastaTmp = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,DiaHastaSave,0,0,0);        
    
    SeleccionaOption(GetComponent("ID_Dia_desde"),DiaDesdeTmp.getDate());                           
    SeleccionaOption(GetComponent("ID_Mes_desde"),parseInt(DiaDesdeTmp.getMonth())+1);                               
        
    SeleccionaOption(GetComponent("ID_Dia_hasta"),DiaHastaTmp.getDate());                           
    SeleccionaOption(GetComponent("ID_Mes_hasta"),parseInt(DiaHastaTmp.getMonth())+1);
    SeleccionaOption(GetComponent("ID_Ano_hasta"),DiaHastaTmp.getYear());
    
    ConsultaDisponibilidad(GetComponent("ID_Mes_desde"));                 
 }


function Calendario_onclick(DesdeHasta)
{       
    var diaConsulta;
           
    if (DesdeHasta==0)
    {
        MesSeleccion = GetValue("ID_Mes_desde")-1;
        AnoSeleccion = GetValue("ID_Ano_desde");
        diaConsulta = "01" + GetIntValue("ID_Mes_desde",2) + GetIntValue("ID_Ano_desde",4);
    }
    else
    {
        MesSeleccion = GetValue("ID_Mes_hasta")-1;
        AnoSeleccion = GetValue("ID_Ano_hasta");
        diaConsulta = "01" + GetIntValue("ID_Mes_hasta",2) + GetIntValue("ID_Ano_hasta",4);
    }
    
    ConsultarDiasCerrados(DesdeHasta,diaConsulta);       
}
 
function MontarCalendario(DesdeHasta,DiasCerrados)
{
  
  Mes = "";
  Ventana = null;
  NameID = "";
  CustomNameID = "";
  Caption = "";
  NombreVentana = "";   
  
  diaSeleccion_Calendario = "1";
  diaAnterior_Calendario_Day ="";
  diaAnterior_Calendario_bkgr =diaAnterior_Calendario_bkgr; 
  
  desde = null;
  hasta = null;
  
  if (DesdeHasta==0)
    {
        diaSeleccion_Calendario = GetComponent("ID_Dia_desde").value;
        diaAnterior_Calendario_Day =GetComponent("ID_Dia_desde").value;
        
        desde = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,
            GetValue("ID_Dia_desde"),0,0,0);
        DiaDeLaSemanaNormalizado = NormalizaLunFirstDay(desde.getDay(),true);           
        if (DiaDeLaSemanaNormalizado == "D" || DiaDeLaSemanaNormalizado =="S")
            diaAnterior_Calendario_bkgr = StrColorFinDeSemana;
    
        NameID = "ID_Mes_desde";  
        NameAno = "ID_Ano_desde";
        CustomNameID = "desde";
        Caption = TEXTO_SELEC_DIA_LLEGADA;
        NombreVentana = "Win_Calendario_" + Caption ;
        Mes =  GetComponent(NameID).options[GetComponent(NameID).selectedIndex].text + 
            " " +  GetComponent(NameAno).options[GetComponent(NameAno).selectedIndex].text;
        Ventana = new CrearVentana(GetComponent(NameID),NombreVentana,null);                
    }
  else 
    {
        NameID = "ID_Mes_hasta";
        NameAno = "ID_Ano_hasta";
        CustomNameID = "hasta";
        Caption = TEXTO_SELEC_DIA_SALIDA;
        NombreVentana = "Win_Calendario_" + Caption ;        
        Mes = GetComponent(NameID).options[GetComponent(NameID).selectedIndex].text + 
            " " +  GetComponent(NameAno).options[GetComponent(NameAno).selectedIndex].text;    
        Ventana = new CrearVentana(GetComponent(NameID),NombreVentana,null);          
        desde = new Date(GetValue("ID_Ano_desde"),GetValue("ID_Mes_desde")-1,
            GetValue("ID_Dia_desde"),0,0,0);        
        hasta = new Date(GetValue("ID_Ano_hasta"),GetValue("ID_Mes_hasta")-1,
            GetValue("ID_Dia_hasta"),0,0,0);
        DiaDeLaSemanaNormalizado = NormalizaLunFirstDay(hasta.getDay(),true);           
        if (DiaDeLaSemanaNormalizado == "D" || DiaDeLaSemanaNormalizado =="S")
            diaAnterior_Calendario_bkgr = StrColorFinDeSemana;                           
    }
  
 
  HTMLCalendario ="";  
  HTMLCalendario = 
    "<table id='Calendario_" + Caption +"' class ='Valor' cellspacing='0' cellpadding='1px' bordercolor='#CECBCE' border='0' style='border-color:#CECBCE;border-width:1px;border-style:solid;width:100%;border-collapse:collapse;'>" +
	"    <tr>" +
	        " <td colspan='7' style='background-color:rgb(207,192,226);'>" +
	            "<table cellspacing='0px' cellpadding='0px' border='0px' style='color:#000000;font-size:10px;font-weight:bold;width:100%;border-collapse:collapse;'>" +
		        "<tr><td style='width:15%;'> ";
		        
    if (GetComponent(NameID).selectedIndex > 1 
         || (GetComponent(NameAno).selectedIndex > 0 && GetComponent(NameID).selectedIndex ==1))
    HTMLCalendario  = HTMLCalendario + 
        "<a href='javascript:void(SaltaOtroMes(-1,\"" + NameID + "\",\"" + NameAno + "\",\"" + NombreVentana + "\"));' style='color:Black'>&lt;</a>";
		         
    HTMLCalendario  = HTMLCalendario + 	         
        "</td> <td align='Center' style='width:70%;'>"+ Caption + " " + Mes + "</td><td align='Right' style='width:15%;'>";		             
 
    if (GetComponent(NameID).selectedIndex < 12 ||
        (GetComponent(NameAno).selectedIndex+1 < GetComponent(NameAno).length && GetComponent(NameID).selectedIndex ==12) )
    HTMLCalendario  = HTMLCalendario +              	               
        "<a href='javascript:void(SaltaOtroMes(1,\"" + NameID + "\",\"" + NameAno + "\",\"" + NombreVentana + "\"));' style='color:Black'>&gt;</a>";
		             
	 HTMLCalendario  = HTMLCalendario  + "</td>" +
		        "</tr>"		+        
		        "</table> " +
		    "</td> " +
    "   </tr>"		 +
    "   <tr>"+
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_LUNES.substring(0,3) + "</td>" +
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_MARTES.substring(0,3) + "</td>" +
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_MIERCOLES.substring(0,3) + "</td>" +
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_JUEVES.substring(0,3) + "</td>" +
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_VIERNES.substring(0,3) + "</td>" +
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_SABADO.substring(0,3) + "</td>" +
		        "<td align='Center' style='background-color:"+ StrColorFinDeSemana +";'>" + TEXTO_DOMINGO.substring(0,3) + "</td>" +		
    "   </tr>";
    
    StrDias = "";
    diaDeSem = 1;
    diaDelMes = 1;       
    
    AnoCalendario = GetValue("ID_Ano_"+CustomNameID);
    MesCalendario = GetValue("ID_Mes_" +CustomNameID)-1;
        
    diaActual = new Date(AnoCalendario,MesCalendario,diaDelMes,0,0,0);          
                                      
    while (!UltimoDiaDelMes(AnoCalendario,MesCalendario,diaDelMes))
        {                        
            StrDias = StrDias + "   <tr style='height:8px;border-width:0px'>";            
            for (diaDeSem = 0;diaDeSem<7;diaDeSem++)
            {                                                                               
                diaActual = new Date(AnoCalendario,MesCalendario,diaDelMes,0,0,0); 
                DiaDeLaSemanaNormalizado = NormalizaLunFirstDay(diaActual.getDay(),true);
                if (!UltimoDiaDelMes(AnoCalendario,MesCalendario,diaDelMes) && DiaDeLaSemanaNormalizado == NormalizaLunFirstDay(diaDeSem,false))
                    {
                        StrdiaDelMes = diaDelMes;
                        if (diaActual + "" == desde +"")
                        {
                            StrdiaDelMes = "<font color='green'>" + diaDelMes +"</font>";
                        }
                    
                        diaSelHTMLAnchor = "<a class='Dia_calendario' href='javascript:void(SeleccionDia(" + DesdeHasta + ",\"" + diaDelMes + "\",\"ID_Dia_" + CustomNameID + "\",\"" + NombreVentana + "\",GetComponent(\"Calendario_Noches\").value));'> " + StrdiaDelMes +"</a>";
                        if (oMethod && oMethod.Tarifas)
                        {   
                            TarifaSel = DameDatosTarifaSel();
                            if (TarifaSel!=null)
                            {
                                if (DesdeHasta ==0 && TarifaSel.DiaSemEntrada.indexOf(DiaDeLaSemanaNormalizado,0)==-1)
                                    diaSelHTMLAnchor = "<font color='Gray'>" + diaDelMes +"</font>"
                                else if (DesdeHasta !=0 && TarifaSel.DiaSemSalida.indexOf(DiaDeLaSemanaNormalizado,0)==-1)                            
                                    diaSelHTMLAnchor = "<font color='Gray'>" + diaDelMes +"</font>"                                                                                       
                            }
                        }   
                        
                        DiaCerrado =  (DiasCerrados != null 
                            && DiasCerrados.indexOf(("," + diaActual.getDate() + ","))!=-1);                                               
                                                                                                                                                                              
                        if ( DiaCerrado || (FechaMenorHoy(diaActual) && diaActual+"" != desde + "")) 
                        {
                                diaSelHTMLAnchor = "<font color='Gray'>" + diaDelMes +"</font>";
                        }                                               
                    
                        if (DiaDeLaSemanaNormalizado == "D" || DiaDeLaSemanaNormalizado=="S")
                            StrDias = StrDias + "<td id='Calendario_dias_"+ diaDelMes +"' align='Center' style='height:8px;border-width:0px;background-color:"+ StrColorFinDeSemana +";'>" + diaSelHTMLAnchor + "</td>";                        
                        else
                            StrDias = StrDias + "<td id='Calendario_dias_"+ diaDelMes +"' align='Center' style='height:8px;border-width:0px;background-color:#FFFFFF;'>" + diaSelHTMLAnchor + "</td>";                        
                                                    
                        diaDelMes++;                                                                               
                    }                    
                else 
                    {                              
                        StrDias = StrDias + "<td align='Center' style='height:8px;border-width:0px;background-color:#FFFFFF;'></td>";		       		                
                    }
            }               
            
            StrDias = StrDias + "   </tr>";        
        }
        
    HTMLCalendario = HTMLCalendario + StrDias + "</table>";
    
    if (DesdeHasta==0)strVisible = "";
    else strVisible=";visibility:hidden";

    HTMLSelectCalendario = "<div class='Fila' style='align:left" + strVisible + "'>";    
    HTMLSelectCalendario = HTMLSelectCalendario + "<div id='Calendario_fsalida_calc' class='Description' style='display:block'></div>";        
    HTMLSelectCalendario = HTMLSelectCalendario + " <div class='Valor'><span class='FilaHabitReservable_AyudaTipHabit'>" + TEXTO_NOCHES +"</span>" +
                           " <select name='Calendario_Noches' id='Calendario_Noches'  onchange='return SeleccionDia(" + DesdeHasta + ",diaSeleccion_Calendario,\"ID_Dia_" + CustomNameID + "\",\"" + NombreVentana + "\",this.value);'> ";
        
    for (ValorNoches = 0 ;ValorNoches<8;ValorNoches++)
        HTMLSelectCalendario =  HTMLSelectCalendario + "<option value=' " + ValorNoches +"'>"+ (ValorNoches==0?"":ValorNoches) + "</option>";
            
    HTMLSelectCalendario = HTMLSelectCalendario + "</select>";           
    HTMLSelectCalendario = HTMLSelectCalendario + "</div></div>";
    
    HTMLBtOk = "<span id='Calendario_Aceptar' style='position:relative;left:220px' class ='AnchorSimulator' onclick='return OnCalendarioAceptar(diaSeleccion_Calendario,\"" + NombreVentana + "\",GetComponent(\"Calendario_Noches\").value);'>Ok</span>";     
    
    Ventana.innerHTML = Ventana.innerHTML + HTMLBtOk + HTMLCalendario + HTMLSelectCalendario;
    
    VentanaTop = getAbsoluteElementPosition("ID_Dia_desde").top-30;
    if (VentanaTop<0)VentanaTop =0;
    Ventana.style.top = VentanaTop + "px";
    Ventana.style.left = getAbsoluteElementPosition("ID_Dia_desde").left-20 + "px";
    
    Ventana.style.height = "140px";            
    Ventana.Show();
    
    //SeleccionDia(0,diaSeleccion_Calendario,"ID_Dia_desde","Win_Calendario_Llegada",GetComponent("Calendario_Noches").value);   
}

function getAbsoluteElementPosition(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return {top:y,left:x};
}



function UltimoDiaDelMes(Ano,Mes,dia)
{    
    PrimerDia = new Date(Ano,Mes,1,0,0,0);                  
    UltimoDia = new Date(Ano,Mes,dia,0,0,0);                  
    return PrimerDia.getMonth()!=UltimoDia.getMonth();
}

function NormalizaLunFirstDay(DiaDeLaSemana,DomFirstDay)
{
    Retorno = "";
    switch(DiaDeLaSemana)
    {
        case 0: {DomFirstDay?Retorno ="D":Retorno = "L";break;}
        case 1: {DomFirstDay?Retorno ="L":Retorno = "M";break;}
        case 2: {DomFirstDay?Retorno ="M":Retorno = "X";break;}
        case 3: {DomFirstDay?Retorno ="X":Retorno = "J";break;}
        case 4: {DomFirstDay?Retorno ="J":Retorno = "V";break;}
        case 5: {DomFirstDay?Retorno ="V":Retorno = "S";break;}
        case 6: {DomFirstDay?Retorno ="S":Retorno = "D";break;}
    }
    
    return Retorno;     
}

function GetNombreDiaSem(fecha)
{
   Retorno = "";
   
   switch(fecha.getDay())
    {
        case 0: {Retorno = TEXTO_DOMINGO;break;}
        case 1: {Retorno = TEXTO_LUNES;break;}
        case 2: {Retorno = TEXTO_MARTES;break;}
        case 3: {Retorno = TEXTO_MIERCOLES;break;}
        case 4: {Retorno = TEXTO_JUEVES;break;}
        case 5: {Retorno = TEXTO_VIERNES;break;}
        case 6: {Retorno = TEXTO_SABADO;break;}       
    }
    
   return Retorno;
}

function CrearNuevoServicio(codigoserv, codigo, fecha, nombre, precio, mostrarfecha) {
    var Servicios = document.getElementById("datosservicios");

    var col0 = document.createElement("td");
    col0.innerHTML = codigo;
    col0.style.display = "none";
    var col1 = document.createElement("td");
    col1.innerHTML = fecha;
    col1.className = "colFechaServicio";
    col1.style.visibility = mostrarfecha ? "visible" : "hidden";
    var col2 = document.createElement("td");
    col2.innerHTML = nombre;
    col2.className = "colNombreServicio";
    var col3 = document.createElement("td");
    col3.innerHTML = precio + " &euro; ";
    col3.className = "colPrecioServicio";
    var col4 = document.createElement("td");
    col4.innerHTML = "x";
    var col5 = document.createElement("td");
    col5.innerHTML = "<input type=\"text\" value=\"0\" autocomplete=\"OFF\" onfocus=\"selecciona_textinput(this)\" onkeyup=\"validarEntero(this);\" style=\"width: 100%; font-family: Verdana; font-size: 10px; line-height: normal; text-align:right\" />";
    col5.className = "colCantidadServicio";
    var col6 = document.createElement("td");
    col6.innerHTML = codigoserv;
    col6.style.display = "none";

    var Servicio = Servicios.insertRow(-1);
    Servicio.appendChild(col0);
    Servicio.appendChild(col1);
    Servicio.appendChild(col2);
    Servicio.appendChild(col3);
    Servicio.appendChild(col4);
    Servicio.appendChild(col5);
    Servicio.appendChild(col6);
}

function selecciona_textinput(objInput) {

    var valor_input = objInput.value;
    var longitud = valor_input.length;

    if (objInput.setSelectionRange) {//FF    
        objInput.focus();
        objInput.setSelectionRange(0, longitud);
    }
    else if (objInput.createTextRange) {//IE
        var range = objInput.createTextRange();
        range.collapse(true);
        range.moveEnd('character', longitud);
        range.moveStart('character', 0);
        range.select();
    }
}


function LimpiarServicios() {

    DesdeServ = "";
    HastaServ = "";

    GetComponent("HelpStringServ").innerText = "";
    GetComponent("ID_SearchGifServ").style.visibility = "hidden";
    GetComponent("ID_Texto_MSJHotelServ").style.visibility = "hidden";

    var Servicios = document.getElementById("datosservicios");
    for (i = Servicios.rows.length - 1; i >= 1; i--) Servicios.deleteRow(i);

}


function RoundNumber(numero, decimales) {
    return Math.round(numero * Math.pow(10, decimales)) / Math.pow(10, decimales);
}

function PreguntarServicios(Desde, Hasta) {
    if (oServicios == null) oServicios = new Object();
    else {
        oServicios.Servicios = null;
        oServicios.IsAbort = true;
        oServicios.XMLHttpRequest.abort();
    }

    oServicios.Invoke = "Reservar_AjaxCmd.aspx?Cmd=servicios&Desde=" +
        Desde + "&Hasta=" + Hasta;

    oServicios.XMLHttpRequest = null;
    oServicios.IsAbort = false;

    oServicios.OnComplete = function() {
        if (oServicios.XMLHttpRequest.readyState == 4 && !oServicios.IsAbort
                && oServicios.XMLHttpRequest.status == 200) {
            try {
                oServicios.Servicios = eval("(" + oServicios.XMLHttpRequest.responseText + ")");

                FechaTemp = "";
                for (a = 0; a < oServicios.Servicios.length; a++) {
                    CodServ = oServicios.Servicios[a].CodServ;
                    Codigo = oServicios.Servicios[a].Codigo;
                    Fecha = oServicios.Servicios[a].Fecha;
                    Fecha = Fecha.substring(0, 2) + "/" + Fecha.substring(2, 4) + "/" + Fecha.substring(4);
                    Nombre = oServicios.Servicios[a].Nombre;
                    Precio = oServicios.Servicios[a].Precio;

                    cambiofechas = false;
                    if (Fecha != FechaTemp) {
                        FechaTemp = Fecha;
                        cambiofechas = true;
                    }

                    CrearNuevoServicio(CodServ, Codigo, Fecha, Nombre, Precio, cambiofechas);
                }
                ModoVisualEsperandoResultadoServicios(false);

            }
            catch (e) {
                UltimoError.Object = e;
                UltimoError.Metodo = "PreguntarServicios";
                ModoVisualEsperandoResultadoServicios(false);
                DesdeServ = "";
                HastaServ = "";
            }
        }
        else if (oServicios.XMLHttpRequest.readyState == 4 && !oServicios.IsAbort
                        && oServicios.XMLHttpRequest.status != 200) {
            Inicializar();
        }

    };

    InvokeMethod(oServicios, true);
}

function ModoVisualEsperandoResultadoServicios(Wait) {
    VisualizacionInputSeleccion(Wait, true);
    var CTextoAyuda = GetComponent("HelpStringServ");
    if (Wait) {
        CTextoAyuda.innerText = TEXTO_CONSUL_SERV;
        GetComponent("ID_Texto_MSJHotelServ").style.visibility = "hidden";
    }
    else {
        var Servicios = document.getElementById("datosservicios");
        if (Servicios.rows.length > 1) {
            CTextoAyuda.innerText = TEXTO_SELEC_SERV;
            GetComponent("ID_Texto_MSJHotelServ").innerText = TEXTO_CONIVA;
            GetComponent("ID_Texto_MSJHotelServ").style.visibility = "visible";
        }
        else {
            CTextoAyuda.innerText = TEXTO_SIN_SERV;
            GetComponent("ID_Texto_MSJHotelServ").style.visibility = "hidden";
        }
    }

    GetComponent("ID_SearchGifServ").style.visibility = Wait ? "visible" : "hidden";
}


function convertirAFloat(valor) {
    resultado = valor.replace(",", ".");
    resultado = parseFloat(resultado);
    if (isNaN(resultado)) {
        resultado = 0;
    }
    return resultado;
}

function validarEntero(Component) {
    valor = Component.value;
    valor = parseInt(valor, 10);
    if (isNaN(valor)) valor = "0";
    Component.value = valor;
}

function ObtenerRegimenes(Desde, Hasta) {
    if (oRegimenes == null) oRegimenes = new Object();
    else {
        oRegimenes.PartRegimenes = null;
        oRegimenes.XMLHttpRequest.abort();
    }

    oRegimenes.Invoke = "Reservar_AjaxCmd.aspx?Cmd=PartRegimenes&Desde="
        + Desde + "&Hasta=" + Hasta + "&Cacheoff=" + Math.random() + new Date().getTime();
    oRegimenes.XMLHttpRequest = null;
    oRegimenes.OnComplete = function() {

        if (oRegimenes.XMLHttpRequest.readyState == 4 && oRegimenes.XMLHttpRequest.status == 200) {

            try {
                oRegimenes.PartRegimenes = eval("(" + oRegimenes.XMLHttpRequest.responseText + ")");
                var PartRegimenes = oRegimenes.PartRegimenes;
                var cbRegimenes = GetComponent("ID_Regimen");

                var RegimenSeleccionado = cbRegimenes.value;
                var iSelectedValue = 0;

                cbRegimenes.options.length = 0;

                for (var a = 0; a < PartRegimenes.length; a++) {
                    var opt = cbRegimenes.appendChild(document.createElement("option"));
                    opt.value = PartRegimenes[a].Codigo;
                    if (RegimenSeleccionado != "" && RegimenSeleccionado == opt.value) {
                        opt.selected = true;
                        iSelectedValue = a;
                    }
                    opt.appendChild(document.createTextNode(PartRegimenes[a].Nombre));
                }

                if (PartRegimenes.length > 0) {
                    Personas = parseInt(GetValue("ID_Adultos")) + parseInt(GetValue("ID_Ninos"));
                    PreguntarDisponbilidad(Desde, Hasta, GetValue("ID_CountHab"), Personas);
                }
                else {                    
                    oRegimenes.PartRegimenes = null;
                    Inicializar();                 
                }
            }
            catch (Exception) {
                UltimoError.Object = Exception;
                UltimoError.Metodo = "ObtenerRegimenes";
                oRegimenes.PartRegimenes = null;
                Inicializar();
            }
        }
        else if (oRegimenes.XMLHttpRequest.readyState == 4
                && oRegimenes.XMLHttpRequest.status != 200) {
            oRegimenes.PartRegimenes = null;
            Inicializar();
        }
    };

    InvokeMethod(oRegimenes, true);
}

