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);
  }
};

window.addEvent("domready", function() {
  var t0 = (new Date()).getTime();
  log("domready start delayed " + (t0 - T0) + "msecs");

  // -------------------------------------------------------------------------
  // Priority: Critical

  // -------------------------------------------------------------------------
  // Priority: High

  // -------------------------------------------------------------------------
  // Priority: Normal

  // Languages and currencies
  if ($("langcur")) {
    $$("#langcur select").addEvent("change", GeneralFuncs.langCurrChanged);
  }
  
  Abstract.init();

  // 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);
  });
  // 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);
  });

  // Destinations autocomplete
  if ($("buscaDestino")) {
    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;
    });
  }

	// 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");});


	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);

  var t1 = (new Date()).getTime();
  log("base.domready finished in " + (t1 - t0) + "msecs");
});

window.addEvent("load", function() {
  var t0 = (new Date()).getTime();
  log("load start delayed " + (t0 - T0) + "msecs");

  $$("img.bImg, img.sImg").each(function(i) {
    i.addEvent("error", imageError);
    if (!i.complete || i.naturalWidth==0) brokenImage(i);
  });
  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);

  if ($("photos")) {
    $$(".bImg").each(GeneralFuncs.fixImageHeight);
  }

  PhotoPopup.init();

  var t1 = (new Date()).getTime();
  log("base.load finished in " + (t1 - t0) + "msecs");
});

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("change", 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);
		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();
	},
	getValue: function() {
		if (this.hidden) return this.hidden.value;
		return this.element.value;
	},
	setSmartInputData: function() {
		var siw = this.siw;
		if (siw) {
			var userInput = this.element.value.toLowerCase().replace(/[\r\n\t\f\s]+/gi,' ').replace(/^ +/gi,'').replace(/ +$/gi,'').replace(/ +/gi,' ').replace(/\\/gi,'').replace(/\[/gi,'').replace(/\(/gi,'').replace(/\./gi,'\.').replace(/\?/gi,'');
			if (userInput && (userInput != "") && (userInput != '"')) this.runMatchingLogic(userInput); // TODO
			else siw.matchCollection = null;
		}
	},
	// Ajax
	goLoad: function() {
		if (!this.checkLoad || this.loading) return false;
		if (this.byLetter) {
			if (!this.loading && (this.letter == null || this.letter != WickUtils.getFirstLetter(this.element.value))) {
				this.load();
				return true;
			} else {
				return false;
			}
		} else {
			this.load();
			return true;
		}
	},
	load: function() {
		if (this.options.list != null) {
			// No ajax load, just local list
			this.setList( this.options.list );
			this.checkLoad = false;
			this.processInput();
		} else {
			var murl = this.options.ajaxUrl;
			var letter;
			if (this.byLetter) {
				letter = WickUtils.getFirstLetter(this.element.value);
				this.loadingLetter = letter;
				if (letter == "" || letter == this.letter || !/[a-z]/.test(letter)) return false;
				murl = murl.replace("[l]", letter.toUpperCase());
			}
			if (this.byLang) {
				murl = murl.replace("[lang]", window.userLang);
			}
			this.setIcon(this.options.loadingText);
			this.loading = true;

			var t = this;
			this.request = new Request({ method: 'get', url: murl, onSuccess: function(res) {
				try { t.setList( eval("[" + res + "]") ); } 
				catch(e) { t.setList( [] ); }
				t.loading = false;
				t.setIcon("");
				if (t.byLetter) t.letter = letter;
				else t.checkLoad = false;
				t.processInput();
			}}).send();
		}
		return true;
	},
	loadLetter11: function() {
		// An ajax call for every letter
		var inputBox = this.element;
		var letter = WickUtils.getFirstLetter(this.element.value);
		this.loadingLetter = letter;
		if (letter == "" || letter == this.letter || !/[a-z]/.test(letter)) return false;

		this.loading = true;
		var murl = this.options.ajaxUrl.replace("[l]", letter.toUpperCase()).replace("[lang]", window.userLang);
		this.setIcon(this.options.loadingText);

		var t = this;
		this.request = new Request({ method: 'get', url: murl, onSuccess: function(res) {
			try { t.setList( eval("[" + res + "]") ); } 
			catch(e) { t.setList( [] ); }
			t.letter = letter;
			t.loading = false;
			t.setIcon("");
			t.processInput();
		}}).send();
		return true;
	},
	// Floater
	hideFloater: function() {
		if (this.siw.floater.getStyle("display")!="none") {
			this.siw.floater.setStyle("display","none");
			this.fireEvent("hide");
		}
	},
	showFloater: function() { 
		this.positionFloater();
		if (this.siw.floater.getStyle("display")=="none") {
			this.siw.floater.setStyle("display", "");
			this.fireEvent("show");
		}
	},
	// Icon
	setIcon: function(tx) { if (this.icon) this.icon.set("html", tx); },
	getIcon: function(tx) { if (this.icon) return this.icon.get("html"); return ""; },
	// Events
	setEvents: function() {
		this.element.addEvents({
			"keyup": this.keyPress,
			"keydown": this.keyDown,
			"focus": this.focus,
			"blur": this.blur
		})
	},
	keyPress: function(event) {
		var el = this.wick;
		var siw = el.siw;
		var kc = event.code;
		if (siw && ((kc == 13) || (kc == 9))) {
			siw.selectingSomething = true;
			siw.inputBox.value = siw.inputBox.value.replace(/[ \r\n\t\f\s]+$/gi,' ');
			el.hideFloater();
		} else if (el.element && (kc != 38) && (kc != 40) && (kc != 37) && (kc != 39) && (kc != 13) && (kc != 27) && (kc != 9)) {
			el.processInput();
		} else if (siw && siw.inputBox) {
			siw.inputBox.focus();
		}
	},
	keyDown: function(event) {
		var el = this.wick, siw = el.siw, kc = event.code;
		if ([40,38,13,9,27].indexOf(kc) >= 0) event.stop();
		if (siw && kc && el.collection!=undefined) {
			if (kc == 40) { 
				el.showFloater();
				siw.selectingSomething = true; 
				el.selectNextItem();
			} else if (kc == 38) {
				el.showFloater();
				siw.selectingSomething = true;
				el.selectPreviousItem();
			} else if ((kc == 13) || (kc == 9)) {
				siw.selectingSomething = true;
				el.activateCurrentSmartInputMatch();
			} else if (kc == 27)  {
				el.hideFloater();
			} else {
				siw.selectingSomething = false;
			}
		}
	},
	mouseMove: function(event) {
		var el = $(event.target);
		if (!el.hasClass("matchedSmartInputItem") && !el.getParent().hasClass("matchedSmartInputItem")) {
			return false;
		}
		el.getParent('.floater').wick.selectFromMouseOver(event.target);
		return true;
	},
	mouseClick: function(event) {
		event.stop();
		var el = $(event.target);
		if (!el.hasClass("matchedSmartInputItem") && !el.getParent().hasClass("matchedSmartInputItem")) {
			return false;
		}
		var wk = el.getParent('.floater').wick;
		wk.selectFromMouseClick();
		return true;
	},
	focus: function(event) { if (this.wick.floater && this.wick.floater.getStyle("display")=="none") this.wick.processInput(); },
	blur: function(event) { setTimeout('$("'+this.id+'").wick.hideFloater()', 300); },
	// Various
	selectMatchItem: function(index) { this.siw.matchCollection[index].isSelected = true; },
	deselectMatchItem: function(index) { this.siw.matchCollection[index].isSelected = false; },
	getBoxContent: function() {
		var a = null, siw = this.siw;
		if (siw && siw.matchCollection && (siw.matchCollection.length > 0)) {
			a = '';
			for (var i = 0;i < siw.matchCollection.length; i++) {
				var cssString = siw.matchCollection[i].isSelected ? 'selectedSmartInputItem ' : '';
				cssString += siw.matchCollection[i].maxPrio ? 'maxPrio ' : '';
				cssString += siw.matchCollection[i].empty ? 'emptyItem ' : '';
				var val = '<li class="' + cssString + 'matchedSmartInputItem">' + siw.matchCollection[i].value.replace(/\{ */gi,"&lt;").replace(/\} */gi,"&gt;") + '</li>';			
				a += val;
			}
		}
		return a;
	},
	modifyBoxContent: function(content) {
		if (this.results) this.results.destroy();
		this.results = new Element("ul", {'class': 'smartInputResults'}).set("html", content);
		this.siw.floaterContent.grab(this.results);
		this.siw.matchListDisplay = this.results;
	},
	selectNextItem: function() {
		var currentIndex = this.getSelectedItem();
		if (currentIndex != null) {
			this.deselectMatchItem(currentIndex);
			if ((currentIndex + 1) < this.siw.matchCollection.length)
				this.selectMatchItem(currentIndex + 1);
			else
				this.selectMatchItem(0);
		} else {
			this.selectMatchItem(0);
		}
		this.modifyBoxContent(this.getBoxContent());
		this.element.focus();
	},
	selectPreviousItem: function() {
		var currentIndex = this.getSelectedItem();
		if (currentIndex != null) {
			this.deselectMatchItem(currentIndex);
			if ((currentIndex - 1) >= 0)
				this.selectMatchItem(currentIndex - 1);
			else
				this.selectMatchItem(this.siw.matchCollection.length - 1);
		} else {
			this.selectMatchItem(this.siw.matchCollection.length - 1);
		}
		this.modifyBoxContent(this.getBoxContent());
		this.element.focus();
	},
	activateCurrentSmartInputMatch: function() {
		if ((selIndex = this.getSelectedItem()) == null) return false;
		var selItem = this.siw.matchCollection[selIndex];
		if (!selItem.empty) this.siw.inputBox.value = selItem.cleanValue;
		this.setValue(selItem.idValue);
		return true;
	},
	getSelectedItem: function() {
		var answer = null;
		for (i = 0; ((i < this.siw.matchCollection.length) && !answer) ; i++) {
			if (this.siw.matchCollection[i].isSelected) answer = i;
		}
		return answer;
	},
	selectFromMouseOver: function(o) {
		o = $(o);
		if (!o.hasClass("matchedSmartInputItem")) o = o.getParent(".matchedSmartInputItem");
		var currentIndex = this.getSelectedItem();
		if (currentIndex != null) this.deselectMatchItem(currentIndex);
		var newIndex = this.getIndexFromElement(o);
		this.selectMatchItem(newIndex);
		this.siw.floater.getElements(".selectedSmartInputItem").removeClass("selectedSmartInputItem");
		$(o).addClass("selectedSmartInputItem");
	},
	selectFromMouseClick: function() {
		this.activateCurrentSmartInputMatch();
		this.siw.inputBox.focus();
		this.hideFloater();
	},
	getIndexFromElement: function(o) {
		var index = 0;
		while (o.previousSibling) {
			o = o.previousSibling
			index++;
		}
		return index;
	},
	// Tools
	simplifyEntry: function(entry) {
		entry = WickUtils.clone(entry);
		var fields = this.options.searchFields;
		for(var i=0; i<fields; i++)
			entry[fields[i]] = WickUtils.simplify(entry[fields[i]]);
		return entry;
	},
	reMatch: function(entry, re) {
		var fields = this.options.searchFields;
		for(var i=0; i<fields.length; i++)
			if (entry[fields[i]] && entry[fields[i]].match(re)) return true;
		return false;
	},
	loading: false, letter: null, oldUrl: null,
	icon: null, hidden: null, silent: false,
	byLetter: false, byLang: false, checkLoad: true,
	cnf: { defLang: 170 }
});

