// Villa Altea - main.js

$(document).ready(function() {
      
      
      $('#prblockSpc-top  ul > li:first').addClass('w-arrow');
      $('#prblockSpc-top  ul > li:first').addClass('w-back');
      
      $('#prblockSpc-top  ul > li:last-child').addClass('w-arrow');
      $('#prblockSpc-top  ul > li:last-child').addClass('w-forward');
      
});



// Product Page Sliders

var fp_counter = 0;
var timer = 0;
var total_property = 0;

$(document).ready(function() {
  var tmp_prop_array = $("img[rel=rel_btm_img]").get();
  total_property = tmp_prop_array.length;
  start_interval();
});

function start_interval(){  timer = setInterval( get_next, 3000);  }

function stop_interval(){  clearInterval( timer ); }

function get_previous() {
  fp_counter --;
  if(fp_counter == 0) {
    fp_counter = total_property;
  }
  set_current(fp_counter);
}

function get_next() {
  fp_counter ++;
  if( fp_counter == total_property + 1 ) {
    fp_counter = 1;
  }
  set_current( fp_counter );
}

function set_current( i ) {
  $('#ImgBoxDiv').html( $('#prime_image_'+i).html() );
}

// Product Page Sliders end here 

//code commun aux pages
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_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_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 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];}
}
function disabling() {
//alert (document.form1.villa_name.value)
if (document.getElementById("villa_name").value != "0"){
	//alert('ok')
	document.getElementById("pax").disabled = true;
	//alert('ok1')
	document.getElementById("typo").disabled = true;
	//alert('ok2')
	document.getElementById("zona").disabled = true;
	//alert('ok3')
}
else {
	document.getElementById("zona").disabled = false;
	document.getElementById("pax").disabled = false;
	document.getElementById("typo").disabled = false;
	//alert('ok2')
	}
}


//code de modification des dates
// ajax
//declare les variables 
var httpReq             = getXmlHttpObject();
var httpReqAnyos        = getXmlHttpObject();
var httpReqMeses        = getXmlHttpObject();
var httpReqDias         = getXmlHttpObject();
var httpReqNombreDia    = getXmlHttpObject();
var httpReqNoches       = getXmlHttpObject();

