var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
// Hide those layers that should be made visible through Javascript (this way, they will be visible if javascript is disabled)
document.write("<style type='text/css'>.closed, .njs { display: none }</style>");
var T0 = (new Date()).getTime();

// Global function declarations
var GeneralFuncs = {
  langCurrChanged: function(ev) {
    location.href = location.href.split("?")[0] + ("?{name}={value}".substitute(ev.target));
  },
  destroy: function(i) {
    i.destroy();
  },
  externalize: function(elem) {
    elem.set("target", "_blank");
  },

  fixImageHeight: function(img) {
    // Asegura que se respeta la altura mínima de las imágenes en las vistas "foto"
    var parent = img.getParent();
    var minh = parent.getSize().y - 2; /* Substract border size */
    if (img.height < minh) img.height = minh;
  },
  
  initGALinks: function(elem) {
    elem.addEvent("click", GeneralFuncs.gaLinkClick);
  },
  
  initAjaxLinks: function(elem) {
    var _width=500;
    var _height;
    var re = /fbw:(\d*)/;
    var rel = elem.get("rel");

    if (elem.hasClass("sub1")) { _width=620; _height=280; }
    if (rel && rel.test(re)) _width = parseInt(rel.match(re)[1], 0);
    
    elem._clickOpts = { width: _width, height: (_height)?_height:150, autoHeight: (_height==undefined)};
    elem.addEvent("click", GeneralFuncs.ajaxLinkClick);
  },
  
  ajaxLinkClick: function(event) {
    event.stop();
    FxBox.open(event.target.href, event.target._clickOpts);
  },
  
  gaLinkClick: function(event) {
    var url = event.target.href;
    if (url !== null) {
      TrackingActions.link(url);
      return false;
    }
    return true;
  },
  
  popupLinkClick: function(event) { 
    event.stop();
    FxBox.showContent( $(event.target.rel).get("html"), event.target._opts);
  },
  domready: function() {

    var langcur = $("langcur");
    if (langcur) { // Home Page

      langcur.getElements("select").addEvent("change", GeneralFuncs.langCurrChanged);

    } else { // Other pages

      if ($("buscaDestino")) {
        // Destinations autocomplete
        new Wick("destSearchText", {
          ajaxUrl: "/Generator/FreeTexts/FreeText_[l]_" + window.siteLang + "_[lang].json",
          iconField: "destSearchIcon",
          hiddenField: "IdSearcher",
          gaEventCategory: "Buscador",
          gaEventAction: "Free-Text Destinos"
        });
        $("buscaDestino").addEvent("submit", function(ev) {
          ev.stop();
          var wk = $("destSearchText").wick;
          if (!wk.valid) return false;
          var list = wk.collection.filter(function(i) { return i.I == $("IdSearcher").value;});
          if (list.length > 0) {
            var reg = list.pop();
            location.href = serverPath + "/{url}/".replace(/{url}/, reg.U);
          };
          return true;
        });
      }

      // Collapsable descriptions
      Abstract.init();
      // Comments
      $$(".commentThings").each(function(i) {
        i._opts = {width: 400, autoHeight: true};
        i.addEvent("click", function(e) { 
          FxBox.showContent( $("commentTemplate").get("html"), e.target._opts); 
          $("fbContent").getElement("input[name=idComments]").value = e.target.rel;
        });
      });
      // Youtube
      $$(".ytvideo").each(function(i) {
        i._opts = {width: 475, height: 406};
        i.addEvent("click", GeneralFuncs.popupLinkClick);
      });

      // Auto show-hide
      $$(".sh_hd").addEvent("click", function(ev) {
              ev.stop();
              this.className.split(" ").each(function(i) {
                      if (i.test(/^sh:/)) $(i.match(/sh:(.*)/)[1]).removeClass("nodis");
                      if (i.test(/^hd:/)) $(i.match(/hd:(.*)/)[1]).addClass("nodis");
              });
      });
      $$(".first_line").addEvent("click", function(ev) {ev.target.removeClass("first_line").set("title", "").removeEvents("click");});

    }

    // All pages

    // Links to open in FxBox
    $$("a.ajxload").each(GeneralFuncs.initAjaxLinks);
  
    // Show hidden div in FxBox
    $$(".showfxb").each(function(i) {
      i._opts = {width: 400, autoHeight: true};
      i.addEvent("click", GeneralFuncs.popupLinkClick);
    });


    if ($("paypal-logo")) {
            $("paypal-logo").addEvent("click", function() {
                    var lang = document.html.getAttribute("lang").substring(0, 2);
                    window.open('https://www.paypal.com/' + lang + '/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside',
                            'olcwhatispaypal',
                            'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=350');
            });
    }

    $$(".ga_linked").each(GeneralFuncs.initGALinks);

    // Footer newsletter form initialization
    NewsletterForm.init();

    // -------------------------------------------------------------------------
    // Priority: Low
    $$("a[rel=external]").each(GeneralFuncs.externalize);
  },
  load: function() {
    
    var langcur = $("langcur");
    if (langcur) { // Home Page
    } else { // Other pages
      $$("img.bImg, img.sImg").each(function(i) {
        i.addEvent("error", imageError);
        if (!i.complete || i.naturalWidth==0) brokenImage(i);
      });
      if ($("photos")) {
        $$(".bImg").each(GeneralFuncs.fixImageHeight);
      }
    
      PhotoPopup.init();
    }

    if ($("errorMessage")) {
      setTimeout(function() {FxBox.showContent("<span class='error_msg'>" + $("errorMessage").get("html") + "</span>")}, 100);
    }
    if ($("flashtext")) {
      setTimeout(function() {FxBox.showContent("<span class='flash_text'>" + $("flashtext").get("html") + "</span>")}, 100);
    }
  
    window.picshow = new PicShow("picshow");
  
    // Booking access form tips
    FormTips.init("my_booking");
    
    $$(".njs").each(GeneralFuncs.destroy);
  
  }
};

