﻿/**
 *
 * Funciones genéricas usadas en todo el site.
 *
 **/

//***************************************** Creacion de eventos dinamicamente **************************************//

function crearEvento(elemento, evento, funcion) {
      if (elemento.addEventListener) {
            elemento.addEventListener(evento, funcion, false);
      } else {
            elemento.attachEvent("on" + evento, funcion);
      }
}

//*******************************************************************************************************************//



//****************************************** Cadenas de Texto *******************************************************//

//comprueba si es formato email
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 caracteres especiales
function contieneCaracteresEspeciales(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("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);
    var r1 = new RegExp("[^A-Za-záéíóúàèìòùÀÈÌÒÙäëïöüÄËÏÖÜAÉÍÓÚÑñ]");
    return (r1.test(str));
} 


// 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;
    } 
}
// 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;
}

/***************************************************************************************************************/








//*************************************************** 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();
            }
            if (d < 1 || d > 31) return false;
            if (m < 0 || m > 11) return false;
            if (y < 1800 || y > 9999) return false;
            if (isNaN(dateVal)) return false;
        } 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;
}


//*******************************************************************************************************************//





//******************************** 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;
        }  
        
//******************************************************************************************************************//
        




//******************************* Funciones para ocultar/mostrar elementos ******************************************//

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);
    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 toggleText(id, idtext, text1, text2){
    toggle(id);
    changeText(idtext, text1, text2);
}


function toggleinnerHTML(id, text){
    var obj = document.getElementById(id);
    obj.innerHTML = text;
    return true;
}

function showHide(id,show,valShow) {
    if (IsNullOrEmpty(valShow)) valShow = "";
    var obj = document.getElementById(id);
    if (show==true) {obj.style.display = valShow} else {obj.style.display = "none"};
}


cambiarClaseCss = function (id,clase){   
    if (document.getElementById(id) != null)
    {        
        document.getElementById(id).className = clase;
    }
}

//**********************************************************************************************************//



//************************************************ Lista Desplegable ****************************************//
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"), "");
	        }
        }   
    }
}
//***********************************************************************************************************//


//************************************************* Popup **************************************************//

function abrirPopUp(url,width,height,resizable){
    if (width == null) width=860;
    if (height == null) height=600;
    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 */
/* 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 (mostrarpreloader != false ) mostrarBuscando();
    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();
} 


/* 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;
}


/* Abre desglose disponibilidad TransHotel */
function abrirDesgloseTH(codMant,orden,f) {
	abrirPopUp("/rAlojamientos/include/desgloseTH/desgloseTH.aspx?CodMant="+codMant+"&orden="+orden+"&f="+f,"","625","580");
}



/****************************************************** HashTable ***********************************************************
  
    This is a Javascript implementation of the Java Hashtable object.
   
    Contructor(s):
     Hashtable()
              Creates a new, empty hashtable
   
    Method(s):
     void clear()
              Clears this hashtable so that it contains no keys.
     boolean containsKey(String key)
              Tests if the specified object is a key in this hashtable.
     boolean containsValue(Object value)
              Returns true if this Hashtable maps one or more keys to this value.
     Object get(String key)
              Returns the value to which the specified key is mapped in this hashtable.
     boolean isEmpty()
              Tests if this hashtable maps no keys to values.
     Array keys()
              Returns an array of the keys in this hashtable.
     void put(String key, Object value)
              Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
     Object remove(String key)
              Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
     int size()
              Returns the number of keys in this hashtable.
     String toString()
              Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space).
     Array values()
              Returns a array view of the values contained in this Hashtable.
           
*/
function Hashtable(){
    this.clear = hashtable_clear;
    this.containsKey = hashtable_containsKey;
    this.containsValue = hashtable_containsValue;
    this.get = hashtable_get;
    this.isEmpty = hashtable_isEmpty;
    this.keys = hashtable_keys;
    this.put = hashtable_put;
    this.remove = hashtable_remove;
    this.size = hashtable_size;
    this.toString = hashtable_toString;
    this.values = hashtable_values;
    this.hashtable = new Array();
}

/*=======Private methods for internal use only========*/

function hashtable_clear(){
    this.hashtable = new Array();
}

function hashtable_containsKey(key){
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }
    }
    return exists;
}

function hashtable_containsValue(value){
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }
    return contains;
}

function hashtable_get(key){
    return this.hashtable[key];
}

function hashtable_isEmpty(){
    return (parseInt(this.size()) == 0) ? true : false;
}

function hashtable_keys(){
    var keys = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            keys.push(i);
    }
    return keys;
}

function hashtable_put(key, value){
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
        this.hashtable[key] = value;
    }
}

function hashtable_remove(key){
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
}

function hashtable_size(){
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            size ++;
    }
    return size;
}

function hashtable_toString(){
    var result = "";
    for (var i in this.hashtable)
    {     
        if (this.hashtable[i] != null)
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";  
    }
    return result;
}

function hashtable_values(){
    var values = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            values.push(this.hashtable[i]);
    }
    return values;
}


/********************************************************************************************************/
