function buscarAnuncio(id) {
	// si es un numero de 5 digitos busca por codigo
	if (id >= 1 && id <= 99999) {
		VesaURL("detall.php?immid="+id);
		return false;	
	} else { //si no busca por telefono... sigue el envio del formulario
		return true;	
	}	
}

//////////////////////////////////////////////////////

function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email;
   if(reg.test(address) == false) {
      //alert('Invalid Email Address');
      return false;
   }
   else return true;
}

function addSuscription(email, sql) {
	if (validateEmail(email)) {
		xmlhttp=GetXmlHttpObject();
		if (xmlhttp==null) {
			alert ("Browser does not support HTTP Request");
			return;
		}
		var url="suscriptions.php?email="+ email+"&SQL="+sql;
		xmlhttp.onreadystatechange=stateChangedAddSuscription;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
		return true;	
	} else {
		return false
	}	
}

function stateChangedAddSuscription()	{
	if (xmlhttp.readyState==4) {
		document.getElementById("resultSubscribe").innerHTML=xmlhttp.responseText;
	}
}

function GetXmlHttpObject()	{
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject) {
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}	

//////////////////////////////////////////////////////

function sprintf()
{
   if (!arguments || arguments.length < 1 || !RegExp)
   {
      return;
   }
   var str = arguments[0];
   var re = /([^%]*)%(.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
   var a = b = [], numSubstitutions = 0, numMatches = 0;
   while (a = re.exec(str))
   {
      var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
      var pPrecision = a[5], pType = a[6], rightPart = a[7];

      numMatches++;
      if (pType == '%')
      {
         subst = '%';
      }
      else
      {
         numSubstitutions++;
         if (numSubstitutions >= arguments.length)
         {
            alert('Error! Not enough function arguments (' + (arguments.length - 1)
               + ', excluding the string)\n'
               + 'for the number of substitution parameters in string ('
               + numSubstitutions + ' so far).');
         }
         var param = arguments[numSubstitutions];
         var pad = '';
                if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
           else if (pPad) pad = pPad;
         var justifyRight = true;
                if (pJustify && pJustify === "-") justifyRight = false;
         var minLength = -1;
                if (pMinLength) minLength = parseInt(pMinLength);
         var precision = -1;
                if (pPrecision && pType == 'f')
                   precision = parseInt(pPrecision.substring(1));
         var subst = param;
         switch (pType)
         {
         case 'b':
            subst = parseInt(param).toString(2);
            break;
         case 'c':
            subst = String.fromCharCode(parseInt(param));
            break;
         case 'd':
            subst = parseInt(param) ? parseInt(param) : 0;
            break;
         case 'u':
            subst = Math.abs(param);
            break;
         case 'f':
            subst = (precision > -1)
             ? Math.round(parseFloat(param) * Math.pow(10, precision))
              / Math.pow(10, precision)
             : parseFloat(param);
            break;
         case 'o':
            subst = parseInt(param).toString(8);
            break;
         case 's':
            subst = param;
            break;
         case 'x':
            subst = ('' + parseInt(param).toString(16)).toLowerCase();
            break;
         case 'X':
            subst = ('' + parseInt(param).toString(16)).toUpperCase();
            break;
         }
         var padLeft = minLength - subst.toString().length;
         if (padLeft > 0)
         {
            var arrTmp = new Array(padLeft+1);
            var padding = arrTmp.join(pad?pad:" ");
         }
         else
         {
            var padding = "";
         }
      }
      str = leftpart + padding + subst + rightPart;
   }
   return str;
}

function VesaURL(url) {
  document.location.href = url;
}
function enviaDades() {
	setTimeout("$('#buscadorCercle').show()",1000);
	document.search.submit();
}

function suscribes(){
/* TODO volver a activar cuando este cambiado
		//agrega cada uno de las consultas a la base de datos teniendo en cuenta cual esta y cual no para no repetir el AND
		var SQL = document.forms[1].provincia.value != "" ? "provincia="+document.forms[1].provincia.value : "";
		if (SQL != null &&  document.forms[1].operacion.value != "") { SQL += " AND "; } else SQL += ""; 
		SQL += document.forms[1].operacion.value != "" ? "operacion="+document.forms[1].operacion.value : "";
		if (SQL != null && document.forms[1].tipo.value != "" )	{ SQL += " AND "; } else SQL += "";
		SQL += document.forms[1].tipo.value != "" ? "tipusImmoble="+document.forms[1].tipo.value : "";
		//construct the SQL query
		if(validate("suscribe", "email") ){
			window.open("suscriptions.php?email="+document.forms["suscribe"].elements["email"].value+"&SQL="+SQL, "");
			//probably add some code to show that the suscription has been made. div=visible ?
		}
*/
	}

/*
 $(document).ready(function () {
	// TODO volver a activar cuando este cambiado
	//load the suscribe button $("#suscribirPersona").click( suscribes());
	

	//load the fields
	var consulta = document.location.search.substr(1);	
	var consulta = consulta.split('&');
	for(var i=0; i< consulta.length; i++){
		if(document.forms['suscribe'].elements[consulta[i].split('=')[0]])
			document.forms['suscribe'].elements[consulta[i].split('=')[0]].value=consulta[i].split('=')[1];
	}
});
	*/

function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {
      //alert('Invalid Email Address');
      return false;
   }
   else return true;
}

function fill_suscription(){
	var email=prompt("Si deseas más información sobre inmuebles similares, déjanos tu e-mail.","email");
	if(email != "" && email != null ){
		document.forms['suscribe'].elements['email'].value=email;
		suscribes();
		document.forms['suscribe'].submit();
	}
}

/////////////////////////////////////////

function VesaURL(url) {
  document.location = url;
}  
function trocar(novo) {
	var obj = document.getElementById("big_foto");
	obj.style.backgroundImage = "url(upload/"+novo+")";
}

function Formata(valor,tammax,decimal) {
	var retornar;
	tecla = 8;
	vr = valor;
	tam = vr.length;
	dec=decimal;
	if (tam < tammax && tecla != 8) tam = vr.length + 1 ;
	if (tecla == 8 ) tam = tam - 1 ;
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) 	{
		if ( tam <= dec ) retornar = vr ;
		if ( (tam > dec) && (tam <= 5) ) retornar = vr.substr( 0, tam - 2 ) + "." + vr.substr( tam - dec, tam );
		if ( (tam >= 6) && (tam <= 8) ) retornar = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - dec, tam );
		if ( (tam >= 9) && (tam <= 11) ) retornar = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - dec, tam );
		if ( (tam >= 12) && (tam <= 14) ) retornar = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam );
		if ( (tam >= 15) && (tam <= 17) ) retornar = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - 2, tam );
	}
	return retornar;
}

function atualizarValor(precio) {
	var precioFinal = parseInt(parseFloat(precio) * parseFloat(document.formSimulador.importe.value));
	document.getElementById("valor").innerHTML = "€ "+Formata(precioFinal.toString(), 20, 2);
	return precioFinal;
}

function atualizarCh(campo, inputName) {
	var $num = 0;
	if(document.formSimulador.importeCh.checked == true)
		$num = $num +1;
	if(document.formSimulador.cuotaCh.checked == true)
		$num = $num +1;
	if(document.formSimulador.plazoCh.checked == true)
		$num = $num +1;
	if($num >2) {
		//alert("Ja he seleccionat 2 camps");
		campo.checked = false;
		trocarValor(inputName);
		return;
	}
}

function trocarValor(campo) {
	if(document.getElementById(campo).disabled == true)
		document.getElementById(campo).disabled = false;
	else
		document.getElementById(campo).disabled = true;
}

////////////////////////////////