window.addEvent("domready", GeneralFuncs.domready);

window.addEvent("load", GeneralFuncs.load);

var NewsletterForm = {
  init: function() {
    NewsletterForm.form = $("sidebar_newsletter");
    if (NewsletterForm.form) {
      NewsletterForm.email = $("nl_email");
      NewsletterForm.accept = $("nl_accept");
      NewsletterForm.button = $("nl_button");
      
      if (NewsletterForm.email.value.trim() === '') {
        $("nl_lbl_email").addEvent("click", NewsletterForm.destroyLabel);
        NewsletterForm.email.addEvent("click", NewsletterForm.destroyLabel);
      } else {
        $("nl_lbl_email").destroy();
      }

      NewsletterForm.email.addEvent("keyup", NewsletterForm.validate);
      NewsletterForm.accept.addEvent("click", NewsletterForm.validate);
      NewsletterForm.form.addEvent("submit", NewsletterForm.submit);
      NewsletterForm.validate();
    }
  },
  destroyLabel: function(event) {
    NewsletterForm.email.removeEvent("click", NewsletterForm.destroyLabel);
    $("nl_lbl_email").destroy();
  },
  validate: function() {
    var error = false;
    if (!NewsletterForm.email.value.trim().test(/.+@.+\.[^\.]{2,3}$/)) {
      error = true;
    }
    if (!NewsletterForm.accept.checked) {
      error = true;
    }
    
    if (error) {
      NewsletterForm.button.set({ "disabled": "disabled", "src": ssp("{ssp}img/minisendd.gif") });
    } else {
      NewsletterForm.button.set({"disabled": "", "src": ssp("{ssp}img/minisend.gif") });
    }
  },
  submit: function(event) {
    var jsonRequest = new Request.JSON({
      url: "/info/newsletter.aspx",
      onSuccess: function(data) {
        NewsletterForm.form.reset();
        NewsletterForm.validate();
        FxBox.showContent("<span class='info_msg'>" + unescape(data.message) + "</span>")
      },
      onFailure: function(xhr) {
        // Performs the form submit
        NewsletterForm.form.submit();
      }
    }).post(NewsletterForm.form);

    return false;
  }
};

