// Variables Resituadas por el controlador

// Periodos Activos del Calendario
GEN_Active_Date_Start = null;
GEN_Active_Date_End = null;
// Fecha Seleccionada
GEN_Selected_Date = null;
GEN_CAL_COOKIE_SEL_Year = "CALSELYEAR";
GEN_CAL_COOKIE_SEL_Month = "CALSELMONTH";
GEN_CAL_COOKIE_SEL_Day = "CALSELDAY";
GEN_CAL_Salida_Interval = null;


// Variables de Trabajo

GEN_Working_Dates = new Array();
GEN_Working_TD = new Array();
GEN_Working_Selected_TD = null;
GEN_Working_Selected_DIV = null;
GEN_Working_Selected_Day = null;
GEN_Day_Height = 19;
GEN_Day_Width = 22;
GEN_Prior_Date = null;
GEN_Next_Date = null;

// Store a Cookie
function CAL_SetCookie(name, value)
{


    var argv = CAL_SetCookie.arguments;
    var argc = CAL_SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;

    document.cookie = name + "=" + escape (value) +
                      ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
                      ((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain)) +
                      ((secure == true) ? "; secure" : "");

}

// Retrieve a Cookie Value
function CAL_GetCookieValue (offset)
{
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

// Get a Cookie
function CAL_GetCookie (name,defaultvalue)
{
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) return CAL_GetCookieValue (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    
    return defaultvalue;
}


function Is_LeapYear(AYear)
{
	if ((AYear/4)   != Math.floor(AYear/4))   return false;
	if ((AYear/100) != Math.floor(AYear/100)) return true;
	if ((AYear/400) != Math.floor(AYear/400)) return false;
	return true;
}//Is_LeapYear

function Days_In_Month(AYear,AMonth)
{
	var _Month_Days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	V_Days_In_Month = _Month_Days[AMonth - 1];

	if (Is_LeapYear(AYear) == true && AMonth == 2)
	{
		return V_Days_In_Month + 1;
	}
	else
	{
		return V_Days_In_Month;
	}
}//Days_In_Month

function Format_Number(ANumber)
{
	if (ANumber < 10) { return "0"+ANumber.toString()} else {return ANumber.toString()};
}//Format_Number

function Check_Active_Date(ADate)
{
	if (ADate < GEN_Active_Date_Start || ADate > GEN_Active_Date_End) { return false;} else {return true;}
}//Check_Active_Date

function Check_Date_Equal(ADate1,ADate2)
{
    // Comprobamos Variables
    if (ADate1 == null || ADate2 == null) { return false;}
    
    V_Year_1 = ADate1.getFullYear(); V_Month_1 = ADate1.getMonth(); V_Day_1 = ADate1.getDate();
    V_Year_2 = ADate2.getFullYear(); V_Month_2 = ADate2.getMonth(); V_Day_2 = ADate2.getDate();

    if (V_Year_1 == V_Year_2 && V_Month_1 == V_Month_2 && V_Day_1 == V_Day_2){ return true;} else { return false;}
}//Check_Date_Equal

function Make_Day_Content(ATD,ADayNumber,ADate,ADiv_Id)
{
	V_Active = Check_Active_Date(ADate);

	if (V_Active == true)
	{
        if (DateIsSaturday(ADate))
        {
            V_CSS = "CALDAYSATURDAY";
            V_CSS_Fill = "CALDAYSATURDAYFILL";
        }
        else
        {
            V_CSS = "CALDAYNORMAL";
            V_CSS_Fill = "CALDAYNORMALFILL";

        }

        ATD.className = V_CSS;
		return "<DIV id=\""+ ADiv_Id +"\" class=\""+ V_CSS_Fill + "\" onmouseout=\"Calendar_Day_MouseLeave(this,"+ ADayNumber.toString() + ")\" onmouseover=\"Calendar_Day_MouseOver(this,"+ ADayNumber.toString() + ")\" onclick=\"Calendar_Day_Click(this,"+ ADayNumber.toString() + ")\" style=\"width=\"100%\" height=\"100%\"\">" + ADayNumber.toString() + "</DIV>";
	}
	else
	{
        ATD.className = "CALDAYINACTIVE";
		return "<DIV id=\"" + ADiv_Id + "\" class=\"CALDAYINACTIVEFILL\" style=\"width=\"100%\" height=\"100%\"\">" + ADayNumber.toString() + "</DIV>";
	}

}//Make_Day_Content

function Calendar_Day_Click(ADayDiv,ADayNumber)
{
	if (ADayDiv == null) {return;}


    if (GEN_Working_Selected_Day != null && DateIsSaturday(GEN_Working_Dates[GEN_Working_Selected_Day]))
    {
        V_CSS = "CALDAYSATURDAY";
        V_CSS_Fill = "CALDAYSATURDAYFILL";
    }
    else
    {
        V_CSS = "CALDAYNORMAL";
        V_CSS_Fill = "CALDAYNORMALFILL";

    }

    if (GEN_Working_Selected_DIV != null) {GEN_Working_Selected_DIV.className = V_CSS_Fill;}


    if (GEN_Working_Selected_TD != null) {GEN_Working_Selected_TD.className = V_CSS;}

    ADayDiv.className = "CALDAYSELECTEDFILL";
    GEN_Working_Selected_DIV = ADayDiv;
    GEN_Working_Selected_Day = ADayNumber;
    GEN_Selected_Date = GEN_Working_Dates[ADayNumber];
    if (GEN_Working_TD[ADayNumber] != null)
    {
        GEN_Working_TD[ADayNumber].className = "CALDAYSELECTED";
        GEN_Working_Selected_TD = GEN_Working_TD[ADayNumber];
    }

    // Guardamos la Fecha Seleccionada en un Cookie
    Store_Selected_Date();

    // Refrescamos el Display de la Fecha Seleccionada
    CAL_Refresh_Entrada_Salida_Display();    
    

}//Calendar_Day_Click

function Calendar_Day_MouseOver(ADayDiv,ADayNumber)
{
	if (ADayDiv == null) {return;}

    if (ADayDiv == GEN_Working_Selected_DIV) {return;}

	ADayDiv.className = "CALDAYMOUSEOVERFILL";

    if (GEN_Working_TD[ADayNumber] != null) {GEN_Working_TD[ADayNumber].className = "CALDAYMOUSEOVER";}

}//Calendar_Day_MouseOver

function Calendar_Day_MouseLeave(ADayDiv,ADayNumber)
{
	if (ADayDiv == null) {return;}

    if (ADayDiv == GEN_Working_Selected_DIV) {return;}

    if (DateIsSaturday(GEN_Working_Dates[ADayNumber]))
    {
        V_CSS = "CALDAYSATURDAY";
        V_CSS_Fill = "CALDAYSATURDAYFILL";
    }
    else
    {
        V_CSS = "CALDAYNORMAL";
        V_CSS_Fill = "CALDAYNORMALFILL";

    }

	ADayDiv.className = V_CSS_Fill;
    if (GEN_Working_TD[ADayNumber] != null) {GEN_Working_TD[ADayNumber].className = V_CSS;}
}//Calendar_Day_MouseOver


function Nav_Prior_Click()
{

    Init_Calendar(false,true,false,false,null);
}

function Nav_Next_Click()
{
    Init_Calendar(false,false,true,false,null);
}

function Store_Selected_Date()
{

    if (GEN_Selected_Date == null) {return;}


    // Convertimos
	V_Selected_Year = GEN_Selected_Date.getFullYear();
	V_Selected_Month = GEN_Selected_Date.getMonth() + 1;
	V_Selected_Day = GEN_Selected_Date.getDate();

    // Guardamos
    CAL_SetCookie(GEN_CAL_COOKIE_SEL_Year, V_Selected_Year);
    CAL_SetCookie(GEN_CAL_COOKIE_SEL_Month, V_Selected_Month);
    CAL_SetCookie(GEN_CAL_COOKIE_SEL_Day, V_Selected_Day);
}

function Selected_Date_To_String()
{
    if (GEN_Selected_Date == null)
    {
        GEN_Selected_Date = new Date();
    }

    V_Selected_Year = GEN_Selected_Date.getFullYear();
    V_Selected_Month = GEN_Selected_Date.getMonth() + 1;
    V_Selected_Day = GEN_Selected_Date.getDate();

    return Format_Number(V_Selected_Day) + "/" + Format_Number(V_Selected_Month) + "/" + V_Selected_Year;
}

function Display_Fecha_Salida(DaySpan_Llegada)
{
    if (GEN_Selected_Date == null)
    {
        GEN_Selected_Date = new Date();
    }

    V_Fecha_Salida = new Date(GEN_Selected_Date.getFullYear(),GEN_Selected_Date.getMonth(),GEN_Selected_Date.getDate());
    V_Fecha_Salida.setDate(V_Fecha_Salida.getDate() + DaySpan_Llegada);

    V_Salida_Year = V_Fecha_Salida.getFullYear();
    V_Salida_Month = V_Fecha_Salida.getMonth() + 1;
    V_Salida_Day = V_Fecha_Salida.getDate();

    return Format_Number(V_Salida_Day) + "/" + Format_Number(V_Salida_Month) + "/" + V_Salida_Year;
}


function DateIsSaturday(ADate)
{

    if (ADate == null){ return false;}

    if (ADate.getDay() == 6)
    {
        return true;
    }
    else
    {
        return false;
    }
}


// Esta funcion se encarga de Inicializar el Calendario
// IsInit = Inicializacion Entrada en Pagina
// IsPrior = Inicializacion de Cambio de Mes a Anterior
// IsNext = Inicializacion de Cambio de Mes a Siguiente
// ASetMonthYear= Carga de Mes aņo desde la combo de Mes/Aņo
// IsInit es Exclusivo y evita los otros ya que si es IsInit no puede ser navegacion
function Init_Calendar(IsInit,IsPrior,IsNext,IsNewSession,ASetMonthYear)
{

    // Inicializamos los Datos de la Fecha Actual
	V_Actual_DateTime = new Date();
	V_Actual_Year = V_Actual_DateTime.getFullYear();
	V_Actual_Month = V_Actual_DateTime.getMonth() + 1;
	V_Actual_Day = V_Actual_DateTime.getDate();

    // Comprobacion de Parametros
    if (IsInit == null) {V_IsInit = true;} else {V_IsInit = IsInit;}
    if (IsNewSession == null) {V_IsNewSession = true;} else {V_IsNewSession = IsNewSession;}
    if (IsPrior == null) {V_IsInit = true; V_IsPrior = false; V_IsNext = false;} else {V_IsPrior = IsPrior;}
    if (IsNext == null) {V_IsInit = true; V_IsPrior = false; V_IsNext = false;} else {V_IsNext = IsNext;}

    if (V_IsInit == true)
    {
        // Obtenemos los posibles datos guardados en un cookie para la Fecha Seleccionada
        V_COK_Year = parseInt(CAL_GetCookie(GEN_CAL_COOKIE_SEL_Year,0));
        V_COK_Month = parseInt(CAL_GetCookie(GEN_CAL_COOKIE_SEL_Month,0));
        V_COK_Day = parseInt(CAL_GetCookie(GEN_CAL_COOKIE_SEL_Day,0));

        // Comprobamos Valores
        if (V_COK_Year == 0 || V_COK_Month == 0 || V_COK_Day == 0)
        {
            // Asignamos los Datos por defecto
            V_COK_Year = GEN_Selected_Date.getFullYear();
            V_COK_Month = GEN_Selected_Date.getMonth() + 1;
            V_COK_Day = GEN_Selected_Date.getDate();
        }
        else
        {
            // Creamos el Objeto Fecha
            V_Cookie_Date = new Date(V_COK_Year,V_COK_Month - 1,V_COK_Day);
            // Comprobamos si esta dentro de los periodos Activos o es una nueva sesion
            if (V_Cookie_Date < GEN_Active_Date_Start || V_Cookie_Date > GEN_Active_Date_End || V_IsNewSession == true)
            {
                // Si esta fuera de los periodos Activos marcamos la Fecha por Defecto
                V_COK_Year = GEN_Selected_Date.getFullYear();
                V_COK_Month = GEN_Selected_Date.getMonth() + 1;
                V_COK_Day = GEN_Selected_Date.getDate();
            }

        }

        // Marcamos los Datos de Trabajo
        V_Working_Year = V_COK_Year;
        V_Working_Month = V_COK_Month;
        V_Working_Day = V_COK_Day;

        // Marcamos la Fecha Seleccionada
        GEN_Selected_Date = new Date(V_Working_Year,V_Working_Month - 1,V_Working_Day);
    }
    else
    {
        if (ASetMonthYear != null)
        {
            // Aņadimos un espacio al final por si el mes es de un digito
            V_ASetMonthYear = ASetMonthYear + " ";
            V_Working_Year = parseInt(V_ASetMonthYear.substring(0,4));
            V_Working_Month = parseInt(V_ASetMonthYear.substring(4,6));
        }
        else
        {
            if (V_IsPrior == true)
            {
                // Comprobamos
                if (GEN_Prior_Date == null) {GEN_Prior_Date = V_Actual_Date_Time;}
                // Marcamos los Datos de Trabajo
                V_Working_Year = GEN_Prior_Date.getFullYear();
                V_Working_Month = GEN_Prior_Date.getMonth() + 1;
                V_Working_Day = GEN_Prior_Date.getDate();
            }
            else
            {
                // Comprobamos
                if (GEN_Next_Date == null) {GEN_Next_Date = V_Actual_Date_Time;}
                // Marcamos los Datos de Trabajo
                V_Working_Year = GEN_Next_Date.getFullYear();
                V_Working_Month = GEN_Next_Date.getMonth() + 1;
                V_Working_Day = GEN_Next_Date.getDate();
            }
        }
    }



	V_Month_First_Day = 1;
	V_Month_Last_Day = Days_In_Month(V_Working_Year,V_Working_Month);

	V_Month_First_Day_Date = new Date(V_Working_Year,V_Working_Month - 1,V_Month_First_Day);

	V_Working_First_Day_Number = V_Month_First_Day_Date.getDay();

	if (V_Working_First_Day_Number == 0) { V_Working_First_Day_Number = 7}


    // Bucle de Limpieza de las TDs
    for (V_Col = 1; V_Col <= 7; V_Col++)
    {
        for (V_Row = 1; V_Row <= 6; V_Row++)
        {
    		V_TD_Id = "CAL" + Format_Number(V_Row) + Format_Number(V_Col);
            V_TD = document.getElementById(V_TD_Id);

            if (V_TD != null)
            {
                V_TD.width = GEN_Day_Width;
                V_TD.height = GEN_Day_Height;
                V_TD.innerHTML = "";
                V_TD.className = "CALDAYNONE";
                GEN_Working_Selected_TD = null;
                GEN_Working_Selected_DIV = null;
                GEN_Working_Selected_Day = null;
            }
        }
    }


    // Inicializacion de los Dias de la Semana
    for (V_Col = 1; V_Col <= 7; V_Col++)
    {
        V_TD_Id = "CALDAY" + Format_Number(V_Col);
        V_TD = document.getElementById(V_TD_Id);

        if (V_TD != null)
        {
            V_TD.width = GEN_Day_Width;
            V_TD.height = GEN_Day_Height;
            V_TD.innerHTML = GEN_Day_Names[V_Col];
            V_TD.className = "CALDAYNAMES";
        }
    }


    // Inicializacion de la Caption del Mes
    V_TD_Id = "CALMONTHYEAR";
    V_TD = document.getElementById(V_TD_Id);

    if (V_TD != null)
    {
/*
        V_Month_Year = GEN_Month_Names[V_Working_Month] + " " + V_Working_Year.toString();
        V_TD.innerHTML = V_Month_Year;
*/        
        V_TD.className = "CALMONTHYEARCAPTION";
    }

    // Actualizamos la combo de Mes
    // GEN_CMB_Month_Year_ID es cargado en el user control del calendario. Hay que hacerlo alli ya que el nombre es dinamico al ser un control de servidor
    V_CMB = document.getElementById(GEN_CMB_Month_Year_ID);
    if (V_CMB != null)
    {
        V_Month_Year = V_Working_Year.toString() + V_Working_Month;

        for (V_Item = 0; V_Item < V_CMB.length; V_Item++)
        {
            if (V_CMB.options[V_Item].value == V_Month_Year)
            {
                V_CMB.selectedIndex = V_Item;
                // salimos del bucle
                break;
            }// Encontrado

        }// for V_Item

    }// V_CMB != null

    // Inicializacion del Navegador de Meses


    // Prior
    GEN_Prior_Date = null;
    V_TD_Id = "NAVPRIOR";
    V_TD = document.getElementById(V_TD_Id);

    if (V_TD != null)
    {
        V_Prior_Month = V_Working_Month - 1;
        if (V_Prior_Month < 1)
        {
            V_Prior_Month = 12; V_Prior_Year = V_Working_Year - 1;
        }
        else
        {
            V_Prior_Year = V_Working_Year;
        }

        // Establecemos la Fecha Maxima del Calendario del Mes Anterior
        V_Prior_Date = new Date(V_Prior_Year,V_Prior_Month - 1,Days_In_Month(V_Prior_Year,V_Prior_Month));

        if (V_Prior_Date < GEN_Active_Date_Start)
        {
            V_TD.innerHTML = "<DIV width=\"16px\">&nbsp;</DIV>";
        }
        else
        {
            V_TD.innerHTML = "<DIV class=\"cal_nav_prior_enabled_fill\" onclick=\"Nav_Prior_Click()\">&nbsp;</DIV>";
            GEN_Prior_Date = V_Prior_Date;
        }

        V_TD.className = "cal_nav_prior_next_background";
    }


    // Next
    GEN_Next_Date = null;
    V_TD_Id = "NAVNEXT";
    V_TD = document.getElementById(V_TD_Id);
    if (V_TD != null)
    {
        V_Next_Month = V_Working_Month + 1;

        if (V_Next_Month > 12)
        {
            V_Next_Month = 1;
            V_Next_Year = V_Working_Year + 1;
        }
        else
        {
            V_Next_Year = V_Working_Year;
        }


        // Establecemos la Fecha Minima del Calendario del Mes Siguiente
        V_Next_Date = null;
        V_Next_Date = new Date(V_Next_Year,V_Next_Month - 1,1);



        if (V_Next_Date > GEN_Active_Date_End)
        {
            V_TD.innerHTML = "<DIV width=\"16px\">&nbsp;</DIV>";
        }
        else
        {
            V_TD.innerHTML = "<DIV class=\"cal_nav_next_enabled_fill\" onclick=\"Nav_Next_Click()\">&nbsp;</DIV>";
            GEN_Next_Date = V_Next_Date;
        }

        V_TD.className = "cal_nav_prior_next_background";        
    }

    // Inicializacion del Calendario
	V_Col = V_Working_First_Day_Number;
	V_Row = 1;

    // Inicializamos las Variables de Control de Refresco del dia Seleccionado
    V_Refresh_Select_Day = null;
    V_Refresh_Select_DIV = null;

    // Bucle de Gestion de Dias
	for (V_Day_Number = 1; V_Day_Number <= V_Month_Last_Day; V_Day_Number ++)
	{
		V_TD_Id = "CAL" + Format_Number(V_Row) + Format_Number(V_Col);
        V_DIV_Id = "DIVCAL" + Format_Number(V_Row) + Format_Number(V_Col);
		V_TD = document.getElementById(V_TD_Id);
		GEN_Working_Dates[V_Day_Number] = null;

		if (V_TD != null)
		{
			V_TD.width = GEN_Day_Width;
			V_TD.height = GEN_Day_Height;
			V_TD_Date = new Date(V_Working_Year,V_Working_Month - 1,V_Day_Number);
			V_TD.innerHTML = Make_Day_Content(V_TD,V_Day_Number,V_TD_Date,V_DIV_Id);
			GEN_Working_Dates[V_Day_Number] = V_TD_Date;
            GEN_Working_TD[V_Day_Number] = V_TD;

            // Comprobamos si es la fecha Seleccionada
            if (Check_Date_Equal(V_TD_Date,GEN_Selected_Date))
            {
                V_Refresh_Select_Day = V_Day_Number;
                V_Refresh_Select_DIV = document.getElementById(V_DIV_Id);
            }

		}

		V_Col = V_Col + 1;

        if ( V_Col > 7)
		{
			V_Col = 1;V_Row = V_Row + 1;
		}

	}

    // controlamos si hemos de Seleccionar alguna Fecha del Calendario Actual
    if (V_Refresh_Select_Day != null && V_Refresh_Select_DIV != null)
    {
        Calendar_Day_Click(V_Refresh_Select_DIV,V_Refresh_Select_Day);
    }

    // Refrescamos el Display de la Fecha Seleccionada
    CAL_Refresh_Entrada_Salida_Display();    


}//Init_Calendar

// Esta funcion se encarga de refrescar el display de la fecha seleccionada
function CAL_Refresh_Entrada_Salida_Display()
{
    // Primero obtenemos la combo de estancia
    V_CMB_Estancia = document.getElementById("CMB_ESTANCIA");

    // Comprobamos si pudo ser encontrada
    if (V_CMB_Estancia == null)
    {
        // Si no pudo ser econtrado y el timer esta activado salimos ya que estamos en bucle de espera de carga de la pagina
        if (GEN_CAL_Salida_Interval != null) {return;}

        // Inicializamos el timer para la recuperacion de la combo de estancias
        GEN_CAL_Salida_Interval = setInterval("CAL_Refresh_Entrada_Salida_Display()",100);
        // salimos
        return;
    }

    // Si el Timer esta activado.. lo liberamos
    if (GEN_CAL_Salida_Interval != null) { clearInterval(GEN_CAL_Salida_Interval);}

    // Obtenemos la TD de la informacion de llegada
    V_TD_Info_Llegada = document.getElementById("td_cal_info_llegada");

    // Marcamos el Texto
    if (V_TD_Info_Llegada != null)
    {
        V_TD_Info_Llegada.innerHTML = Selected_Date_To_String();
    }

    // Marcamos los dias de estancia
    V_Dias_Estancia = parseInt(V_CMB_Estancia.value);

    // Obtenemos la TD de la informacion de salida
    V_TD_Info_Salida = document.getElementById("td_cal_info_salida");


    // Marcamos el Texto
    if (V_TD_Info_Salida != null)
    {
        V_TD_Info_Salida.innerHTML = Display_Fecha_Salida(V_Dias_Estancia);
    }







}//CAL_Refresh_Entrada_Salida_Display


