/*
.........................
:: Variables GLOBALES  ::
.........................
*/

var apartat = 0  // Controla a quin de les 5 opcions d'Hotel ha entrat per mostrar la seva frase corresponent
var categoria = new Array // Posicions de les imatges al MENU
	categoria[8] = 1; // LUJO
	categoria[2] = 2; // BALNEARIOS Y SALUD
	categoria[5] = 3; // ESTANCIAS CON ENCANTO
	categoria[1] = 4; // URBANOS
	categoria[3] = 5; // MONTAÑA Y ESQUÍ


/*
.........................
:: Menu Switcheroo ::
.........................
*/

function switchBorder(yo,numfrase,situacion){
	yo.style.border="2px solid #BD0006";
	/*
	objfrase = document.getElementById('lafrase');
	if (situacion == 0) { // Viene de los menús de la HOME
		objfrase.innerHTML = frasehoteleshome[numfrase];
		} else {
		objfrase.innerHTML = frasehotelesmenu[numfrase];
		}
	*/
	}
	
function switchBorderBack(yo,frase,situacion){
	yo.style.border="2px solid #C6C5C4";
	/*
	objfrase = document.getElementById('lafrase');
	if (situacion == 0) { // Viene de los menús de la HOME
		objfrase.innerHTML = frasehoteleshome[apartat];
		} else {
		objfrase.innerHTML = frasehotelesmenu[apartat];
		}
	*/
	}


/*
.......................................................
:: En quin HOTEL ha entrat. Pinta el marc i la frase ::
.......................................................
*/

function quinhotel(x) {
	// dISCRIMINO ELS hotels AMS LES CATEGORÍES 4 I 7 QUE NO ESTÀN ACTIVES A LA web
	if (x == 4 || x == 7 || x == null) {
		x = 0;
		} 
		
	if (x != 0) { // Si no viene de una sección, es decir, viene de la búsqueda
		apartat = categoria[x];  // Li dic a quin tipus d'Hotel he entrat
		// Escric la imatge sense els rollover per deixar-la sempre marcada
		reescriu = document.getElementById('opcio' + categoria[x]);
		reescriu.innerHTML = '<a href="hoteles.php?t=' + x + '"><img id="img' + categoria[x] + '" src="../img/hotel' + categoria[x] + '_peq.gif" width="40" height="40" class="marcs" /></a>';
		// Li poso el border a la imatge sel.leccionada
		quin = document.getElementById('img' + categoria[x]);
		quin.style.border="2px solid #BD0006";
		// Escric la frase
		objfrase = document.getElementById('lafrase');
		objfrase.innerHTML = frasehotelesmenu[categoria[x]];
	}
}

/*
........................
:: Iconografía fitxes ::
........................
*/

var objico; // Objecte ICONE
var objtexte; // Objecte TEXTE
var ruta = "../img/icons/"; // Nom de la ruta dels icones
var img;

function activaico(texte,seccio,imagen) {
	// texte = identificador de l'imatge i texte descriptiu a mostrar
	// seccio : infhotel= Informació de l'hotel  servihotel= Serveis de l'hotel
	
	// Activo el icono actual
	img = imagen;
	objico = document.getElementById(imagen);
	objico.src = ruta + imagen + ".on.gif";
	objtexte = document.getElementById(seccio);
	objtexte.innerHTML = texte;
}

function desactivaico() {
	objico.src = ruta + img + ".gif";
	objtexte.innerHTML = "&nbsp;";
}



/*
........................
:: Iconografía fitxes ::
........................
*/