var PhotoPopup = {
  enabled: true,
  init: function() {
    var smallImages = $$('.sImg');
    if (smallImages === null || smallImages.length === 0) return

    this.layer = $('photoPopup');
    if (this.layer === null) {
      this.layer = new Element('div', { 'id':'photoPopup'});
      this.image = new Element('img');
      this.text  = new Element('div');
      
      this.layer.adopt(this.image);
      this.layer.adopt(this.text);
      $(document.body).adopt(this.layer);
    }
    smallImages.each(function(img) {
      img.addEvent('mouseover', PhotoPopup.onMouseOver);
      img.addEvent('mouseout', PhotoPopup.onMouseOut);
    });
  },
  clear: function() {
    $$('.sImg').each(function(img) {
      img.removeEvent('mouseover', PhotoPopup.onMouseOver);
      img.removeEvent('mouseout', PhotoPopup.onMouseOut);
    });
  },
  onMouseOver: function(event) {
    if (!PhotoPopup.enabled) return false;

    try {
      var url = $(event.target).src.replace('small/', '');

      // El popup no se debe mostrar cuando no hay foto, ni cuando el hotel es confidencial
      if (!url.contains("nofoto_sm.jpg") && !url.contains("selloconf.jpg")) {
        var pos = $(event.target).getPosition();
        var txt = $(event.target).alt;
        PhotoPopup.image.src = url;
        PhotoPopup.text.innerHTML = txt;
        PhotoPopup.layer.setStyles({
          left: pos.x + 75 + (Browser.Engine.trident ? 0 : 1),  /* Offsets are different for IE */
          top:  pos.y + (Browser.Engine.trident ? 0 : 1),
          opacity:0,
          display:'block'
        });
        PhotoPopup.layer.tween('opacity', 1);
      }
    } catch (err) {
      log(err);
    }
    return false;
  },
  onMouseOut: function(event) {
    PhotoPopup.layer.setStyle('display', 'none');
  }
};

var MapPopup = {
  init: function() {
    this.layer = $('mapPopup');
    if (this.layer !== null) {
      var gd = $("geodata");
      if (gd == null) return;
      var json = gd.get("html");
      window.geodata = JSON.decode(json);

      ResultsMap.setHotels();

      this.icon  = $$('#mapPopup .closeIcon')[0];
      this.icon.addEvent('click', MapPopup.hide);

      $$('.hotel_map').each(function(img) {
        img.addEvent('click', MapPopup.show);
      });
    }
  },

  clear: function() {
    $$('.hotel_map img').each(function(img) {
      img.removeEvent('click', MapPopup.show);
    });
  },

  show: function(event) {
    try {
      var anchor = $(event.target);
      var pos = anchor.getPosition();

      
      var code = anchor.rel.substring(3);
      var hotel = window.geodata[code];

      if (hotel != null) {
        MapPopup.layer.setStyles({
          left: pos.x + 75 + (Browser.Engine.trident ? 0 : 1),  /* Offsets are different for IE */
          top:  pos.y + (Browser.Engine.trident ? 0 : 1),
          opacity:0,
          visibility:'visible'
        });

        ResultsMap.centerAt(hotel);
        MapPopup.layer.tween('opacity', 1);
        PhotoPopup.enabled = false;
      }
    } catch (err) {
      log(err);
    }
    
    // This disables the link
    return false;
  },

  hide: function(event) {
    PhotoPopup.enabled = true;
    MapPopup.layer.setStyle('visibility', 'hidden');
  }
};

var RateSwitcher = {
  show: function(tableId) {
    log("Showing other rates");
    $$("#" + tableId + " .rate-group").each(function(group){
            group.set("style", "");
    });
    $$("#" + tableId + " .first-rate-group .button .show").each(function(item) { item.getParent().set("style", "display:none"); });
    $$("#" + tableId + " .first-rate-group .button .hide").each(function(item) { item.getParent().set("style", ""); });
    return void(0);
  },
  hide: function(tableId) {
    log("Hiding other rates");
    $$("#" + tableId + " .rate-group").each(function(group){
            group.set("style", "display:none");
    });
    $$("#" + tableId + " .first-rate-group .button .show").each(function(item) { item.getParent().set("style", ""); });
    $$("#" + tableId + " .first-rate-group .button .hide").each(function(item) { item.getParent().set("style", "display:none"); });
    return void(0);
  }
};

function JSlid(_mod) {
	this.mod = (typeof _mod == "string")? $(_mod):_mod;
	this.wrap = new Element("div", {style: "overflow: hidden; position:relative;"})
		.setStyle("height", this.mod.getHeight());
	this.wrap.wraps(this.mod);
	this.close = function() { this.wrap.tween("height", 0); }
	this.open = function() { this.wrap.tween("height", this.mod.getHeight()); }
	this.toggle = function() { (this.isOpen())? this.close():this.open(); }
	this.hide = function() { this.wrap.setStyle("height", 0); }
	this.show = function() { this.wrap.setStyle("height", this.mod.getHeight()); }
	this.isOpen = function() { return (this.wrap.getHeight()!=0);}
}

