﻿/**
 *
 * Funciones genéricas usadas en todo el site.
 *
 **/

// Comprobar e-mail

function isEml(str){ 
   var supported = 0; 
   if (window.RegExp) { 
	  var tempStr = "a"; 
	  var tempReg = new RegExp(tempStr); 
	  if (tempReg.test(tempStr)) supported = 1; 
   } 
   if (!supported) return (str.indexOf(".") > 2) && (str.indexOf("@") > 0); 
 
   var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
   var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,6}|[0-9]{1,3})(\\]?)$"); 
   return (!r1.test(str) && r2.test(str)); 
}

//comprueba si una cadena contiene numeros
function contieneNumeros(str) {
    return (str.indexOf("0") + str.indexOf("1") + str.indexOf("2") + str.indexOf("3") + str.indexOf("4") + str.indexOf("5") + str.indexOf("6") + str.indexOf("7") + str.indexOf("8") + str.indexOf("9") + 10 > 0);
} 

listaDesplegable = function(id) {
     if (document.all && document.getElementById) {
       var lis = document.getElementById(id).getElementsByTagName("li");/* aqui la id de la lista que tiene submenus que aparecen y deasaparecen*/
        for (var i=0; i<lis.length; i++) {
	        lis[i].onmouseover=function() {
		        this.className+=" iehover";
	        }
	        lis[i].onmouseout=function() {
		        this.className=this.className.replace(new RegExp(" iehover\\b"), "");
	        }
        }   
    }
}


// Quitar espacios en blanco al principio y al final
function trim(str) {
    var st = new String(str);
    st = st.replace(/^\s*|\s*$/g, "");
    str = st.toString();
    return str;
}

// devuelve si la cadena viene vacia
function IsNullOrEmpty(str) {
    if (str == null) return true;
    if (trim(str) == "") {
        return true;
    } else {
        return false;
    }
}


// Validar una fecha

function validaFecha_ddmmyyyy (strFecha){

	var arrayFecha;
	var dia;
	var mes;
	var anyo;

	arrayFecha = strFecha.split("/");

	if (arrayFecha.length < 3)
		return false;
		
	dia = arrayFecha[0];
	mes = arrayFecha[1];
	anyo = arrayFecha[2];
	
	if (dia == "")
		return false;
	
	if (mes == "")
		return false;
		
	if (anyo == "" || anyo<1900 || anyo>9999)
		return false;
			
	if (anyo.indexOf('.')>0)
		return false;

	if (anyo.length!=2 && anyo.length!=4)
		return false;
	
	mes = mes - 1;

	with (new Date(anyo, mes, dia)) {
		return (getDate()==dia && getMonth()==mes);
	}
};

function validaFecha_ddmmyyyy2(strFecha) {

    var arrayFecha;
    var dia;
    var mes;
    var anyo;

    arrayFecha = strFecha.split(".");

    if (arrayFecha.length < 3)
        return false;

    dia = arrayFecha[0];
    mes = arrayFecha[1];
    anyo = arrayFecha[2];

    if (dia == "")
        return false;

    if (mes == "")
        return false;

    if (anyo == "" || anyo < 1900 || anyo > 9999)
        return false;

    if (anyo.indexOf('.') > 0)
        return false;

    if (anyo.length != 2 && anyo.length != 4)
        return false;

    mes = mes - 1;

    with (new Date(anyo, mes, dia)) {
        return (getDate() == dia && getMonth() == mes);
    }
};


//*************************************************** Funciones para Fechas ***********************************// 

function isValidDate(dateString, format) {
    var dateVal;
    var dArray;
    var d, m, y;

    if (format == null) format = "dd/MM/yyyy";
    try {
        dArray = splitDateString(dateString);
        if (dArray) {
            switch (format) {
                case "dd/MM/yyyy":
                    d = parseInt(dArray[0], 10);
                    m = parseInt(dArray[1], 10) - 1;
                    y = parseInt(dArray[2], 10);
                    break;
                case "yyyy/MM/dd":
                    d = parseInt(dArray[2], 10);
                    m = parseInt(dArray[1], 10) - 1;
                    y = parseInt(dArray[0], 10);
                    break;
                case "MM/dd/yyyy":
                default:
                    d = parseInt(dArray[1], 10);
                    m = parseInt(dArray[0], 10) - 1;
                    y = parseInt(dArray[2], 10);
                    break;
            }
            dateVal = new Date(y, m, d);
        } else if (dateString) {
            dateVal = new Date(dateString);
        } else {
            dateVal = new Date();
        }
    } catch (e) {
        return false;
    }
    return true;
}