var DateFormat = {
	weekdays: {
		'33' : /* Català     */ ['Diumenge', 'Dilluns',       'Dimarts',     'Dimecres',     'Dijous',       'Divendres',   'Dissabte'],
		'45' : /* Danish     */ ['Søndag',   'Mandag',        'Tirsdag',     'Onsdag',       'Torsdag',      'Fredag',      'Lørdag'],
		'49' : /* Nederlands */ ['Zondag',   'Maandag',       'Dinsdag',     'Woensdag',     'Donderdag',    'Vrijdag',     'Zaterdag'],
		'52' : /* English    */ ['Sunday',   'Monday',        'Tuesday',     'Wednesday',    'Thursday',     'Friday',      'Saturday'],
		'57' : /* Ireland    */ ['Sunday',   'Monday',        'Tuesday',     'Wednesday',    'Thursday',     'Friday',      'Saturday'],
		'64' : /* USA        */ ['Sunday',   'Monday',        'Tuesday',     'Wednesday',    'Thursday',     'Friday',      'Saturday'],
		'74' : /* Français   */ ['Dimanche', 'Lundi',         'Mardi',       'Mercredi',     'Jeudi',        'Vendredi',    'Samedi'],
		'84' : /* Deutch     */ ['Sonntag',  'Montag',        'Dienstag',    'Mittwoch',     'Donnerstag',   'Freitag',     'Samstag'],
		'104': /* Italiano   */ ['Domenica', 'Lunedì',        'Martedì',     'Mercoledì',    'Giovedì',      'Venerdì',     'Sabato'],
		'137': /* Português  */ ['Domingo',  'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
		'138': /* Brazil     */ ['Domingo',  'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
		'164': /* Mexico     */ ['Domingo',  'Lunes',         'Martes',      'Miércoles',    'Jueves',       'Viernes',     'Sábado'],
		'170': /* Español    */ ['Domingo',  'Lunes',         'Martes',      'Miércoles',    'Jueves',       'Viernes',     'Sábado'],
		'175': /* Swedish    */ ['Söndag',   'Måndag',        'Tisdag',      'Onsdag',       'Torsdag',      'Fredag',      'Lördag']
	},
        weekday_initials: {
                '33' : /* Català     */ ['D', 'L', 'M', 'X', 'J', 'V', 'S'],
		'45' : /* Danish     */ ['S', 'M', 'T', 'O', 'T', 'F', 'L'],
		'49' : /* Nederlands */ ['Z', 'M', 'D', 'W', 'D', 'V', 'Z'],
		'52' : /* English    */ ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
		'57' : /* Ireland    */ ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
		'64' : /* USA        */ ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
		'74' : /* Français   */ ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
		'84' : /* Deutch     */ ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
		'104': /* Italiano   */ ['D', 'L', 'M', 'M', 'G', 'V', 'S'],
		'137': /* Português  */ ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
		'138': /* Brazil     */ ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
		'164': /* Mexico     */ ['D', 'L', 'M', 'X', 'J', 'V', 'S'],
		'170': /* Español    */ ['D', 'L', 'M', 'X', 'J', 'V', 'S'],
		'175': /* Swedish    */ ['S', 'M', 'T', 'O', 'T', 'F', 'L']
        },
	months: {
		'33' : /* Català     */ ['Gener',   'Febrer',    'Març',  'Abril',  'Maig',   'Juny',   'Juliol',  'Agost',    'Setembre',   'Octubre', 'Novembre',  'Desembre'],
		'45' : /* Danish     */ ['Januar',  'Februar',   'Marts', 'April',  'Maj',    'Juni',   'Juli',    'August',   'September',  'Oktober', 'November',  'December'],
		'49' : /* Nederlands */ ['Januari', 'Februari',  'Maart', 'April',  'Mei',    'Juni',   'Juli',    'Augustus', 'September',  'Oktober', 'November',  'December'],
		'52' : /* English    */ ['January', 'February',  'March', 'April',  'May',    'June',   'July',    'August',   'September',  'October', 'November',  'December'],
		'57' : /* Ireland    */ ['January', 'February',  'March', 'April',  'May',    'June',   'July',    'August',   'September',  'October', 'November',  'December'],
		'64' : /* USA        */ ['January', 'February',  'March', 'April',  'May',    'June',   'July',    'August',   'September',  'October', 'November',  'December'],
		'74' : /* Français   */ ['Janvier', 'Février',   'Mars',  'Avril',  'Mai',    'Juin',   'Juillet', 'Août',     'Septembre',  'Octobre', 'Novembre',  'Décembre'],
		'84' : /* Deutch     */ ['Januar',  'Februar',   'März',  'April',  'Mai',    'Juni',   'Juli',    'August',   'September',  'Oktober', 'November',  'Dezember'],
		'104': /* Italiano   */ ['Gennaio', 'Febbraio',  'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio',  'Agosto',   'Settembre',  'Ottobre', 'Novembre',  'Dicembre'],
		'137': /* Português  */ ['Janeiro', 'Fevereiro', 'Março', 'Abril',  'Maio',   'Junho',  'Julho',   'Agosto',   'Setembro',   'Outubro', 'Novembro',  'Dezembro'],
		'138': /* Brazil     */ ['Janeiro', 'Fevereiro', 'Março', 'Abril',  'Maio',   'Junho',  'Julho',   'Agosto',   'Setembro',   'Outubro', 'Novembro',  'Dezembro'],
		'164': /* Mexico     */ ['Enero',   'Febrero',   'Marzo', 'Abril',  'Mayo',   'Junio',  'Julio',   'Agosto',   'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
		'170': /* Español    */ ['Enero',   'Febrero',   'Marzo', 'Abril',  'Mayo',   'Junio',  'Julio',   'Agosto',   'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
		'175': /* Swedish    */ ['Januari', 'Februari',  'Mars',  'April',  'Maj',    'Juni',   'Juli',    'Augusti',  'September',  'Oktober', 'November',  'December']
	},
	ordinals: {
		'52' : /* English    */ ['st', 'nd', 'rd', 'th'],
		'64' : /* USA        */ ['st', 'nd', 'rd', 'th'],
		'164': /* mexico     */ ['o'],
		'170': /* Español    */ ['o']
	},
	locale: window.userLang,
	templates: {
		'33' : /* Català     */ '%ddd, %d de %mmm de %yyyy',
		'45' : /* Danish     */ '%ddd, %d. %mmm %yyyy',
		'49' : /* Nederlands */ '%ddd, %dd %mmm %yyyy',
		'52' : /* English    */ '%ddd, %o of %mmm %yyyy',
		'57' : /* Ireland    */ '%ddd, %o of %mmm %yyyy',
		'64' : /* USA        */ '%ddd, %o of %mmm %yyyy',
		'74' : /* Français   */ '%ddd, %dd %mmm %yyyy',
		'84' : /* Deutch     */ '%ddd, %d. %mmm %yyyy',
		'104': /* Italiano   */ '%ddd, %dd %mmm %yyyy',
		'137': /* Português  */ '%ddd, %d de %mmm %yyyy',
		'138': /* Brazil     */ '%ddd, %d de %mmm %yyyy',
		'164': /* Mexico     */ '%ddd, %d de %mmm de %yyyy',
		'170': /* Español    */ '%ddd, %d de %mmm de %yyyy',
		'175': /* Swedish    */ '%ddd, %dd %mmm %yyyy'
	},

	getMonthNames: function() {
		return this.months[this.locale];
	},

	getWeekDays: function() {
                var src = this.weekdays[this.locale];
                var days = new Array();
                for (var i = 0; i < src.length; i++) days.push(src[i]);
		return days;
	},

        getWeekDayInitials: function() {
                var src = this.weekday_initials[this.locale];
                var days = new Array();
                for (var i = 0; i < src.length; i++) days.push(src[i]);
		return days;
        },

	format: function(date) {
		date = date || new Date();

		var template = DateFormat.templates[DateFormat.locale];
		var d = date.getDate();
		var w = date.getDay();
		var m = date.getMonth();
		var y = date.getFullYear();

		if (!template) template = DateFormat.templates['en'];

		var s = template;
		while (s.contains('%yyyy')) {
			s = s.replace('\%yyyy', y);
		}
		while (s.contains('%yy')) {
			s = s.replace('\%yy', ("" + y).substring(2));
		}
		while (s.contains('%mmm')) {
			s = s.replace('\%mmm', DateFormat.months[DateFormat.locale][m]);
		}
		while (s.contains('%mm')) {
			// Months are in the range [0..11]
			s = s.replace('\%mm', (m < 9 ? "0" : "") + (m + 1));
		}
		while (s.contains('%m')) {
			// Months are in the range [0..11]
			s = s.replace('\%m', (m + 1));
		}
		while (s.contains('%ddd')) {
			s = s.replace('\%ddd', DateFormat.weekdays[DateFormat.locale][w]);
		}
		while (s.contains('%dd')) {
			s = s.replace('\%dd', (d < 10 ? "0" : "") + d);
		}
		while (s.contains('%d')) {
			s = s.replace('\%d', d);
		}
		while (s.contains('%o')) {
			var suffixes = DateFormat.ordinals[DateFormat.locale];
			var suffix = (suffixes) ? '<sup>' + suffixes[Math.min(d - 1, suffixes.length - 1)] + '</sup>' : '';
			s = s.replace('\%o', d + suffix);
		}

		return s;
	}
};

var WickUtils = {
	getFirstLetter: function(s) {
		return 	s.toLowerCase().replace(/[\r\n\t\f\s]+/gi,' ').replace(/^ +/gi,'').replace(/ +$/gi,'').replace(/ +/gi,' ').replace(/\\/gi,'').replace(/\[/gi,'').replace(/\(/gi,'').replace(/\./gi,'\.').replace(/\?/gi,'').charAt(0);
	},
	simplify: function(s) { return s.toLowerCase().replace(/^[ \s\f\t\n\r]+/,'').replace(/[ \s\f\t\n\r]+$/,''); },
	clone: function(obj) {
		function F() {}
		F.prototype = obj;
		return new F();
	},
	init: function() {
		$$(".wick").each(function(i) { var a = new Wick(i.id) });
	}
}

function smartInputWindow() {
	this.customFloater = false;
	this.floater = null;
	this.floaterContent = null;
	this.selectedSmartInputItem = null;
	this.isGecko = (navigator.userAgent.indexOf("Gecko/200") != -1);
	this.isSafari = (navigator.userAgent.indexOf("Safari") != -1);
	this.isWinIE = ((navigator.userAgent.indexOf("Win") != -1 ) && (navigator.userAgent.indexOf("MSIE") != -1 ));
	this.showCredit = false;
}
function smartInputMatch(cleanValue, value, id, maxPrio, empty) {
	this.cleanValue = cleanValue;
	this.value = value;
	this.idValue = id;
	this.maxPrio = maxPrio;
	this.isSelected = false;
	this.empty = (empty==true);
}

/*
---

script: More.js

description: MooTools More

license: MIT-style license

authors:
- Guillermo Rauch
- Thomas Aylott
- Scott Kyle

requires:
- core:1.2.4/MooTools

provides: [MooTools.More]

...
*/
MooTools.More = {
	'version': '1.2.4.2',
	'build': 'bd5a93c0913cce25917c48cbdacde568e15e02ef'
};

/*
---

script: Hash.Cookie.js

description: Class for creating, reading, and deleting Cookies in JSON format.

license: MIT-style license

authors:
- Valerio Proietti
- Aaron Newton

requires:
- core:1.2.4/Cookie
- core:1.2.4/JSON

provides: [Hash.Cookie]

...
*/
Hash.Cookie = new Class({

	Extends: Cookie,

	options: {
		autoSave: true
	},

	initialize: function(name, options){
		this.parent(name, options);
		this.load();
	},

	save: function(){
		var value = JSON.encode(this.hash);
		if (!value || value.length > 4096) return false; //cookie would be truncated!
		if (value == '{}') this.dispose();
		else this.write(value);
		return true;
	},

	load: function(){
		this.hash = new Hash(JSON.decode(this.read(), true));
		return this;
	},
	get: function(key) {
		return this.hash.get(key);
	},
	set: function(key, value) {
		this.hash.set(key, value);
		if (this.options.autoSave) this.save();
	}

});

/*
---

script: Assets.js

description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document.

license: MIT-style license

authors:
- Valerio Proietti

requires:
- core:1.2.4/Element.Event
- /MooTools.More

provides: [Assets]

...
*/

var Asset = {

	javascript: function(source, properties){
		properties = $extend({
			onload: $empty,
			document: document,
			check: $lambda(true)
		}, properties);

		var script = new Element('script', {src: source, type: 'text/javascript'});

		var load = properties.onload.bind(script), 
			check = properties.check, 
			doc = properties.document;
		delete properties.onload;
		delete properties.check;
		delete properties.document;

		script.addEvents({
			load: load,
			readystatechange: function(){
				if (['loaded', 'complete'].contains(this.readyState)) load();
			}
		}).set(properties);

		if (Browser.Engine.webkit419) var checker = (function(){
			if (!$try(check)) return;
			$clear(checker);
			load();
		}).periodical(50);

		return script.inject(doc.head);
	},

	css: function(source, properties){
		return new Element('link', $merge({
			rel: 'stylesheet',
			media: 'screen',
			type: 'text/css',
			href: source
		}, properties)).inject(document.head);
	},

	image: function(source, properties){
		properties = $merge({
			onload: $empty,
			onabort: $empty,
			onerror: $empty
		}, properties);
		var image = new Image();
		var element = document.id(image) || new Element('img');
		['load', 'abort', 'error'].each(function(name){
			var type = 'on' + name;
			var event = properties[type];
			delete properties[type];
			image[type] = function(){
				if (!image) return;
				if (!element.parentNode){
					element.width = image.width;
					element.height = image.height;
				}
				image = image.onload = image.onabort = image.onerror = null;
				event.delay(1, element, element);
				element.fireEvent(name, element, 1);
			};
		});
		image.src = element.src = source;
		if (image && image.complete) image.onload.delay(1);
		return element.set(properties);
	},

	images: function(sources, options){
		options = $merge({
			onComplete: $empty,
			onProgress: $empty,
			onError: $empty,
			properties: {}
		}, options);
		sources = $splat(sources);
		var images = [];
		var counter = 0;
		return new Elements(sources.map(function(source){
			return Asset.image(source, $extend(options.properties, {
				onload: function(){
					options.onProgress.call(this, counter, sources.indexOf(source));
					counter++;
					if (counter == sources.length) options.onComplete();
				},
				onerror: function(){
					options.onError.call(this, counter, sources.indexOf(source));
					counter++;
					if (counter == sources.length) options.onComplete();
				}
			}));
		}));
	}

};

var PicShow = new Class({
  Implements: [Options],
  
  options: {
    timeout: 4000
  },

  initialize: function(id, options) {
    if ($(id) == null) return;

    this.setOptions(options);
    this.pictures = $$("#" + id + " .pic");
    this.links = $$("#" + id + " .buttonbar a");
    this.current = 0;

    this.links.addEvent("click", this.stopAt.bind(this));
    this.timer = setTimeout(this.nextPic.bind(this), this.options.timeout);
  },
  
  nextPic: function(event) {
    var next = (this.current + 1) % 5;
    this.setCurrent(next);
    this.timer = setTimeout(this.nextPic.bind(this), this.options.timeout);
  },
  
  stopAt: function(event) {
    event.stop();
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = 0;
    }
    this.setCurrent(parseInt(event.target.rel));
    return false;
  },
  
  setCurrent: function(pos) {
    if (pos != this.current) {
      this.links[this.current].removeClass("current");
      this.links[pos].addClass("current");
      this.pictures[this.current].setStyle("opacity", 0);
      this.pictures[this.current].setStyle("visibility", "hidden");
      this.pictures[pos].setStyle("opacity", 0);
      this.pictures[pos].setStyle("visibility", "visible");
      this.pictures[pos].tween("opacity", 1);
      this.current = pos;
    }
  }
});