/*JAVASCRIPT */

$.fn._blank = function() {
    // Choan: http://blog.scriptia.net/articulos/2007/08/ventanas-popup-con-jquery-y-un-poco-de-respeto.html
	function clickHandler(e) {
		// si el usuario ha utilizado una tecla de control
		// no hacemos nada
		if (e.ctrlKey || e.shiftKey || e.metaKey)
			return;

		// abrimos la ventana
		var w = window.open(this.href, '_blank');
		if (w && !w.closed) {
			// si efectivamente hemos logrado abrirla
			// la ponemos en foco
			w.focus();
			// y cancelamos el comportamiento por defecto
			// del enlace
			e.preventDefault();
		}
	}

	this
		.filter('a[@href]') // que no se nos cuele algo que no sea un enlace
		.bind('click', clickHandler);

	return this; // permitimos concatenabilidad

}
/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "preloadCssImages"
 * by Scott Jehl, scott@filamentgroup.com
 * http://www.filamentgroup.com
 * reference article: http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
 * demo page: http://www.filamentgroup.com/examples/preloadImages/index_v2.php
 *
 * Copyright (c) 2008 Filament Group, Inc
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Version: 3.0, 06.21.2008
 * Changelog:
 * 	02.20.2008 initial Version 1.0
 *    06.04.2008 Version 2.0 : removed need for any passed arguments. Images load from any and all directories.
 *    06.21.2008 Version 3.0 : Added options for loading status. Fixed IE abs image path bug (thanks Sam Pohlenz).
 * --------------------------------------------------------------------
 */
jQuery.preloadCssImages = function(settings){
	var settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null
	}, settings);

	var allImgs = [];//new array for all the image urls
	var k = 0; //iterator for adding images
	var sheets = document.styleSheets;//array of stylesheets

	for(var i = 0; i<sheets.length; i++){//loop through each stylesheet
		var cssPile = '';//create large string of all css rules in sheet
		var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
		var baseURLarr = csshref.split('/');//split href at / to make array
		baseURLarr.pop();//remove file path from baseURL array
		var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
		if(baseURL!="") baseURL+='/'; //tack on a / if needed
		if(document.styleSheets[i].cssRules){//w3
			var thisSheetRules = document.styleSheets[i].cssRules; //w3
			for(var j = 0; j<thisSheetRules.length; j++){
				cssPile+= thisSheetRules[j].cssText;
			}
		}
		else {
			cssPile+= document.styleSheets[i].cssText;
		}

		//parse cssPile for image urls and load them into the DOM
		var imgUrls = cssPile.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename"
		var loaded = 0; //number of images loaded
		if(imgUrls != null && imgUrls.length>0 && imgUrls != ''){//loop array\
			var arr = jQuery.makeArray(imgUrls);//create array from regex obj
			jQuery(arr).each(function(){
				allImgs[k] = new Image(); //new img obj
				allImgs[k].src = (this.charAt(0) == '/' || this.match('http://')) ? this : baseURL + this;	//set src either absolute or rel to css dir

				$(allImgs[k]).load(function(){
						loaded++;
						//send updates to status elements if applicable
						if(settings.statusTextEl) {$(settings.statusTextEl).html('<span class="numLoaded">'+loaded+'</span> of <span class="numTotal">'+allImgs.length+'</span> loaded (<span class="percentLoaded">'+(loaded/allImgs.length*100).toFixed(0)+'%</span>) <span class="currentImg">Now Loading: <span>'+allImgs[loaded-1].src.split('/')[allImgs[loaded-1].src.split('/').length-1]+'</span></span>');
					}
					if(settings.statusBarEl) {
						var barWidth = $(settings.statusBarEl).width();
						$(settings.statusBarEl).css('background-position', -(barWidth-(barWidth*loaded/allImgs.length).toFixed(0))+'px 50%');
					}
				});
				k++;
			});
		}
	}//loop
	return allImgs;
}




jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}
/*
jQuery delayed observer
(c) 2007 - Maxime Haineault (max@centdessin.com)
http://www.studio-cdd.com:8080/haineault/blog/17/
*/