var club = new Array()
club[1] = 'En aquellos de nuestros restaurantes adheridos al Club, el socio disfrutar&aacute; de comidas gratuitas siempre y cuando vaya, como m&iacute;nimo, acompa&ntilde;ado de otro comensal,. El importe de la invitaci&oacute;n se calcular&aacute; dividiendo el importe de la factura (excluyendo bebidas e impuestos) entre el total de comensales.';
club[2] = 'Los socios y sus invitados tienen derecho a tarifas especiales en los hoteles que se facilitan en relaci&oacute;n adjunta.';
club[3] = 'Como bienvenida al Club se entrega al socio un t&iacute;tulo v&aacute;lido para una estancia de 4 noches (en habitaci&oacute;n doble o individual) en los hoteles adheridos al Club, siendo su precio del 50% de la tarifa oficial del establecimiento. Para los poseedores de la Tarjet Club Husa Oro lujo es v&aacute;lido hasta 6 noches.';
club[4] = 'Como bienvenida se entrega al socio un bono por importe de 60.10 €, 90.15 € o 120.20 € (según categoría del hotel) y que podrá ser descontado del total de la factura del hotel (sobre tarifa oficial), siempre y cuando haya pernoctado en el mismo.';
club[5] = 'Este bono le dar&aacute; derecho a utilizar una habitaci&oacute;n de categor&iacute;a superior a la categoria est&aacute;ndar, con su tarifa de socio sin suplementos, para los poseedores de la tarjeta Club Husa Oro Lujo.';
club[6] = 'Dos bonos anuales que incluyen la estancia de ni&ntilde;os hasta 12 a&ntilde;os compartiendo habitaci&oacute;n con dos adultos o de un acompa&ntilde;ante en habitaci&oacute;n doble, siendo el pago de esta habitaci&oacute;n como si fuera individual.';
club[7] = 'El socio obtendr&aacute; un descuento del 10% en banquetes o reuniones, hasta un m&aacute;ximo de 450.76 € en los hoteles adheridos al Club.';

function privilegios(num) {
	opc = document.getElementById('opcprivilegios');
	opc.innerHTML = club[num] + '<br/><br/><a href="javascript:pop_club();" class="granateBold">Consultar cl&aacute;usulas de adhesi&oacute;n.</a>';
}


var eclub = new Array()
eclub[1] = 'At participating Club restaurants, members will enjoy a free meal, provided that they are accompanied by at least one other diner. The amount of the discount is calculated by dividing the total amount of the bill (excluding drinks and taxes) between the total number of diners.';
eclub[2] = 'Members and their guests have the right to special rates at the participating hotels detailed on the attached list.';
eclub[3] = 'As a welcome gift, new Club members are presented with a voucher for four nights in a single or double room at participating hotels, at 50% of the official hotel rate. For holders of the Husa Gold Club Luxury Card, the voucher is valid for six nights.';
eclub[4] = 'New club members are welcomed with a voucher for 60.10 €, 90.15 € o 120.20 €; (depending upon hotel category), which can be used against the their hotel bills, provided that they have stayed overnight at the hotel.';
eclub[5] = 'This voucher can be used by holders of the Husa Gold Club Luxury Card to upgrade from a standard room, at the normal member rate (without surcharges).';
eclub[6] = 'Two annual vouchers for children up to the age of twelve sharing a room with two adults or for a fellow guest in a double room charged at the single room rate.';
eclub[7] = 'Members are granted a 10% discount on banquets and meetings, up to a limit of 450.76 €, in participating hotels.';

function eprivilegios(num) {
	opc = document.getElementById('opcprivilegios');
	opc.innerHTML = eclub[num] + '<br/><br/><a href="javascript:pop_club();" class="granateBold">Club\'s terms and conditions.</a>';
}
/*
................
::  Rollover  ::
................
*/

function xOn(theId) {
	xfile=document.getElementById(theId)
	xname=xfile.getAttribute('src')
	x=xname.length
	xext=xname.substring(x-4,xname.length)
	xname=xname.substring(0,x-4)
	xfile.src=xname+".on"+xext
}

function xOff(theId) {
	xfile=document.getElementById(theId)
	xname=xfile.getAttribute('src')
	x=xname.length
	xext=xname.substring(x-4,xname.length)
	xname=xname.substring(0,x-7)
	xfile.src=xname+xext
}

function xClick(theId) {
	if (theId == "AE") theId = "tamericanexpress";
	if (theId == "MC") theId = "tmastercard";
	if (theId == "VI") theId = "tvisa";
	ResetCards();
	xdiv=document.getElementById(theId);
	xdiv.style.border = '1px solid #c00';
}

function ResetCards() {
	x=document.getElementById('tvisa');
	x.style.border = '1px solid #ffffff';
	x=document.getElementById('tmastercard');
	x.style.border = '1px solid #ffffff';
	x=document.getElementById('tamericanexpress');
	x.style.border = '1px solid #ffffff';
}

/*
................
::   POPUPS   ::
................
*/

function pop_club() {
	pop('club_popup.php','club','scrollbars=yes',500,450,1);
}

function pop_restaurante(x) {
	pop(x,'restaurante','scrollbars=yes',400,300,1);
}