//declare l'objet XMLHttp
function getXmlHttpObject()
{
	var xmlhttp;

  	try
	{
  		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  	}
  	catch (e)
  	{
  		try
  		{
  			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		catch (e)
  		{
  			try
  			{
  				xmlhttp = new XMLHttpRequest();
  			}
	  		catch (e)
	  		{
	  			xmlhttp = false;
	  			alert('No se pudo instanciar el xmlHttpObject');
	  		}
		}
  	}
  	return xmlhttp;
}

// Node cleaner
			function go(c){
				if(!c.data.replace(/\s/g,''))
					c.parentNode.removeChild(c);
			}

			function clean(d){
				var bal=d.getElementsByTagName('*');

				for(i=0;i<bal.length;i++){
					a=bal[i].previousSibling;
					if(a && a.nodeType==3)
						go(a);
					b=bal[i].nextSibling;
					if(b && b.nodeType==3)
						go(b);
				}
				return d;
			} 


//modifs des Annees, agit sur les mois
function updateComboAnyos()
{

  	if (httpReqAnyos.readyState == 1) //requete en chargement
   	{	
		
		// effaces les options anterieures
		document.getElementById("mes").options.length = 0;

		//txt temporaire en attente reponse serveur
		document.getElementById("mes").options[0] = new Option("...","cargando");

		// bouton de lancement de la recherche desactive
		document.getElementById("buscar").disabled = true;
   	}

	if (httpReqAnyos.readyState == 4) //chargement des infos terminee
	{
   		
		var docXML= clean(httpReqAnyos.responseXML.documentElement);
		var mes_value = docXML.getElementsByTagName("mes_value");
		var mes_name = docXML.getElementsByTagName("mes_name");
		
		//debugg/////////////////////////////////////////////////////////
    	//on fait juste une boucle sur chaque element "donnee" trouvé
    	//for (i=0;i<mes_value.length;i++)
    	//{
    	//	alert(docXML.getElementsByTagName("mes_name")[i].firstChild.nodeValue);
    	//}
		///////////////////////////////////////////////////////////////
		
        if(docXML.getElementsByTagName("mes_value")[0].firstChild.nodeValue != "")
   		{
		
   			iterMeses = 0;

			// efface les opcions precedentes
			document.getElementById("mes").options.length = 0;


			for(i = 0; i < mes_value.length; i++)
			{
				//alert("añadiendo elemento a meses: id= " + mesArray[0] + " , nombreMes: " + mesArray[1]);
				document.getElementById("mes").options[i] = new Option(mes_name.item(i).firstChild.data,mes_value.item(i).firstChild.data);
			}

			// habilito el boton buscar
			document.getElementById("buscar").disabled = false;

			// Ahora hemos de sacar los datos para refrescar el form dias
			var anyoSeleccionado = document.getElementById('an').value;
			var mesSeleccionado  = document.getElementById('mes').value;
			var cadenaParametros = "nameselect=dia" + "&anyos=" + anyoSeleccionado + "&mes=" + mesSeleccionado;

			httpReqMeses.open("POST", url, true);
	        httpReqMeses.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
	        httpReqMeses.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	        httpReqMeses.onreadystatechange = updateComboMeses;
		    httpReqMeses.send(cadenaParametros);

		}
   	}
}

// modif du mois, agit sur les jours
function updateComboMeses()
{

  	if (httpReqMeses.readyState == 1)
   	{
		// Primero borro los options antiguos
		document.getElementById("dia").options.length = 0;
		//document.getElementById("estancia").options.length = 0;
		//document.getElementById("labelNombreDia").innerHTML = "...";

		// Ahora inserto uno temporal mientras se carga
		document.getElementById("dia").options[0] = new Option("...","cargando");
		//document.getElementById("estancia").options[0] = new Option("...","cargando");

		// Deshabilito el boton buscar
		document.getElementById("buscar").disabled = true;

   	}


   	if (httpReqMeses.readyState == 4)
   	{
	
        var docXML= clean(httpReqMeses.responseXML.documentElement);
		var dia_value = docXML.getElementsByTagName("dia_value");
		
   		if(docXML.getElementsByTagName("dia_value")[0].firstChild.nodeValue != "")
   		{
   			// Primero borro los options antiguos
			document.getElementById("dia").options.length = 0;
		

			// Ahora añado los nuevos options
			for(i = 0; i < dia_value.length; i++)
			{
				document.getElementById("dia").options[i] = new Option(dia_value.item(i).firstChild.data, dia_value.item(i).firstChild.data);
			}

			// habilito el boton buscar
			document.getElementById("buscar").disabled = false;

			// Ahora hemos de sacar los datos para refrescar el form noches
			var anyoSeleccionado=document.getElementById('an').value;
			var mesSeleccionado=document.getElementById('mes').value;
			var diaSeleccionado=document.getElementById('dia').value;
			
			var cadenaParametros = "nameselect=estancia" + "&fecha=" +  diaSeleccionado + "/" + mesSeleccionado +  "/" + anyoSeleccionado;

			httpReqDias.open("POST", url, true);
	        httpReqDias.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
	        httpReqDias.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	        httpReqDias.onreadystatechange = updateDias;
		    httpReqDias.send(cadenaParametros);

		}
	}
}

//calcula las noches de la estancia
function updateDias()
{
	//alert('coucou')

  	if (httpReqDias.readyState == 1)
   	{
		// Primero borro los options antiguos
		document.getElementById("estancia").options.length = 0;

		// Ahora inserto uno temporal mientras se carga
		document.getElementById("estancia").options[0] = new Option("...","cargando");

		// Deshabilito el boton buscar
		document.getElementById("buscar").disabled = true;

   	}


   	if (httpReqDias.readyState == 4)
   	{
		//alert('coucou')
		
        var docXML= clean(httpReqDias.responseXML.documentElement);
		var stay_value = docXML.getElementsByTagName("stay_value");
		
		//alert(docXML.getElementsByTagName("stay_value")[0].firstChild.nodeValue)
		
   		if(docXML.getElementsByTagName("stay_value")[0].firstChild.nodeValue != "")
   		{
   			// Primero borro los options antiguos
			document.getElementById("estancia").options.length = 0;

			// Ahora añado los nuevos options de las noches
			for(i = 0; i < stay_value.length; i++) 
			{
				document.getElementById("estancia").options[i] = new Option(stay_value.item(i).firstChild.data, stay_value.item(i).firstChild.data);
			}

			//habilito el boton buscar
			document.getElementById("buscar").disabled = false;

			 // Ahora hemos de sacar los datos para refrescar el nombre del dia
			//var anyoSeleccionado=document.getElementById('an').value;
			//var mesSeleccionado=document.getElementById('mes').value;
			//var diaSeleccionado=document.getElementById('dia').value;
			//var cadenaParametros = "nameselect=nombredia" + "&fecha=" + diaSeleccionado + "/" + mesSeleccionado + "/" + anyoSeleccionado;
			//alert(cadenaParametros)
			
		    //httpReqNombreDia.open("POST", url, true);
	        //httpReqNombreDia.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
	        //httpReqNombreDia.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	        //httpReqNombreDia.onreadystatechange = updatenombredia;
		    //httpReqNombreDia.send(cadenaParametros);

		}
	}
}

//code de rafraichissement des champs de recherche
//sur modif de la selection dans le formulaire
function refreshlist(nameSelect)
{
	url = "buscador.asp?lang=<%=lang%>";  //chemin vers le script d'access a la db
		
	//annee
	if(nameSelect == "an")
	{
		// Tengo que refrescar a comboMeses, comboDias, div nombre dia, comboNoches
		// los bloqueo primero para que no refresquen en cada carga de sus combos
		// no hace falta bloquear las noches pq no se refrescan automaticamente

		var anyoSeleccionado=document.getElementById('an').value;
		var cadenaParametros = "nameselect=mes" + "&anyos=" + anyoSeleccionado;
		//alert("cadena de parametros: " + cadenaParametros);
		
		httpReqAnyos.open("post", url, true);	//true pour reponse asynchrone
		httpReqAnyos.setRequestHeader("Method", "post " + url + " HTTP/1.1");
        httpReqAnyos.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        httpReqAnyos.onreadystatechange = updateComboAnyos;
	    httpReqAnyos.send(cadenaParametros);

	}
	
	//mois
	if(nameSelect == "mes")
	{
		// Ahora hemos de sacar los datos para refrescar el form dias
		var anyoSeleccionado = document.getElementById('an').value;
		var mesSeleccionado  = document.getElementById('mes').value;
		var cadenaParametros = "nameselect=dia" + "&anyos=" + anyoSeleccionado + "&mes=" + mesSeleccionado;
		//alert(cadenaParametros)
		
		httpReqMeses.open("POST", url, true);
        httpReqMeses.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
        httpReqMeses.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        httpReqMeses.onreadystatechange = updateComboMeses;
	    httpReqMeses.send(cadenaParametros);

	}
	
	
	//jours
	if(nameSelect == "dia")
	{
		// Ahora hemos de sacar los datos para refrescar el form estancia
		var anyoSeleccionado=document.getElementById('an').value;
		var mesSeleccionado=document.getElementById('mes').value;
		var diaSeleccionado=document.getElementById('dia').value;
		var cadenaParametros = "nameSelect=estancia" + "&fecha=" + diaSeleccionado + "/" + mesSeleccionado +  "/" + anyoSeleccionado;
		//alert(cadenaParametros)
		
		httpReqDias.open("POST", url, true);
        httpReqDias.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
        httpReqDias.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        httpReqDias.onreadystatechange = updateDias;
	    httpReqDias.send(cadenaParametros);

	}
	
}

//devuelve el nombre del dia seleccionado
function updatenombredia()
{
	var docXML= clean(httpReqNombreDia.responseXML.documentElement);
	var dia_nombre = docXML.getElementsByTagName("dia_name");
		
   	if (httpReqNombreDia.readyState == 1)
   	{
		// Primero borro la etiqueta antigua
		document.getElementById("dianame").value = "...";
		
   	}


   	if (httpReqNombreDia.readyState == 4)
   	{
		if(docXML.getElementsByTagName("dia_name")[0].firstChild.nodeValue != "")
   		{
        // Ahora meto el dia
		document.getElementById("dianame").value = docXML.getElementsByTagName("dia_name")[0].firstChild.nodeValue;
		}
   	}

}

function esconde() {
     var obj = document.getElementById('precarga')
     if(obj.style.display == 'block') obj.style.display = 'none'
     else obj.style.display = 'block'
}


//****GOOGLE***///

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-3520576-11']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
  
  //**** Avertissement de fin de session *****//
  /**
 * affiche une boîte de dialogue d'information sur l'expiration imminente de la session utilisateur :
 * si l'utilisateur clique sur OK, la page est rechargée pour réinitialiser le chronomètre de session
 
 * @param int minutes délai avant l'expiration de la session 
 */
function rappelSession(minutes)
{
   var msg='Votre session expirera dans '+minutes+' minute';
   if(minutes>1) msg+='s';
   msg+='.\nVoulez-vous recharger la page pour éviter la déconnexion automatique ?';
   
   if(confirm(msg)) location.reload();
}

/**
 * affiche une alerte sur l'expiration de la session et redirige vers une autre page
 
 * @param string url URL de redirection en cas de déconnexion
 */
function expirationSession(url)
{
   alert('Votre session a expiré !\nVous êtes déconnecté à présent.');
   location.href=url;
}

/**
 * affiche des avertissements sur le délai d'expiration de la session :
 * - un premier au bout de (expiration-rappel) minutes (par ex. : 20-3 = 17 minutes)
 * - un second au bout de (expiration) minutes (par ex. : 20 minutes)
 
 * @param int expiration délai en minutes d'expiration de la session
 * @param int rappel délai en minutes avant l'expiration de la session pour l'affichage du rappel
 * @param string redirection URL de redirection en cas de déconnexion
 */
function session(expiration, rappel, redirection)
{
   // affichage du rappel
   var chronoRappel=setTimeout('rappelSession('+rappel+')', (expiration-rappel)*60*1000);
   
   // une fois le rappel affiché, on avertit uniquement de l'expiration
   var chronoExpiration=setTimeout('expirationSession(\''+redirection+'\')', expiration*60*1000);
}