jQuery.fn.extend({
    delayedObserver:function(delay, callback){
        $this = $(this);
        if (typeof window.delayedObserverStack == 'undefined') {
            window.delayedObserverStack = [];
        }
        if (typeof window.delayedObserverCallback == 'undefined') {
            window.delayedObserverCallback = function(stackPos) {
                observed = window.delayedObserverStack[stackPos];
                if (observed.timer) clearTimeout(observed.timer);

                observed.timer = setTimeout(function(){
                    observed.timer = null;
                    observed.callback(observed.obj.val(), observed.obj);
                }, observed.delay * 1000);

                observed.oldVal = observed.obj.val();
            }
        }
        window.delayedObserverStack.push({
            obj: $this, timer: null, delay: delay,
            oldVal: $this.val(), callback: callback });

            stackPos = window.delayedObserverStack.length-1;

        $this.keyup(function() {
            observed = window.delayedObserverStack[stackPos];
                if (observed.obj.val() == observed.obj.oldVal) return;
                else window.delayedObserverCallback(stackPos);
        });
    }
});

  /*$(document).ready(function(){
    $("#accordion").accordion({ active: false });
  });*/
function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
/*
Author: Robert Hashemian
http://www.hashemian.com/

You can use this code in any manner so long as the author's
name, Web address and this disclaimer is kept intact.
********************************************************
Usage Sample:

document.write(FormatNumberBy3("1234512345.12345", ".", ","));
*/

// function to format a number with separators. returns formatted number.
// num - the number to be formatted
// decpoint - the decimal point character. if skipped, "." is used
// sep - the separator character. if skipped, "," is used
function FormatNumberBy3(num, decpoint, sep) {
  // Eliminamos trailing 0's
  num = num.replace(/^([0]*)/,"");
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ".";
  }
  if (arguments.length == 1) {
    sep = ".";
    decpoint = ",";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x + "€";
}