var FormTips = {
	init: function(element) {
          if (!$(element)) return;
          element = $(element);
          element.getElements("input[type=text]").each(FormTips.addTip);
	},
	addTip: function(input) {
          var tip = input.getParent().getElement("span");
          if (!tip) return;
          input.formtip = tip;
          input.formtip.input = input;
          // Hide tip if field has text
          if (input.value.trim() !== "") input.formtip.setStyle("display","none");
          input.addEvents({ "focus": FormTips.focus, "blur": FormTips.blur });
          input.formtip.addEvent("click", function(ev) {
            ev.target.setStyle("display", "none"); ev.target.input.focus();
          });
	},
	focus: function(ev) {
		ev.target.formtip.setStyle("display", "none");
	},
	blur: function(ev) {
		if (ev.target.value < " ") ev.target.formtip.setStyle("display", "block");
	}
}

var Abstract = {
	init: function() {
		$$(".abstract").each(Abstract.set);
	},
	set: function(obj) {
          var height = (obj.get("class").test(Abstract.cnf.re))? Abstract.getLinesHeight(obj) : Abstract.cnf.height;
          obj.collapsedHeight = height;
          obj.expandedHeight = obj.scrollHeight;
          obj.collapsed = true;
          obj.setStyle("height", height);
          obj.expander  = obj.getNext().getElement("a.expand");
          obj.collapser = obj.getNext().getElement("a.collapse");
          
          if (obj.expander === null) {
            obj.expander = obj.getNext().getElement("a");
            obj.collapser = null;
          }

          if (obj.expander)  obj.expander.addEvent("click",  function(ev) { ev.stop(); Abstract.open(obj); });
          if (obj.collapser) obj.collapser.addEvent("click", function(ev) { ev.stop(); Abstract.open(obj); });
	},

	open: function(obj) {
            if (obj.collapsed) {
                obj.tween("height", obj.expandedHeight);
                obj.collapsed = false;
                if (obj.expander) obj.expander.setStyle("display", "none");
                if (obj.collapser) obj.collapser.setStyle("display", "inline");
            } else {
                obj.tween("height", obj.collapsedHeight);
                obj.collapsed = true;
                if (obj.expander) obj.expander.setStyle("display", "inline");
                if (obj.collapser) obj.collapser.setStyle("display", "none");
            }
	},
	getLinesHeight: function(obj) {
		var lines = parseInt(obj.get("class").match(Abstract.cnf.re)[1], 0);
		// var lineHeight = parseInt(obj.getStyle("line-height"), 0);
		var lineHeight = Abstract.cnf.lineHeight;
		return (lines * lineHeight) + "px";
	},
	cnf: {
		lineHeight: 15,
		height: "151px",
		re: /abs_lines:([\d]*)/
	}
}

