/******************/
/* inici execució */
/******************/
if( navigator.userAgent.indexOf('MSIE')!=-1 ){
    window.attachEvent('onload', loadExternalUrl );
}		
if( navigator.userAgent.indexOf('Gecko')!=-1 ){
    window.addEventListener( 'load', loadExternalUrl, false );
}


/**************************************************************/
/**************************************************************/
/**************************************************************/


/* Modificar los enlaces externos (aquellos con el atributo rel="external") para que se abran
 en ventana nueva. */
function loadExternal(){
    loadExternalUrl();
}

function loadExternalUrl(){
	if( !document.getElementsByTagName ){
        return;
    }
	var links=document.getElementsByTagName( 'a' );
	for( var i=0; i<links.length; i++ ){
		if( links[i].rel=="external" ){
			links[i].target="_blank";
		}
	}
}


// Abir una ventana popup
function abrirPopup( url ,f_amp, f_alt, nom_finestra, scroll ){
	ancho=screen.width;				//ample pantalla
	alto=screen.height;				//alt pantalla
	v_top=(alto-f_alt)/2;	
	v_left=(ancho-f_amp)/2;
	if (typeof(v_fin)!="undefined"){
		v_fin.close();
	}
	v_fin=window.open(url,nom_finestra,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars="+(scroll?'yes':'no')+",resizable=no,width="+f_amp+",height="+f_alt+",top="+v_top+",left="+v_left);
}

// Contador de caracteres para formularios.
function dcoTextCounter(field, countfield, maxlimit){
	if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit);
	else countfield.value = maxlimit - field.value.length;
}

//canvi d'idioma
function wmsCambioIdioma(idiCambio){
    var newPath="";
    var path=window.location.pathname;
    var ini=window.location.protocol+"//"+window.location.host;
    var fin="";
    if (window.location.hash!=""){
        fin+=window.location.hash;
    }
    if (window.location.search!=""){
        fin+=window.location.search;
    }
    if (path.indexOf(".")!=-1) {
        var pArray=path.split(".");
        var darrer=pArray.length-1;
        if (pArray[darrer-1].length==2){
            pArray[darrer-1]=idiCambio;
        }else{
            pArray[darrer]=idiCambio+'.'+pArray[darrer];
        }
        newPath=pArray.join(".");
    }else{
        if (path.charAt(path.length-1)!="/"){
            barra="/";
        }else{
            barra="";
        }
        newPath=path+barra+"index."+idiCambio+".jsp";
    }
    window.location.href=ini+newPath+fin;
}


function sendForm(nomObjForm){
    objForm = document.getElementById(nomObjForm);
    if (objForm){
        objForm.submit();
    }
}


function submitFormResultados(index, paso, enlaceHotel){
    var objForm = document.getElementById("formResultados_" + index);
    var ocupacionHabitacion = new Array();


    //alert("divisa al selector : " + conversorMultidivisa.DIVISA_ACTUAL);
    if (conversorMultidivisa != null)
        objForm.divisaActual.value=conversorMultidivisa.DIVISA_ACTUAL;


    if (objForm){
        var objEle, objSel, objSelText, objReg, objRegText, objRegNom;
        objForm.pasoDestino.value = paso;    

        for (var i = 1; i <= 10; i ++) { //como máximo habrá 10 unidades
            //eval ("objEle = objForm.alojamientoNom_" + i);
            objEle = document.getElementById('alojamientoNom_' + index + '_' + i);
            if (objEle) {

                //1.- Rellenamos los nombres de unidades seleccionadas para usarlas en la ficha de hotel
                // Nombre de la habitación
                objSel = document.getElementById('alojamiento_' + index + '_' + i);
                objSelText = document.getElementById('alojamientoText_' + index + '_' + i);
                if (objSel.nodeName == "SELECT")
                    objEle.value = objSel.options[objSel.selectedIndex].text;
                else {
                    objEle.value = objSelText.value;
                }
                
                // Nombre del regimen
                objRegNom = document.getElementById('regimenNom_' + index + '_' + i);
                objReg = document.getElementById('regimen_' + index + '_' + i);
                objRegText = document.getElementById('regimenText_' + index + '_' + i);
                // Si "objReg" es SELECT, agafam .selectedIndex.value, sino el el .value
                if (objReg.nodeName == "SELECT") {
                    objRegNom.value = objReg.options[objReg.selectedIndex].text;
                } else {
                    objRegNom.value = objRegText.value;      
                }


                //2.- Comprobamos cupos: pueden haberse seleccionado más habitaciones iguales de las existentes
                var opcioId;
                if (objSel.nodeName == "SELECT")
                    opcioId = objSel.options[objSel.selectedIndex].value;
                else {
                    opcioId = objSel.value;
                }
                
                if ( !ocupacionHabitacion[opcioId] ) {
                    ocupacionHabitacion[opcioId] = 0;
                }
                ocupacionHabitacion[opcioId]++;
                if (ocupacionHabitacion[opcioId] > cupo_js[index][opcioId]) {
                
                    //uep, hemos rebasado el cupo
                    if(!enlaceHotel){ //miramos si se va desde el botón o desde los enlaces  
                        var txt = mensajeErrorCupos.replace ('%%CUPO%%', cupo_js[index][opcioId]);
                        txt = txt.replace ('%%NOMBRE%%', '"' + objEle.value + '"');
                        alert (txt);
                        return;
                    } else {
                        objForm.cupoRebasado.value = 1;
                    }
                    
                }

            } else {
                break; //no hay más unidades o no existe el campo alojamientoNom (no estamos en listado resultados)
            }
        }
        
        if (!enlaceHotel) {
            objForm.action = objForm.reservarAction.value;
        }
        objForm.submit();
    }
}