function pop_room(x) {
	pop(x,'room','scrollbars=yes',450,400,1);
}

function pop_servgen(x) {
	pop(x,'servgen','scrollbars=yes',450,360,1);
}

function pop_ficha(x) {
	pop(x,'ficha','scrollbars=yes',460,370,1);
}

function pop_localizacion(x) {
	pop(x,'localizacion','scrollbars=yes',460,370,1);
}

function pop_convenciones(x) {
	pop(x,'convenciones','scrollbars=yes',560,400,1);
}

function pop_avis() {
	pop('http://www.avis.es/avisonline/es/ibe.nsf/reservationhomemicrosite?openview&MST=CFBC9F751DF260F5C1256B83005AF89C','AVIS','scrollbars=yes',670,450,1);
}

function pop_visahusa() {
	pop('visa.husa.htm','HUSA','scrollbars=yes',500,450,1);
}

function pop_promohusa() {
	pop('promo.husa.htm','HUSA2','scrollbars=no',500,520,1);
}

function pop_detalle(x) {
	pop(x,'detalle','scrollbars=yes',570,400,1);
}

function dramatispersonae(){
	if(document.getElementById){
		window.open('creditos/index.htm','creditum','width=200,height=100,top=0,left=0');
	}else{
		window.open('creditos/index.htm','creditum','width=200,height=200,top=0,left=0');
	}
}


function pop(url,name,features, myWidth, myHeight, isCenter) {
  if(window.screen)if(isCenter)if(isCenter=="1"){
    var myLeft = (screen.width-myWidth)/2;
    var myTop = (screen.height-myHeight)/2;
    features+=(features!='')?',':'';
    features+=',left='+myLeft+',top='+myTop;
  }
flop=window.open(url,name,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
flop.focus();
}


/*
.........................
:: Cookie Check & Resave ::
.........................
*/

function checkTheCookie(theLang) {
	x=readCookie('husaLang');
	if (x){
		saveCookie('husaLang', x, 666);
		location=x+"/";
	}else {
		x=idiomaNavegador();
		if(x!='escoge') {
			saveCookie('husaLang', x, 666);
			location=x+"/";
		}
	}
}

function idiomaNavegador() {
 if(document.all) {
	theLang=navigator.browserLanguage.substring(0,2).toLowerCase();
 }else{
	theLang=navigator.language.substring(0,2).toLowerCase();
 }
 if(theLang=='es') {
	return 'cas';
 }else if(theLang=='en') {
 	return 'eng';
 }else {
 	return 'escoge';
 }
}

/*
.........................
:: switch Lang ::
.........................
*/

function switchLang() {
	whereAmI=String(location);
	
	//Averiguamos la posición de los : para saber si se trata de una conexión http o https
	conexion = whereAmI.indexOf(':',0);
	if (conexion == 4) { //http
		a=whereAmI.substring(0,19);
		b=whereAmI.substring(19,22);
		c=whereAmI.substring(22,whereAmI.length);
	} else if (conexion == 5) { //https
		a=whereAmI.substring(0,20);
		b=whereAmI.substring(20,23);
		c=whereAmI.substring(23,whereAmI.length);
	}
	
	x=readCookie('husaLang');
	
	if (x=='cas'){
		saveCookie('husaLang', 'eng', 666);
		location='http://www.husa.es/eng/index.php';
	} else if (x=='eng'){
		saveCookie('husaLang', 'cas', 666);
		location='http://www.husa.es/cas/index.php';
	}else{
	}
}

/*
.........................
:: switch Lang ::
.........................


function switchLang() {

  var posBarraLang=14;
	whereAmI=String(location);
  posBarraLang = whereAmI.indexOf('/',posBarraLang)+1;

	a=whereAmI.substring(0,posBarraLang);
	b=whereAmI.substring(posBarraLang,posBarraLang+3);
	c=whereAmI.substring(posBarraLang+3,whereAmI.length);
	
	//alert(a+"\n"+b+"\n"+c);
	
	x=readCookie('husaLang');
	
	if (x=='cas'){
		saveCookie('husaLang', 'eng', 666);
		location=a+'eng'+c;
	}
	if (x=='eng'){
		saveCookie('husaLang', 'cas', 666);
		location=a+'cas'+c;
	}else{
		
	}
}
*/




/*
.........................
:: NADALA ::
.........................
*/

function nadala(u,n,f, w, h, c) {
  if(window.screen)if(c)if(c=="1"){
    var l = (screen.width-w)/2;
    var t = (screen.height-h)/2;
    f+=(f!='')?',':'';
    f+='left='+l+',top='+t;
  }
  flop=window.open(u,n,f+((f!='')?',':'')+'width='+w+',height='+h);
  flop.focus();
}
function nadala_eng(u,n,f, w, h, c) {
  if(window.screen)if(c)if(c=="1"){
    var l = (screen.width-w)/2;
    var t = (screen.height-h)/2;
    f+=(f!='')?',':'';
    f+='left='+l+',top='+t;
  }
  flop=window.open(u,n,f+((f!='')?',':'')+'width='+w+',height='+h);
  flop.focus();
}

/*
.........................
:: Cookie Recipes ::
.........................
*/

function saveCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000))
                var expires = "; expires="+date.toGMTString()
        }
        else expires = ""
        document.cookie = name+"="+value+expires+"; path=/"
}