var FxBox = (function() {
	var win=window,ie6=Browser.Engine.trident4,options,
	overlay,container,wrapper,content,closer,request,width,height,
	round_l,round_r,subcont,fxOverlay;

	win.addEvent("domready", function() {
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "fbOverlay", events: {click: close}}),
				container = new Element("div", {id: "fbContainer"})
			).setStyle("display", "none")
		);
		wrapper = new Element("div", {id: "fbWrapper"}).injectInside(container).adopt(
			content = new Element("div", {id: "fbContent"})
		);
		round_l = new Element("div", {id: "fbRound_l"}).injectInside(container).adopt(
			new Element("div", {id: "fbRound_ul", 'class': "corner"}),
			new Element("div", {'class': "fbRoundFill"}),
			new Element("div", {id: "fbRound_dl", 'class': "corner"})
		);
		round_r = new Element("div", {id: "fbRound_r"}).injectInside(container).adopt(
			new Element("div", {id: "fbRound_dr", 'class': "corner"}),
			new Element("div", {'class': "fbRoundFill"})
		);
		closer = new Element("a", {id: "fbCloser", href: "#", events: {click: close}}).injectInside(container);
	});

	function wait() {
		content.empty().addClass("fbLoading").setStyles({width: options.initialWidth, height: options.initialHeight});
		if (IE6) {
			$$(".fbRoundFill").setStyle("height", options.initialHeight-8);
			$$("#fbRound_l,#fbRound_r").setStyle("height", options.initialHeight);
			$$("#fbRound_dl,#fbRound_dr").setStyle("top", options.initialHeight-4);
		}
		if (parseInt(container.getStyle("width"), 0) != options.initialWidth+options.widthGap) container.morph({
			"width": options.initialWidth+options.widthGap,
			"height": options.initialHeight+options.heightGap,
			"marginLeft": (-(options.initialWidth+options.widthGap)/2),
			"marginTop": 0
		});
	}

	function load(_url) {
		wait();
		container.set("opacity", 0).setStyle("display", "").fade(1);
		if (request) request.cancel();
		request = new Request({method: 'get', url: _url, data: 'ajx=true', onSuccess: show}).send();
	}

	function show(res) {
		var tdiv;
		content.removeClass("fbLoading").set("opacity",0).empty().grab(tdiv = new Element("div").set("html", res).setStyle("width", width));
		if (options.autoHeight) height = tdiv.getHeight() + options.heightGap;
		content.setStyles({width: width, height: height });

		setAjx();
		container.morph({
			"width": width+options.widthGap,
			"height": height+options.heightGap,
			"marginLeft": (-(width+options.widthGap)/2),
			"marginTop": ( (options.initialHeight-height+options.heightGap)/2 )
		});
		if (IE6) {
			$$(".fbRoundFill").setStyle("height", height-8);
			$$("#fbRound_l,#fbRound_r").setStyle("height", height);
			$$("#fbRound_dl,#fbRound_dr").setStyle("top", height-4);
		}
		setTimeout("$('fbContent').fade(1)", 500);
		if (options.callback) options.callback();
	}

	function setAjx() {
		if ($("res_ok")) { close(); return; };
		$$(".forlogin").each(function(i) { 
			$("logged").set('html', i.innerHTML); i.innerHTML = ''; 
			$("logged").getElement("a").addEvent("click", function() { $("logged").empty(); });
			close();
			location.href = "#";
		});
		content.getElements("form.ajx").each(function(i) {
			if (i.hasClass("pcs")) return;
			i.grab(new Element("input", {type: "hidden", name: "ajx", value: "true"}));
			i.addEvent("submit", function() {FxBox.ajxSendForm(i)}) 
			i.addClass("pcs");
		});
		$$("a.ajx").each(function(i) {
			if (i.hasClass("pcs")) return;
			i.addEvent("click", function(e) { e.stop(); FxBox.open(i.href); });
			i.addClass("pcs");
		});
		$$("form.ajxnow").each(function(i) { 
			if (i.hasClass("pcs")) return;
			i.grab(new Element("input", {type: "hidden", name: "ajx", value: "true"}));
			i.addEvent("submit", function() {FxBox.ajxSendForm(i)});
			setTimeout(function() { FxBox.ajxSendForm(i) }, 5000);
			i.addClass("pcs");
		});
	}

	function ajxSendForm(form) {
		if (request) request.cancel();
		request = new Request({method: form.method, data: form, url: form.action, onSuccess: show});
		(form.method.toLowerCase() == "post") ? request.post() : request.send();
		wait();
	}

	function position() {
		var scroll = win.getScroll(), size = win.getSize();
		$$(container).setStyles({ "left": scroll.x + (size.x / 2), "top": scroll.y + (size.y / 2) });
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
                log("scroll : " + scroll.x + ":" + scroll.y);
                log("size   : " + size.x + ":" + size.y);
	}

	function setup(open) {
		["object", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._fxbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._fxbox || "";
			});
		});
		overlay.style.display = open ? "" : "none";
		var fn = open ? "addEvent" : "removeEvent";
		win[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}
	function keyDown(event) {
		var code = event.code;
		return options.closeKeys.contains(code) ? close() : true;
	}
	function stop() { if (request != undefined) request.cancel(); }
	function close() {
		stop();
		container.setStyle("display", "none");
		fxOverlay.cancel().chain(setup).start(0);
		return false;
	};

	return {
		open: function(_url, _options) {
			options = $extend({
				className: "", overlayOpacity: 0.8, overlayFadeDuration: 400, initialWidth: 100, initialHeight: 100,
				width: 500, height: 150, widthGap: 26, heightGap: 19, closeKeys: [27], callback: null, autoHeight: false }, _options || {});

			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});

			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			if (overlay.get("opacity")!=options.overlayOpacity) fxOverlay.set(0).start(options.overlayOpacity);

			width = options.width;
			height = options.height;
			middle = win.getScrollTop() + (win.getHeight() / 2);
			container.width = options.initialWidth + options.widthGap;
			container.height = options.initialHeight + options.heightGap;
			container.setStyles({top: Math.max(0, middle - (container.height / 2)), marginTop: 0, marginLeft: -container.width/2, display: "",
				width: container.width, height: container.height });
			position();
			setup(1);
			load(_url);
		},
		send: load,
		ajxSendForm: ajxSendForm,
		showContent: function(_content, _options) {
			options = $extend({
				className: "", overlayOpacity: 0.8, overlayFadeDuration: 400, initialWidth: 100, initialHeight: 100,
				width: 500, height: 150, widthGap: 26, heightGap: 19, closeKeys: [27], callback: null, autoHeight: false }, _options || {});

			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});

			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			if (overlay.get("opacity")!=options.overlayOpacity) fxOverlay.set(0).start(options.overlayOpacity);

			width = options.width;
			height = options.height;
			middle = win.getScrollTop() + (win.getHeight() / 2);
			container.width = options.initialWidth + options.widthGap;
			container.height = options.initialHeight + options.heightGap;
			container.setStyles({top: Math.max(0, middle - (container.height / 2)), marginTop: 0, marginLeft: -container.width/2, display: "",
				width: container.width, height: container.height });
			position();
			setup(1);
			show(_content);
		}
	}
})();