function submitFormDatosUsuario(paso, url){
    // Expresión regular para la validación de e-mails.
    var reg_exp = /^[a-z][\w\.-]*@[\w\.-]+\.[a-z]{2,4}$/i
    objForm = document.getElementById("formDatosUsuario");
    
    if (objForm){
        objForm.pasoDestino.value = paso;    
        if (paso == PASO_ANTERIOR) {
            //Al volver a los resultados, no debemos ejecutar el paso de datos de usuario,
            //pues estamos desaciendo la reserva
            if (url!=""){
               objForm.action = url; 
            }
            objForm.pasoOrigen.value = PASO_INICIO;
            objForm.submit();
        } else {
            //Validamos el formulario
            var ok = true;
            var okMsg = '';
            if (objForm.nom.value=="") {
                okMsg += nomMal + "\n"; 
                ok = false;
            }
            if (objForm.llinatges.value=="") {
                okMsg += llinatgesMal + "\n"; 
                ok = false;
            }
            if (objForm.email.value=="") {
                okMsg += emailMal + "\n"; 
                ok = false;
            } else if (!reg_exp.test( objForm.email.value )){
                okMsg += emailMal + "\n"; 
                ok = false;
            }
            if (objForm.email2.value=="") {
                okMsg += email2Mal + "\n"; 
                ok = false;
            } else if (!reg_exp.test( objForm.email2.value )){
                okMsg += email2Mal + "\n"; 
                ok = false;
            } else if (objForm.email.value!=objForm.email2.value) {
                okMsg += maildiferent + "\n"; 
                ok = false;
            }
            if (objForm.telefon.value=="") {
                okMsg += telefonMal + "\n"; 
                ok = false;
            }
			
            if (ok) {
                objForm.submit();
            } else {
                alert (okMsg);
            }

        }
        
    }
}



function submitFormConfirmacionDatosReserva(paso){
    if (paso == PASO_ANTERIOR) {
        objForm = document.getElementById("anteriorDatosReserva");
        if (objForm){
            objForm.submit();
        }
    } else {
        //Debe estar marcado (o no existir, para agencias ) el checkbox "acepto condiciones"
        objForm = document.getElementById("confirmacionDatosReserva");
        if (objForm.paycheck2 && objForm.paycheck2.checked) { // se ha elegido pago con factura proforma
            objForm.action="mostraFactura.svr";
        }
        if (!objForm.accept || objForm.accept.checked){
            objForm.submit();
        } else {
            alert(mensajeAcepta);
        }
    }
}

/* funció que ens serveix per controlar el valor per defecte als camps de tipus text*/
function initField(objField,valorInicial){
    if (objField && objField.value==valorInicial){
        objField.value='';
    }
}

function marcarSelect( objSelect, valor ){
    var marcado = false;
    
    if (objSelect.options){
        for (i = 0 ; i < objSelect.options.length ; i++){
            if (objSelect.options[i].value == valor){
                objSelect.options[i].selected = true;
                marcado = true;
            }else{
                objSelect.options[i].selected = false;
            }
        }
    }
    return marcado;
}

/* función que marca un select con el valor que se aproxime más al parámetro valor */
function marcarSelectMasProximo( objSelect, valor ){
    var indice=0, dif=9999999;
    
    if (objSelect.options){
        for (i = 0 ; i < objSelect.options.length ; i++){
            var selValue = parseInt(objSelect.options[i].value,10);
            if( Math.abs( selValue - valor ) < dif ){
                dif = Math.abs( selValue - valor );
                indice = i;
            }
            objSelect.options[i].selected = false;                    
        }
    }
    objSelect.options[indice].selected = true;    
    return objSelect.options[indice].value;
}

//	MM Genéricas ----------

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/** Heredado la "end" */
function mostraTexte(url){
    open(url,"","screenX=10,screenY=150,scrollbars=yes,width=626,height=530,alwaysRaised=yes");
}

// Intercambia el valor style.display de un objeto entre "block" y "none".
function switchDisplay( id ){    
    var obj = document.getElementById( id );    
    obj.style.display = obj.style.display == "block" ? "none" : "block";
}