function DateToString(dateVal, format) {
    // ********************************************************************************
    // Devuelve un string con la fecha en el formato especificado...
    // ********************************************************************************
    var dayString = "00" + dateVal.getDate();
    var monthString = "00" + (dateVal.getMonth() + 1);
    dayString = dayString.substring(dayString.length - 2);
    monthString = monthString.substring(monthString.length - 2);
    switch (format) {
        case "dd/MM/yyyy":
            return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
        case "yyyy/MM/dd":
            return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
        case "MM/dd/yyyyy":
        default:
            return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
    }
}

function StringToDate(dateString, format) {
    var dateVal;
    var dArray;
    var d, m, y;
    // ********************************************************************************
    // Devuelve una fecha (date()) desde un string...
    // ********************************************************************************
    try {
        dArray = splitDateString(dateString);
        if (dArray) {
            switch (format) {
                case "dd/MM/yyyy":
                    d = parseInt(dArray[0], 10);
                    m = parseInt(dArray[1], 10) - 1;
                    y = parseInt(dArray[2], 10);
                    break;
                case "yyyy/MM/dd":
                    d = parseInt(dArray[2], 10);
                    m = parseInt(dArray[1], 10) - 1;
                    y = parseInt(dArray[0], 10);
                    break;
                case "MM/dd/yyyy":
                default:
                    d = parseInt(dArray[1], 10);
                    m = parseInt(dArray[0], 10) - 1;
                    y = parseInt(dArray[2], 10);
                    break;
            }
            dateVal = new Date(y, m, d);
        } else if (dateString) {
            dateVal = new Date(dateString);
        } else {
            dateVal = new Date();
        }
    } catch (e) {
        dateVal = new Date();
    }
    return dateVal;
}


//*******************************************************************************************************************//


function showHide(id, show) {
    var obj = document.getElementById(id);
    if (show == true) { obj.style.display = "block" } else { obj.style.display = "none" };
}

// Funcion para cambiar la clase a un elemento

cambiarClaseCss = function (id,clase){   
    if (document.getElementById(id) != null)
    {        
        document.getElementById(id).className = clase;
    }
}


// Funcion para ocultar / mostrar un elemento

function toggle(id) {
    var obj = document.getElementById(id);
    if (obj.style.display == 'block') obj.style.display = '';
    obj.style.display = (obj.style.display == '') ? 'none' : ''; 
    return true;
}

function changeText(id, text1, text2){
    var obj = document.getElementById(id);
    if (obj == null) return false;
    var text
     if (obj.tagName == "INPUT") {
        text = obj.value;
    }
    else {
        text = obj.innerHTML;
    }

    text = (text == text1 ? text2 : text1);
    if (obj.tagName == "INPUT") {
        obj.value  = text;
    }
    else {
        obj.innerHTML = text;
    }
    
    return true;
}

function toggleinnerHTML(id, text){
    var obj = document.getElementById(id);
    if (obj == null) return false;
    obj.innerHTML = text;
    return true;
 }


 function toggleText(id, idtext, text1, text2) {
    toggle(id);
    changeText(idtext, text1, text2);
}

function toggleText2(id, idtext, text1, text2) {

    toggle(id);
    changeText(idtext, text1, text2);
    //Añadimos esta comprobación, para que el ocultar/mostrar resultados no pise el pie.
    if ((document.getElementById("FiltroHotelesIzq").style.display == "none") |
        ((document.getElementById("FiltroHotelesIzq").style.display == "none") && (document.getElementById("MensajeSinResultados").style.display == "")) |
        (document.getElementById("buscador").style.display =="none")) {
        document.getElementById("contenido").style.minHeight = "530px";
    } else {
        document.getElementById("contenido").style.minHeight = "820px";
    }   
}

// Función para capitalizar una string 
// EJ: Hola Que Tal --> Hola que tal 

function Capitalize(Str){
    var Aux1 = Str;
    Aux1 = Aux1.toLowerCase();
    Aux1 = Aux1.substring(1);
    var Aux2 = Str.charAt(0);
    var Resultado = Aux2 + Aux1;
    return Resultado;
}


// Abrir un bonito popup

function abrirPopUp(url,width,height,resizable){
    if (width == null) width=650;
    if (height == null) height=580;
    if (resizable == null) resizable="yes";
    window.open(url,"Info","resizable=" + resizable + ",menubars=no,toolbars=no,status=no,scrollbars=yes,width=" + width + ",height=" + height + ",left=50,top=50");
}
/* combobox utilities */

/**
 * Recupera el combobox con el identificador indicado.
 *
 * @param   id       El identificador del combobox.
 * @return      El combobox con el id especificado.
 *
 * @throws      Si no se encuentra ningún combobox con el identificador indicado.
 */