// Utils
var evalErrors = [];
function evalJson(tx) {
	var jseval = function(txt) {
		try {
			var re1 = /(##[^##]*##)/, tmp;
			while(re1.test(txt)) {
				var str = txt.match(re1)[1];
				txt = txt.replace(str, str.replace(/\"/g, '\\\"').replace(/##/g, '\"') );
			}
			txt = txt.replace(/[\n\r]/g, "").replace("'", "\'");
			eval("tmp=" + txt);
			return tmp; 
		} catch(e) { return null; }
	}

	var res = jseval(tx);
	if (tx.length > 0 && res == null && tx.test(/^\s*\[\s*{/)) {
		// Trim and clean branches
		tx = tx.replace(/^\s*\[\s*/, "").replace(/\s*\]\s*$/, "").replace(/}\s*,\s*{/g, "}@@{");
		var list = tx.split("@@");
		res = [];
		list.each(function(i) {
			var line = jseval(i);
			(line!=null) ? res.push(line) : evalErrors.push(i);
		})
	}
	return (res==null)? []:res;
}

function oldEvalJson(tx) {
	try { 
		var re1 = /(##[^##]*##)/;
		while(re1.test(tx)) {
			var str = tx.match(re1)[1];
			tx = tx.replace(str, str.replace(/\"/g, '\\\"').replace(/##/g, '\"') );
		}
		tx = tx.replace(/\n/g, "").replace("'", "\'");
		return eval(tx); 
	}
	catch(e) { return (tx.indexOf("[") == 0)? [] : null; }
}

function loadJs(url) {
	if ($$("script[src='{url}']".replace(/{url}/, url)).length == 0) {
		$(document.head).grab(new Element("script", {src: url, type: "text/javascript"}));
	}
}

function loadCss(url) {
	if ($$("link[href='{url}']".replace(/{url}/, url)).length == 0)
		$(document.head).grab(new Element("link", {type:"text/css", rel:"stylesheet", href: url}));
}

function ssp(tx) {
	var result = tx.replace(/{ssp}/g, staticServerPath+"/").replace(/{sp}/g, serverPath+"/");
	return result;
}

function brokenImage(img) {
	img.src = ssp( img.hasClass("bImg") ? "{ssp}img/nofoto.jpg":"{ssp}img/nofoto_sm.jpg" );
}

function imageError(ev) {
	brokenImage(this);
}

function testVar(vr) {
	try { return eval(vr+"!= undefined && "+vr+"!=null"); }
	catch(e) { return false; }
}


function log() {
	try {
		if (console && console.log) {
			try {
				console.log.apply(console, arguments);
			} catch(e) {
				console.log(Array.slice(arguments));
			}
		}
	} catch (e) { }
}

function inspect(obj) {
  var n = 0;
  var s = '';
  for (var i in obj) {
    s += i + ": " + obj[i];
    if (++n >= 10) {
      if (!confirm(s)) return;
      s = '';
      n = 0;
    }
  }
  if (s != '') alert(s);
}


// ----------------------------------------------------------------------------
// wick.js (import)
/*
	Wick for Mootools inspired on Wick http://sourceforge.net/projects/wick/
	@author Jose Infantes
	@version 0.4.0
*/


var Wick;
window.addEvent("domready", function() {
	if (Wick) WickUtils.init();
});

var Wick = new Class({
	Implements: [Events, Options],
	options: {
		// Common
		maxMatches: 10,
		emptyItem: (window.noMatchText) ? window.noMatchText : "-----",
		re: null,
		// Json data
		list: null, listFilter: null,
		ajaxUrl: "/Generator/FreeTexts/FreeText_[l]_[lang].json", // [l]: first letter, [lang]: language
		searchFields: ["N","A","F"], valueField: "I", textField: "N", prioField: "P",
		// Hidden and icon fields
		hiddenField: null, iconField: null,
		loadingText: ssp("<img alt='...' src='{ssp}img/search/cargando.gif' />"),
		matchOkText: ssp("<img alt='OK' src='{ssp}img/search/correcto.gif' />"),
		noMatchText: "",
                // Used for tracking no-match errors with Google Analytics
                gaEventCategory: "Buscador",
                gaEventAction: "Error"
		// Events: onChange, onMatch, onDematch, onListLoaded, onShow, onHide
	},
	initialize: function(element, _options) {
		this.element = $(element);
                if (this.element === null) return;
		this.element.set("autocomplete", "OFF").wick = this;
		this.setOptions(_options);
		if (this.options.hiddenField) this.hidden = $(this.options.hiddenField);
		else if ( $$(".wickValue[rel='{id}']".replace(/{id}/, this.element.id)).length > 0 )
			this.hidden = $$(".wickValue[rel='{id}']".replace(/{id}/, this.element.id))[0];
		if (this.options.iconField) this.icon = $(this.options.iconField);
		else if ( $$(".wickIcon[rel='{id}']".replace(/{id}/, this.element.id)).length > 0 )
			this.icon = $$(".wickIcon[rel='{id}']".replace(/{id}/, this.element.id))[0];
		if (this.element.className.test(/wickcb:(\D+)/))
			this.addEvent("change", eval(this.element.className.match(/wickcb:(\D+)/)[1]) );

		if (this.options.list == null && this.options.ajaxUrl != "") {
			if (/\[l\]/.test(this.options.ajaxUrl)) this.byLetter = true;
			if (/\[lang\]/.test(this.options.ajaxUrl)) this.byLang = true;
		}
		if (this.options.re==null) this.options.re = (this.byLetter)? "^([ \"\>\<\-]*)({userInput})":"({userInput})";

		this.build();
		this.setEvents();
		this.collectionIndex = new Array();
		this.wickInit();
		if (this.element.value != "" && this.hidden.value == "") { this.silent = true; this.processInput(); };
	},
	build: function() {
		// Build floater
		var floater, content;
		if ($("siw_" + this.element.id)) $("siw_" + this.element.id).destroy();
		this.siw = new smartInputWindow();
		this.siw.floater = new Element("div", {id: "siw_" + this.element.id, 'class': "siw floater"}).setStyle("display", "none")
			.grab(content = new Element("div", {id: "siwc_" + this.element.id, 'class': "siwc", nowrap: "nowrap"}));
		this.siw.floater.wick = this;
		this.siw.floater.addEvents({"click": this.mouseClick, "mousemove": this.mouseMove});
		this.positionFloater();
		$(document.body).adopt(this.siw.floater);
		this.siw.floaterContent = content;
		this.siw.inputBox = this.element;
	},
	positionFloater: function() {
		try {
			this.siw.floater.setStyles({
				position: 'absolute',
				top: this.element.getPosition().y + this.element.getHeight(), 
				left: this.element.getPosition().x,
				width: this.element.getWidth() - 2
			});
		} catch(e) {};
	},
	setList: function(list) {
		this.fullList = list;
		this.filterList();
		this.fireEvent("listLoaded");
	},
	filterList: function() {
		if (!this.fullList) return;
		this.collection = (this.options.listFilter)? this.fullList.filter( this.options.listFilter ) : this.fullList;
		this.collectionIndex = [];
		this.siw.revisedCollection = [];
	},
	wickInit: function() {
		if (document.wicked == true) return false;
		window.addEvent("resize", function(e) {
			$$(".siw").each(function(i) { i.wick.positionFloater(); });
		});
		document.wicked = true;
		return true;
	},
	// Logic 
	processInput: function() {
		var inputBox = this.element, siw = this.siw;
		if (inputBox.value == "") { this.hideFloater(); this.setValue("", true); }
		if (this.goLoad()) return false;

		this.setSmartInputData();
		if (siw.matchCollection && (siw.matchCollection.length > 0)) this.selectMatchItem(0);
		var content = this.getBoxContent();
		if (content) {
			this.modifyBoxContent(content);
			if (!this.silent) this.showFloater();
			this.silent = false;
		} else this.hideFloater();
		return true;
	},
	runMatchingLogic: function() {
		var siw = this.siw;
		if (!siw || (this.byLetter && this.letter == null) || this.loading) return false;
		var userInput = WickUtils.simplify(this.element.value);
		var uifc = userInput.charAt(0).toLowerCase();
		if (uifc == '"') uifc = (n = userInput.charAt(1)) ? n.toLowerCase() : "z";
		if (siw) siw.matchCollection = new Array();
		var pointerToCol = this.collection;

		if (siw && siw.revisedCollection && (siw.revisedCollection.length > 0) && siw.lastUserInput && (userInput.indexOf(siw.lastUserInput) == 0)) {
			pointerToCol = siw.revisedCollection;
		} else if (this.collectionIndex[userInput] && (this.collectionIndex[userInput].length > 0)) 
			pointerToCol = this.collectionIndex[userInput];
		else if (this.collectionIndex[uifc] && (this.collectionIndex[uifc].length > 0)) 
			pointerToCol = this.collectionIndex[uifc];
		else if (siw && (userInput.length == 1) && (!this.collectionIndex[uifc])) 
			siw.buildIndex = true;
		else if (siw) siw.buildIndex = false;
		tempCollection = new Array();
		// var re1m = new RegExp("^([ \"\>\<\-]*)("+userInput+")","i");
		var re1m = new RegExp(this.options.re.replace("{userInput}", userInput), "i");

		this.setValue("");
		for (var i=0, j=0;(i<pointerToCol.length);i++) {
			displayMatches = (j < this.options.maxMatches);
			entry = pointerToCol[i];
			mEntry = this.simplifyEntry(entry);
			if (this.reMatch(entry, re1m)) {
				re = new RegExp("(" + userInput + ")","gi");
				if (displayMatches) {
					if (entry[this.options.textField].toLowerCase() == userInput.toLowerCase()) 
						this.setValue(entry[this.options.valueField]);
					siw.matchCollection[j] = new smartInputMatch(entry[this.options.textField], 
						mEntry[this.options.textField].replace(re,"<strong>$1</strong>"), entry[this.options.valueField], entry[this.options.prioField]==10);				
				}
				tempCollection[j] = WickUtils.clone(entry);
				j++;
			}
		}
		if (tempCollection.length == 0) {
			siw.matchCollection[j] = new smartInputMatch("", this.options.emptyItem, "", false, true);
                        if (TrackingActions) {
                          TrackingActions.trackEvent(this.options.gaEventCategory, this.options.gaEventAction, userInput);
                        }
		}

		if (siw) {
			siw.lastUserInput = userInput;
			siw.revisedCollection = WickUtils.clone(tempCollection);
			this.collectionIndex[userInput] = WickUtils.clone(tempCollection);
		}
		if (siw.buildIndex) {
			this.collectionIndex[uifc] = WickUtils.clone(tempCollection);
			if (siw) siw.buildIndex = false;
		}
		return true;
	},
	setValue: function(value, empty) {
		if (this.hidden) this.hidden.value = value;
		var whereValid = this.valid;
		this.valid = (value!="" && !empty);
		var loadingTx = "";
		if (empty==undefined) loadingTx = (value == "") ? this.options.noMatchText : this.options.matchOkText;
		if (this.getIcon() != loadingTx) this.setIcon(loadingTx);
		this.fireEvent("change");
		if (this.valid) this.fireEvent("match");
		if (!this.valid && whereValid) this.fireEvent("dematch");
	},
	setText: function(text) {
		this.silent = true;
		this.element.value = text;
		this.processInput