function readCookie(name) {
        var nameEQ = name + "="
        var ca = document.cookie.split(';')
        for(var i=0;i<ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length)
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length)
        }
        return null
}

function deleteCookie(name) {
        saveCookie(name,"",-1)
}


/*
.....................
:: Form Focus&Blur ::
.....................
*/

function focusForm() {
	
}

function blurForm() {
	
}


/*
.....................
::  Layer mngment  ::
.....................
*/

function MM_findObj(n, d) { //v4.01
  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 && d.getElementById) x=d.getElementById(n); return x;
}


function tmt_findObj(n){
	var x,t; if((n.indexOf("?"))>0&&parent.frames.length){t=n.split("?");
	x=eval("parent.frames['"+t[1]+"'].document.getElementById('"+t[0]+"')");
	}else{x=document.getElementById(n)}return x;
}


function MM_setTextOfLayer(objName,x,newText) {//v3.0A Modified by Uncle Massimo and packaged by Uncle Al  for NN6 Compatibility
  var obj = (document.getElementById) ? tmt_findObj(objName) : MM_findObj(objName);
  if (obj!=null) with (obj)
    if (document.layers) {document.write(unescape(newText)); document.close();}
    else innerHTML = unescape(newText);
}

/*
........................................
::   Hotel search & Calendar mngment  ::
........................................
*/

function setDate(id, formName, formid, date) { // la sintaxis del valor es P.Ej.: 'd/m/a'.
	if(date) {
    date_array=date.split('/');
    MM_setTextOfLayer(id+'Div','','&nbsp;'+date_array[0]+'&nbsp;'+textomes[date_array[1]]+'&nbsp;');
    eval('document.'+formName+'.'+formid+'.value=date');
  }
}

function setDatePlus(id, formName, formid, date) { // escribe date en dos sitios: en formName.formid en literal, y en formName.id en bonito
	if(date) {
    date_array=date.split('/');
    eval('document.'+formName+'.'+formid+'.value=date');
    eval('document.'+formName+'.'+id+'Div.value=\' '+date_array[0]+' / '+date_array[1]+' / '+date_array[2]+'\'');
  }
}

function ocurta(id) {
	eval('document.getElementById(\''+id+'\').style.visibility=\'hidden\'');
}

function futuriza(dateid,id,check,form,formid) { //origen fecha, id del iframe a cambiar, id input valor real, form, id input valor bonito
	eval('var date=document.'+form+'.'+dateid+'.value');
	if (date.length>1)
	{
		var date_array=date.split('/');
		var url='calendario.php?id='+check+'&form='+form+'&formid='+formid+'&nuevo_mes='+date_array[1]+'&nuevo_ano='+date_array[2]+'&oculta='+id+'&v2=1';
		document.getElementById(id).src=url;
	}
}