// end of function CurrencyFormatted()
$(document).ready(
 function()
 {
  // aplicamos el pijama a nivel de TD
  $("#relacion-trueques tbody tr:even").find("td").addClass("pijama");

  $("#filtrarInmuebleBusco").addClass("filtrarPopup");

  $("#pivot").click(function() {
     repl = window.location.href;
     urlbase = repl.replace(/#(.)*$/, ""); //drops any anchor
     getprmt = urlbase.replace(/^http[s]?:\/\/[^?]*\??/, "");
     urlbase = urlbase.replace(/\?(.)*$/, "");
     if (urlbase.match(/\/Pivota-\d\//)) {
       repl = urlbase.replace(/\/Pivota-1\//,"");
       repl = repl.replace(/Pivota-0/,"/Pivota-1/");
     } else {repl = urlbase + "Pivota-1/";}
     if (getprmt!='') repl = repl + '?' + getprmt;
     window.location.href = repl;
  });

  $("#relacion-trueques tbody tr td").click(function(e) {

    // comprobamos si es un Inmueble (tiene ID)
    if ($(this).attr('id').match(/_i_/)) { // Estamos en un Inmueble
      buscaHref = $(this).attr('id').replace(/_i_\w$/,""); // quitamos la letra de la columna del id
      // quitamos la parte del busco del id y buscamos en enlace Action Inmueble
      enlace = $("#ver_" + buscaHref).attr('href');
    } else { // Estamos en un busco
      // Usamos el busco:
      // llamamos a parent, y a su ID le quitamos la parte del inmueble, y buscamos el enlace en el Action Busco
      enlace = $("#ver_" + $(this).parent().attr('id').replace(/^\d+_inmueble_\d+__/,"")).attr('href');
    }
    if (enlace != undefined) {
      if(e.ctrlKey) {
       var w = window.open(enlace, '_blank');
	   if (w && !w.closed) {
			// si efectivamente hemos logrado abrirla
			// la ponemos en foco
			w.focus();
	   } else {
	       window.location = enlace; // Actuamos como Anchor (ej. bloqueador de popups)
	   }

      } else {
       window.location = enlace; // Actuamos como Anchor
      }
    }
  });

  $("a.rwal").click(function(e) {e.preventDefault();/*permitimos al anterior gestionarlo todo*/});


  $("#relacion-trueques tbody tr td").hover(
   function()
   {
    if ($(this).attr('id').match(/_i_/)) { // Estamos en un Inmueble
      // pintamos el inmueble y todos sus buscos
      prefijo=$(this).parent().attr('id').replace(/busco_\d+/,"");
      $("tr[id^='"+prefijo+"']").addClass("linea-activa"); // Pintamos todas las filas
    } else { // Estamos en un busco
      prefijo=$(this).parent().attr('id').replace(/_busco_\d+/,"");
      $("td[id^='"+prefijo+"i_']").addClass("lineactivatd"); // Pintamos el Inmueble (otro color?)

      // tenemos que quitarle el pijama al group, si lo tiene
      if ($("tr[id^='"+prefijo+"']").find("td[id^='"+prefijo+"i_']").hasClass("pijama")) {
          $("tr[id^='"+prefijo+"']").find("td[id^='"+prefijo+"i_']").removeClass("pijama").addClass("pijamaActivo");
      }
      prefijob=$(this).parent().attr('id').replace(/_inmueble_\d+_/,"");

      if ($(this).parent().find("td[id^='"+prefijob+"_b_']").hasClass("pijama")) {
        $(this).parent().find("td[id^='"+prefijob+"_b_']").removeClass("pijama").addClass("pijamaActivoBusco");
      }
      $(this).parent().find("td[id^='"+prefijob+"_b_']").addClass("lineactivatdbusco"); // sólo el trueque que toca
    }
   },
   function()
   {
     if ($(this).attr('id').match(/_i_/)) { // Estamos en un Inmueble
      // pintamos el inmueble y todos sus buscos
      prefijo=$(this).parent().attr('id').replace(/busco_\d+/,"");
      $("tr[id^='"+prefijo+"']").removeClass("linea-activa"); // Pintamos todas las filas
     } else { // Estamos en un busco

    /* permite resaltar sólo las filas de 1 trueque */
      prefijo=$(this).parent().attr('id').replace(/_busco_\d+/,"");
      $("td[id^='"+prefijo+"i_']").removeClass("lineactivatd");
      if ($("tr[id^='"+prefijo+"']").find("td[id^='"+prefijo+"i_']").hasClass("pijamaActivo")) { // si tr tiene pijama
        $("tr[id^='"+prefijo+"']").find("td[id^='"+prefijo+"i_']").removeClass("pijamaActivo").addClass("pijama");
      }
      prefijob=$(this).parent().attr('id').replace(/_inmueble_\d+_/,"");

      if ($(this).parent().find("td[id^='"+prefijob+"_b_']").hasClass("pijamaActivoBusco")) {
        $(this).parent().find("td[id^='"+prefijob+"_b_']").addClass("pijama").removeClass("pijamaActivoBusco");
      }
      $(this).parent().find("td[id^='"+prefijob+"_b_']").removeClass("lineactivatdbusco");
     }
   }
  );




  function precioDelayedObserverCallback(value, object)
        {
          if (object.attr('value').length!=0) {
            $("div[id='" + object.attr('id') + "_helper']").html(FormatNumberBy3(object.attr('value')));
          } else {
            $("div[id='" + object.attr('id') + "_helper']").html("-");
          }
         };

  $(".precio_field").focus(function () {
      $(this).delayedObserver(0.3, precioDelayedObserverCallback);
      }
  );
  /* Precio helper */
  $(".precio_field").keypress(
    function(e) {
      //if the letter is not digit then display error and don't type anything
      if( e.which!=9 && e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
      {
        return false;
      }
    }
  );
  $(".precio_field").change(
     function (e) {
        if ($(this).attr('value').length==0) {
           $("div[id='" + $(this).attr('id') + "_helper']").html("-");
        } else {
           $("div[id='" + $(this).attr('id') + "_helper']").html(FormatNumberBy3($(this).attr('value')));
        }
     }
  );
  $("#id_mun_i").change(
    function (e) {
        if ($(this).attr('value')!='') {
           idmun = parseInt($(this).attr('value'));
           if (idmun==881 || idmun==4354) { // Barcelona-Madrid
               if ($("#id_zona_i").attr('value')!= '-'+idmun) { //only update if needed
                  $("#id_zona_i").attr('value','-' + idmun);
               }
           } else {
               $("#id_zona_i").attr('value','');
           }
        }
    }
  );
  $("#id_zona_i_DISABLED").change(
    function (e) {
        if ($(this).attr('value')!='') {
           idzona = parseInt($(this).attr('value'));
           if (idzona==-881 || idzona <= 10 && idzona!=-4354) { // Barcelona
               if ($("#id_mun_i").attr('value'!='881')) $("#id_mun_i").attr('value',881);
           } else { // Madrid
               if ($("#id_mun_i").attr('value'!='4354')) $("#id_mun_i").attr('value',4354);
           }
        }
    }
  );
  /* Busco ... */
  $("#id_mun_b").change(
    function (e) {
        if ($(this).attr('value')!='') {
           idmun = parseInt($(this).attr('value'));
           if (idmun==881 || idmun==4354) { // Barcelona-Madrid
               if ($("#id_zona_b").attr('value')!= '-'+idmun) { //only update if needed
                  $("#id_zona_b").attr('value','-' + idmun);
               }
           } else {
               $("#id_zona_b").attr('value','');
           }
        }
    }
  );

    var popupStatus = ""; /* 1 semaphor - 1 popup at a time*/


    //centering popup
    function centerPopup(id){
        //get the position of the placeholder element
        var pos = $("#area_popup_" + id).offset();
        var eWidth = $("#area_popup_" + id).outerWidth();
        var mWidth = $("#"+id).outerWidth();
        var left = (pos.left) + "px"; // + eWidth - mWidth) + "px";

        if (pos.left>300 && document.documentElement.clientWidth <1000) left = (pos.left-100) + "px";
        if (pos.left == 0) {
            // Centramos en pantalla
            pos.left = (document.documentElement.clientWidth-(mWidth))/2;
            left = (pos.left) + "px";
            //alert(pos.left);
        }
        var top = 3+pos.top + "px";
        //show the menu directly over the placeholder
        $("#"+id).css( {
                position: 'absolute',
                "z-index": 2000,
                left: left,
                top: "5%"
        } );
            /*"height": windowHeight*/
        var windowHeight = document.documentElement.clientHeight;
        $("#bgFadeOut").css({
            "height": window.top.document.body.scrollHeight
        });
    }

    function centerPopupStd(id){
        //request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;

        var popupHeight = $("#"+id).height();
        var popupWidth = $("#"+id).width();
        //centering  , , */
        $("#"+id).css({
            "position": "absolute",
            "top": windowHeight/2-popupHeight/2,
            "left": windowWidth/2-popupWidth/2-60,
            "margin": "auto"
        });
        //only need force for IE6

        $("#bgFadeOut").css({
            /*"height": windowHeight*/
            "height": window.top.document.body.scrollHeight
        });
    }


    /* filtrar Inmueble / Busco ... */
    function loadPopup(id){
        //loads popup only if it is disabled
        if(popupStatus==""){
            $("#bgFadeOut").css({
            "opacity": "0.6"
            });
            $("#bgFadeOut").fadeIn("fast");
            $("#"+id).fadeIn("fast");
            popupStatus = id;
        }
    }

    //disabling popup with jQuery magic!
    function disablePopup(){
        //disables popup only if it is enabled
        if(popupStatus!=""){
            $("#bgFadeOut").fadeOut("slow");
            $("#"+popupStatus).fadeOut("slow");
            popupStatus = "";
        }
    }


    $(".fakeLink").click(function(){
        centerPopup($(this).attr('id').slice(6));
        loadPopup($(this).attr('id').slice(6));
    });

    $(".fakeLinkClose").click(function(){
        disablePopup();
    });

    //Click out event!
    $("#bgFadeOut").click(function(){
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus!=""){
            disablePopup();
        }
    });

    $(".TextoAyudame").hover(
       function()
       {
         $("#texto_ayuda_container").html($(this).attr('_textoayuda')); // title
         $("#texto_ayuda_container").css({ "display": "block" });
       },
       function()
       {
         $("#texto_ayuda_container").css({ "display": "none" });
         $("#texto_ayuda_container").html("");
       }
      );


    function loadPopupDataAsistente(htmlfile){
       var COOKIE_NAME = 'trocasistini_sess_nmm';
       //var options = { path: '/', expires: 365 };
       var options = { path: '/', expires: 0 };

       $("#asistente").load("/css/help/"+ htmlfile,{},function(){
                  centerPopup('asistente'); // centra según contenidos
                  $(".asistenteLink").click(function(){
                    loadPopupDataAsistente($(this).attr('id'));
                  });
                  // Asignamos eventos una vez cargados
                  $(".fakeLinkClose").click(function(){
                        disablePopup();
                  });
                  $("#nomostrar").click(function(){
                       if ($(this).attr("checked")) {
                           $.cookie(COOKIE_NAME, '0', options); // no mostrar
                       } else {
                       }
                     });
                  if ($.cookie(COOKIE_NAME)==0) {
                     $("#nomostrar").attr("checked", true);
                  }
              });
    }

    $("#troca_help").unbind('click',no_assist).removeClass("notroca_help");
    $("#troca_help").click(function(){
        $("#asistente").addClass("filtrarPopup");
        loadPopupDataAsistente("cambiar_trocar.html");
        loadPopup("asistente");

    });

      // Comprobamos si el asistente está solicitado
      /*{
         var COOKIE_NAME = 'trocasistini_sess_nmm';
         var COOKIE_NAME_SESS = 'trocasistini_sess';
         var options = { path: '/', expires: 0 };
         var options_sess = { path: '/', expires: 0 }; // expire when session is closed

         if ($.cookie(COOKIE_NAME)==null) {
            $.cookie(COOKIE_NAME, '3', options); // mostrar por defecto
         }
         if ($.cookie(COOKIE_NAME_SESS)==null) {
            $.cookie(COOKIE_NAME_SESS, '1', options_sess); // mostrar por defecto
         }
         direcc = window.location.href;
         if ($.cookie(COOKIE_NAME)>1 ) {

            $.cookie(COOKIE_NAME_SESS, 0, options_sess);
            $.cookie(COOKIE_NAME,$.cookie(COOKIE_NAME)-1,options);
            $("#asistente").addClass("filtrarPopup");
            loadPopupDataAsistente("cambiar_trocar.html");
            centerPopup("asistente");
            loadPopup("asistente");
         }

      }*/

    $.preloadImages("/css/help/asistini002.png","/css/help/asistini001.png","/css/trokimg/Cambiar.png", "/css/trokimg/Buscar.png");



    /* mini buscador ***************************************************************/
    var curFilter = 'o'; // default - will be overrided

    if ($("select#xfilter").val() != '') {
        curFilter = $("select#xfilter").val();
    }
    if ($("select#id_zona_i").val()!=undefined && $("select#id_zona_i").val()!='' && $("select#id_zona_b").val()=='') {
      curFilter = 'o'; // Es decir, siempre que se busque por inmueble, el 'ganador' para el mini buscador es Inmueble
      $("select#xfilter").val(curFilter);
    }
    if ($("select#id_zona_b").val()!=undefined && $("select#id_zona_b").val()!='' && $("select#id_zona_i").val()=='') {
      curFilter = 'b'; // Es decir, siempre que se busque por Busco, el 'ganador' para el mini buscador es Busco
      $("select#xfilter").val(curFilter);
    }
    if (curFilter == 'o') {
        $("select#xzonas").html($("select#id_zona_i").html());
        if ($("select#id_zona_i").val()!='') {
          if (!$.browser.msie) { // Bug MSIE6  y no es necesario en MSIE
           $("select#xzonas").val($("select#id_zona_i").val()); // Actualizamos valor (por si lo hemos cambiado)
          }
        }
    } else {
        $("select#xzonas").html($("select#id_zona_b").html());
        if ($("select#id_zona_b").val()!='') {
          if (!$.browser.msie) { // Bug MSIE6  y no es necesario en MSIE
           $("select#xzonas").val($("select#id_zona_b").val());
          }
        }
    }

    infijo = (curFilter=='o')?'i':'b';
    if ($("#id_kms_redonda_"+infijo).val()=='20') {
        $("input#xkmsr").attr('checked',true);
    } else {
        $("input#xkmsr").attr('checked',false);
    }
    if (!$.browser.msie && !$.browser.version=="6.0") { // en IE el scroll del mouse afecta siempre al select en focus, lo cual es perjudicial para la navegación
      $("select#xfilter").focus();
    }
    $("select#xfilter").change(function(){
      if (curFilter == $(this).val()) return; // useful for click event
      curFilter = $(this).val();
      $("input#xzona").val('');
      $("#xzonalbl").html("Zona:");
      if ($(this).val() == 'o') {
          $("select#xzonas").html($("select#id_zona_i").html());
          $("select#xzonas").val($("select#id_zona_i").val()); // Actualizamos valor (por si lo hemos cambiado)
      } else {
          $("select#xzonas").html($("select#id_zona_b").html());
          $("select#xzonas").val($("select#id_zona_b").val());
      }
      infijo = (curFilter=='o')?'i':'b';
      if ($("#id_kms_redonda_"+infijo).val()=='20') {
          $("input#xkmsr").attr('checked',true);
      } else {
          $("input#xkmsr").attr('checked',false);
      }
    });
    $("#xzonas").change(function(){
        if (curFilter == 'o') {
            $("select#id_zona_i").val($(this).val());
        } else {
            $("select#id_zona_b").val($(this).val());
        }
    });
    function quitaTildes(str) {
        return str.replace("Á","A").replace("À","A").replace("É","E").replace("È","E").replace("Í","I").replace("Ó","O").replace("Ò","O").replace("Ú","U");
    }
    $("#xzona").keypress(
        function(e) {
           if (e.which == 13) {
               $("#xzonas").focus();
               e.preventDefault();
               cambioXZona($(this));
               //return false;
           }
        });
    $("#xzona").change(function(){
        cambioXZona($(this));
    });
    function cambioXZona(obj){
        // Aplicar delay...
        var $dd; // http://rickyrosario.com/blog/sorting-dropdown-select-options-using-jquery
        var texto=quitaTildes(obj.val().toUpperCase());
        //alert(texto);
        if (curFilter == 'o') {
          $dd = $("select#id_zona_i");
        } else {
          $dd = $("select#id_zona_b");
        }
        var selectedVal = $dd.val();
        if (obj.val() == '' || obj.val() == '%' || obj.val() == '*') {
            $("#xzonalbl").html("<b>Selecciona Zona:</b>");
            $("select#xzonas").html($dd.html());
            $("select#xzonas").val(selectedVal);
            return;
        }

        var selectedText='';
        var $options = $('option', $dd);
        var arrVals = [];

        $options.each(function(){
            // push each option value and text into an array
            ct = quitaTildes($(this).text().toUpperCase());
            if (ct.indexOf(texto)>=0) {
              if ($(this).parent("optgroup").attr("label")!=undefined) {
               arrVals.push({
                   val: $(this).val(),
                   text: $(this).text(),
                   optgroup: $(this).parent("optgroup").attr("label")
               });
              } else {
               arrVals.push({
                   val: $(this).val(),
                   text: $(this).text()
               });
              }
              if (selectedVal == $(this).val()) {
                  selectedText = $(this).text(); // aprovechamos el viaje
              }
            }
        });
        if (arrVals.length == 0) {
            $("#xzonalbl").html("<b>Selecciona Zona:</b>");
            $("select#xzonas").html($dd.html());
            $("select#xzonas").val(selectedVal);
            return;
        }
        var options2 = '<option value="">--------</option>';
        var curGroup = '';
        for (var i = 0, l = arrVals.length; i < l; i++) {
          // Creamos nuevo options...
          if (arrVals[i].optgroup != curGroup && arrVals[i].optgroup != undefined) {
              if (curGroup != '') options2 += '</optgroup>';
              options2 += '<optgroup label="' +arrVals[i].optgroup + '">';
              curGroup =arrVals[i].optgroup;
          }
          if (curGroup != '' && arrVals[i].optgroup == undefined) {
              options2 += '</optgroup>';
          }
          options2 += '<option value="' + arrVals[i].val + '">' + arrVals[i].text + '</option>';
        }
        $("select#xzonas").html(options2);
        $("select#xzonas").val(selectedVal);
        $("#xzonalbl").html("<b>" + arrVals.length + " encontradas:</b>");
    }
    function actualizaXKmsR(obj) {
        infijo = (curFilter=='o')?'i':'b';
        if (obj.attr('checked') == false) {
            $("#id_kms_redonda_"+infijo).val('0');
        } else {
            $("#id_kms_redonda_"+infijo).val('20');
        }
    }
    $("input#xkmsr").keypress(
        function(e) {
           if (e.which == 13) {
               $("#xprecio").focus();
               e.preventDefault();
               actualizaXKmsR($(this));
           }
        });
    $("input#xkmsr").change(function(){
        actualizaXKmsR($(this));
    });
    function actualizaPrecio(valor) {
       var precio_aprox_techo = Math.round(valor * 1.30);
       var precio_aprox_suelo = Math.round(valor * 0.70);

       if (precio_aprox_techo != NaN  && precio_aprox_suelo>10000) {
         infijo = (curFilter=='o')?'i':'b';
         $("input#id_pr_"+infijo+"_desde").val(precio_aprox_suelo);
         $("input#id_pr_"+infijo+"_hasta").val(precio_aprox_techo);
       } else {
         if (valor != '') {
             // borramos valor, para que el usuario vuelva a escribirlo (TODO: Nota, )
             $("#xpreciohelper").html("* inválido");
             $("#xpreciohelper").addClass("error");
             $("input#xprecio").val('');
         }
         $("input#id_pr_"+infijo+"_desde").val('');
         $("input#id_pr_"+infijo+"_hasta").val('');
       }
    }
    $("input#xprecio").keypress(
        function(e) {
           if (e.which == 13) {
               $("#xm2").focus();
               e.preventDefault();
               actualizaPrecio($(this).val());
           }
        });
    $("input#xprecio").change(function(){
       actualizaPrecio($(this).val());
    });
    function actualizaSuperficie(valor) {
       var m2_aprox_techo = Math.round(valor * 1.15);
       var m2_aprox_suelo = Math.round(valor * 0.85);
       if (m2_aprox_techo != NaN && m2_aprox_techo>1) {
         infijo = (curFilter=='o')?'i':'b';
         $("input#id_m2_"+infijo+"_desde").val(m2_aprox_suelo);
         $("input#id_m2_"+infijo+"_hasta").val(m2_aprox_techo);
       } else {
         if (valor != '') {
             // borramos valor, para que el usuario vuelva a escribirlo (TODO: Nota, )
             $("#xm2helper").html("* inválido");
             $("#xm2helper").addClass("error");
             $("input#xm2").val('');
         }
         $("input#id_m2_"+infijo+"_desde").val('');
         $("input#id_m2_"+infijo+"_hasta").val('');
       }
    }
    $("input#xm2").keypress(
        function(e) {
           if (e.which == 13) {
               $("input#xbutt").focus();
               e.preventDefault();
               actualizaSuperficie($(this).val());
           }
        });
    $("input#xm2").change(function(){
        actualizaSuperficie($(this).val());
    });
    $("input#xbutt").click(function(e){
      if(e.ctrlKey) {
      } else {
        // Tenemos que quitar del filtro el que no esté en uso...
        infijo = (curFilter=='o')?'b':'i'; // al revés
        $("input#id_m2_"+infijo+"_desde").val('');
        $("input#id_m2_"+infijo+"_hasta").val('');
        $("input#id_pr_"+infijo+"_desde").val('');
        $("input#id_pr_"+infijo+"_hasta").val('');
        $("select#id_zona_"+infijo).val('');
      }
      actualizaPrecio($("input#xprecio").val());
      actualizaSuperficie($("input#xm2").val());
      $("#filtroBuscadorTrocapiso").submit();
    });

});