function _cmbGet(id) {
    var callerName;
    try {
        callerName = _cmbGet.caller.toString().match(/function (\w*)/)[1];
    } catch(ex) {
        callerName = 'Unknown';
    }

    var cmb = document.getElementById(id);
    if (cmb == null) throw new Error(callerName + ": Invalid id '" + id + "'");
    if (cmb.tagName.toUpperCase() != 'SELECT') throw new Error(callerName + ": Invalid node type '" + cmb.tagName + "' for id '" + id + "', 'SELECT' type expected");
    
    return cmb;
}

/**
 * Recupera el valor seleccionado del combobox con el identificador indicado.
 *
 * @param   id       El identificador del combobox.
 * @return      El valor seleccionado, o un string vacío '' si no hay ninguno. 
 *
 * @throws      Si no se encuentra ningún combobox con el identificador indicado.
 */
function cmbGetValue(id) {
    var cmb = _cmbGet(id);
   
    if (cmb.hasChildNodes() && cmb.options) {
        return cmb.options[cmb.selectedIndex].value;
    }
    
    return '';
}

/**
 * Selecciona el valor especificado para el combobox con el identificador indicado.
 * Si el combobox no tiene ese valor, entonces esta función no hace nada.
 *
 * @param   id      El identificador del combobox.
 * @param   value   El valor que se quiere seleccionar.
 *
 * @throws      Si no se encuentra ningún combobox con el identificador indicado.
 */
function cmbSelectValue(id, value) {
    var cmb = _cmbGet(id);

    if (cmb.hasChildNodes() && cmb.options) {
        for (i = 0; i < cmb.options.length; i++) {
            if (cmb.options[i].value == value) {
                    //cmb.selectedIndex = i; no funciona
                    try {
                    cmb.options[i].selected=true;
                    } catch (e) {
                    cmb.selectedIndex = i;
                    }
                return;
            }
        }
    }
}

/**
 * Rellena el combobox con los valores indicados en el array. El array estará compuesto
 * por parejas de (valor, texto) de modo que el elemento arr[i] es el 'value' y el elemento
 * arr[i+1] es el texto del 'OPTION' generado.
 *
 * @param   id      El identificador del combobox.
 * @param   arr     Array de parejas (valor, texto) para generar las opciones.
 *
 * @throws      Si no se encuentra ningún combobox con el identificador indicado. 
 */
function cmbSetValues(id, arr) {
    var cmb = _cmbGet(id);

    nodeRemoveAllChilds(cmb);

    for (i = 0; i < arr.length; i += 2) {
        var oOption;        
        oOption = document.createElement("OPTION");
        oOption.value = i;
        oOption.innerHTML = i+1;
        cmb.appendChild(oOption);
    }
}

/**
 * Rellena el combobox con los valores desde min hasta max, abmos inclusive.
 *
 * @param   id      El identificador del combobox.
 * @param   min     Valor mínimo.
 * @param   max     Valor máximo.
 *
 * @throws      Si no se encuentra ningún combobox con el identificador indicado. 
 */
function cmbSetValues(id, min, max) {
    var cmb = _cmbGet(id);

    nodeRemoveAllChilds(id);

    for (i = min; i <= max; i ++) {
        var oOption;        
        oOption = document.createElement("OPTION");
        oOption.value = i;
        oOption.innerHTML = i;
        cmb.appendChild(oOption);
    }
}

/* DOM generic */

/**
 * Elimina todos los nodos hijos del elemento indicado. Si no se encuentra el
 * elemento está función no hace nada.
 *
 * @param   id  El identificador del elemento.
 */
function nodeRemoveAllChilds(id) {
    var obj = document.getElementById(id);
    if (obj != null) {
        while (obj.firstChild) {
            obj.removeChild(obj.firstChild);
        }
    }
}




/* Pop-up */

/**
 * Abre un popup de contenido. Función creada para el nuevo editor HTML.
 *
 * @param   id_con Identificador de contenido.
 * @param   ancho Ancho de la ventana
 * @param   alto Alto de la ventana
 */
function abrir_contenido_popup(url_base, id_con, ancho, alto) {
	    return window.open(url_base + 'home/contenidoPopup.aspx?id=' + id_con , 'Pop', 'toolbar=0,width=' + ancho + ', height=' + alto + ', left=80, top=80');
}

/**

 * Abre un popup de contenido. Función creada para el nuevo editor HTML.

 *

 * @param   id_con Identificador de contenido.

 * @param   ancho Ancho de la ventana

 * @param   alto Alto de la ventana

 */

function abrir_contenido_popup(id_con, ancho, alto) {

          return window.open('../../home/contenidoPopup.aspx?id=' + id_con , 'Pop', 'toolbar=0,width=' + ancho + ', height=' + alto + ', left=80, top=80');

}