function pop_calendar(id, formName, fieldId) {
	
	// searching default date
	var defDate = '';
	var checkinValue  = document.forms[formName].checkin.value;
  var checkoutValue = document.forms[formName].checkout.value;
	
	if (fieldId == 'checkin') {
	  defDate = checkinValue;
	  
	} else {
	  
	  if (checkoutValue != '' && daysElapsed_DDMMYY(checkinValue,checkoutValue)>0) {
	    defDate = checkoutValue;
	  } else {
	    defDate = checkinValue;
	  }
	} 
		
	var url = 'calendario.php?dd='+defDate+'&id='+id+'&form='+formName+'&formid='+fieldId;
	pop(url,'calendario','scrollbars=no',210,200,1);
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


function showCalendar(id, idpos) {					// id es el iframe, idpos es un div como referencia de posicion
	var iframeid = document.getElementById(id);
	var pos = document.getElementById(idpos);
	iframeid.style.left=(findPosX(pos)-8)+'px';
	iframeid.style.top=(findPosY(pos)-16)+'px';
	iframeid.style.visibility='visible';
}


function showHideProv(theform) { 
	
	theCountryCode = theform.pais.options[theform.pais.selectedIndex].value;
	
	if(theCountryCode =='' || theCountryCode == 'E') {
    theform.prov.disabled = false;
  } else {
    theform.prov.selectedIndex = 0;
    theform.prov.disabled = true;
  }
}


function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function daysElapsed(date1,date2) {
    var difference =
        Date.UTC(y2k(date1.getYear()),date1.getMonth(),date1.getDate(),0,0,0)
      - Date.UTC(y2k(date2.getYear()),date2.getMonth(),date2.getDate(),0,0,0);
    return difference/1000/60/60/24;
}

function daysElapsed_DDMMYY(date1,date2) {

    var dtCh= "/";
    
    var pos1=date1.indexOf(dtCh);
    var pos2=date1.indexOf(dtCh,pos1+1);
    var strDay1  =date1.substring(0,pos1);
    var strMonth1=date1.substring(pos1+1,pos2);
    var strYear1 =date1.substring(pos2+1);

    var pos1=date2.indexOf(dtCh);
    var pos2=date2.indexOf(dtCh,pos1+1);
    var strDay2  =date2.substring(0,pos1);
    var strMonth2=date2.substring(pos1+1,pos2);
    var strYear2 =date2.substring(pos2+1);

    return daysElapsed(new Date(strYear2,strMonth2-1,strDay2),new Date(strYear1,strMonth1-1,strDay1));
}


function validateSearch(theform, onlydates) { 
  
  var retval = true;
  
  date1 = theform.checkin.value;
  date2 = theform.checkout.value;
  
  if(date1!='' && date2!='') {
    
    var daysElapsed = daysElapsed_DDMMYY(date1,date2);
    if (daysElapsed<1) {
      alert(searchform[1]);
      retval = false;
    } else if (daysElapsed>15) {
      alert(searchform[3]);
      retval = false;
    } else if (!onlydates) {
      
      var other_fields = '';
      other_fields += theform.cat.options[theform.cat.selectedIndex].value;
      other_fields += theform.fprecio.options[theform.fprecio.selectedIndex].value;
      other_fields += theform.thotel.options[theform.thotel.selectedIndex].value;
      other_fields += theform.prov.options[theform.prov.selectedIndex].value;
      other_fields += theform.pais.options[theform.pais.selectedIndex].value; 

      if (!theform.wifi.checked && theform.desc.value == desc_default_value && other_fields == '') {
        alert(searchform[2]);
        retval = false;
      }
    
    }
  } else if (date1!='' || date2!='' || onlydates) {
    alert(searchform[0]);
    retval = false;
  }
  
  return retval;

}

function validateBooking(theform) { 
  
  var retval = false;

  for (i=0; i<theform.length;i++) {
    field_name=theform.elements[i].name;
    if ((field_name.indexOf('cantidad') != -1) && (theform.elements[i].selectedIndex>0)) retval = true;
  }

  if (retval != true) alert(bookform[0]);
  
  return retval;

}

//////////////////////////////////////////////////////////////////
// INICI Controlamos que no puedan introducir letras en los campos

var valoranterior;

function nonumerovaloranterior(x) {
	valoranterior = x;
}

function nonumero(x) {

    var tp = window.event.keyCode;
	var campo = eval("document.getElementById('" + x + "')");
	
	// Si el código ASCII pertenece a cualquier número
    if(tp == 49 || tp == 50 || tp == 51 || tp == 52 || tp == 53 || tp == 54 || tp == 55 || tp == 56 || tp == 57 || tp == 48 )
    {
	} else {
       alert("No puede introducir letras");
	   campo.focus();
	   campo.value = valoranterior;
     } 
}

function reescribe() {
	
}

// FI Controlamos que no puedan introducir letras en los campos
///////////////////////////////////////////////////////////////