/* Cancelar la cesta de la compra */

function cancelarCesta(mens) {
    if (mens == null) mens = "¿Está seguro de que desea cancelar la cesta?"
    if (window.confirm(mens))
    {
       window.location.href = "/reserva/cancelarReserva.aspx";
    }

}


/* Mostrar el divBuscando*/
function mostrarBuscando() {
    var divTodo = document.getElementById('pagina');
    var divBuscando = document.getElementById('buscando');
    if (divTodo != null & divBuscando != null)
    {
        divTodo.style.display = "none";
        divBuscando.style.display = "block";
    }

}

/* Ocultar el divBuscando*/
function ocultarBuscando() {
    var divTodo = document.getElementById('pagina');
    var divBuscando = document.getElementById('buscando');
    if (divTodo != null & divBuscando != null)
    {
        divTodo.style.display = "block";
        divBuscando.style.display = "none";
    }

}


/*
   Funcion de Submit
    frm -> (form) es el formulario sobre el que queremos hacer submit
    urlpost -> (string) la direccion hacia la que queremos hacer ese submit
    accion -> (string) dara valor al input hidden accion de la masterpage
    mostrarpreloader ->(boolean) hara que se muestre o no el preloader (por defecto lo muestra)
*/
function submit(frm,urlpost,accion,parametros,mostrarpreloader) {
    if (urlpost != null  & urlpost != '' )  frm.action = urlpost;
    if (accion != null  & accion != '' )  frm.accion.value = accion;
    if (parametros != null  & parametros != '' )  frm.parametros.value = parametros;
	frm.submit();
    if (mostrarpreloader != false) mostrarBuscando();

} 


/* Funcion para obtener el valor seleccionado de un grupo de Radio Buttons
   ctrl (radiobutton)
*/
function getRadioButtonSelectedValue(ctrl)
{
    for(i=0;i<ctrl.length;i++)
        if(ctrl[i].checked) return ctrl[i].value;
}




/*Funciones que sirven para dar un valor al texto de un input si este se encuentra vacio y para mostrar un mensaje de lo que se tiene que introducir*/
function inputIn(id,textocomparacion){
    var elemento = document.getElementById(id);
    elemento.style.color = "";
    if (elemento.value == textocomparacion) elemento.value = "";

}
function inputOut(id,textocomparacion){
    var elemento = document.getElementById(id);
   
    if (elemento.value == "") {
        elemento.value = textocomparacion;
        elemento.style.color = "#666666";
    }
}


/* Funcion para obtener el valor seleccionado de un grupo de Radio Buttons
   ctrl (radiobutton)
*/
function getChecked(idCtrl)
{
    var ctrl = document.getElementById (idCtrl);
    if (!ctrl) {
        return false;
    }
    return ctrl.checked;
}
//******************************** Cargar contenido de una url en un div mediante Ajax ******************************//
function cargarUrlAjax(fragment_url, element_id, default_content) {
    var peticion = false;
    try {
        peticion = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            peticion = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                peticion = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                peticion = false;
            }
        }
    }
    if (!peticion) alert("ERROR AL INICIALIZAR!");

    var element = document.getElementById(element_id);
    element.innerHTML = default_content;
    peticion.open("GET", fragment_url);
    peticion.onreadystatechange = function() {
        if (peticion.readyState == 4) {
            element.innerHTML = peticion.responseText;
        }
    }
    peticion.send(null);
}

/* abre una caja con el contenido de la url que se especifique en una caja con posicion absoluta llamando a una funcion Ajax
--urlSrc es la url de la que queremos cargar el contenido
--defaultConten es el contenido por defecto mientras se carga el contenido del urlSrc(...loading)
--boxWidth es la anchura de la caja
--objReference es el objeto que hace la llamada (lo pasamos para tomarlo como punto de referencia al pintar la caja)
--idBox es la id que queremos especificar para la caja
*/
function abrirCajaAjax(urlSrc, defaultContent, objReference, idBox, boxWidth) {
    if (boxWidth == undefined) {
        boxWidth = 416;
    }
    window.setTimeout("cargarFragmentoAjax('" + urlSrc + "','" + idBox + "')", 5);
    var curleft = 0;
    var curtop = 0;
    if (objReference.offsetParent) {
        do {
            curleft += objReference.offsetLeft;
            curtop += objReference.offsetTop;
        } while (objReference = objReference.offsetParent);
    }
    if (curleft > boxWidth)
        curleft = curleft - boxWidth;
    else
        curleft = 220;
    document.getElementById(idBox).style.left = curleft;
    document.getElementById(idBox).style.top = curtop;
    document.getElementById(idBox).style.display = "";
    return true;
}

//******************************************************************************************************************//