﻿/*!	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/

var swfobject = function() {
	
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",
		ON_READY_STATE_CHANGE = "onreadystatechange",
		
		win = window,
		doc = document,
		nav = navigator,
		
		plugin = false,
		domLoadFnArr = [main],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		storedAltContent,
		storedAltContentId,
		storedCallbackFn,
		storedCallbackObj,
		isDomLoaded = false,
		isExpressInstallActive = false,
		dynamicStylesheet,
		dynamicStylesheetMedia,
		autoHideShow = true,
	
	/* Centralized function for browser feature detection
		- User agent string detection is only used when no good alternative is possible
		- Is executed directly for optimal performance
	*/	
	ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				plugin = true;
				ie = false; // cascaded feature detection for Internet Explorer
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			try {
				var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
				if (a) { // a will return null when ActiveX is disabled
					d = a.GetVariable("$version");
					if (d) {
						ie = true; // cascaded feature detection for Internet Explorer
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
			}
			catch(e) {}
		}
		return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
	}(),
	
	/* Cross-browser onDomLoad
		- Will fire an event as soon as the DOM of a web page is loaded
		- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
		- Regular onload serves as fallback
	*/ 
	onDomLoad = function() {
		if (!ua.w3) { return; }
		if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically 
			callDomLoadFunctions();
		}
		if (!isDomLoaded) {
			if (typeof doc.addEventListener != UNDEF) {
				doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
			}		
			if (ua.ie && ua.win) {
				doc.attachEvent(ON_READY_STATE_CHANGE, function() {
					if (doc.readyState == "complete") {
						doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
						callDomLoadFunctions();
					}
				});
				if (win == top) { // if not inside an iframe
					(function(){
						if (isDomLoaded) { return; }
						try {
							doc.documentElement.doScroll("left");
						}
						catch(e) {
							setTimeout(arguments.callee, 0);
							return;
						}
						callDomLoadFunctions();
					})();
				}
			}
			if (ua.wk) {
				(function(){
					if (isDomLoaded) { return; }
					if (!/loaded|complete/.test(doc.readyState)) {
						setTimeout(arguments.callee, 0);
						return;
					}
					callDomLoadFunctions();
				})();
			}
			addLoadEvent(callDomLoadFunctions);
		}
	}();
	
	function callDomLoadFunctions() {
		if (isDomLoaded) { return; }
		try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
			var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
			t.parentNode.removeChild(t);
		}
		catch (e) { return; }
		isDomLoaded = true;
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}
	
	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else { 
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}
	
	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded 
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}
	
	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { 
		if (plugin) {
			testPlayerVersion();
		}
		else {
			matchVersions();
		}
	}
	
	/* Detect the Flash Player version for non-Internet Explorer browsers
		- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
		  a. Both release and build numbers can be detected
		  b. Avoid wrong descriptions by corrupt installers provided by Adobe
		  c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
		- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
	*/
	function testPlayerVersion() {
		var b = doc.getElementsByTagName("body")[0];
		var o = createElement(OBJECT);
		o.setAttribute("type", FLASH_MIME_TYPE);
		var t = b.appendChild(o);
		if (t) {
			var counter = 0;
			(function(){
				if (typeof t.GetVariable != UNDEF) {
					var d = t.GetVariable("$version");
					if (d) {
						d = d.split(" ")[1].split(",");
						ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				else if (counter < 10) {
					counter++;
					setTimeout(arguments.callee, 10);
					return;
				}
				b.removeChild(o);
				t = null;
				matchVersions();
			})();
		}
		else {
			matchVersions();
		}
	}
	
	/* Perform Flash Player and SWF version matching; static publishing only
	*/
	function matchVersions() {
		var rl = regObjArr.length;
		if (rl > 0) {
			for (var i = 0; i < rl; i++) { // for each registered object element
				var id = regObjArr[i].id;
				var cb = regObjArr[i].callbackFn;
				var cbObj = {success:false, id:id};
				if (ua.pv[0] > 0) {
					var obj = getElementById(id);
					if (obj) {
						if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
							setVisibility(id, true);
							if (cb) {
								cbObj.success = true;
								cbObj.ref = getObjectById(id);
								cb(cbObj);
							}
						}
						else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
							var att = {};
							att.data = regObjArr[i].expressInstall;
							att.width = obj.getAttribute("width") || "0";
							att.height = obj.getAttribute("height") || "0";
							if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
							if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
							// parse HTML object param element's name-value pairs
							var par = {};
							var p = obj.getElementsByTagName("param");
							var pl = p.length;
							for (var j = 0; j < pl; j++) {
								if (p[j].getAttribute("name").toLowerCase() != "movie") {
									par[p[j].getAttribute("name")] = p[j].getAttribute("value");
								}
							}
							showExpressInstall(att, par, id, cb);
						}
						else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
							displayAltContent(obj);
							if (cb) { cb(cbObj); }
						}
					}
				}
				else {	// if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
					setVisibility(id, true);
					if (cb) {
						var o = getObjectById(id); // test whether there is an HTML object element or not
						if (o && typeof o.SetVariable != UNDEF) { 
							cbObj.success = true;
							cbObj.ref = o;
						}
						cb(cbObj);
					}
				}
			}
		}
	}
	
	function getObjectById(objectIdStr) {
		var r = null;
		var o = getElementById(objectIdStr);
		if (o && o.nodeName == "OBJECT") {
			if (typeof o.SetVariable != UNDEF) {
				r = o;
			}
			else {
				var n = o.getElementsByTagName(OBJECT)[0];
				if (n) {
					r = n;
				}
			}
		}
		return r;
	}
	
	/* Requirements for Adobe Express Install
		- only one instance can be active at a time
		- fp 6.0.65 or higher
		- Win/Mac OS only
		- no Webkit engines older than version 312
	*/
	function canExpressInstall() {
		return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
	}
	
	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
		isExpressInstallActive = true;
		storedCallbackFn = callbackFn || null;
		storedCallbackObj = {success:false, id:replaceElemIdStr};
		var obj = getElementById(replaceElemIdStr);
		if (obj) {
			if (obj.nodeName == "OBJECT") { // static publishing
				storedAltContent = abstractAltContent(obj);
				storedAltContentId = null;
			}
			else { // dynamic publishing
				storedAltContent = obj;
				storedAltContentId = replaceElemIdStr;
			}
			att.id = EXPRESS_INSTALL_ID;
			if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
			if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
			if (typeof par.flashvars != UNDEF) {
				par.flashvars += "&" + fv;
			}
			else {
				par.flashvars = fv;
			}
			// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
			// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceElemIdStr += "SWFObjectNew";
				newObj.setAttribute("id", replaceElemIdStr);
				obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				(function(){
					if (obj.readyState == 4) {
						obj.parentNode.removeChild(obj);
					}
					else {
						setTimeout(arguments.callee, 10);
					}
				})();
			}
			createSWF(att, par, replaceElemIdStr);
		}
	}
	
	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
			// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			(function(){
				if (obj.readyState == 4) {
					obj.parentNode.removeChild(obj);
				}
				else {
					setTimeout(arguments.callee, 10);
				}
			})();
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	} 

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}
	
	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (ua.wk && ua.wk < 312) { return r; }
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);	
			}
			else { // well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}
	
	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);	
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}
	
	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && obj.nodeName == "OBJECT") {
			if (ua.ie && ua.win) {
				obj.style.display = "none";
				(function(){
					if (obj.readyState == 4) {
						removeObjectInIE(id);
					}
					else {
						setTimeout(arguments.callee, 10);
					}
				})();
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}
	
	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}
	
	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}
	
	function createElement(el) {
		return doc.createElement(el);
	}
	
	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/	
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}
	
	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}
	
	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/	
	function createCSS(sel, decl, media, newStyle) {
		if (ua.ie && ua.mac) { return; }
		var h = doc.getElementsByTagName("head")[0];
		if (!h) { return; } // to also support badly authored HTML pages that lack a head element
		var m = (media && typeof media == "string") ? media : "screen";
		if (newStyle) {
			dynamicStylesheet = null;
			dynamicStylesheetMedia = null;
		}
		if (!dynamicStylesheet || dynamicStylesheetMedia != m) { 
			// create dynamic stylesheet + get a global reference to it
			var s = createElement("style");
			s.setAttribute("type", "text/css");
			s.setAttribute("media", m);
			dynamicStylesheet = h.appendChild(s);
			if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
				dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
			}
			dynamicStylesheetMedia = m;
		}
		// add style rule
		if (ua.ie && ua.win) {
			if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
				dynamicStylesheet.addRule(sel, decl);
			}
		}
		else {
			if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
				dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
			}
		}
	}
	
	function setVisibility(id, isVisible) {
		if (!autoHideShow) { return; }
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
	}
	
	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();
	
	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/documentation
		*/ 
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
			if (ua.w3 && objectIdStr && swfVersionStr) {
				var regObj = {};
				regObj.id = objectIdStr;
				regObj.swfVersion = swfVersionStr;
				regObj.expressInstall = xiSwfUrlStr;
				regObj.callbackFn = callbackFn;
				regObjArr[regObjArr.length] = regObj;
				setVisibility(objectIdStr, false);
			}
			else if (callbackFn) {
				callbackFn({success:false, id:objectIdStr});
			}
		},
		
		getObjectById: function(objectIdStr) {
			if (ua.w3) {
				return getObjectById(objectIdStr);
			}
		},
		
		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
			var callbackObj = {success:false, id:replaceElemIdStr};
			if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					widthStr += ""; // auto-convert to string
					heightStr += "";
					var att = {};
					if (attObj && typeof attObj === OBJECT) {
						for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
							att[i] = attObj[i];
						}
					}
					att.data = swfUrlStr;
					att.width = widthStr;
					att.height = heightStr;
					var par = {}; 
					if (parObj && typeof parObj === OBJECT) {
						for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
							par[j] = parObj[j];
						}
					}
					if (flashvarsObj && typeof flashvarsObj === OBJECT) {
						for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
					if (hasPlayerVersion(swfVersionStr)) { // create SWF
						var obj = createSWF(att, par, replaceElemIdStr);
						if (att.id == replaceElemIdStr) {
							setVisibility(replaceElemIdStr, true);
						}
						callbackObj.success = true;
						callbackObj.ref = obj;
					}
					else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
						att.data = xiSwfUrlStr;
						showExpressInstall(att, par, replaceElemIdStr, callbackFn);
						return;
					}
					else { // show alternative content
						setVisibility(replaceElemIdStr, true);
					}
					if (callbackFn) { callbackFn(callbackObj); }
				});
			}
			else if (callbackFn) { callbackFn(callbackObj);	}
		},
		
		switchOffAutoHideShow: function() {
			autoHideShow = false;
		},
		
		ua: ua,
		
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},
		
		hasFlashPlayerVersion: hasPlayerVersion,
		
		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},
		
		showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
			if (ua.w3 && canExpressInstall()) {
				showExpressInstall(att, par, replaceElemIdStr, callbackFn);
			}
		},
		
		removeSWF: function(objElemIdStr) {
			if (ua.w3) {
				removeSWF(objElemIdStr);
			}
		},
		
		createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
			if (ua.w3) {
				createCSS(selStr, declStr, mediaStr, newStyleBoolean);
			}
		},
		
		addDomLoadEvent: addDomLoadEvent,
		
		addLoadEvent: addLoadEvent,
		
		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (q) {
				if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
				if (param == null) {
					return urlEncodeIfNecessary(q);
				}
				var pairs = q.split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},
		
		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj && storedAltContent) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
					}
					if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
				}
				isExpressInstallActive = false;
			} 
		}
	};
}();
/*!
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){

var 
	// Will speed up references to window, and allows munging its name.
	window = this,
	// Will speed up references to undefined, and allows munging its name.
	undefined,
	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,
	// Map over the $ in case of overwrite
	_$ = window.$,

	jQuery = window.jQuery = window.$ = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context );
	},

	// A simple way to check for HTML strings or ID strings
	// (both of which we optimize for)
	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
	// Is it a simple selector
	isSimple = /^.[^:#\[\.,]*$/;

jQuery.fn = jQuery.prototype = {
	init: function( selector, context ) {
		// Make sure that a selection was provided
		selector = selector || document;

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this[0] = selector;
			this.length = 1;
			this.context = selector;
			return this;
		}
		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			var match = quickExpr.exec( selector );

			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] )
					selector = jQuery.clean( [ match[1] ], context );

				// HANDLE: $("#id")
				else {
					var elem = document.getElementById( match[3] );

					// Handle the case where IE and Opera return items
					// by name instead of ID
					if ( elem && elem.id != match[3] )
						return jQuery().find( selector );

					// Otherwise, we inject the element directly into the jQuery object
					var ret = jQuery( elem || [] );
					ret.context = document;
					ret.selector = selector;
					return ret;
				}

			// HANDLE: $(expr, [context])
			// (which is just equivalent to: $(content).find(expr)
			} else
				return jQuery( context ).find( selector );

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) )
			return jQuery( document ).ready( selector );

		// Make sure that old selector state is passed along
		if ( selector.selector && selector.context ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return this.setArray(jQuery.isArray( selector ) ?
			selector :
			jQuery.makeArray(selector));
	},

	// Start with an empty selector
	selector: "",

	// The current version of jQuery being used
	jquery: "1.3.2",

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num === undefined ?

			// Return a 'clean' array
			Array.prototype.slice.call( this ) :

			// Return just the object
			this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {
		// Build a new jQuery matched element set
		var ret = jQuery( elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		ret.context = this.context;

		if ( name === "find" )
			ret.selector = this.selector + (this.selector ? " " : "") + selector;
		else if ( name )
			ret.selector = this.selector + "." + name + "(" + selector + ")";

		// Return the newly-formed element set
		return ret;
	},

	// Force the current matched set of elements to become
	// the specified array of elements (destroying the stack in the process)
	// You should use pushStack() in order to do this, but maintain the stack
	setArray: function( elems ) {
		// Resetting the length to 0, then using the native Array push
		// is a super-fast way to populate an object with array-like properties
		this.length = 0;
		Array.prototype.push.apply( this, elems );

		return this;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem && elem.jquery ? elem[0] : elem
		, this );
	},

	attr: function( name, value, type ) {
		var options = name;

		// Look for the case where we're accessing a style value
		if ( typeof name === "string" )
			if ( value === undefined )
				return this[0] && jQuery[ type || "attr" ]( this[0], name );

			else {
				options = {};
				options[ name ] = value;
			}

		// Check to see if we're setting style values
		return this.each(function(i){
			// Set all the styles
			for ( name in options )
				jQuery.attr(
					type ?
						this.style :
						this,
					name, jQuery.prop( this, options[ name ], type, i, name )
				);
		});
	},

	css: function( key, value ) {
		// ignore negative width and height values
		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
			value = undefined;
		return this.attr( key, value, "curCSS" );
	},

	text: function( text ) {
		if ( typeof text !== "object" && text != null )
			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

		var ret = "";

		jQuery.each( text || this, function(){
			jQuery.each( this.childNodes, function(){
				if ( this.nodeType != 8 )
					ret += this.nodeType != 1 ?
						this.nodeValue :
						jQuery.fn.text( [ this ] );
			});
		});

		return ret;
	},

	wrapAll: function( html ) {
		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).clone();

			if ( this[0].parentNode )
				wrap.insertBefore( this[0] );

			wrap.map(function(){
				var elem = this;

				while ( elem.firstChild )
					elem = elem.firstChild;

				return elem;
			}).append(this);
		}

		return this;
	},

	wrapInner: function( html ) {
		return this.each(function(){
			jQuery( this ).contents().wrapAll( html );
		});
	},

	wrap: function( html ) {
		return this.each(function(){
			jQuery( this ).wrapAll( html );
		});
	},

	append: function() {
		return this.domManip(arguments, true, function(elem){
			if (this.nodeType == 1)
				this.appendChild( elem );
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, function(elem){
			if (this.nodeType == 1)
				this.insertBefore( elem, this.firstChild );
		});
	},

	before: function() {
		return this.domManip(arguments, false, function(elem){
			this.parentNode.insertBefore( elem, this );
		});
	},

	after: function() {
		return this.domManip(arguments, false, function(elem){
			this.parentNode.insertBefore( elem, this.nextSibling );
		});
	},

	end: function() {
		return this.prevObject || jQuery( [] );
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: [].push,
	sort: [].sort,
	splice: [].splice,

	find: function( selector ) {
		if ( this.length === 1 ) {
			var ret = this.pushStack( [], "find", selector );
			ret.length = 0;
			jQuery.find( selector, this[0], ret );
			return ret;
		} else {
			return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
				return jQuery.find( selector, elem );
			})), "find", selector );
		}
	},

	clone: function( events ) {
		// Do the clone
		var ret = this.map(function(){
			if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
				// IE copies events bound via attachEvent when
				// using cloneNode. Calling detachEvent on the
				// clone will also remove the events from the orignal
				// In order to get around this, we use innerHTML.
				// Unfortunately, this means some modifications to
				// attributes in IE that are actually only stored
				// as properties will not be copied (such as the
				// the name attribute on an input).
				var html = this.outerHTML;
				if ( !html ) {
					var div = this.ownerDocument.createElement("div");
					div.appendChild( this.cloneNode(true) );
					html = div.innerHTML;
				}

				return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
			} else
				return this.cloneNode(true);
		});

		// Copy the events from the original to the clone
		if ( events === true ) {
			var orig = this.find("*").andSelf(), i = 0;

			ret.find("*").andSelf().each(function(){
				if ( this.nodeName !== orig[i].nodeName )
					return;

				var events = jQuery.data( orig[i], "events" );

				for ( var type in events ) {
					for ( var handler in events[ type ] ) {
						jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
					}
				}

				i++;
			});
		}

		// Return the cloned set
		return ret;
	},

	filter: function( selector ) {
		return this.pushStack(
			jQuery.isFunction( selector ) &&
			jQuery.grep(this, function(elem, i){
				return selector.call( elem, i );
			}) ||

			jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
				return elem.nodeType === 1;
			}) ), "filter", selector );
	},

	closest: function( selector ) {
		var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
			closer = 0;

		return this.map(function(){
			var cur = this;
			while ( cur && cur.ownerDocument ) {
				if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
					jQuery.data(cur, "closest", closer);
					return cur;
				}
				cur = cur.parentNode;
				closer++;
			}
		});
	},

	not: function( selector ) {
		if ( typeof selector === "string" )
			// test special case where just one selector is passed in
			if ( isSimple.test( selector ) )
				return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
			else
				selector = jQuery.multiFilter( selector, this );

		var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
		return this.filter(function() {
			return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
		});
	},

	add: function( selector ) {
		return this.pushStack( jQuery.unique( jQuery.merge(
			this.get(),
			typeof selector === "string" ?
				jQuery( selector ) :
				jQuery.makeArray( selector )
		)));
	},

	is: function( selector ) {
		return !!selector && jQuery.multiFilter( selector, this ).length > 0;
	},

	hasClass: function( selector ) {
		return !!selector && this.is( "." + selector );
	},

	val: function( value ) {
		if ( value === undefined ) {			
			var elem = this[0];

			if ( elem ) {
				if( jQuery.nodeName( elem, 'option' ) )
					return (elem.attributes.value || {}).specified ? elem.value : elem.text;
				
				// We need to handle select boxes special
				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type == "select-one";

					// Nothing was selected
					if ( index < 0 )
						return null;

					// Loop through all the selected options
					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
						var option = options[ i ];

						if ( option.selected ) {
							// Get the specifc value for the option
							value = jQuery(option).val();

							// We don't need an array for one selects
							if ( one )
								return value;

							// Multi-Selects return an array
							values.push( value );
						}
					}

					return values;				
				}

				// Everything else, we just grab the value
				return (elem.value || "").replace(/\r/g, "");

			}

			return undefined;
		}

		if ( typeof value === "number" )
			value += '';

		return this.each(function(){
			if ( this.nodeType != 1 )
				return;

			if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
				this.checked = (jQuery.inArray(this.value, value) >= 0 ||
					jQuery.inArray(this.name, value) >= 0);

			else if ( jQuery.nodeName( this, "select" ) ) {
				var values = jQuery.makeArray(value);

				jQuery( "option", this ).each(function(){
					this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
						jQuery.inArray( this.text, values ) >= 0);
				});

				if ( !values.length )
					this.selectedIndex = -1;

			} else
				this.value = value;
		});
	},

	html: function( value ) {
		return value === undefined ?
			(this[0] ?
				this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
				null) :
			this.empty().append( value );
	},

	replaceWith: function( value ) {
		return this.after( value ).remove();
	},

	eq: function( i ) {
		return this.slice( i, +i + 1 );
	},

	slice: function() {
		return this.pushStack( Array.prototype.slice.apply( this, arguments ),
			"slice", Array.prototype.slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function(elem, i){
			return callback.call( elem, i, elem );
		}));
	},

	andSelf: function() {
		return this.add( this.prevObject );
	},

	domManip: function( args, table, callback ) {
		if ( this[0] ) {
			var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
				scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
				first = fragment.firstChild;

			if ( first )
				for ( var i = 0, l = this.length; i < l; i++ )
					callback.call( root(this[i], first), this.length > 1 || i > 0 ?
							fragment.cloneNode(true) : fragment );
		
			if ( scripts )
				jQuery.each( scripts, evalScript );
		}

		return this;
		
		function root( elem, cur ) {
			return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
				(elem.getElementsByTagName("tbody")[0] ||
				elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
				elem;
		}
	}
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

function evalScript( i, elem ) {
	if ( elem.src )
		jQuery.ajax({
			url: elem.src,
			async: false,
			dataType: "script"
		});

	else
		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );

	if ( elem.parentNode )
		elem.parentNode.removeChild( elem );
}

function now(){
	return +new Date;
}

jQuery.extend = jQuery.fn.extend = function() {
	// copy reference to target object
	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) )
		target = {};

	// extend jQuery itself if only one argument is passed
	if ( length == i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ )
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null )
			// Extend the base object
			for ( var name in options ) {
				var src = target[ name ], copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy )
					continue;

				// Recurse if we're merging object values
				if ( deep && copy && typeof copy === "object" && !copy.nodeType )
					target[ name ] = jQuery.extend( deep, 
						// Never move original objects, clone them
						src || ( copy.length != null ? [ ] : { } )
					, copy );

				// Don't bring in undefined values
				else if ( copy !== undefined )
					target[ name ] = copy;

			}

	// Return the modified object
	return target;
};

// exclude the following css properties to add px
var	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
	// cache defaultView
	defaultView = document.defaultView || {},
	toString = Object.prototype.toString;

jQuery.extend({
	noConflict: function( deep ) {
		window.$ = _$;

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return toString.call(obj) === "[object Function]";
	},

	isArray: function( obj ) {
		return toString.call(obj) === "[object Array]";
	},

	// check if an element is in a (or is an) XML document
	isXMLDoc: function( elem ) {
		return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
			!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
	},

	// Evalulates a script in a global context
	globalEval: function( data ) {
		if ( data && /\S/.test(data) ) {
			// Inspired by code by Andrea Giammarchi
			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
			var head = document.getElementsByTagName("head")[0] || document.documentElement,
				script = document.createElement("script");

			script.type = "text/javascript";
			if ( jQuery.support.scriptEval )
				script.appendChild( document.createTextNode( data ) );
			else
				script.text = data;

			// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
			// This arises when a base node is used (#2709).
			head.insertBefore( script, head.firstChild );
			head.removeChild( script );
		}
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
	},

	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0, length = object.length;

		if ( args ) {
			if ( length === undefined ) {
				for ( name in object )
					if ( callback.apply( object[ name ], args ) === false )
						break;
			} else
				for ( ; i < length; )
					if ( callback.apply( object[ i++ ], args ) === false )
						break;

		// A special, fast, case for the most common use of each
		} else {
			if ( length === undefined ) {
				for ( name in object )
					if ( callback.call( object[ name ], name, object[ name ] ) === false )
						break;
			} else
				for ( var value = object[0];
					i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
		}

		return object;
	},

	prop: function( elem, value, type, i, name ) {
		// Handle executable functions
		if ( jQuery.isFunction( value ) )
			value = value.call( elem, i );

		// Handle passing in a number to a CSS property
		return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
			value + "px" :
			value;
	},

	className: {
		// internal only, use addClass("class")
		add: function( elem, classNames ) {
			jQuery.each((classNames || "").split(/\s+/), function(i, className){
				if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
					elem.className += (elem.className ? " " : "") + className;
			});
		},

		// internal only, use removeClass("class")
		remove: function( elem, classNames ) {
			if (elem.nodeType == 1)
				elem.className = classNames !== undefined ?
					jQuery.grep(elem.className.split(/\s+/), function(className){
						return !jQuery.className.has( classNames, className );
					}).join(" ") :
					"";
		},

		// internal only, use hasClass("class")
		has: function( elem, className ) {
			return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};
		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( var name in options )
			elem.style[ name ] = old[ name ];
	},

	css: function( elem, name, force, extra ) {
		if ( name == "width" || name == "height" ) {
			var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];

			function getWH() {
				val = name == "width" ? elem.offsetWidth : elem.offsetHeight;

				if ( extra === "border" )
					return;

				jQuery.each( which, function() {
					if ( !extra )
						val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
					if ( extra === "margin" )
						val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
					else
						val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
				});
			}

			if ( elem.offsetWidth !== 0 )
				getWH();
			else
				jQuery.swap( elem, props, getWH );

			return Math.max(0, Math.round(val));
		}

		return jQuery.curCSS( elem, name, force );
	},

	curCSS: function( elem, name, force ) {
		var ret, style = elem.style;

		// We need to handle opacity special in IE
		if ( name == "opacity" && !jQuery.support.opacity ) {
			ret = jQuery.attr( style, "opacity" );

			return ret == "" ?
				"1" :
				ret;
		}

		// Make sure we're using the right name for getting the float value
		if ( name.match( /float/i ) )
			name = styleFloat;

		if ( !force && style && style[ name ] )
			ret = style[ name ];

		else if ( defaultView.getComputedStyle ) {

			// Only "float" is needed here
			if ( name.match( /float/i ) )
				name = "float";

			name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();

			var computedStyle = defaultView.getComputedStyle( elem, null );

			if ( computedStyle )
				ret = computedStyle.getPropertyValue( name );

			// We should always get a number back from opacity
			if ( name == "opacity" && ret == "" )
				ret = "1";

		} else if ( elem.currentStyle ) {
			var camelCase = name.replace(/\-(\w)/g, function(all, letter){
				return letter.toUpperCase();
			});

			ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];

			// From the awesome hack by Dean Edwards
			// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

			// If we're not dealing with a regular pixel number
			// but a number that has a weird ending, we need to convert it to pixels
			if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
				// Remember the original values
				var left = style.left, rsLeft = elem.runtimeStyle.left;

				// Put in the new values to get a computed value out
				elem.runtimeStyle.left = elem.currentStyle.left;
				style.left = ret || 0;
				ret = style.pixelLeft + "px";

				// Revert the changed values
				style.left = left;
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret;
	},

	clean: function( elems, context, fragment ) {
		context = context || document;

		// !context.createElement fails in IE with an error but returns typeof 'object'
		if ( typeof context.createElement === "undefined" )
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

		// If a single string is passed in and it's a single tag
		// just do a createElement and skip the rest
		if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
			var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
			if ( match )
				return [ context.createElement( match[1] ) ];
		}

		var ret = [], scripts = [], div = context.createElement("div");

		jQuery.each(elems, function(i, elem){
			if ( typeof elem === "number" )
				elem += '';

			if ( !elem )
				return;

			// Convert html string into DOM nodes
			if ( typeof elem === "string" ) {
				// Fix "XHTML"-style tags in all browsers
				elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
					return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
						all :
						front + "></" + tag + ">";
				});

				// Trim whitespace, otherwise indexOf won't work as expected
				var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();

				var wrap =
					// option or optgroup
					!tags.indexOf("<opt") &&
					[ 1, "<select multiple='multiple'>", "</select>" ] ||

					!tags.indexOf("<leg") &&
					[ 1, "<fieldset>", "</fieldset>" ] ||

					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
					[ 1, "<table>", "</table>" ] ||

					!tags.indexOf("<tr") &&
					[ 2, "<table><tbody>", "</tbody></table>" ] ||

				 	// <thead> matched above
					(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
					[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||

					!tags.indexOf("<col") &&
					[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||

					// IE can't serialize <link> and <script> tags normally
					!jQuery.support.htmlSerialize &&
					[ 1, "div<div>", "</div>" ] ||

					[ 0, "", "" ];

				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + elem + wrap[2];

				// Move to the right depth
				while ( wrap[0]-- )
					div = div.lastChild;

				// Remove IE's autoinserted <tbody> from table fragments
				if ( !jQuery.support.tbody ) {

					// String was a <table>, *may* have spurious <tbody>
					var hasBody = /<tbody/i.test(elem),
						tbody = !tags.indexOf("<table") && !hasBody ?
							div.firstChild && div.firstChild.childNodes :

						// String was a bare <thead> or <tfoot>
						wrap[1] == "<table>" && !hasBody ?
							div.childNodes :
							[];

					for ( var j = tbody.length - 1; j >= 0 ; --j )
						if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
							tbody[ j ].parentNode.removeChild( tbody[ j ] );

					}

				// IE completely kills leading whitespace when innerHTML is used
				if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
					div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
				
				elem = jQuery.makeArray( div.childNodes );
			}

			if ( elem.nodeType )
				ret.push( elem );
			else
				ret = jQuery.merge( ret, elem );

		});

		if ( fragment ) {
			for ( var i = 0; ret[i]; i++ ) {
				if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
				} else {
					if ( ret[i].nodeType === 1 )
						ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
					fragment.appendChild( ret[i] );
				}
			}
			
			return scripts;
		}

		return ret;
	},

	attr: function( elem, name, value ) {
		// don't set attributes on text and comment nodes
		if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
			return undefined;

		var notxml = !jQuery.isXMLDoc( elem ),
			// Whether we are setting (or getting)
			set = value !== undefined;

		// Try to normalize/fix the name
		name = notxml && jQuery.props[ name ] || name;

		// Only do all the following if this is a node (faster for style)
		// IE elem.getAttribute passes even for style
		if ( elem.tagName ) {

			// These attributes require special treatment
			var special = /href|src|style/.test( name );

			// Safari mis-reports the default selected property of a hidden option
			// Accessing the parent's selectedIndex property fixes it
			if ( name == "selected" && elem.parentNode )
				elem.parentNode.selectedIndex;

			// If applicable, access the attribute via the DOM 0 way
			if ( name in elem && notxml && !special ) {
				if ( set ){
					// We can't allow the type property to be changed (since it causes problems in IE)
					if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
						throw "type property can't be changed";

					elem[ name ] = value;
				}

				// browsers index elements by id/name on forms, give priority to attributes.
				if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
					return elem.getAttributeNode( name ).nodeValue;

				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				if ( name == "tabIndex" ) {
					var attributeNode = elem.getAttributeNode( "tabIndex" );
					return attributeNode && attributeNode.specified
						? attributeNode.value
						: elem.nodeName.match(/(button|input|object|select|textarea)/i)
							? 0
							: elem.nodeName.match(/^(a|area)$/i) && elem.href
								? 0
								: undefined;
				}

				return elem[ name ];
			}

			if ( !jQuery.support.style && notxml &&  name == "style" )
				return jQuery.attr( elem.style, "cssText", value );

			if ( set )
				// convert the value to a string (all browsers do this but IE) see #1070
				elem.setAttribute( name, "" + value );

			var attr = !jQuery.support.hrefNormalized && notxml && special
					// Some attributes require a special call on IE
					? elem.getAttribute( name, 2 )
					: elem.getAttribute( name );

			// Non-existent attributes return null, we normalize to undefined
			return attr === null ? undefined : attr;
		}

		// elem is actually elem.style ... set the style

		// IE uses filters for opacity
		if ( !jQuery.support.opacity && name == "opacity" ) {
			if ( set ) {
				// IE has trouble with opacity if it does not have layout
				// Force it by setting the zoom level
				elem.zoom = 1;

				// Set the alpha filter to set the opacity
				elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
					(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
			}

			return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
				(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
				"";
		}

		name = name.replace(/-([a-z])/ig, function(all, letter){
			return letter.toUpperCase();
		});

		if ( set )
			elem[ name ] = value;

		return elem[ name ];
	},

	trim: function( text ) {
		return (text || "").replace( /^\s+|\s+$/g, "" );
	},

	makeArray: function( array ) {
		var ret = [];

		if( array != null ){
			var i = array.length;
			// The window, strings (and functions) also have 'length'
			if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
				ret[0] = array;
			else
				while( i )
					ret[--i] = array[i];
		}

		return ret;
	},

	inArray: function( elem, array ) {
		for ( var i = 0, length = array.length; i < length; i++ )
		// Use === because on IE, window == document
			if ( array[ i ] === elem )
				return i;

		return -1;
	},

	merge: function( first, second ) {
		// We have to loop this way because IE & Opera overwrite the length
		// expando of getElementsByTagName
		var i = 0, elem, pos = first.length;
		// Also, we need to make sure that the correct elements are being returned
		// (IE returns comment nodes in a '*' query)
		if ( !jQuery.support.getAll ) {
			while ( (elem = second[ i++ ]) != null )
				if ( elem.nodeType != 8 )
					first[ pos++ ] = elem;

		} else
			while ( (elem = second[ i++ ]) != null )
				first[ pos++ ] = elem;

		return first;
	},

	unique: function( array ) {
		var ret = [], done = {};

		try {

			for ( var i = 0, length = array.length; i < length; i++ ) {
				var id = jQuery.data( array[ i ] );

				if ( !done[ id ] ) {
					done[ id ] = true;
					ret.push( array[ i ] );
				}
			}

		} catch( e ) {
			ret = array;
		}

		return ret;
	},

	grep: function( elems, callback, inv ) {
		var ret = [];

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ )
			if ( !inv != !callback( elems[ i ], i ) )
				ret.push( elems[ i ] );

		return ret;
	},

	map: function( elems, callback ) {
		var ret = [];

		// Go through the array, translating each of the items to their
		// new value (or values).
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			var value = callback( elems[ i ], i );

			if ( value != null )
				ret[ ret.length ] = value;
		}

		return ret.concat.apply( [], ret );
	}
});

// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
	safari: /webkit/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

jQuery.each({
	parent: function(elem){return elem.parentNode;},
	parents: function(elem){return jQuery.dir(elem,"parentNode");},
	next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
	prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
	nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
	prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
	siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
	children: function(elem){return jQuery.sibling(elem.firstChild);},
	contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
	jQuery.fn[ name ] = function( selector ) {
		var ret = jQuery.map( this, fn );

		if ( selector && typeof selector == "string" )
			ret = jQuery.multiFilter( selector, ret );

		return this.pushStack( jQuery.unique( ret ), name, selector );
	};
});

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function(name, original){
	jQuery.fn[ name ] = function( selector ) {
		var ret = [], insert = jQuery( selector );

		for ( var i = 0, l = insert.length; i < l; i++ ) {
			var elems = (i > 0 ? this.clone(true) : this).get();
			jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
			ret = ret.concat( elems );
		}

		return this.pushStack( ret, name, selector );
	};
});

jQuery.each({
	removeAttr: function( name ) {
		jQuery.attr( this, name, "" );
		if (this.nodeType == 1)
			this.removeAttribute( name );
	},

	addClass: function( classNames ) {
		jQuery.className.add( this, classNames );
	},

	removeClass: function( classNames ) {
		jQuery.className.remove( this, classNames );
	},

	toggleClass: function( classNames, state ) {
		if( typeof state !== "boolean" )
			state = !jQuery.className.has( this, classNames );
		jQuery.className[ state ? "add" : "remove" ]( this, classNames );
	},

	remove: function( selector ) {
		if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
			// Prevent memory leaks
			jQuery( "*", this ).add([this]).each(function(){
				jQuery.event.remove(this);
				jQuery.removeData(this);
			});
			if (this.parentNode)
				this.parentNode.removeChild( this );
		}
	},

	empty: function() {
		// Remove element nodes and prevent memory leaks
		jQuery(this).children().remove();

		// Remove any remaining nodes
		while ( this.firstChild )
			this.removeChild( this.firstChild );
	}
}, function(name, fn){
	jQuery.fn[ name ] = function(){
		return this.each( fn, arguments );
	};
});

// Helper function used by the dimensions and offset modules
function num(elem, prop) {
	return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};

jQuery.extend({
	cache: {},

	data: function( elem, name, data ) {
		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ];

		// Compute a unique ID for the element
		if ( !id )
			id = elem[ expando ] = ++uuid;

		// Only generate the data cache if we're
		// trying to access or manipulate it
		if ( name && !jQuery.cache[ id ] )
			jQuery.cache[ id ] = {};

		// Prevent overriding the named cache with undefined values
		if ( data !== undefined )
			jQuery.cache[ id ][ name ] = data;

		// Return the named cache data, or the ID for the element
		return name ?
			jQuery.cache[ id ][ name ] :
			id;
	},

	removeData: function( elem, name ) {
		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ];

		// If we want to remove a specific section of the element's data
		if ( name ) {
			if ( jQuery.cache[ id ] ) {
				// Remove the section of cache data
				delete jQuery.cache[ id ][ name ];

				// If we've removed all the data, remove the element's cache
				name = "";

				for ( name in jQuery.cache[ id ] )
					break;

				if ( !name )
					jQuery.removeData( elem );
			}

		// Otherwise, we want to remove all of the element's data
		} else {
			// Clean up the element expando
			try {
				delete elem[ expando ];
			} catch(e){
				// IE has trouble directly removing the expando
				// but it's ok with using removeAttribute
				if ( elem.removeAttribute )
					elem.removeAttribute( expando );
			}

			// Completely remove the data cache
			delete jQuery.cache[ id ];
		}
	},
	queue: function( elem, type, data ) {
		if ( elem ){
	
			type = (type || "fx") + "queue";
	
			var q = jQuery.data( elem, type );
	
			if ( !q || jQuery.isArray(data) )
				q = jQuery.data( elem, type, jQuery.makeArray(data) );
			else if( data )
				q.push( data );
	
		}
		return q;
	},

	dequeue: function( elem, type ){
		var queue = jQuery.queue( elem, type ),
			fn = queue.shift();
		
		if( !type || type === "fx" )
			fn = queue[0];
			
		if( fn !== undefined )
			fn.call(elem);
	}
});

jQuery.fn.extend({
	data: function( key, value ){
		var parts = key.split(".");
		parts[1] = parts[1] ? "." + parts[1] : "";

		if ( value === undefined ) {
			var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

			if ( data === undefined && this.length )
				data = jQuery.data( this[0], key );

			return data === undefined && parts[1] ?
				this.data( parts[0] ) :
				data;
		} else
			return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
				jQuery.data( this, key, value );
			});
	},

	removeData: function( key ){
		return this.each(function(){
			jQuery.removeData( this, key );
		});
	},
	queue: function(type, data){
		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
		}

		if ( data === undefined )
			return jQuery.queue( this[0], type );

		return this.each(function(){
			var queue = jQuery.queue( this, type, data );
			
			 if( type == "fx" && queue.length == 1 )
				queue[0].call(this);
		});
	},
	dequeue: function(type){
		return this.each(function(){
			jQuery.dequeue( this, type );
		});
	}
});/*!
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
	done = 0,
	toString = Object.prototype.toString;

var Sizzle = function(selector, context, results, seed) {
	results = results || [];
	context = context || document;

	if ( context.nodeType !== 1 && context.nodeType !== 9 )
		return [];
	
	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	var parts = [], m, set, checkSet, check, mode, extra, prune = true;
	
	// Reset the position of the chunker regexp (start from head)
	chunker.lastIndex = 0;
	
	while ( (m = chunker.exec(selector)) !== null ) {
		parts.push( m[1] );
		
		if ( m[2] ) {
			extra = RegExp.rightContext;
			break;
		}
	}

	if ( parts.length > 1 && origPOS.exec( selector ) ) {
		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
			set = posProcess( parts[0] + parts[1], context );
		} else {
			set = Expr.relative[ parts[0] ] ?
				[ context ] :
				Sizzle( parts.shift(), context );

			while ( parts.length ) {
				selector = parts.shift();

				if ( Expr.relative[ selector ] )
					selector += parts.shift();

				set = posProcess( selector, set );
			}
		}
	} else {
		var ret = seed ?
			{ expr: parts.pop(), set: makeArray(seed) } :
			Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
		set = Sizzle.filter( ret.expr, ret.set );

		if ( parts.length > 0 ) {
			checkSet = makeArray(set);
		} else {
			prune = false;
		}

		while ( parts.length ) {
			var cur = parts.pop(), pop = cur;

			if ( !Expr.relative[ cur ] ) {
				cur = "";
			} else {
				pop = parts.pop();
			}

			if ( pop == null ) {
				pop = context;
			}

			Expr.relative[ cur ]( checkSet, pop, isXML(context) );
		}
	}

	if ( !checkSet ) {
		checkSet = set;
	}

	if ( !checkSet ) {
		throw "Syntax error, unrecognized expression: " + (cur || selector);
	}

	if ( toString.call(checkSet) === "[object Array]" ) {
		if ( !prune ) {
			results.push.apply( results, checkSet );
		} else if ( context.nodeType === 1 ) {
			for ( var i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
					results.push( set[i] );
				}
			}
		} else {
			for ( var i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
					results.push( set[i] );
				}
			}
		}
	} else {
		makeArray( checkSet, results );
	}

	if ( extra ) {
		Sizzle( extra, context, results, seed );

		if ( sortOrder ) {
			hasDuplicate = false;
			results.sort(sortOrder);

			if ( hasDuplicate ) {
				for ( var i = 1; i < results.length; i++ ) {
					if ( results[i] === results[i-1] ) {
						results.splice(i--, 1);
					}
				}
			}
		}
	}

	return results;
};

Sizzle.matches = function(expr, set){
	return Sizzle(expr, null, null, set);
};

Sizzle.find = function(expr, context, isXML){
	var set, match;

	if ( !expr ) {
		return [];
	}

	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
		var type = Expr.order[i], match;
		
		if ( (match = Expr.match[ type ].exec( expr )) ) {
			var left = RegExp.leftContext;

			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace(/\\/g, "");
				set = Expr.find[ type ]( match, context, isXML );
				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}

	if ( !set ) {
		set = context.getElementsByTagName("*");
	}

	return {set: set, expr: expr};
};

Sizzle.filter = function(expr, set, inplace, not){
	var old = expr, result = [], curLoop = set, match, anyFound,
		isXMLFilter = set && set[0] && isXML(set[0]);

	while ( expr && set.length ) {
		for ( var type in Expr.filter ) {
			if ( (match = Expr.match[ type ].exec( expr )) != null ) {
				var filter = Expr.filter[ type ], found, item;
				anyFound = false;

				if ( curLoop == result ) {
					result = [];
				}

				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

					if ( !match ) {
						anyFound = found = true;
					} else if ( match === true ) {
						continue;
					}
				}

				if ( match ) {
					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							var pass = not ^ !!found;

							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;
								} else {
									curLoop[i] = false;
								}
							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}

				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}

					expr = expr.replace( Expr.match[ type ], "" );

					if ( !anyFound ) {
						return [];
					}

					break;
				}
			}
		}

		// Improper expression
		if ( expr == old ) {
			if ( anyFound == null ) {
				throw "Syntax error, unrecognized expression: " + expr;
			} else {
				break;
			}
		}

		old = expr;
	}

	return curLoop;
};

var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],
	match: {
		ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
	},
	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},
	attrHandle: {
		href: function(elem){
			return elem.getAttribute("href");
		}
	},
	relative: {
		"+": function(checkSet, part, isXML){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !/\W/.test(part),
				isPartStrNotTag = isPartStr && !isTag;

			if ( isTag && !isXML ) {
				part = part.toUpperCase();
			}

			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

					checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
						elem || false :
						elem === part;
				}
			}

			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},
		">": function(checkSet, part, isXML){
			var isPartStr = typeof part === "string";

			if ( isPartStr && !/\W/.test(part) ) {
				part = isXML ? part : part.toUpperCase();

				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
					var elem = checkSet[i];
					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName === part ? parent : false;
					}
				}
			} else {
				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
					var elem = checkSet[i];
					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},
		"": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck;

			if ( !part.match(/\W/) ) {
				var nodeCheck = part = isXML ? part : part.toUpperCase();
				checkFn = dirNodeCheck;
			}

			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
		},
		"~": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck;

			if ( typeof part === "string" && !part.match(/\W/) ) {
				var nodeCheck = part = isXML ? part : part.toUpperCase();
				checkFn = dirNodeCheck;
			}

			checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
		}
	},
	find: {
		ID: function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? [m] : [];
			}
		},
		NAME: function(match, context, isXML){
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [], results = context.getElementsByName(match[1]);

				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}

				return ret.length === 0 ? null : ret;
			}
		},
		TAG: function(match, context){
			return context.getElementsByTagName(match[1]);
		}
	},
	preFilter: {
		CLASS: function(match, curLoop, inplace, result, not, isXML){
			match = " " + match[1].replace(/\\/g, "") + " ";

			if ( isXML ) {
				return match;
			}

			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
						if ( !inplace )
							result.push( elem );
					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}

			return false;
		},
		ID: function(match){
			return match[1].replace(/\\/g, "");
		},
		TAG: function(match, curLoop){
			for ( var i = 0; curLoop[i] === false; i++ ){}
			return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
		},
		CHILD: function(match){
			if ( match[1] == "nth" ) {
				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
				var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
					match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

				// calculate the numbers (first)n+(last) including if they are negative
				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}

			// TODO: Move to normal caching system
			match[0] = done++;

			return match;
		},
		ATTR: function(match, curLoop, inplace, result, not, isXML){
			var name = match[1].replace(/\\/g, "");
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

			if ( match[2] === "~=" ) {
				match[4] = " " + match[4] + " ";
			}

			return match;
		},
		PSEUDO: function(match, curLoop, inplace, result, not){
			if ( match[1] === "not" ) {
				// If we're dealing with a complex expression, or a simple one
				if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
					match[3] = Sizzle(match[3], null, null, curLoop);
				} else {
					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
					if ( !inplace ) {
						result.push.apply( result, ret );
					}
					return false;
				}
			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
				return true;
			}
			
			return match;
		},
		POS: function(match){
			match.unshift( true );
			return match;
		}
	},
	filters: {
		enabled: function(elem){
			return elem.disabled === false && elem.type !== "hidden";
		},
		disabled: function(elem){
			return elem.disabled === true;
		},
		checked: function(elem){
			return elem.checked === true;
		},
		selected: function(elem){
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			elem.parentNode.selectedIndex;
			return elem.selected === true;
		},
		parent: function(elem){
			return !!elem.firstChild;
		},
		empty: function(elem){
			return !elem.firstChild;
		},
		has: function(elem, i, match){
			return !!Sizzle( match[3], elem ).length;
		},
		header: function(elem){
			return /h\d/i.test( elem.nodeName );
		},
		text: function(elem){
			return "text" === elem.type;
		},
		radio: function(elem){
			return "radio" === elem.type;
		},
		checkbox: function(elem){
			return "checkbox" === elem.type;
		},
		file: function(elem){
			return "file" === elem.type;
		},
		password: function(elem){
			return "password" === elem.type;
		},
		submit: function(elem){
			return "submit" === elem.type;
		},
		image: function(elem){
			return "image" === elem.type;
		},
		reset: function(elem){
			return "reset" === elem.type;
		},
		button: function(elem){
			return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
		},
		input: function(elem){
			return /input|select|textarea|button/i.test(elem.nodeName);
		}
	},
	setFilters: {
		first: function(elem, i){
			return i === 0;
		},
		last: function(elem, i, match, array){
			return i === array.length - 1;
		},
		even: function(elem, i){
			return i % 2 === 0;
		},
		odd: function(elem, i){
			return i % 2 === 1;
		},
		lt: function(elem, i, match){
			return i < match[3] - 0;
		},
		gt: function(elem, i, match){
			return i > match[3] - 0;
		},
		nth: function(elem, i, match){
			return match[3] - 0 == i;
		},
		eq: function(elem, i, match){
			return match[3] - 0 == i;
		}
	},
	filter: {
		PSEUDO: function(elem, match, i, array){
			var name = match[1], filter = Expr.filters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
			} else if ( name === "not" ) {
				var not = match[3];

				for ( var i = 0, l = not.length; i < l; i++ ) {
					if ( not[i] === elem ) {
						return false;
					}
				}

				return true;
			}
		},
		CHILD: function(elem, match){
			var type = match[1], node = elem;
			switch (type) {
				case 'only':
				case 'first':
					while (node = node.previousSibling)  {
						if ( node.nodeType === 1 ) return false;
					}
					if ( type == 'first') return true;
					node = elem;
				case 'last':
					while (node = node.nextSibling)  {
						if ( node.nodeType === 1 ) return false;
					}
					return true;
				case 'nth':
					var first = match[2], last = match[3];

					if ( first == 1 && last == 0 ) {
						return true;
					}
					
					var doneName = match[0],
						parent = elem.parentNode;
	
					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
						var count = 0;
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 
						parent.sizcache = doneName;
					}
					
					var diff = elem.nodeIndex - last;
					if ( first == 0 ) {
						return diff == 0;
					} else {
						return ( diff % first == 0 && diff / first >= 0 );
					}
			}
		},
		ID: function(elem, match){
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},
		TAG: function(elem, match){
			return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
		},
		CLASS: function(elem, match){
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},
		ATTR: function(elem, match){
			var name = match[1],
				result = Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];

			return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value != check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},
		POS: function(elem, match, i, array){
			var name = match[2], filter = Expr.setFilters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			}
		}
	}
};

var origPOS = Expr.match.POS;

for ( var type in Expr.match ) {
	Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}

var makeArray = function(array, results) {
	array = Array.prototype.slice.call( array );

	if ( results ) {
		results.push.apply( results, array );
		return results;
	}
	
	return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
try {
	Array.prototype.slice.call( document.documentElement.childNodes );

// Provide a fallback method if it does not work
} catch(e){
	makeArray = function(array, results) {
		var ret = results || [];

		if ( toString.call(array) === "[object Array]" ) {
			Array.prototype.push.apply( ret, array );
		} else {
			if ( typeof array.length === "number" ) {
				for ( var i = 0, l = array.length; i < l; i++ ) {
					ret.push( array[i] );
				}
			} else {
				for ( var i = 0; array[i]; i++ ) {
					ret.push( array[i] );
				}
			}
		}

		return ret;
	};
}

var sortOrder;

if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( "sourceIndex" in document.documentElement ) {
	sortOrder = function( a, b ) {
		var ret = a.sourceIndex - b.sourceIndex;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( document.createRange ) {
	sortOrder = function( a, b ) {
		var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
		aRange.selectNode(a);
		aRange.collapse(true);
		bRange.selectNode(b);
		bRange.collapse(true);
		var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
}

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
	// We're going to inject a fake input element with a specified name
	var form = document.createElement("form"),
		id = "script" + (new Date).getTime();
	form.innerHTML = "<input name='" + id + "'/>";

	// Inject it into the root element, check its status, and remove it quickly
	var root = document.documentElement;
	root.insertBefore( form, root.firstChild );

	// The workaround has to do additional checks after a getElementById
	// Which slows things down for other browsers (hence the branching)
	if ( !!document.getElementById( id ) ) {
		Expr.find.ID = function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
			}
		};

		Expr.filter.ID = function(elem, match){
			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
			return elem.nodeType === 1 && node && node.nodeValue === match;
		};
	}

	root.removeChild( form );
})();

(function(){
	// Check to see if the browser returns only elements
	// when doing getElementsByTagName("*")

	// Create a fake element
	var div = document.createElement("div");
	div.appendChild( document.createComment("") );

	// Make sure no comments are found
	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function(match, context){
			var results = context.getElementsByTagName(match[1]);

			// Filter out possible comments
			if ( match[1] === "*" ) {
				var tmp = [];

				for ( var i = 0; results[i]; i++ ) {
					if ( results[i].nodeType === 1 ) {
						tmp.push( results[i] );
					}
				}

				results = tmp;
			}

			return results;
		};
	}

	// Check to see if an attribute returns normalized href attributes
	div.innerHTML = "<a href='#'></a>";
	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#" ) {
		Expr.attrHandle.href = function(elem){
			return elem.getAttribute("href", 2);
		};
	}
})();

if ( document.querySelectorAll ) (function(){
	var oldSizzle = Sizzle, div = document.createElement("div");
	div.innerHTML = "<p class='TEST'></p>";

	// Safari can't handle uppercase or unicode characters when
	// in quirks mode.
	if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
		return;
	}
	
	Sizzle = function(query, context, extra, seed){
		context = context || document;

		// Only use querySelectorAll on non-XML documents
		// (ID selectors don't work in non-HTML documents)
		if ( !seed && context.nodeType === 9 && !isXML(context) ) {
			try {
				return makeArray( context.querySelectorAll(query), extra );
			} catch(e){}
		}
		
		return oldSizzle(query, context, extra, seed);
	};

	Sizzle.find = oldSizzle.find;
	Sizzle.filter = oldSizzle.filter;
	Sizzle.selectors = oldSizzle.selectors;
	Sizzle.matches = oldSizzle.matches;
})();

if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
	var div = document.createElement("div");
	div.innerHTML = "<div class='test e'></div><div class='test'></div>";

	// Opera can't find a second classname (in 9.6)
	if ( div.getElementsByClassName("e").length === 0 )
		return;

	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";

	if ( div.getElementsByClassName("e").length === 1 )
		return;

	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function(match, context, isXML) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};
})();

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	var sibDir = dir == "previousSibling" && !isXML;
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			if ( sibDir && elem.nodeType === 1 ){
				elem.sizcache = doneName;
				elem.sizset = i;
			}
			elem = elem[dir];
			var match = false;

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 && !isXML ){
					elem.sizcache = doneName;
					elem.sizset = i;
				}

				if ( elem.nodeName === cur ) {
					match = elem;
					break;
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	var sibDir = dir == "previousSibling" && !isXML;
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			if ( sibDir && elem.nodeType === 1 ) {
				elem.sizcache = doneName;
				elem.sizset = i;
			}
			elem = elem[dir];
			var match = false;

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem.sizcache = doneName;
						elem.sizset = i;
					}
					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
						match = elem;
						break;
					}
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

var contains = document.compareDocumentPosition ?  function(a, b){
	return a.compareDocumentPosition(b) & 16;
} : function(a, b){
	return a !== b && (a.contains ? a.contains(b) : true);
};

var isXML = function(elem){
	return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
		!!elem.ownerDocument && isXML( elem.ownerDocument );
};

var posProcess = function(selector, context){
	var tmpSet = [], later = "", match,
		root = context.nodeType ? [context] : context;

	// Position selectors must be done after the filter
	// And so must :not(positional) so we move all PSEUDOs to the end
	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
		later += match[0];
		selector = selector.replace( Expr.match.PSEUDO, "" );
	}

	selector = Expr.relative[selector] ? selector + "*" : selector;

	for ( var i = 0, l = root.length; i < l; i++ ) {
		Sizzle( selector, root[i], tmpSet );
	}

	return Sizzle.filter( later, tmpSet );
};

// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;

Sizzle.selectors.filters.hidden = function(elem){
	return elem.offsetWidth === 0 || elem.offsetHeight === 0;
};

Sizzle.selectors.filters.visible = function(elem){
	return elem.offsetWidth > 0 || elem.offsetHeight > 0;
};

Sizzle.selectors.filters.animated = function(elem){
	return jQuery.grep(jQuery.timers, function(fn){
		return elem === fn.elem;
	}).length;
};

jQuery.multiFilter = function( expr, elems, not ) {
	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	return Sizzle.matches(expr, elems);
};

jQuery.dir = function( elem, dir ){
	var matched = [], cur = elem[dir];
	while ( cur && cur != document ) {
		if ( cur.nodeType == 1 )
			matched.push( cur );
		cur = cur[dir];
	}
	return matched;
};

jQuery.nth = function(cur, result, dir, elem){
	result = result || 1;
	var num = 0;

	for ( ; cur; cur = cur[dir] )
		if ( cur.nodeType == 1 && ++num == result )
			break;

	return cur;
};

jQuery.sibling = function(n, elem){
	var r = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType == 1 && n != elem )
			r.push( n );
	}

	return r;
};

return;

window.Sizzle = Sizzle;

})();
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code originated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {

	// Bind an event to an element
	// Original by Dean Edwards
	add: function(elem, types, handler, data) {
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		// For whatever reason, IE has trouble passing the window object
		// around, causing it to be cloned in the process
		if ( elem.setInterval && elem != window )
			elem = window;

		// Make sure that the function being executed has a unique ID
		if ( !handler.guid )
			handler.guid = this.guid++;

		// if data is passed, bind to handler
		if ( data !== undefined ) {
			// Create temporary function pointer to original handler
			var fn = handler;

			// Create unique handler function, wrapped around original handler
			handler = this.proxy( fn );

			// Store data in unique handler
			handler.data = data;
		}

		// Init the element's event structure
		var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
				// Handle the second event of a trigger and when
				// an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
					jQuery.event.handle.apply(arguments.callee.elem, arguments) :
					undefined;
			});
		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native
		// event in IE.
		handle.elem = elem;

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		jQuery.each(types.split(/\s+/), function(index, type) {
			// Namespaced event handlers
			var namespaces = type.split(".");
			type = namespaces.shift();
			handler.type = namespaces.slice().sort().join(".");

			// Get the current list of functions bound to this event
			var handlers = events[type];
			
			if ( jQuery.event.specialAll[type] )
				jQuery.event.specialAll[type].setup.call(elem, data, namespaces);

			// Init the event handler queue
			if (!handlers) {
				handlers = events[type] = {};

				// Check for a special event handler
				// Only use addEventListener/attachEvent if the special
				// events handler returns false
				if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
					// Bind the global event handler to the element
					if (elem.addEventListener)
						elem.addEventListener(type, handle, false);
					else if (elem.attachEvent)
						elem.attachEvent("on" + type, handle);
				}
			}

			// Add the function to the element's handler list
			handlers[handler.guid] = handler;

			// Keep track of which events have been used, for global triggering
			jQuery.event.global[type] = true;
		});

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	guid: 1,
	global: {},

	// Detach an event or set of events from an element
	remove: function(elem, types, handler) {
		// don't do events on text and comment nodes
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		var events = jQuery.data(elem, "events"), ret, index;

		if ( events ) {
			// Unbind all events for the element
			if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
				for ( var type in events )
					this.remove( elem, type + (types || "") );
			else {
				// types is actually an event object here
				if ( types.type ) {
					handler = types.handler;
					types = types.type;
				}

				// Handle multiple events seperated by a space
				// jQuery(...).unbind("mouseover mouseout", fn);
				jQuery.each(types.split(/\s+/), function(index, type){
					// Namespaced event handlers
					var namespaces = type.split(".");
					type = namespaces.shift();
					var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

					if ( events[type] ) {
						// remove the given handler for the given type
						if ( handler )
							delete events[type][handler.guid];

						// remove all handlers for the given type
						else
							for ( var handle in events[type] )
								// Handle the removal of namespaced events
								if ( namespace.test(events[type][handle].type) )
									delete events[type][handle];
									
						if ( jQuery.event.specialAll[type] )
							jQuery.event.specialAll[type].teardown.call(elem, namespaces);

						// remove generic event handler if no more handlers exist
						for ( ret in events[type] ) break;
						if ( !ret ) {
							if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
								if (elem.removeEventListener)
									elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
								else if (elem.detachEvent)
									elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
							}
							ret = null;
							delete events[type];
						}
					}
				});
			}

			// Remove the expando if it's no longer used
			for ( ret in events ) break;
			if ( !ret ) {
				var handle = jQuery.data( elem, "handle" );
				if ( handle ) handle.elem = null;
				jQuery.removeData( elem, "events" );
				jQuery.removeData( elem, "handle" );
			}
		}
	},

	// bubbling is internal
	trigger: function( event, data, elem, bubbling ) {
		// Event object or event type
		var type = event.type || event;

		if( !bubbling ){
			event = typeof event === "object" ?
				// jQuery.Event object
				event[expando] ? event :
				// Object literal
				jQuery.extend( jQuery.Event(type), event ) :
				// Just the event type (string)
				jQuery.Event(type);

			if ( type.indexOf("!") >= 0 ) {
				event.type = type = type.slice(0, -1);
				event.exclusive = true;
			}

			// Handle a global trigger
			if ( !elem ) {
				// Don't bubble custom events when global (to avoid too much overhead)
				event.stopPropagation();
				// Only trigger if we've ever bound an event for it
				if ( this.global[type] )
					jQuery.each( jQuery.cache, function(){
						if ( this.events && this.events[type] )
							jQuery.event.trigger( event, data, this.handle.elem );
					});
			}

			// Handle triggering a single element

			// don't do events on text and comment nodes
			if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
				return undefined;
			
			// Clean up in case it is reused
			event.result = undefined;
			event.target = elem;
			
			// Clone the incoming data, if any
			data = jQuery.makeArray(data);
			data.unshift( event );
		}

		event.currentTarget = elem;

		// Trigger the event, it is assumed that "handle" is a function
		var handle = jQuery.data(elem, "handle");
		if ( handle )
			handle.apply( elem, data );

		// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
		if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
			event.result = false;

		// Trigger the native events (except for clicks on links)
		if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
			this.triggered = true;
			try {
				elem[ type ]();
			// prevent IE from throwing an error for some hidden elements
			} catch (e) {}
		}

		this.triggered = false;

		if ( !event.isPropagationStopped() ) {
			var parent = elem.parentNode || elem.ownerDocument;
			if ( parent )
				jQuery.event.trigger(event, data, parent, true);
		}
	},

	handle: function(event) {
		// returned undefined or false
		var all, handlers;

		event = arguments[0] = jQuery.event.fix( event || window.event );
		event.currentTarget = this;
		
		// Namespaced event handlers
		var namespaces = event.type.split(".");
		event.type = namespaces.shift();

		// Cache this now, all = true means, any handler
		all = !namespaces.length && !event.exclusive;
		
		var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

		handlers = ( jQuery.data(this, "events") || {} )[event.type];

		for ( var j in handlers ) {
			var handler = handlers[j];

			// Filter the functions by class
			if ( all || namespace.test(handler.type) ) {
				// Pass in a reference to the handler function itself
				// So that we can later remove it
				event.handler = handler;
				event.data = handler.data;

				var ret = handler.apply(this, arguments);

				if( ret !== undefined ){
					event.result = ret;
					if ( ret === false ) {
						event.preventDefault();
						event.stopPropagation();
					}
				}

				if( event.isImmediatePropagationStopped() )
					break;

			}
		}
	},

	props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

	fix: function(event) {
		if ( event[expando] )
			return event;

		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = jQuery.Event( originalEvent );

		for ( var i = this.props.length, prop; i; ){
			prop = this.props[ --i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Fix target property, if necessary
		if ( !event.target )
			event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either

		// check if target is a textnode (safari)
		if ( event.target.nodeType == 3 )
			event.target = event.target.parentNode;

		// Add relatedTarget, if necessary
		if ( !event.relatedTarget && event.fromElement )
			event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var doc = document.documentElement, body = document.body;
			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
		}

		// Add which for key events
		if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
			event.which = event.charCode || event.keyCode;

		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey )
			event.metaKey = event.ctrlKey;

		// Add which for click: 1 == left; 2 == middle; 3 == right
		// Note: button is not normalized, so don't use it
		if ( !event.which && event.button )
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

		return event;
	},

	proxy: function( fn, proxy ){
		proxy = proxy || function(){ return fn.apply(this, arguments); };
		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
		// So proxy can be declared as an argument
		return proxy;
	},

	special: {
		ready: {
			// Make sure the ready event is setup
			setup: bindReady,
			teardown: function() {}
		}
	},
	
	specialAll: {
		live: {
			setup: function( selector, namespaces ){
				jQuery.event.add( this, namespaces[0], liveHandler );
			},
			teardown:  function( namespaces ){
				if ( namespaces.length ) {
					var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
					
					jQuery.each( (jQuery.data(this, "events").live || {}), function(){
						if ( name.test(this.type) )
							remove++;
					});
					
					if ( remove < 1 )
						jQuery.event.remove( this, namespaces[0], liveHandler );
				}
			}
		}
	}
};

jQuery.Event = function( src ){
	// Allow instantiation without the 'new' keyword
	if( !this.preventDefault )
		return new jQuery.Event(src);
	
	// Event object
	if( src && src.type ){
		this.originalEvent = src;
		this.type = src.type;
	// Event type
	}else
		this.type = src;

	// timeStamp is buggy for some events on Firefox(#3843)
	// So we won't rely on the native value
	this.timeStamp = now();
	
	// Mark it as fixed
	this[expando] = true;
};

function returnFalse(){
	return false;
}
function returnTrue(){
	return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;

		var e = this.originalEvent;
		if( !e )
			return;
		// if preventDefault exists run it on the original event
		if (e.preventDefault)
			e.preventDefault();
		// otherwise set the returnValue property of the original event to false (IE)
		e.returnValue = false;
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;

		var e = this.originalEvent;
		if( !e )
			return;
		// if stopPropagation exists run it on the original event
		if (e.stopPropagation)
			e.stopPropagation();
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation:function(){
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Traverse up the tree
	while ( parent && parent != this )
		try { parent = parent.parentNode; }
		catch(e) { parent = this; }
	
	if( parent != this ){
		// set the correct event type
		event.type = event.data;
		// handle event if we actually just moused on to a non sub-element
		jQuery.event.handle.apply( this, arguments );
	}
};
	
jQuery.each({ 
	mouseover: 'mouseenter', 
	mouseout: 'mouseleave'
}, function( orig, fix ){
	jQuery.event.special[ fix ] = {
		setup: function(){
			jQuery.event.add( this, orig, withinElement, fix );
		},
		teardown: function(){
			jQuery.event.remove( this, orig, withinElement );
		}
	};			   
});

jQuery.fn.extend({
	bind: function( type, data, fn ) {
		return type == "unload" ? this.one(type, data, fn) : this.each(function(){
			jQuery.event.add( this, type, fn || data, fn && data );
		});
	},

	one: function( type, data, fn ) {
		var one = jQuery.event.proxy( fn || data, function(event) {
			jQuery(this).unbind(event, one);
			return (fn || data).apply( this, arguments );
		});
		return this.each(function(){
			jQuery.event.add( this, type, one, fn && data);
		});
	},

	unbind: function( type, fn ) {
		return this.each(function(){
			jQuery.event.remove( this, type, fn );
		});
	},

	trigger: function( type, data ) {
		return this.each(function(){
			jQuery.event.trigger( type, data, this );
		});
	},

	triggerHandler: function( type, data ) {
		if( this[0] ){
			var event = jQuery.Event(type);
			event.preventDefault();
			event.stopPropagation();
			jQuery.event.trigger( event, data, this[0] );
			return event.result;
		}		
	},

	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments, i = 1;

		// link all the functions, so any of them can unbind this click handler
		while( i < args.length )
			jQuery.event.proxy( fn, args[i++] );

		return this.click( jQuery.event.proxy( fn, function(event) {
			// Figure out which function to execute
			this.lastToggle = ( this.lastToggle || 0 ) % i;

			// Make sure that clicks stop
			event.preventDefault();

			// and execute the function
			return args[ this.lastToggle++ ].apply( this, arguments ) || false;
		}));
	},

	hover: function(fnOver, fnOut) {
		return this.mouseenter(fnOver).mouseleave(fnOut);
	},

	ready: function(fn) {
		// Attach the listeners
		bindReady();

		// If the DOM is already ready
		if ( jQuery.isReady )
			// Execute the function immediately
			fn.call( document, jQuery );

		// Otherwise, remember the function for later
		else
			// Add the function to the wait list
			jQuery.readyList.push( fn );

		return this;
	},
	
	live: function( type, fn ){
		var proxy = jQuery.event.proxy( fn );
		proxy.guid += this.selector + type;

		jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );

		return this;
	},
	
	die: function( type, fn ){
		jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
		return this;
	}
});

function liveHandler( event ){
	var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
		stop = true,
		elems = [];

	jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
		if ( check.test(fn.type) ) {
			var elem = jQuery(event.target).closest(fn.data)[0];
			if ( elem )
				elems.push({ elem: elem, fn: fn });
		}
	});

	elems.sort(function(a,b) {
		return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
	});
	
	jQuery.each(elems, function(){
		if ( this.fn.call(this.elem, event, this.fn.data) === false )
			return (stop = false);
	});

	return stop;
}

function liveConvert(type, selector){
	return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}

jQuery.extend({
	isReady: false,
	readyList: [],
	// Handle when the DOM is ready
	ready: function() {
		// Make sure that the DOM is not already loaded
		if ( !jQuery.isReady ) {
			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If there are functions bound, to execute
			if ( jQuery.readyList ) {
				// Execute all of them
				jQuery.each( jQuery.readyList, function(){
					this.call( document, jQuery );
				});

				// Reset the list of functions
				jQuery.readyList = null;
			}

			// Trigger any bound ready events
			jQuery(document).triggerHandler("ready");
		}
	}
});

var readyBound = false;

function bindReady(){
	if ( readyBound ) return;
	readyBound = true;

	// Mozilla, Opera and webkit nightlies currently support this event
	if ( document.addEventListener ) {
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", function(){
			document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
			jQuery.ready();
		}, false );

	// If IE event model is used
	} else if ( document.attachEvent ) {
		// ensure firing before onload,
		// maybe late but safe also for iframes
		document.attachEvent("onreadystatechange", function(){
			if ( document.readyState === "complete" ) {
				document.detachEvent( "onreadystatechange", arguments.callee );
				jQuery.ready();
			}
		});

		// If IE and not an iframe
		// continually check to see if the document is ready
		if ( document.documentElement.doScroll && window == window.top ) (function(){
			if ( jQuery.isReady ) return;

			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch( error ) {
				setTimeout( arguments.callee, 0 );
				return;
			}

			// and execute any waiting functions
			jQuery.ready();
		})();
	}

	// A fallback to window.onload, that will always work
	jQuery.event.add( window, "load", jQuery.ready );
}

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
	"mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
	"change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

	// Handle event binding
	jQuery.fn[name] = function(fn){
		return fn ? this.bind(name, fn) : this.trigger(name);
	};
});

// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){ 
	for ( var id in jQuery.cache )
		// Skip the window
		if ( id != 1 && jQuery.cache[ id ].handle )
			jQuery.event.remove( jQuery.cache[ id ].handle.elem );
}); 
(function(){

	jQuery.support = {};

	var root = document.documentElement,
		script = document.createElement("script"),
		div = document.createElement("div"),
		id = "script" + (new Date).getTime();

	div.style.display = "none";
	div.innerHTML = '   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';

	var all = div.getElementsByTagName("*"),
		a = div.getElementsByTagName("a")[0];

	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return;
	}

	jQuery.support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: div.firstChild.nodeType == 3,
		
		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,
		
		// Make sure that you can get all elements in an <object> element
		// IE 7 always returns no results
		objectAll: !!div.getElementsByTagName("object")[0]
			.getElementsByTagName("*").length,
		
		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,
		
		// Get the style information from getAttribute
		// (IE uses .cssText insted)
		style: /red/.test( a.getAttribute("style") ),
		
		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: a.getAttribute("href") === "/a",
		
		// Make sure that element opacity exists
		// (IE uses filter instead)
		opacity: a.style.opacity === "0.5",
		
		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Will be defined later
		scriptEval: false,
		noCloneEvent: true,
		boxModel: null
	};
	
	script.type = "text/javascript";
	try {
		script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
	} catch(e){}

	root.insertBefore( script, root.firstChild );
	
	// Make sure that the execution of code works by injecting a script
	// tag with appendChild/createTextNode
	// (IE doesn't support this, fails, and uses .text instead)
	if ( window[ id ] ) {
		jQuery.support.scriptEval = true;
		delete window[ id ];
	}

	root.removeChild( script );

	if ( div.attachEvent && div.fireEvent ) {
		div.attachEvent("onclick", function(){
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			jQuery.support.noCloneEvent = false;
			div.detachEvent("onclick", arguments.callee);
		});
		div.cloneNode(true).fireEvent("onclick");
	}

	// Figure out if the W3C box model works as expected
	// document.body must exist before we can do this
	jQuery(function(){
		var div = document.createElement("div");
		div.style.width = div.style.paddingLeft = "1px";

		document.body.appendChild( div );
		jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
		document.body.removeChild( div ).style.display = 'none';
	});
})();

var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";

jQuery.props = {
	"for": "htmlFor",
	"class": "className",
	"float": styleFloat,
	cssFloat: styleFloat,
	styleFloat: styleFloat,
	readonly: "readOnly",
	maxlength: "maxLength",
	cellspacing: "cellSpacing",
	rowspan: "rowSpan",
	tabindex: "tabIndex"
};
jQuery.fn.extend({
	// Keep a copy of the old load
	_load: jQuery.fn.load,

	load: function( url, params, callback ) {
		if ( typeof url !== "string" )
			return this._load( url );

		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params )
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else if( typeof params === "object" ) {
				params = jQuery.param( params );
				type = "POST";
			}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" )
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );

				if( callback )
					self.each( callback, [res.responseText, status, res] );
			}
		});
		return this;
	},

	serialize: function() {
		return jQuery.param(this.serializeArray());
	},
	serializeArray: function() {
		return this.map(function(){
			return this.elements ? jQuery.makeArray(this.elements) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				(this.checked || /select|textarea/i.test(this.nodeName) ||
					/text|hidden|password|search/i.test(this.type));
		})
		.map(function(i, elem){
			var val = jQuery(this).val();
			return val == null ? null :
				jQuery.isArray(val) ?
					jQuery.map( val, function(val, i){
						return {name: elem.name, value: val};
					}) :
					{name: elem.name, value: val};
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
	jQuery.fn[o] = function(f){
		return this.bind(o, f);
	};
});

var jsc = now();

jQuery.extend({
  
	get: function( url, data, callback, type ) {
		// shift arguments if data argument was ommited
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = null;
		}

		return jQuery.ajax({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	getScript: function( url, callback ) {
		return jQuery.get(url, null, callback, "script");
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get(url, data, callback, "json");
	},

	post: function( url, data, callback, type ) {
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = {};
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	ajaxSetup: function( settings ) {
		jQuery.extend( jQuery.ajaxSettings, settings );
	},

	ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		username: null,
		password: null,
		*/
		// Create the request object; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
		// This function can be overriden by calling jQuery.ajaxSetup
		xhr:function(){
			return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
		},
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	},

	// Last-Modified header cache for next request
	lastModified: {},

	ajax: function( s ) {
		// Extend the settings, but re-extend 's' so that it can be
		// checked again later (in the test suite, specifically)
		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

		var jsonp, jsre = /=\?(&|$)/g, status, data,
			type = s.type.toUpperCase();

		// convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" )
			s.data = jQuery.param(s.data);

		// Handle JSONP Parameter Callbacks
		if ( s.dataType == "jsonp" ) {
			if ( type == "GET" ) {
				if ( !s.url.match(jsre) )
					s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
			} else if ( !s.data || !s.data.match(jsre) )
				s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
			s.dataType = "json";
		}

		// Build temporary JSONP function
		if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
			jsonp = "jsonp" + jsc++;

			// Replace the =? sequence both in the query string and the data
			if ( s.data )
				s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
			s.url = s.url.replace(jsre, "=" + jsonp + "$1");

			// We need to make sure
			// that a JSONP style response is executed properly
			s.dataType = "script";

			// Handle JSONP-style loading
			window[ jsonp ] = function(tmp){
				data = tmp;
				success();
				complete();
				// Garbage collect
				window[ jsonp ] = undefined;
				try{ delete window[ jsonp ]; } catch(e){}
				if ( head )
					head.removeChild( script );
			};
		}

		if ( s.dataType == "script" && s.cache == null )
			s.cache = false;

		if ( s.cache === false && type == "GET" ) {
			var ts = now();
			// try replacing _= if it is there
			var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
			// if nothing was replaced, add timestamp to the end
			s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
		}

		// If data is available, append data to url for get requests
		if ( s.data && type == "GET" ) {
			s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

			// IE likes to send both get and post data, prevent this
			s.data = null;
		}

		// Watch for a new set of requests
		if ( s.global && ! jQuery.active++ )
			jQuery.event.trigger( "ajaxStart" );

		// Matches an absolute URL, and saves the domain
		var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );

		// If we're requesting a remote document
		// and trying to load JSON or Script with a GET
		if ( s.dataType == "script" && type == "GET" && parts
			&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){

			var head = document.getElementsByTagName("head")[0];
			var script = document.createElement("script");
			script.src = s.url;
			if (s.scriptCharset)
				script.charset = s.scriptCharset;

			// Handle Script loading
			if ( !jsonp ) {
				var done = false;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function(){
					if ( !done && (!this.readyState ||
							this.readyState == "loaded" || this.readyState == "complete") ) {
						done = true;
						success();
						complete();

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;
						head.removeChild( script );
					}
				};
			}

			head.appendChild(script);

			// We handle everything using the script element injection
			return undefined;
		}

		var requestDone = false;

		// Create the request object
		var xhr = s.xhr();

		// Open the socket
		// Passing null username, generates a login popup on Opera (#2865)
		if( s.username )
			xhr.open(type, s.url, s.async, s.username, s.password);
		else
			xhr.open(type, s.url, s.async);

		// Need an extra try/catch for cross domain requests in Firefox 3
		try {
			// Set the correct header, if data is being sent
			if ( s.data )
				xhr.setRequestHeader("Content-Type", s.contentType);

			// Set the If-Modified-Since header, if ifModified mode.
			if ( s.ifModified )
				xhr.setRequestHeader("If-Modified-Since",
					jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );

			// Set header so the called script knows that it's an XMLHttpRequest
			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

			// Set the Accepts header for the server, depending on the dataType
			xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
				s.accepts[ s.dataType ] + ", */*" :
				s.accepts._default );
		} catch(e){}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
			// close opended socket
			xhr.abort();
			return false;
		}

		if ( s.global )
			jQuery.event.trigger("ajaxSend", [xhr, s]);

		// Wait for a response to come back
		var onreadystatechange = function(isTimeout){
			// The request was aborted, clear the interval and decrement jQuery.active
			if (xhr.readyState == 0) {
				if (ival) {
					// clear poll interval
					clearInterval(ival);
					ival = null;
					// Handle the global AJAX counter
					if ( s.global && ! --jQuery.active )
						jQuery.event.trigger( "ajaxStop" );
				}
			// The transfer is complete and the data is available, or the request timed out
			} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;

				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}

				status = isTimeout == "timeout" ? "timeout" :
					!jQuery.httpSuccess( xhr ) ? "error" :
					s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
					"success";

				if ( status == "success" ) {
					// Watch for, and catch, XML document parse errors
					try {
						// process the data (runs the xml through httpData regardless of callback)
						data = jQuery.httpData( xhr, s.dataType, s );
					} catch(e) {
						status = "parsererror";
					}
				}

				// Make sure that the request was successful or notmodified
				if ( status == "success" ) {
					// Cache Last-Modified header, if ifModified mode.
					var modRes;
					try {
						modRes = xhr.getResponseHeader("Last-Modified");
					} catch(e) {} // swallow exception thrown by FF if header is not available

					if ( s.ifModified && modRes )
						jQuery.lastModified[s.url] = modRes;

					// JSONP handles its own success callback
					if ( !jsonp )
						success();
				} else
					jQuery.handleError(s, xhr, status);

				// Fire the complete handlers
				complete();

				if ( isTimeout )
					xhr.abort();

				// Stop memory leaks
				if ( s.async )
					xhr = null;
			}
		};

		if ( s.async ) {
			// don't attach the handler to the request, just poll it instead
			var ival = setInterval(onreadystatechange, 13);

			// Timeout checker
			if ( s.timeout > 0 )
				setTimeout(function(){
					// Check to see if the request is still happening
					if ( xhr && !requestDone )
						onreadystatechange( "timeout" );
				}, s.timeout);
		}

		// Send the data
		try {
			xhr.send(s.data);
		} catch(e) {
			jQuery.handleError(s, xhr, null, e);
		}

		// firefox 1.5 doesn't fire statechange for sync requests
		if ( !s.async )
			onreadystatechange();

		function success(){
			// If a local callback was specified, fire it and pass it the data
			if ( s.success )
				s.success( data, status );

			// Fire the global callback
			if ( s.global )
				jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
		}

		function complete(){
			// Process result
			if ( s.complete )
				s.complete(xhr, status);

			// The request was completed
			if ( s.global )
				jQuery.event.trigger( "ajaxComplete", [xhr, s] );

			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
		}

		// return XMLHttpRequest to allow aborting the request etc.
		return xhr;
	},

	handleError: function( s, xhr, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error ) s.error( xhr, status, e );

		// Fire the global callback
		if ( s.global )
			jQuery.event.trigger( "ajaxError", [xhr, s, e] );
	},

	// Counter for holding the number of active queries
	active: 0,

	// Determines if an XMLHttpRequest was successful or not
	httpSuccess: function( xhr ) {
		try {
			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
			return !xhr.status && location.protocol == "file:" ||
				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
		} catch(e){}
		return false;
	},

	// Determines if an XMLHttpRequest returns NotModified
	httpNotModified: function( xhr, url ) {
		try {
			var xhrRes = xhr.getResponseHeader("Last-Modified");

			// Firefox always returns 200. check Last-Modified date
			return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
		} catch(e){}
		return false;
	},

	httpData: function( xhr, type, s ) {
		var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";
			
		// Allow a pre-filtering function to sanitize the response
		// s != null is checked to keep backwards compatibility
		if( s && s.dataFilter )
			data = s.dataFilter( data, type );

		// The filter can actually parse the response
		if( typeof data === "string" ){

			// If the type is "script", eval it in global context
			if ( type == "script" )
				jQuery.globalEval( data );

			// Get the JavaScript object, if JSON is used.
			if ( type == "json" )
				data = window["eval"]("(" + data + ")");
		}
		
		return data;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a ) {
		var s = [ ];

		function add( key, value ){
			s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
		};

		// If an array was passed in, assume that it is an array
		// of form elements
		if ( jQuery.isArray(a) || a.jquery )
			// Serialize the form elements
			jQuery.each( a, function(){
				add( this.name, this.value );
			});

		// Otherwise, assume that it's an object of key/value pairs
		else
			// Serialize the key/values
			for ( var j in a )
				// If the value is an array then the key names need to be repeated
				if ( jQuery.isArray(a[j]) )
					jQuery.each( a[j], function(){
						add( j, this );
					});
				else
					add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );

		// Return the resulting serialization
		return s.join("&").replace(/%20/g, "+");
	}

});
var elemdisplay = {},
	timerId,
	fxAttrs = [
		// height animations
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		// width animations
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		// opacity animations
		[ "opacity" ]
	];

function genFx( type, num ){
	var obj = {};
	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
		obj[ this ] = type;
	});
	return obj;
}

jQuery.fn.extend({
	show: function(speed,callback){
		if ( speed ) {
			return this.animate( genFx("show", 3), speed, callback);
		} else {
			for ( var i = 0, l = this.length; i < l; i++ ){
				var old = jQuery.data(this[i], "olddisplay");
				
				this[i].style.display = old || "";
				
				if ( jQuery.css(this[i], "display") === "none" ) {
					var tagName = this[i].tagName, display;
					
					if ( elemdisplay[ tagName ] ) {
						display = elemdisplay[ tagName ];
					} else {
						var elem = jQuery("<" + tagName + " />").appendTo("body");
						
						display = elem.css("display");
						if ( display === "none" )
							display = "block";
						
						elem.remove();
						
						elemdisplay[ tagName ] = display;
					}
					
					jQuery.data(this[i], "olddisplay", display);
				}
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( var i = 0, l = this.length; i < l; i++ ){
				this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
			}
			
			return this;
		}
	},

	hide: function(speed,callback){
		if ( speed ) {
			return this.animate( genFx("hide", 3), speed, callback);
		} else {
			for ( var i = 0, l = this.length; i < l; i++ ){
				var old = jQuery.data(this[i], "olddisplay");
				if ( !old && old !== "none" )
					jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( var i = 0, l = this.length; i < l; i++ ){
				this[i].style.display = "none";
			}

			return this;
		}
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,

	toggle: function( fn, fn2 ){
		var bool = typeof fn === "boolean";

		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle.apply( this, arguments ) :
			fn == null || bool ?
				this.each(function(){
					var state = bool ? fn : jQuery(this).is(":hidden");
					jQuery(this)[ state ? "show" : "hide" ]();
				}) :
				this.animate(genFx("toggle", 3), fn, fn2);
	},

	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	animate: function( prop, speed, easing, callback ) {
		var optall = jQuery.speed(speed, easing, callback);

		return this[ optall.queue === false ? "each" : "queue" ](function(){
		
			var opt = jQuery.extend({}, optall), p,
				hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
				self = this;
	
			for ( p in prop ) {
				if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
					return opt.complete.call(this);

				if ( ( p == "height" || p == "width" ) && this.style ) {
					// Store display property
					opt.display = jQuery.css(this, "display");

					// Make sure that nothing sneaks out
					opt.overflow = this.style.overflow;
				}
			}

			if ( opt.overflow != null )
				this.style.overflow = "hidden";

			opt.curAnim = jQuery.extend({}, prop);

			jQuery.each( prop, function(name, val){
				var e = new jQuery.fx( self, opt, name );

				if ( /toggle|show|hide/.test(val) )
					e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
				else {
					var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
						start = e.cur(true) || 0;

					if ( parts ) {
						var end = parseFloat(parts[2]),
							unit = parts[3] || "px";

						// We need to compute starting value
						if ( unit != "px" ) {
							self.style[ name ] = (end || 1) + unit;
							start = ((end || 1) / e.cur(true)) * start;
							self.style[ name ] = start + unit;
						}

						// If a +=/-= token was provided, we're doing a relative animation
						if ( parts[1] )
							end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

						e.custom( start, end, unit );
					} else
						e.custom( start, val, "" );
				}
			});

			// For JS strict compliance
			return true;
		});
	},

	stop: function(clearQueue, gotoEnd){
		var timers = jQuery.timers;

		if (clearQueue)
			this.queue([]);

		this.each(function(){
			// go in reverse order so anything added to the queue during the loop is ignored
			for ( var i = timers.length - 1; i >= 0; i-- )
				if ( timers[i].elem == this ) {
					if (gotoEnd)
						// force the next step to be the last
						timers[i](true);
					timers.splice(i, 1);
				}
		});

		// start the next in the queue if the last step wasn't forced
		if (!gotoEnd)
			this.dequeue();

		return this;
	}

});

// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx("show", 1),
	slideUp: genFx("hide", 1),
	slideToggle: genFx("toggle", 1),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" }
}, function( name, props ){
	jQuery.fn[ name ] = function( speed, callback ){
		return this.animate( props, speed, callback );
	};
});

jQuery.extend({

	speed: function(speed, easing, fn) {
		var opt = typeof speed === "object" ? speed : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
		};

		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
			jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;

		// Queueing
		opt.old = opt.complete;
		opt.complete = function(){
			if ( opt.queue !== false )
				jQuery(this).dequeue();
			if ( jQuery.isFunction( opt.old ) )
				opt.old.call( this );
		};

		return opt;
	},

	easing: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
		}
	},

	timers: [],

	fx: function( elem, options, prop ){
		this.options = options;
		this.elem = elem;
		this.prop = prop;

		if ( !options.orig )
			options.orig = {};
	}

});

jQuery.fx.prototype = {

	// Simple function for setting a style value
	update: function(){
		if ( this.options.step )
			this.options.step.call( this.elem, this.now, this );

		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );

		// Set display property to block for height/width animations
		if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
			this.elem.style.display = "block";
	},

	// Get the current size
	cur: function(force){
		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
			return this.elem[ this.prop ];

		var r = parseFloat(jQuery.css(this.elem, this.prop, force));
		return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
	},

	// Start an animation from one number to another
	custom: function(from, to, unit){
		this.startTime = now();
		this.start = from;
		this.end = to;
		this.unit = unit || this.unit || "px";
		this.now = this.start;
		this.pos = this.state = 0;

		var self = this;
		function t(gotoEnd){
			return self.step(gotoEnd);
		}

		t.elem = this.elem;

		if ( t() && jQuery.timers.push(t) && !timerId ) {
			timerId = setInterval(function(){
				var timers = jQuery.timers;

				for ( var i = 0; i < timers.length; i++ )
					if ( !timers[i]() )
						timers.splice(i--, 1);

				if ( !timers.length ) {
					clearInterval( timerId );
					timerId = undefined;
				}
			}, 13);
		}
	},

	// Simple 'show' function
	show: function(){
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.show = true;

		// Begin the animation
		// Make sure that we start at a small width/height to avoid any
		// flash of content
		this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());

		// Start by showing the element
		jQuery(this.elem).show();
	},

	// Simple 'hide' function
	hide: function(){
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.hide = true;

		// Begin the animation
		this.custom(this.cur(), 0);
	},

	// Each step of an animation
	step: function(gotoEnd){
		var t = now();

		if ( gotoEnd || t >= this.options.duration + this.startTime ) {
			this.now = this.end;
			this.pos = this.state = 1;
			this.update();

			this.options.curAnim[ this.prop ] = true;

			var done = true;
			for ( var i in this.options.curAnim )
				if ( this.options.curAnim[i] !== true )
					done = false;

			if ( done ) {
				if ( this.options.display != null ) {
					// Reset the overflow
					this.elem.style.overflow = this.options.overflow;

					// Reset the display
					this.elem.style.display = this.options.display;
					if ( jQuery.css(this.elem, "display") == "none" )
						this.elem.style.display = "block";
				}

				// Hide the element if the "hide" operation was done
				if ( this.options.hide )
					jQuery(this.elem).hide();

				// Reset the properties, if the item has been hidden or shown
				if ( this.options.hide || this.options.show )
					for ( var p in this.options.curAnim )
						jQuery.attr(this.elem.style, p, this.options.orig[p]);
					
				// Execute the complete function
				this.options.complete.call( this.elem );
			}

			return false;
		} else {
			var n = t - this.startTime;
			this.state = n / this.options.duration;

			// Perform the easing function, defaults to swing
			this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
			this.now = this.start + ((this.end - this.start) * this.pos);

			// Perform the next step of the animation
			this.update();
		}

		return true;
	}

};

jQuery.extend( jQuery.fx, {
	speeds:{
		slow: 600,
 		fast: 200,
 		// Default speed
 		_default: 400
	},
	step: {

		opacity: function(fx){
			jQuery.attr(fx.elem.style, "opacity", fx.now);
		},

		_default: function(fx){
			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
				fx.elem.style[ fx.prop ] = fx.now + fx.unit;
			else
				fx.elem[ fx.prop ] = fx.now;
		}
	}
});
if ( document.documentElement["getBoundingClientRect"] )
	jQuery.fn.offset = function() {
		if ( !this[0] ) return { top: 0, left: 0 };
		if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
		var box  = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
			clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
			top  = box.top  + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop  || body.scrollTop ) - clientTop,
			left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
		return { top: top, left: left };
	};
else 
	jQuery.fn.offset = function() {
		if ( !this[0] ) return { top: 0, left: 0 };
		if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
		jQuery.offset.initialized || jQuery.offset.initialize();

		var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
			doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
			body = doc.body, defaultView = doc.defaultView,
			prevComputedStyle = defaultView.getComputedStyle(elem, null),
			top = elem.offsetTop, left = elem.offsetLeft;

		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
			computedStyle = defaultView.getComputedStyle(elem, null);
			top -= elem.scrollTop, left -= elem.scrollLeft;
			if ( elem === offsetParent ) {
				top += elem.offsetTop, left += elem.offsetLeft;
				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
					top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
					left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
				prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
			}
			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
				top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
				left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
			prevComputedStyle = computedStyle;
		}

		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
			top  += body.offsetTop,
			left += body.offsetLeft;

		if ( prevComputedStyle.position === "fixed" )
			top  += Math.max(docElem.scrollTop, body.scrollTop),
			left += Math.max(docElem.scrollLeft, body.scrollLeft);

		return { top: top, left: left };
	};

jQuery.offset = {
	initialize: function() {
		if ( this.initialized ) return;
		var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
			html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';

		rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
		for ( prop in rules ) container.style[prop] = rules[prop];

		container.innerHTML = html;
		body.insertBefore(container, body.firstChild);
		innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;

		this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
		this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

		innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
		this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

		body.style.marginTop = '1px';
		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
		body.style.marginTop = bodyMarginTop;

		body.removeChild(container);
		this.initialized = true;
	},

	bodyOffset: function(body) {
		jQuery.offset.initialized || jQuery.offset.initialize();
		var top = body.offsetTop, left = body.offsetLeft;
		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
			top  += parseInt( jQuery.curCSS(body, 'marginTop',  true), 10 ) || 0,
			left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
		return { top: top, left: left };
	}
};


jQuery.fn.extend({
	position: function() {
		var left = 0, top = 0, results;

		if ( this[0] ) {
			// Get *real* offsetParent
			var offsetParent = this.offsetParent(),

			// Get correct offsets
			offset       = this.offset(),
			parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();

			// Subtract element margins
			// note: when an element has margin: auto the offsetLeft and marginLeft 
			// are the same in Safari causing offset.left to incorrectly be 0
			offset.top  -= num( this, 'marginTop'  );
			offset.left -= num( this, 'marginLeft' );

			// Add offsetParent borders
			parentOffset.top  += num( offsetParent, 'borderTopWidth'  );
			parentOffset.left += num( offsetParent, 'borderLeftWidth' );

			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}

		return results;
	},

	offsetParent: function() {
		var offsetParent = this[0].offsetParent || document.body;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return jQuery(offsetParent);
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
	var method = 'scroll' + name;
	
	jQuery.fn[ method ] = function(val) {
		if (!this[0]) return null;

		return val !== undefined ?

			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo(
						!i ? val : jQuery(window).scrollLeft(),
						 i ? val : jQuery(window).scrollTop()
					) :
					this[ method ] = val;
			}) :

			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
					jQuery.boxModel && document.documentElement[ method ] ||
					document.body[ method ] :
				this[0][ method ];
	};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){

	var tl = i ? "Left"  : "Top",  // top or left
		br = i ? "Right" : "Bottom", // bottom or right
		lower = name.toLowerCase();

	// innerHeight and innerWidth
	jQuery.fn["inner" + name] = function(){
		return this[0] ?
			jQuery.css( this[0], lower, false, "padding" ) :
			null;
	};

	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function(margin) {
		return this[0] ?
			jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
			null;
	};
	
	var type = name.toLowerCase();

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		return this[0] == window ?
			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
			document.body[ "client" + name ] :

			// Get document width or height
			this[0] == document ?
				// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
				Math.max(
					document.documentElement["client" + name],
					document.body["scroll" + name], document.documentElement["scroll" + name],
					document.body["offset" + name], document.documentElement["offset" + name]
				) :

				// Get or set width or height on the element
				size === undefined ?
					// Get width or height on the element
					(this.length ? jQuery.css( this[0], type ) : null) :

					// Set the width or height on the element (default to pixels if value is unitless)
					this.css( type, typeof size === "string" ? size : size + "px" );
	};

});
})();

// register the namespace first
//
function registerNS(ns)
{
    var nsParts = ns.split(".");
    var root = window;

    for(var i=0; i<nsParts.length; i++) {
        if(typeof root[nsParts[i]] == "undefined")
        root[nsParts[i]] = new Object();
        root = root[nsParts[i]];
    }
}

registerNS('o8.Gis');


// this is a proxy used to call the script service methods
//


o8.Gis.fetchDataFromService = function(operationName, jsonData, successFunc) {
// fetch markers within bounds
	$.ajax({
  		type: 'POST',
  		url: geoScriptServiceUrl + '/' + operationName,
  		data: jsonData,
  		contentType: 'application/json; charset=utf-8',
  		dataType: 'json',
  		success: function(msg) {alert(msg); }
	});
}

o8.Gis.fetchDataFromServiceSync = function(operationName, jsonData) {
    var result = null;
	$.ajax({
	    async:false,
  		type: 'POST',
  		url: geoScriptServiceUrl + '/' + operationName,
  		data: jsonData,
  		contentType: 'application/json; charset=utf-8',
  		dataType: 'json',
  		success: function(msg) { result = msg; }
	});
	return result;
}



// this is the google map implementation
//
o8.Gis.Map = function(customLayoutCallback, markerInfoHtmlProvider) {
    this._customLayoutCallback = customLayoutCallback;
    this._markerInfoHtmlProvider = markerInfoHtmlProvider;
    this._map = null;
    this._mapControls = [];
    this._avgPixelDistance = 0.0;
    this._bounds = null;
}

o8.Gis.Map.prototype.initialize = function(containerid, centerPos, zoomLevel) {
	if (!GBrowserIsCompatible()) {
	    return;
	}

	this._map = new GMap2(document.getElementById(containerid));
	this._map.setCenter(new GLatLng(centerPos.Lat, centerPos.Lon), zoomLevel);
	this._avgPixelDistance = this.getAvgMapPixelDistance();
	
	var self = this;	 
	
	if(!this._customLayoutCallback) {
	    // add the default map controls

	    //var uiMapOptions = this._map.getDefaultUI();
        //uiMapOptions.zoom.doubleclick = false;
        //this._map.setUI(uiMapOptions);
        this._map.setUIToDefault();
	}
	else {	    
	    this._customLayoutCallback(self);	    
	}
		
	// wire events
	GEvent.addListener(this._map,'move', GEvent.callback(this, this.move));
	GEvent.addListener(this._map,'moveend', GEvent.callback(this, this.moveEnd));
	GEvent.addListener(this._map,'zoomend', GEvent.callback(this, this.zoomEnd));	
	// wire the click handler
	GEvent.addListener(this._map, 'click', function(overlay, latlng, overlaylatlng) {
	    if(overlay instanceof GMarker) {
	        self.displayMarkerInfoWindow(overlay);
	    }
	    else if(overlay instanceof GPolyline) {
	        self.displayPolylineInfoWindow(overlay);
	    }
	    else {
	        // do nothing
	    }
	});	
}

// public interface

// restricts the scrollable area to specific bounds
o8.Gis.Map.prototype.setBounds = function(southWest, northEast) {
    // rtemember the set bounds
    this._bounds = new GLatLngBounds(new GLatLng(southWest.Lat, southWest.Lon), new GLatLng(northEast.Lat, northEast.Lon));
    // do an initial bounds check
    this.checkBounds();   
}

// sets the zoom level range to max 1..18. where 18 is the most detailed view.
o8.Gis.Map.prototype.setAllowedZoomLevels = function(minZoom, maxZoom) {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    
    if(minZoom >= maxZoom) {
        alert('minZoom is greater or equals to maxZoom');
        return;
    }
    
    var mt = this._map.getMapTypes();
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i = 0; i < mt.length; i++) {
        mt[i].getMinimumResolution = function() {return minZoom;}
        mt[i].getMaximumResolution = function() {return maxZoom;}
    }
}

o8.Gis.Map.prototype.isLoaded = function() {
    if(!this._map) {
        return false;
    }
    
    return this._map.isLoaded();
}

o8.Gis.Map.prototype.getCenter = function() {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    var centerPos = this._map.getCenter();
    return {'Lat': centerPos.lat(), 'Lon': centerPos.lng() };
}

o8.Gis.Map.prototype.setCenter = function(geoPos, zoomLevel) {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    this._map.setCenter(new GLatLng(geoPos.Lat, geoPos.Lon), zoomLevel);
}

o8.Gis.Map.prototype.panTo = function(geoPos) {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    this._map.panTo(new GLatLng(geoPos.Lat, geoPos.Lon));
}

o8.Gis.Map.prototype.getZoom = function() {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    return this._map.getZoom();
}

o8.Gis.Map.prototype.setZoom = function(zoomLevel) {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    this._map.setZoom(zoomLevel);
}

o8.Gis.Map.prototype.zoomIn = function() {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    this._map.zoomIn();
}

o8.Gis.Map.prototype.zoomOut = function() {
    if(!this.isLoaded()) {
        alert('Map not initialized!');
        return;
    }
    this._map.zoomOut();
}

// private interface

// adds a control to the map at a specific position
o8.Gis.Map.prototype.addControl = function(mapControl, controlPosition) {
    this._mapControls.push(mapControl);
    this._map.addControl(mapControl, controlPosition);
}

// shows the info window of the clicked marker.
o8.Gis.Map.prototype.displayMarkerInfoWindow = function(marker) {
    if(this._markerInfoHtmlProvider) {
        var markerId = marker.extendedGisMarkerId;
        var markerType = marker.extendedGisMarkerType;
	    var markerProperties = marker.extendedGisMarkerProperties;
        var markerHtml = this._markerInfoHtmlProvider(markerId, markerType, markerProperties);
        
        //suppressMapPan is an undocumented option
        marker.openInfoWindowHtml(markerHtml, { suppressMapPan: false });
    }
}

// shows the info window of the clicked polyline.
o8.Gis.Map.prototype.displayPolylineInfoWindow = function(polyline) {
    if(this._polylineInfoHtmlProvider) {
        var polylineId = polyline.extendedGisPolylineId;
	    var polylineProperties = marker.extendedGisPolylineProperties;
        var polylineHtml = this._polylineInfoHtmlProvider(polylineId, polylineProperties);
        
        //suppressMapPan is an undocumented option
        polyline.openInfoWindowHtml(polylineHtml, { suppressMapPan: true });
    }
}


o8.Gis.Map.prototype.checkBounds = function() {
    if(!this.isLoaded() || !this._bounds) {
        return;
    }
    
    // Perform the check and return if OK
    var mapCeter = this._map.getCenter();
    if (this._bounds.contains(mapCeter)) {
        return;
    }
    
    // It`s not OK, so find the nearest allowed point and move there
    var X = mapCeter.lng();
    var Y = mapCeter.lat();

    var AmaxX = this._bounds.getNorthEast().lng();
    var AmaxY = this._bounds.getNorthEast().lat();
    var AminX = this._bounds.getSouthWest().lng();
    var AminY = this._bounds.getSouthWest().lat();

    if (X < AminX) {X = AminX;}
    if (X > AmaxX) {X = AmaxX;}
    if (Y < AminY) {Y = AminY;}
    if (Y > AmaxY) {Y = AmaxY;}
    this._map.setCenter(new GLatLng(Y,X));
}

// move handler
o8.Gis.Map.prototype.move = function() {
    // check if we're (still) in the allowed bounds, if any
    this.checkBounds();
}

// move end handler. the markers out of the visible bounds will be removed.
// markers in the visible area are (re)loaded.
o8.Gis.Map.prototype.moveEnd = function() {
    // remove markers out of bounds on the visible layers
    var selectedLayers = this.getSelectedLayers();    
    var workingAreaBounds = this.getWorkingAreaBounds();
    
    for(var i = 0; i < selectedLayers.length; i++) {
        selectedLayers[i].removeMarkers(workingAreaBounds);
    }
    
	// update markers
	this.updateMarkers();
	// update polylines
	this.updatePolylines();
}

o8.Gis.Map.prototype.zoomEnd = function(oldLevel, newLevel) {
	// recalculate the average pixel distance
    this._avgPixelDistance = this.getAvgMapPixelDistance();
}

// determines the average distance in meters of one pixel. this is
// used for the clustering algorithm.
o8.Gis.Map.prototype.getAvgMapPixelDistance = function() {
	var size = this._map.getSize();

	// at low zoom levels, for places far from the equator, the
	// lngdist and latdist may differ significantly
	var p1 = this._map.fromContainerPixelToLatLng(new GPoint(1,size.height / 2)); 
    var p2 = this._map.fromContainerPixelToLatLng(new GPoint(1,(size.height / 2) + 1)); 
	var p3 = this._map.fromContainerPixelToLatLng(new GPoint(2,size.height / 2)); 
    var lngdist = p1.distanceFrom(p2);       
    var latdist = p1.distanceFrom(p3); 

	return (lngdist + latdist) / 2.0;
}

// toggles the sidepanel (open/close)
o8.Gis.Map.prototype.toggleSidePanel = function(xPosition) {
	this._map.removeControl(this.lmc);
	this._map.addControl(this.lmc, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(xPosition + 30, 7)));
}

// determines the working area of the map. it is intentionally slightliy
// greater (the double size of the currently visible area) than the
// visible area to provide a more fluent interaction. 
o8.Gis.Map.prototype.getWorkingAreaBounds = function() {
    var self = this;
	var bounds = self._map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();	

	var lngExtend = (northEast.lng() - southWest.lng()) / 2.0;
	var latExtend = (northEast.lat() - southWest.lat()) / 2.0;
	// limit the glatlng values from -180 to 180 and -90 to 90
	var tmpLat = southWest.lat() - latExtend < -90.0 ? -90.0 : southWest.lat() - latExtend;
	var tmpLng = southWest.lng() - lngExtend < -180.0 ? -180.0 : southWest.lng() - lngExtend;
	var workingSouthWest = new GLatLng(tmpLat, tmpLng);
	tmpLat = northEast.lat() + latExtend > 90.0 ? 90.0 : northEast.lat() + latExtend;
	tmpLng = northEast.lng() + lngExtend > 180.0 ? 180.0 : northEast.lng() + lngExtend;
	var workingNorthEast = new GLatLng(tmpLat, tmpLng);
	var workingBounds = new GLatLngBounds(workingSouthWest, workingNorthEast);

	return workingBounds;
}

// this is a helper function to retrieve the selected dynamic
// layers that might require updated data.
o8.Gis.Map.prototype.getSelectedLayers = function() {
    var selectedLayers = [];
	for(var i = 0; i < this._mapControls.length; i++) {
        if(this._mapControls[i].getSelectedLayers) {
            var tmpLayers = this._mapControls[i].getSelectedLayers();
            for(var j = 0; j < tmpLayers.length; j++) {
                selectedLayers.push(tmpLayers[j]);
            }
        }
    }
    return selectedLayers;
}

// updates the markers of the map on all visible layers.
o8.Gis.Map.prototype.updateMarkers = function() {
    // determine the selected layers, if any		
	var selectedLayers = this.getSelectedLayers();
	var layerIds = [];
    for(var i = 0; i < selectedLayers.length; i++) {
        layerIds.push(selectedLayers[i].getLayerId());
    }

    //nothing to do?
    if(layerIds.length == 0) {
	    return;
	}	
	
	// get working area bounds
	var self = this;
	var bounds = this.getWorkingAreaBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	
	var layerIdStr = "['" + layerIds.join("','") + "']";	
	var jsonReq = '{layerIds:' + layerIdStr + ', southWest:{Lat:' + southWest.lat() + ', Lon:' + southWest.lng() + '}, northEast:{Lat:' + northEast.lat() + ', Lon:' + northEast.lng() + '}, clusterRadius:' + (self._avgPixelDistance * 30) + '}';	

	// fetch markers within bounds
	$.ajax({
  		type: "POST",
  		url: geoScriptServiceUrl + '/GetLyrMarkersClustered',
  		data: jsonReq,
  		contentType: 'application/json; charset=utf-8',
  		dataType: 'json',
  		success: function(data) {
  		    var selectedLayers = self.getSelectedLayers();
  		    for(var i = 0; i < data.length; i++) {
  		        for(var j = 0; j < selectedLayers.length; j++) {
  		            if(data[i].LayerId == selectedLayers[j].getLayerId()) {
  		                selectedLayers[j].updateMarkers(data[i]);
                        break;
  		            }
                }
  		    }
  		}
	});
}

// updates the polylines of the map on all visible layers. 
o8.Gis.Map.prototype.updatePolylines = function() {
    // determine the selected layers, if any
	var selectedLayers = this.getSelectedLayers();	
	var layerIds = [];
    for(var i = 0; i < selectedLayers.length; i++) {
        if(!selectedLayers[i].polylinesLoaded()) {
            layerIds.push(selectedLayers[i].getLayerId());
        }
    }
    
    //nothing to do?
    if(layerIds.length == 0) {
	    return;
	}

    var self = this;
	var layerIdStr = "['" + layerIds.join("','") + "']";	
	var jsonReq = '{layerIds:' + layerIdStr + '}';	

	// fetch markers within bounds
	$.ajax({
  		type: "POST",
  		url: geoScriptServiceUrl + '/GetLyrPolylines',
  		data: jsonReq,
  		contentType: 'application/json; charset=utf-8',
  		dataType: 'json',
  		success: function(data) {
  		    var selectedLayers = self.getSelectedLayers();
  		    for(var i = 0; i < data.length; i++) {
  		        for(var j = 0; j < selectedLayers.length; j++) {
  		            if(data[i].LayerId == selectedLayers[j].getLayerId()) {
  		                selectedLayers[j].updatePolylines(data[i]);
                        break;
  		            }
                }
  		    }
  		}
	});
}


// this class implements the layering functionality of google maps.
//
o8.Gis.MapLayer = function(layerId, icons) {
    this._layerId = layerId;
    this._icons = icons;
    this._map = null;
    this._polylinesLoaded = false;	
	this._markers = [];
	this._polylines = [];
}

o8.Gis.MapLayer.prototype = new GOverlay();

o8.Gis.MapLayer.prototype.getLayerId = function() {
    return this._layerId;
}

o8.Gis.MapLayer.prototype.polylinesLoaded = function() {
    return this._polylinesLoaded;
}

// interface implementation of GOverlay. Initializes the layer.
o8.Gis.MapLayer.prototype.initialize = function(map) {
	this._map = map;
	
	// forces the map to refresh (load) the markers
	this._map.setCenter(this._map.getCenter());
}

// interface implementation of GOverlay. Removes the current layer
// with all contents from the map.
o8.Gis.MapLayer.prototype.remove = function() {
    this._polylinesLoaded = false;

	this.removeMarkers();
	this.removePolylines();
}

// interface implementation of GOverlay. Don't get the idea behind.
o8.Gis.MapLayer.prototype.copy = function() {
	return new GOverlay();
}

// interface implementation of GOverlay. This method is called from
// within Google Maps. The argument force is true upon map scaling.
o8.Gis.MapLayer.prototype.redraw = function(force) {
	// force is true, on zoom in/out
	if(force) {
	    // redraw is called earlier than moveend
	    // byremoving the markers here displaying the markers shortly
	    // on a wrong position is prevented	
		this.removeMarkers();	
	}	
}

// adds a new marker to the map layer. The layer now takes care of
// removin it if it's falls out of the visibility range.
o8.Gis.MapLayer.prototype.addMarker = function(marker) {
    // check, if marker not already added
	if(this.containsMarker(marker)) {
			return false;
    }

    // add the new marker
	this._markers.push(marker);
	this._map.addOverlay(marker);
	return true;
}

// removes a marker from the map layer.
o8.Gis.MapLayer.prototype.removeMarker = function(marker) {
	// do event housekeeping (prevent memory leaking)
	GEvent.clearInstanceListeners(marker);

	// remove the marker from the map and from the array
	this._map.removeOverlay(marker);
	this.removeFromArray(this._markers, marker); 
}

// determines, if there is a marker at the given geo position.
o8.Gis.MapLayer.prototype.containsMarker = function(marker) {
	var found = false;
	for(var i = 0; i < this._markers.length; i++) {
		var otherLatLong = this._markers[i].getLatLng();
		if(otherLatLong.equals(marker.getLatLng())) {
			found = true;
			break;
		}
	}

	return found;
}

// removes all markers on the current map layer if no bounds are
// given, all markers will be removed.
o8.Gis.MapLayer.prototype.removeMarkers = function(bounds) {
	for (var i = this._markers.length - 1; i >= 0; i--) {
	    if(!bounds || !bounds.containsLatLng(this._markers[i].getLatLng())) {
		    this.removeMarker(this._markers[i]);
		}
	}
	
	//GLog.write('removeMarkers .. now containing ' + this._markers.length + ' markers');
}

// adds a polyline to the current layer
o8.Gis.MapLayer.prototype.addPolyline = function(polyline) {
    this._polylinesLoaded = true;
    // add the new polylines
	this._polylines.push(polyline);
	this._map.addOverlay(polyline);
	return true;
}

// removes all polylines from the current layer
o8.Gis.MapLayer.prototype.removePolylines = function() {
    for(var i = this._polylines.length - 1; i >= 0; i--) {
        // do event housekeeping (prevent memory leaking)
	    GEvent.clearInstanceListeners(this._polylines[i]);

	    // remove the marker from the map and from the array
	    this._map.removeOverlay(this._polylines[i]);
	    this.removeFromArray(this._polylines, this._polylines[i]); 
    }
}

o8.Gis.MapLayer.prototype.updateMarkers = function(data) {
    if(data == null) {
        return;
    }

    // add markers to map
	if(data.GeoMarkers != null) {
	    for(var i = 0; i < data.GeoMarkers.length; i++) {
	        var geoMarker = data.GeoMarkers[i];
		    var latLong = new GLatLng(geoMarker.GeoPos.Lat, geoMarker.GeoPos.Lon);
		    var m = new GMarker(latLong, { icon: this._icons[geoMarker.Type], title: geoMarker.Title });
		    // add specific properties
		    m.extendedGisMarkerId = geoMarker.MarkerId;
		    m.extendedGisMarkerType = geoMarker.Type;
		    m.extendedGisMarkerProperties = geoMarker.Properties;
            if(this.addMarker(m)) {
                // click handler is registeres on the map level				
		    }
	    }
	}
	
	if(data.GeoMarkerClusters != null) {
	    var self = this;
	    for(var i = 0; i < data.GeoMarkerClusters.length; i++) {
	        var geoMarkerCluster = data.GeoMarkerClusters[i];
		    var latLong = new GLatLng(geoMarkerCluster.GeoPos.Lat, geoMarkerCluster.GeoPos.Lon);
		    var m = new GMarker(latLong, { icon: this._icons[geoMarkerCluster.Type], title: geoMarkerCluster.ClusterSize + ' Optionen' });
	        // add specific properties
		    m.extendedGisMarkerId = geoMarkerCluster.MarkerId;
		    m.extendedGisMarkerType = geoMarkerCluster.Type;
		    m.extendedGisMarkerProperties = geoMarkerCluster.Properties;
	        if(this.addMarker(m)) {
			    // move the clicked cluster to center, zoom in
			    GEvent.addListener(m, 'click', function() { 
           		    self._map.setCenter(this.getLatLng(), self._map.getZoom() + 2);
        	    });
		    }
	    }
	}
	
	//GLog.write('Fetched (' + data.GeoMarkers.length + ') markers...');
	//GLog.write('Fetched (' + data.GeoMarkerClusters.length + ') marker clusters...');
	//GLog.write('now containing ' + this._markers.length + ' markers');
}

o8.Gis.MapLayer.prototype.updatePolylines = function(data) {
    if((data == null) || (data.GeoPolylines == null)) {
        return;
    }
    
    for(var i = 0; i < data.GeoPolylines.length; i++) {
        var polyline = data.GeoPolylines[i];
        var m = GPolyline.fromEncoded({   
            color: '#FF0000',   
            weight: polyline.Weight,   
            opacity: polyline.Opacity,   
            points: polyline.PointsEncoded,   
            levels: polyline.LevelsEncoded,   
            numLevels: polyline.NumLevels,   
            zoomFactor: polyline.ZoomFactor   
        });
        
        // add specific properties
        m.extendedGisPolylineId = polyline.PolylineId;
        m.extendedGisPolylineProperties = polyline.Properties;
        
        this.addPolyline(m);   
    }
}

/**
 * Removes value from array. O(N).
 *
 * @param {Array} array  The array to modify.
 * @param {any} value  The value to remove.
 * @param {Boolean} opt_notype  Flag to disable type checking in equality.
 * @return {Number}  The number of instances of value that were removed.
 */
o8.Gis.MapLayer.prototype.removeFromArray = function(array, value, opt_notype) {
	var shift = 0;
	for(var i = 0; i < array.length; ++i) {
		if (array[i] === value || (opt_notype && array[i] == value)) {
			array.splice(i--, 1);
			shift++;
		}
	}
	return shift;
}



// Layer Control
o8.Gis.LayerControl = function(opts, controlPos) {
    this._opts = opts;
    this._controlPos = controlPos;
    this._layerstate = null;
}

// Our control inherits from GControl
o8.Gis.LayerControl.prototype = new GControl();

o8.Gis.LayerControl.prototype.initialize = function(map) {  
    // creating the needed div's
    var container = document.createElement('div');
    var button = document.createElement('div');
    var panel = document.createElement('div');
    var timer = null;

    container.className = 'gis-layer-ctl-container';
    button.className = 'gis-layer-ctl-more-btn';
    panel.className = 'gis-layer-ctl-pnl';

    button.appendChild(document.createTextNode('Mehr...'));

    // adding functionalities to the button events
    $(button).hover(function() {
            clearTimeout(timer);
            // using jQuery fade-in animation
            $(panel).animate({ opacity: 'show' }, 100);
        },
        function() {
            timer = setTimeout(function() {
                // using jQuery fade-out animation                                             
                $(panel).animate({ opacity: 'hide' }, 150);
            }, 200);
    });

    // adding button to the container div
    container.appendChild(button);

    // adding funcionalities to the panel events
    $(panel).hover(function() {
            clearTimeout(timer);
        },
        function() {
            clearTimeout(timer);
            timer = setTimeout(function() {
                $(panel).animate({ opacity: 'hide' }, 400);
            }, 500);
    });

    // creating checkboxes and adding them to the panel
    this._layerstate = [];
    var self = this;
    for (var i = 0; i < this._opts.length; i++) {
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.defaultChecked = this._opts[i].Checked;
        $(checkbox).attr('layerindex', i);     
    
        $(checkbox).click(function() {    
            var index = $(this).attr('layerindex');
            if(this.checked) {
                map.addOverlay(self._opts[index].obj);
            }
            else {
                map.removeOverlay(self._opts[index].obj);
            }
        });

        panel.appendChild(checkbox);

        var label = document.createElement('label');
        label.appendChild(document.createTextNode(this._opts[i].name));        
        panel.appendChild(label);
        panel.appendChild(document.createElement('br'));

        this._layerstate[i] = this._opts[i];
        this._layerstate[i].cbx = checkbox;

        // adding default layers
        if (checkbox.defaultChecked) {
            map.addOverlay(this._opts[i].obj);
        }
    }
    //Horizontal bar only when more than one check box
    if(this._opts.length > 1)
    {
        // adding horizontal separator line
        var hr = document.createElement('hr');
        hr.style.width = '92%';
        hr.style.height = '1px';
        hr.style.textAlign = 'center';
        hr.style.border = '1px';
        hr.style.color = '#e2e2e2';
        hr.style.backgroundColor = '#e2e2e2';
        panel.appendChild(hr);
    }
    
    // adding 'Hide All' Link
    var linkDiv = document.createElement('div');
    linkDiv.style.textAlign = 'center';
    var hideAllLnk = document.createElement('a');
    hideAllLnk.className = 'gis-layer-ctl-hide-all-lnk';
    hideAllLnk.appendChild(document.createTextNode('alle löschen'));
    $(hideAllLnk).click(function() {
        for(var i = 0; i < self._layerstate.length; i++) {
            if(self._layerstate[i].cbx.checked) {
                $(self._layerstate[i].cbx).attr('checked', '');
                map.removeOverlay(self._opts[i].obj);
            }
        }
    });
    //'Alle löschen' only when more than one check box
    if(this._opts.length > 1)
    {
        linkDiv.appendChild(hideAllLnk);
        panel.appendChild(linkDiv);
    }

    container.appendChild(panel);
    map.getContainer().appendChild(container);
    return container;
}

o8.Gis.LayerControl.prototype.getSelectedLayers = function() {
    var selLayers = [];
    for(var i = 0; i < this._layerstate.length; i++) {
        if(this._layerstate[i].cbx.checked &&
                    (this._layerstate[i].obj instanceof o8.Gis.MapLayer)) {
            selLayers.push(this._layerstate[i].obj);
        }
    }   
    return selLayers;
}
	  
o8.Gis.LayerControl.prototype.getDefaultPosition = function() {
    if(typeof(this._controlPos) != 'undefined') {
	    return this._controlPos;
    }
    else {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(230, 7));
    }
}



// Sidebar Control
o8.Gis.SidebarControl = function(parent, opts, controlPos) {
    this.parentInst = parent;
    this._opts = opts;
    this._controlPos = controlPos;
    this._map = null;
    this._layerstate = null;
}

o8.Gis.SidebarControl.prototype = new GControl();

o8.Gis.SidebarControl.prototype.initialize = function(map) {
    this._map = map;

    // creating the needed div's
    var sidebarContainer = document.createElement('div');
    var sidebarPanel = document.createElement('div');
    var sidebarToggleButton = document.createElement('div');

    sidebarContainer.className = 'gis-sidebar-ctl-container';
    sidebarPanel.className = 'gis-sidebar-ctl-pnl';

    // adding 'Fill All' Link
    linkDiv = document.createElement('div');
    linkDiv.style.textAlign = 'center';
    hideAllLnk = document.createElement('a');
    hideAllLnk.className = 'gis-layer-ctl-hide-all-lnk';
    hideAllLnk.appendChild(document.createTextNode('Alle Aktivitäten einblenden'));
    $(hideAllLnk).click(function() {
        for (var i = 0; i < self._layerstate.length; i++) {
            if (!self._layerstate[i].cbx.checked) {
                if (self._opts[i].name != '------Winter-----' && self._opts[i].name != '------Sommer-----') {
                    $(self._layerstate[i].cbx).attr('checked', 'checked');
                    map.addOverlay(self._opts[i].obj);
                }
            }
        }
    });

    linkDiv.appendChild(hideAllLnk);
    sidebarPanel.appendChild(linkDiv);

    // adding 'Hide All' Link
    var linkDiv = document.createElement('div');
    linkDiv.style.textAlign = 'center';
    var hideAllLnk = document.createElement('a');
    hideAllLnk.className = 'gis-layer-ctl-hide-all-lnk';
    hideAllLnk.appendChild(document.createTextNode('Alle Aktivitäten ausblenden'));
    $(hideAllLnk).click(function() {
        for (var i = 0; i < self._layerstate.length; i++) {
            if (self._layerstate[i].cbx.checked) {
                if (self._opts[i].name != '------Winter-----' && self._opts[i].name != '------Sommer-----') {
                    $(self._layerstate[i].cbx).attr('checked', '');
                    map.removeOverlay(self._opts[i].obj);
                }
            }
        }
    });

    linkDiv.appendChild(hideAllLnk);
    sidebarPanel.appendChild(linkDiv);

    // adding horizontal separator line
    var hr = document.createElement('hr');
    hr.style.width = '92%';
    hr.style.height = '1px';
    hr.style.textAlign = 'center';
    hr.style.border = '1px';
    hr.style.color = '#e2e2e2';
    hr.style.backgroundColor = '#e2e2e2';
    sidebarPanel.appendChild(hr);

    this._layerstate = [];
    var self = this;

    for (var i = 0; i < this._opts.length; i++) {
        if (this._opts[i].name == '------Winter-----') {
            var title = document.createElement('b');
            title.appendChild(document.createElement('label').appendChild(document.createTextNode("Winter")));
            sidebarPanel.appendChild(title);
            sidebarPanel.appendChild(document.createElement('br'));

            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.defaultChecked = true;
            checkbox.className = 'gis-layer-checkbox-' + i;
            $(checkbox).attr('layerindex', i);

            this._layerstate[i] = this._opts[i + 1];
            this._layerstate[i].cbx = checkbox;
        }
        else if (this._opts[i].name == '------Sommer-----') {
            var title = document.createElement('b');
            title.appendChild(document.createElement('label').appendChild(document.createTextNode("Sommer")));
            sidebarPanel.appendChild(title);
            sidebarPanel.appendChild(document.createElement('br'));

            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.defaultChecked = true;
            checkbox.className = 'gis-layer-checkbox-' + i;
            $(checkbox).attr('layerindex', i);

            this._layerstate[i] = this._opts[i + 1];
            this._layerstate[i].cbx = checkbox;
        }
        else {
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.defaultChecked = this._opts[i].Checked;
            checkbox.className = 'gis-layer-checkbox-' + i;
            $(checkbox).attr('layerindex', i);

            checkbox.mapUpdateLayer = function() {
                var index = $(this).attr('layerindex');
                if ($(this).is(":checked")) {
                    //if(!checkbox.mapOverlayIsShown){
                    map.addOverlay(self._opts[index].obj);
                    //    checkbox.mapOverlayIsShown = true;
                    //}
                }
                else {
                    //if(checkbox.mapOverlayIsShown){
                    map.removeOverlay(self._opts[index].obj);
                    //    checkbox.mapOverlayIsShown = false;
                    //}
                }
            }

            $(checkbox).click(function() {
                this.mapUpdateLayer();
            });

            sidebarPanel.appendChild(checkbox);

            if (this._opts[i].iconUrl) {
                var icon = document.createElement('img');
                icon.src = this._opts[i].iconUrl;
                sidebarPanel.appendChild(icon);
            }
            var label = document.createElement('label');
            label.appendChild(document.createTextNode(this._opts[i].name));
            sidebarPanel.appendChild(label);
            sidebarPanel.appendChild(document.createElement('br'));

            this._layerstate[i] = this._opts[i];
            this._layerstate[i].cbx = checkbox;

            // add default layers
            if (checkbox.defaultChecked) {
                map.addOverlay(this._opts[i].obj);
            }
        }
    }

    sidebarToggleButton.className = 'gis-sidebar-ctl-tgl-btn';
    sidebarContainer.appendChild(sidebarToggleButton);
    sidebarContainer.appendChild(sidebarPanel);

    var theParent = this.parentInst;
    $(sidebarToggleButton).click().toggle(function() {
        $(sidebarPanel).animate({
            width: 'show',
            opacity: 'show'
        }, {
            duration: 200,
            complete: function() { theParent.toggleSidePanel($(sidebarContainer).width()); }
        });
    }, function() {
        $(sidebarPanel).animate({
            width: 'hide',
            opacity: 'hide'
        }, {
            duration: 200,
            complete: function() { theParent.toggleSidePanel(0); }
        });

    });

    map.getContainer().appendChild(sidebarContainer);
    return sidebarContainer;
}

o8.Gis.SidebarControl.prototype.getSelectedLayers = function() {
    var selLayers = [];
    for(var i = 0; i < this._layerstate.length; i++) {
        if(this._layerstate[i].cbx.checked &&
                    (this._layerstate[i].obj instanceof o8.Gis.MapLayer)) {
            selLayers.push(this._layerstate[i].obj);
        }
    }   
    return selLayers;
}

o8.Gis.SidebarControl.prototype.getDefaultPosition = function() {
    if(typeof(this._controlPos) != 'undefined') {
	    return this._controlPos;
    }
    else {
	    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 7));
    }
}



// Coordbox Control
o8.Gis.CoordboxControl = function(controlPos) {
    this.controlPos = controlPos;
    this._map = null;
    this.div = null;
    this.movehandler = null;
}

o8.Gis.CoordboxControl.prototype = new GControl(false, true);

o8.Gis.CoordboxControl.prototype.initialize = function(map) {
    this._map = map;

    this.container = document.createElement('div');
    this.container.className = 'GMapCtlCoordbox';
    this.container.style.width = '180px';
    this.container.style.border = '1px solid black';
    this.container.style.backgroundColor = 'white';
    this.container.style.color = 'black';
    this.container.style.textAlign = 'center';
    this.container.style.font = 'normal 12px Arial,sans-serif';
    this.container.style.padding = '1px 3px';
    
    map.getContainer().appendChild(this.container);
    var self = this;
    this.movehandler = GEvent.addListener(this._map, 'move', function() { self.update(); });

    this.update();
    return this.container;
}

o8.Gis.CoordboxControl.prototype.getDefaultPosition = function() {
    if(typeof(this.controlPos) != 'undefined') {
	return this.controlPos;
    }
    else {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 35));
    }
}

o8.Gis.CoordboxControl.prototype.update = function() {
    var lat = this._map.getCenter().lat();
    var lng = this._map.getCenter().lng();
    // Latitude
    var sign = (lat > 0 ? 'N' : 'S');
    lat = Math.abs(lat);
    var degrees = Math.floor(lat);
    var minutes = Math.floor((lat - degrees) * 60);
    var seconds = Math.floor(((lat - degrees) * 60 - minutes) * 60);
    var deglat = degrees + '°' + minutes + '\' ' + seconds + '" ' + sign;
    // Longitude
    sign = (lng > 0 ? 'E' : 'W');
    lng = Math.abs(lng);
    degrees = Math.floor(lng);
    minutes = Math.floor((lng - degrees) * 60);
    seconds = Math.floor(((lng - degrees) * 60 - minutes) * 60);
    var deglng = degrees + '°' + minutes + '\' ' + seconds + '" ' + sign;
    this.container.innerHTML = deglat + ' ' + deglng;
}

o8.Gis.CoordboxControl.prototype.unload = function() {
    GEvent.removeListener(this.movehandler);
    return;
}



// Crosshair Control
o8.Gis.CrosshairControl = function() {
    this._map = null; 
    this.movehandler = null;
}

o8.Gis.CrosshairControl.prototype = new GControl(false, false);

o8.Gis.CrosshairControl.prototype.unload = function() {
    GEvent.removeListener(this.movehandler);
}

o8.Gis.CrosshairControl.prototype.initialize = function(map) {
    this._map = map;
    
    this.container = document.createElement('div');
    this.container.style.width = '15px';
    this.container.style.height = '15px';
    
    var box1 = document.createElement('div');
    box1.style.position = 'absolute';
    box1.style.width = '7px';
    box1.style.height = '7px';
    box1.style.borderRight = 'solid 1px black';
    box1.style.borderBottom = 'solid 1px black';
    this.container.appendChild(box1);
    
    var box2 = document.createElement('div');
    box2.style.position = 'absolute';
    box2.style.top = '7px';
    box2.style.left = '7px';
    box2.style.width = '7px';
    box2.style.height = '7px';
    box2.style.borderLeft = 'solid 1px black';
    box2.style.borderTop = 'solid 1px black';
    this.container.appendChild(box2);
    
    map.getContainer().appendChild(this.container);   
    return this.container;
}

o8.Gis.CrosshairControl.prototype.getDefaultPosition = function() {
    var cc = this._map.fromLatLngToDivPixel(this._map.getCenter());
    var left = cc.x - 15 / 2;
    var right = cc.y - 15 / 2;
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(left, right));
}


/*
 * jQuery UI 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);

/*
 * jQuery UI Autocomplete @VERSION
 *
 * Copyright (c) 2007, 2008 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.autocomplete", {

	_init: function() {
		// TODO move these to instance properties?
		$.extend(this.options, {
			delay: this.options.delay != undefined ? this.options.delay : (this.options.url? this.options.ajaxDelay : this.options.localDelay),
			max: this.options.max != undefined ? this.options.max : (this.options.scroll? this.options.scrollMax : this.options.noScrollMax),
			highlight: this.options.highlight || function(value) { return value; }, // if highlight is set to false, replace it with a do-nothing function
			formatMatch: this.options.formatMatch || this.options.formatItem // if the formatMatch option is not specified, then use formatItem for backwards compatibility
		});

		var input = this.element[0],
			options = this.options,
			// Create $ object for input element
			$input = $(input).attr("autocomplete", "off").addClass(options.inputClass),
			KEY = $.ui.keyCode,
			previousValue = "",
			cache = $.ui.autocomplete.cache(options),
			hasFocus = 0,
			config = {
				mouseDownOnSelect: false
			},
			timeout,
			blockSubmit,
			lastKeyPressCode,
			select = $.ui.autocomplete.select(options, input, selectCurrent, config);

		if(options.result) {
			$input.bind('result.autocomplete', options.result);
		}

		// prevent form submit in opera when selecting with return key
		$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
			if (blockSubmit) {
				blockSubmit = false;
				return false;
			}
		});

		// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
		$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
			// track last key pressed
			lastKeyPressCode = event.keyCode;
			switch(event.keyCode) {

				case KEY.UP:
					event.preventDefault();
					if ( select.visible() ) {
						select.prev();
					} else {
						onChange(0, true);
					}
					break;

				case KEY.DOWN:
					event.preventDefault();
					if ( select.visible() ) {
						select.next();
					} else {
						onChange(0, true);
					}
					break;

				case KEY.PAGE_UP:
					event.preventDefault();
					if ( select.visible() ) {
						select.pageUp();
					} else {
						onChange(0, true);
					}
					break;

				case KEY.PAGE_DOWN:
					event.preventDefault();
					if ( select.visible() ) {
						select.pageDown();
					} else {
						onChange(0, true);
					}
					break;

				// matches also semicolon
				case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
				case KEY.TAB:
				case KEY.ENTER:
					if( selectCurrent() ) {
						// stop default to prevent a form submit, Opera needs special handling
						event.preventDefault();
						blockSubmit = true;
						return false;
					}
					break;

				case KEY.ESCAPE:
					select.hide();
					break;

				default:
					clearTimeout(timeout);
					timeout = setTimeout(onChange, options.delay);
					break;
			}
		})
		.bind('focus.autocomplete', function(){
			// track whether the field has focus, we shouldn't process any
			// results if the field no longer has focus
			hasFocus++;
		})
		.bind('blur.autocomplete', function() {
			hasFocus = 0;
			if (!config.mouseDownOnSelect) {
				hideResults();
			}
		})
		.bind('click.autocomplete', function() {
			// show select when clicking in a focused field
			if ( hasFocus++ > 1 && !select.visible() ) {
				onChange(0, true);
			}
		}).bind("search.autocomplete", function() {
			// TODO why not just specifying both arguments?
			var fn = (arguments.length > 1) ? arguments[1] : null;
			function findValueCallback(q, data) {
				var result;
				if( data && data.length ) {
					for (var i=0; i < data.length; i++) {
						if( data[i].result.toLowerCase() == q.toLowerCase() ) {
							result = data[i];
							break;
						}
					}
				}
				if( typeof fn == "function" ) fn(result);
				else $input.trigger("result.autocomplete", result && [result.data, result.value]);
			}
			$.each(trimWords($input.val()), function(i, value) {
				request(value, findValueCallback, findValueCallback);
			});
		})
		.bind("flushCache.autocomplete", function() {
			cache.flush();
		})
		.bind("setOptions.autocomplete", function() {
			$.extend(options, arguments[1]);
			// if we've updated the data, repopulate
			if ( "data" in arguments[1] )
				cache.populate();
		})
		.bind("unautocomplete", function() {
			select.unbind();
			//$input.unbind(); << this would unbind all events. Bad news if we've had another plugin applied to this element. AAP 03.12.09
			$(input).unbind(".autocomplete");
			$(input.form).unbind(".autocomplete");
		});

		// Private methods
		function selectCurrent() {
			var selected = select.selected();
			if( !selected ) return false;

			var v = selected.result;
			previousValue = v;

			if ( options.multiple ) {
				var words = trimWords($input.val());
				if ( words.length > 1 ) {
					v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
				}
				v += options.multipleSeparator;
			}

			$input.val(v);
			hideResultsNow();
			$input.trigger("result.autocomplete", [selected.data, selected.value]);
			return true;
		};

		function onChange(crap, skipPrevCheck) {
			if( lastKeyPressCode == KEY.DELETE ) {
				select.hide();
				return;
			}

			var currentValue = $input.val();

			if ( !skipPrevCheck && currentValue == previousValue )
				return;

			previousValue = currentValue;

			currentValue = lastWord(currentValue);
			if ( currentValue.length >= options.minChars) {
				//$input.addClass(options.loadingClass);
				//IE6-7 Bug with this class
				if (!options.matchCase)
					currentValue = currentValue.toLowerCase();
				request(currentValue, receiveData, hideResultsNow);
			} else {
				stopLoading();
				select.hide();
			}
		};

		function trimWords(value) {
			if ( !value ) {
				return [""];
			}
			if ( !options.multiple ) {
				return [value];
			}
			var words = value.split( options.multipleSeparator );
			var result = [];
			$.each(words, function(i, value) {
				if ( $.trim(value) )
					result[i] = $.trim(value);
			});
			return result;
		};

		function lastWord(value) {
			var words = trimWords(value);
			return words[words.length - 1];
		};

		// fills in the input box w/the first match (assumed to be the best match)
		// q: the term entered
		// sValue: the first matching result
		function autoFill(q, sValue){
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			// if the last user key pressed was backspace, don't autofill
			if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != $.ui.keyCode.BACKSPACE ) {
				// fill in the value (keep the case the user has typed)
				$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
				// select the portion of the value not typed by the user (so the next character will erase)
				$.ui.autocomplete.selection(input, previousValue.length, previousValue.length + sValue.length);
			}
		};

		function hideResults() {
			clearTimeout(timeout);
			timeout = setTimeout(hideResultsNow, 200);
		};

		function hideResultsNow() {
			var wasVisible = select.visible();
			select.hide();
			clearTimeout(timeout);
			stopLoading();
			if (options.mustMatch) {
				// call search and run callback
				$input.autocomplete("search", function (result){
						// if no value found, clear the input box
						if( !result ) {
							if (options.multiple) {
								var words = trimWords($input.val()).slice(0, -1);
								$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
							}
							else
								$input.val( "" );
						}
					}
				);
			}
			if (wasVisible)
				// position cursor at end of input field
				$.ui.autocomplete.selection(input, input.value.length, input.value.length);
		};

		function receiveData(q, data) {
			if ( data && data.length && hasFocus ) {
				stopLoading();
				select.display(data, q);
				autoFill(q, data[0].value);
				select.show();
			} else {
				hideResultsNow();
			}
		};

		function request(term, success, failure) {
			if (!options.matchCase)
				term = term.toLowerCase();
			var data = cache.load(term);
			// recieve the cached data
			if (data && data.length) {
				success(term, data);
			} // if an AJAX url has been supplied, try loading the data now
			else if( (typeof options.url == "string") && (options.url.length > 0) ){

				var extraParams = {
					timestamp: +new Date()
				};
				$.each(options.extraParams, function(key, param) {
					extraParams[key] = typeof param == "function" ? param(term) : param;
				});

				$.ajax({
					// try to leverage ajaxQueue plugin to abort previous requests
					mode: "abort",
					// limit abortion to this input
					port: "autocomplete" + input.name,
					dataType: options.dataType,
					url: options.url,
					data: $.extend({
						q: lastWord(term),
						limit: options.max
					}, extraParams),
					success: function(data) {
						var parsed = options.parse && options.parse(data) || parse(data);
						cache.add(term, parsed);
						success(term, parsed);
					}
				});
			}

			else if (options.source && typeof options.source == 'function') {
				var resultData = options.source(term);
				var parsed = (options.parse) ? options.parse(resultData) : resultData;

				cache.add(term, parsed);
				success(term, parsed);
			} else {
				// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
				select.emptyList();
				failure(term);
			}
		};

		function parse(data) {
			var parsed = [];
			var rows = data.split("\n");
			for (var i=0; i < rows.length; i++) {
				var row = $.trim(rows[i]);
				if (row) {
					row = row.split("|");
					parsed[parsed.length] = {
						data: row,
						value: row[0],
						result: options.formatResult && options.formatResult(row, row[0]) || row[0]
					};
				}
			}
			return parsed;
		};

		function stopLoading() {
			//$input.removeClass(options.loadingClass);
			//IE6-7 Bug with this class
		};

	}, //End _init
	
	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this.ui()]);
		return this.element.triggerHandler(n == 'autocomplete' ? n : 'autocomplete'+n, [event, this.ui()], this.options[n]);
	},

	// Public methods
	ui: function(event) {
		return {
			options: this.options,
			element: this.element
		};
	},
	result: function(handler) {
		return this.element.bind("result.autocomplete", handler);
	},
	search: function(handler) {
		return this.element.trigger("search.autocomplete", [handler]);
	},
	flushCache: function() {
		return this.element.trigger("flushCache.autocomplete");
	},
	setData: function(key, value){
		return this.element.trigger("setOptions.autocomplete", [{ key: value }]);
	},
	destroy: function() {
		this.element
			.removeAttr('disabled')
			.removeClass('ui-autocomplete-input');
		return this.element.trigger("unautocomplete");
	},
	enable: function() {
		this.element
			.removeAttr('disabled')
			.removeClass('ui-autocomplete-disabled');
		this.disabled = false;
	},
	disable: function() {
		this.element
			.attr('disabled', true)
			.addClass('ui-autocomplete-disabled');
		this.disabled = true;
	}
});

$.extend($.ui.autocomplete, {
	defaults: {
		inputClass: "ui-autocomplete-input",
		resultsClass: "ui-widget ui-widget-content ui-autocomplete-results",
		loadingClass: "ui-autocomplete-loading",
		minChars: 1,
		ajaxDelay: 400,
		localDelay: 10,
		matchCase: false,
		matchSubset: true,
		matchContains: false,
		cacheLength: 10,
		scrollMax: 150,
		noScrollMax: 10,
		mustMatch: false,
		extraParams: {},
		selectFirst: true,
		formatItem: function(row) { return row[0]; },
		formatMatch: null,
		autoFill: false,
		width: 0,
		multiple: false,
		multipleSeparator: ", ",
		highlight: function(value, term) {
			return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
		},
		scroll: true,
		scrollHeight: 180
	}
});

$.ui.autocomplete.cache = function(options) {

	var data = {};
	var length = 0;

	function matchSubset(s, sub) {
		if (!options.matchCase)
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){ 
			length++;
		}
		data[q] = value;
	}

	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;

		// track all options for minChars = 0
		stMatchSets[""] = [];

		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;

			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] )
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};

			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}

	// populate any existing data
	setTimeout(populate, 25);

	function flush(){
		data = {};
		length = 0;
	}

	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/* 
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}
				return csub;
			} else 
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.ui.autocomplete.select = function (options, input, select, config) {
	var CLASSES = {
		//ACTIVE: "ui-state-active" << From the Css Framework Docs : .ui-state-active: Class to be applied on mousedown to clickable button-like elements.
		//Since this isnt a button element, but a hybrid 'menu item', use a custom class.
		//See: http://jqueryui.pbwiki.com/Menu 2- Visual Design
		DEFAULT: 'ui-autocomplete-state-default',
		ACTIVE: 'ui-autocomplete-state-active'
	};

	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

	// Create results
	function init() {
		if (!needsInit) return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		//.css("position", "absolute") set this up in the css in case users want to do something wonky with the positioning.
		.appendTo(document.body);

		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			var e = target(event);
			if(e.nodeName && e.nodeName.toUpperCase() == 'LI') {
				active = $("li", list).removeClass(CLASSES.ACTIVE).index(e);
				$(e).addClass(CLASSES.ACTIVE);
			}
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});

		if( options.width > 0 )
			element.css("width", options.width);

		needsInit = false;
	} 

	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
		var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
		if(options.scroll) {
			var offset = 0;
			listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
			if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
				list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
			} else if(offset < list.scrollTop()) {
				list.scrollTop(offset);
			}
		}
	};

	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}

	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}

	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>")
				.html( options.highlight(formatted, term) )
				.addClass(i%2 == 0 ? "ui-autocomplete-even" : "ui-autocomplete-odd")
				.addClass(CLASSES.DEFAULT)
				.appendTo(list)[0];
			$.data(li, "ui-autocomplete-data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}

	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE)
			active = -1;
			$(input).triggerHandler("autocompletehide", [{}, { options: options }], options["hide"]);
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();

			if(options.scroll) {
				list.scrollTop(0);
				list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});

				if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
					list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						//listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
						//(only necessary if the lol-doctype transitional is used)
						//Ie6 Bug ?? InnerWidth > width !!!!
					}
				}

			}

			$(input).triggerHandler("autocompleteshow", [{}, { options: options }], options["show"]);

		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ui-autocomplete-data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.ui.autocomplete.selection = function(field, start, end) {
	if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	} else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

})(jQuery);

/*
 * jQuery UI Datepicker 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.7.1" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false // True to show button panel, false to not show it
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))
			return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText)
			input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked			
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}		
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});			
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) { 
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.trigger.remove();
			$target.siblings('.' + this._appendClass).remove().end().
				removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = false;
			inst.trigger.filter("button").
			each(function() { this.disabled = false; }).end().
				filter("img").
				css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = true;
			inst.trigger.filter("button").
			each(function() { this.disabled = true; }).end().
				filter("img").
				css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_optionDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		var inst = this._getInst(target);
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			extendRemove(inst.settings, settings);
			var date = new Date();
			extendRemove(inst, {rangeStart: null, // start of range
				endDay: null, endMonth: null, endYear: null, // end of range
				selectedDay: date.getDate(), selectedMonth: date.getMonth(),
				selectedYear: date.getFullYear(), // starting point
				currentDay: date.getDate(), currentMonth: date.getMonth(),
				currentYear: date.getFullYear(), // current selection
				drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) { alert('_refreshDP');
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1] - 1};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		
		// woodi: new, setting the width (browser dependant..) of the datepicker div via options (settings.width)						
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px', width: ($.browser.msie ? (inst.settings.width+2) : inst.settings.width) +'px'});	
				
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) { //alert('width: ' +inst.dpDiv.width() +'\nsettings: ' +inst.settings.width);
		var dims = {width: inst.dpDiv.width(),
			height: inst.dpDiv.height() + 4};
		var self = this;
		inst.dpDiv.empty().append(this._generateHTML(inst))
			.find('iframe.ui-datepicker-cover').
				css({width: dims.width, height: dims.height})
			.end()
			.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1) {
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		} else {
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		}
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
			
			
		// woodi: we need this to re-set the width of the datepicker div after switching selecting another month	
		if($.browser.msie)
		{						
			$('#ui-datepicker-div').width((inst.settings.width+2));	
		}
		else
		{			
			$('#ui-datepicker-div').width((dims.width));	
		}
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
		var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
		offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val() : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			date = defaultDate;
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '') + // highlight selected day
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, monthNames, monthNamesShort) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-year" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				'>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() { 
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.1";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;

})(jQuery);

/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
	$.datepicker.regional['de'] = {
		closeText: 'schließen',
		prevText: '&#x3c;zurück',
		nextText: 'Vor&#x3e;',
		currentText: 'heute',
		monthNames: ['Januar','Februar','März','April','Mai','Juni',
		'Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
		'Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
		dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		firstDay: 1,
		dateFormat: 'DD, dd. MM yy',
		altFormat: $.datepicker.TIMESTAMP,
		isRTL: false
	};
	$.datepicker.setDefaults($.datepicker.regional['de']);
});

/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood@virginbroadband.com.au) and Stéphane Nahmani (sholby@sholby.net). */
jQuery(function($){
	$.datepicker.regional['fr'] = {
		closeText: 'Fermer',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dateFormat: 'dd/mm/yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});
/*
 * jQuery UI Dialog 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function($) {

var setDataSwitch = {
		dragStart: "start.draggable",
		drag: "drag.draggable",
		dragStop: "stop.draggable",
		maxHeight: "maxHeight.resizable",
		minHeight: "minHeight.resizable",
		maxWidth: "maxWidth.resizable",
		minWidth: "minWidth.resizable",
		resizeStart: "start.resizable",
		resize: "drag.resizable",
		resizeStop: "stop.resizable"
	},
	
	uiDialogClasses =
		'ui-dialog ' +
		'ui-widget ' +
		'ui-widget-content ' +
		'ui-corner-all ';

$.widget("ui.dialog", {

	_init: function() {
		this.originalTitle = this.element.attr('title');

		var self = this,
			options = this.options,

			title = options.title || this.originalTitle || '&nbsp;',
			titleId = $.ui.dialog.getTitleId(this.element),

			uiDialog = (this.uiDialog = $('<div/>'))
				.appendTo(document.body)
				.hide()
				.addClass(uiDialogClasses + options.dialogClass)
				.css({
					position: 'absolute',
					overflow: 'hidden',
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(event) {
					(options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && self.close(event));
				})
				.attr({
					role: 'dialog',
					'aria-labelledby': titleId
				})
				.mousedown(function(event) {
					self.moveToTop(false, event);
				}),

			uiDialogContent = this.element
				.show()
				.removeAttr('title')
				.addClass(
					'ui-dialog-content ' +
					'ui-widget-content')
				.appendTo(uiDialog),

			uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>'))
				.addClass(
					'ui-dialog-titlebar ' +
					'ui-widget-header ' +
					'ui-corner-all ' +
					'ui-helper-clearfix'
				)
				.prependTo(uiDialog),

			uiDialogTitlebarClose = $('<a href="#"/>')
				.addClass(
					'ui-dialog-titlebar-close ' +
					'ui-corner-all'
				)
				.attr('role', 'button')
				.hover(
					function() {
						uiDialogTitlebarClose.addClass('ui-state-hover');
					},
					function() {
						uiDialogTitlebarClose.removeClass('ui-state-hover');
					}
				)
				.focus(function() {
					uiDialogTitlebarClose.addClass('ui-state-focus');
				})
				.blur(function() {
					uiDialogTitlebarClose.removeClass('ui-state-focus');
				})
				.mousedown(function(ev) {
					ev.stopPropagation();
				})
				.click(function(event) {
					self.close(event);
					return false;
				})
				.appendTo(uiDialogTitlebar),

			uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>'))
				.addClass(
					'ui-icon ' +
					'ui-icon-closethick'
				)
				.text(options.closeText)
				.appendTo(uiDialogTitlebarClose),

			uiDialogTitle = $('<span/>')
				.addClass('ui-dialog-title')
				.attr('id', titleId)
				.html(title)
				.prependTo(uiDialogTitlebar);

		uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		(options.draggable && $.fn.draggable && this._makeDraggable());
		(options.resizable && $.fn.resizable && this._makeResizable());

		this._createButtons(options.buttons);
		this._isOpen = false;

		(options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
		(options.autoOpen && this.open());
		
	},

	destroy: function() {
		(this.overlay && this.overlay.destroy());
		this.uiDialog.hide();
		this.element
			.unbind('.dialog')
			.removeData('dialog')
			.removeClass('ui-dialog-content ui-widget-content')
			.hide().appendTo('body');
		this.uiDialog.remove();

		(this.originalTitle && this.element.attr('title', this.originalTitle));
	},

	close: function(event) {
		var self = this;
		
		if (false === self._trigger('beforeclose', event)) {
			return;
		}

		(self.overlay && self.overlay.destroy());
		self.uiDialog.unbind('keypress.ui-dialog');

		(self.options.hide
			? self.uiDialog.hide(self.options.hide, function() {
				self._trigger('close', event);
			})
			: self.uiDialog.hide() && self._trigger('close', event));

		$.ui.dialog.overlay.resize();

		self._isOpen = false;
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force, event) {

		if ((this.options.modal && !force)
			|| (!this.options.stack && !this.options.modal)) {
			return this._trigger('focus', event);
		}
		
		if (this.options.zIndex > $.ui.dialog.maxZ) {
			$.ui.dialog.maxZ = this.options.zIndex;
		}
		(this.overlay && this.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = ++$.ui.dialog.maxZ));

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') };
		this.uiDialog.css('z-index', ++$.ui.dialog.maxZ);
		this.element.attr(saveScroll);
		this._trigger('focus', event);
	},

	open: function() {
		if (this._isOpen) { return; }

		var options = this.options,
			uiDialog = this.uiDialog;

		this.overlay = options.modal ? new $.ui.dialog.overlay(this) : null;
		(uiDialog.next().length && uiDialog.appendTo('body'));
		this._size();
		this._position(options.position);
		uiDialog.show(options.show);
		this.moveToTop(true);

		// prevent tabbing out of modal dialogs
		(options.modal && uiDialog.bind('keypress.ui-dialog', function(event) {
			if (event.keyCode != $.ui.keyCode.TAB) {
				return;
			}

			var tabbables = $(':tabbable', this),
				first = tabbables.filter(':first')[0],
				last  = tabbables.filter(':last')[0];

			if (event.target == last && !event.shiftKey) {
				setTimeout(function() {
					first.focus();
				}, 1);
			} else if (event.target == first && event.shiftKey) {
				setTimeout(function() {
					last.focus();
				}, 1);
			}
		}));

		// set focus to the first tabbable element in the content area or the first button
		// if there are no tabbable elements, set focus on the dialog itself
		$([])
			.add(uiDialog.find('.ui-dialog-content :tabbable:first'))
			.add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first'))
			.add(uiDialog)
			.filter(':first')
			.focus();

		this._trigger('open');
		this._isOpen = true;
	},

	_createButtons: function(buttons) {
		var self = this,
			hasButtons = false,
			uiDialogButtonPane = $('<div></div>')
				.addClass(
					'ui-dialog-buttonpane ' +
					'ui-widget-content ' +
					'ui-helper-clearfix'
				);

		// if we already have a button pane, remove it
		this.uiDialog.find('.ui-dialog-buttonpane').remove();

		(typeof buttons == 'object' && buttons !== null &&
			$.each(buttons, function() { return !(hasButtons = true); }));
		if (hasButtons) {
			$.each(buttons, function(name, fn) {
				$('<button type="button"></button>')
					.addClass(
						'ui-state-default ' +
						'ui-corner-all'
					)
					.text(name)
					.click(function() { fn.apply(self.element[0], arguments); })
					.hover(
						function() {
							$(this).addClass('ui-state-hover');
						},
						function() {
							$(this).removeClass('ui-state-hover');
						}
					)
					.focus(function() {
						$(this).addClass('ui-state-focus');
					})
					.blur(function() {
						$(this).removeClass('ui-state-focus');
					})
					.appendTo(uiDialogButtonPane);
			});
			uiDialogButtonPane.appendTo(this.uiDialog);
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = this.options,
			heightBeforeDrag;

		this.uiDialog.draggable({
			cancel: '.ui-dialog-content',
			handle: '.ui-dialog-titlebar',
			containment: 'document',
			start: function() {
				heightBeforeDrag = options.height;
				$(this).height($(this).height()).addClass("ui-dialog-dragging");
				(options.dragStart && options.dragStart.apply(self.element[0], arguments));
			},
			drag: function() {
				(options.drag && options.drag.apply(self.element[0], arguments));
			},
			stop: function() {
				$(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag);
				(options.dragStop && options.dragStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = this.options,
			resizeHandles = typeof handles == 'string'
				? handles
				: 'n,e,s,w,se,sw,ne,nw';

		this.uiDialog.resizable({
			cancel: '.ui-dialog-content',
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: options.minHeight,
			start: function() {
				$(this).addClass("ui-dialog-resizing");
				(options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
			},
			resize: function() {
				(options.resize && options.resize.apply(self.element[0], arguments));
			},
			handles: resizeHandles,
			stop: function() {
				$(this).removeClass("ui-dialog-resizing");
				options.height = $(this).height();
				options.width = $(this).width();
				(options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		})
		.find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se');
	},

	_position: function(pos) {
		var wnd = $(window), doc = $(document),
			pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
			minTop = pTop;

		if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
			pos = [
				pos == 'right' || pos == 'left' ? pos : 'center',
				pos == 'top' || pos == 'bottom' ? pos : 'middle'
			];
		}
		if (pos.constructor != Array) {
			pos = ['center', 'middle'];
		}
		if (pos[0].constructor == Number) {
			pLeft += pos[0];
		} else {
			switch (pos[0]) {
				case 'left':
					pLeft += 0;
					break;
				case 'right':
					pLeft += wnd.width() - this.uiDialog.outerWidth();
					break;
				default:
				case 'center':
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
			}
		}
		if (pos[1].constructor == Number) {
			pTop += pos[1];
		} else {
			switch (pos[1]) {
				case 'top':
					pTop += 0;
					break;
				case 'bottom':
					pTop += wnd.height() - this.uiDialog.outerHeight();
					break;
				default:
				case 'middle':
					pTop += (wnd.height() - this.uiDialog.outerHeight()) / 2;
			}
		}

		// prevent the dialog from being too high (make sure the titlebar
		// is accessible)
		pTop = Math.max(pTop, minTop);
		this.uiDialog.css({top: pTop, left: pLeft});
	},

	_setData: function(key, value){
		(setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
		switch (key) {
			case "buttons":
				this._createButtons(value);
				break;
			case "closeText":
				this.uiDialogTitlebarCloseText.text(value);
				break;
			case "dialogClass":
				this.uiDialog
					.removeClass(this.options.dialogClass)
					.addClass(uiDialogClasses + value);
				break;
			case "draggable":
				(value
					? this._makeDraggable()
					: this.uiDialog.draggable('destroy'));
				break;
			case "height":
				this.uiDialog.height(value);
				break;
			case "position":
				this._position(value);
				break;
			case "resizable":
				var uiDialog = this.uiDialog,
					isResizable = this.uiDialog.is(':data(resizable)');

				// currently resizable, becoming non-resizable
				(isResizable && !value && uiDialog.resizable('destroy'));

				// currently resizable, changing handles
				(isResizable && typeof value == 'string' &&
					uiDialog.resizable('option', 'handles', value));

				// currently non-resizable, becoming resizable
				(isResizable || this._makeResizable(value));
				break;
			case "title":
				$(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;');
				break;
			case "width":
				this.uiDialog.width(value);
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);
	},

	_size: function() {
		/* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		 * divs will both have width and height set, so we need to reset them
		 */
		var options = this.options;

		// reset content sizing
		this.element.css({
			height: 0,
			minHeight: 0,
			width: 'auto'
		});

		// reset wrapper sizing
		// determine the height of all the non-content elements
		var nonContentHeight = this.uiDialog.css({
				height: 'auto',
				width: options.width
			})
			.height();

		this.element
			.css({
				minHeight: Math.max(options.minHeight - nonContentHeight, 0),
				height: options.height == 'auto'
					? 'auto'
					: Math.max(options.height - nonContentHeight, 0)
			});
	}
});

$.extend($.ui.dialog, {
	version: "1.7.1",
	defaults: {
		autoOpen: true,
		bgiframe: false,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		dialogClass: '',
		draggable: true,
		hide: null,
		height: 'auto',
		maxHeight: false,
		maxWidth: false,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: 'center',
		resizable: true,
		show: null,
		stack: true,
		title: '',
		width: 300,
		zIndex: 1000
	},

	getter: 'isOpen',

	uuid: 0,
	maxZ: 0,

	getTitleId: function($el) {
		return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
	},

	overlay: function(dialog) {
		this.$el = $.ui.dialog.overlay.create(dialog);
	}
});

$.extend($.ui.dialog.overlay, {
	instances: [],
	maxZ: 0,
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				$(document).bind($.ui.dialog.overlay.events, function(event) {
					var dialogZ = $(event.target).parents('.ui-dialog').css('zIndex') || 0;
					return (dialogZ > $.ui.dialog.overlay.maxZ);
				});
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				(dialog.options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
		}

		var $el = $('<div></div>').appendTo(document.body)
			.addClass('ui-widget-overlay').css({
				width: this.width(),
				height: this.height()
			});

		(dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());

		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		this.instances.splice($.inArray(this.instances, $el), 1);

		if (this.instances.length === 0) {
			$([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
	},

	height: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ui.dialog.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ui.dialog.overlay.width(),
			height: $.ui.dialog.overlay.height()
		});
	}
});

$.extend($.ui.dialog.overlay.prototype, {
	destroy: function() {
		$.ui.dialog.overlay.destroy(this.$el);
	}
});

})(jQuery);

/*
 * jQuery UI Resizable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.resizable", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this, o = this.options;
		this.element.addClass("ui-resizable");

		$.extend(this, {
			_aspectRatio: !!(o.aspectRatio),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null
		});

		//Wrap the element if it cannot hold child nodes
		if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {

			//Opera fix for relative positioning
			if (/relative/.test(this.element.css('position')) && $.browser.opera)
				this.element.css({ position: 'relative', top: 'auto', left: 'auto' });

			//Create a wrapper element and set the wrapper to the new current internal element
			this.element.wrap(
				$('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
					position: this.element.css('position'),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css('top'),
					left: this.element.css('left')
				})
			);

			//Overwrite the original this.element
			this.element = this.element.parent().data(
				"resizable", this.element.data('resizable')
			);

			this.elementIsWrapper = true;

			//Move margins to the wrapper
			this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
			this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});

			//Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css('resize');
			this.originalElement.css('resize', 'none');

			//Push the actual element to our proportionallyResize internal array
			this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' }));

			// avoid IE jump (hard set the margin)
			this.originalElement.css({ margin: this.originalElement.css('margin') });

			// fix handlers offset
			this._proportionallyResize();

		}

		this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' });
		if(this.handles.constructor == String) {

			if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw';
			var n = this.handles.split(","); this.handles = {};

			for(var i = 0; i < n.length; i++) {

				var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle;
				var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>');

				// increase zIndex of sw, se, ne, nw axis
				//TODO : this modifies original option
				if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex });

				//TODO : What's going on here?
				if ('se' == handle) {
					axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se');
				};

				//Insert into internal handles object and append to element
				this.handles[handle] = '.ui-resizable-'+handle;
				this.element.append(axis);
			}

		}

		this._renderAxis = function(target) {

			target = target || this.element;

			for(var i in this.handles) {

				if(this.handles[i].constructor == String)
					this.handles[i] = $(this.handles[i], this.element).show();

				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {

					var axis = $(this.handles[i], this.element), padWrapper = 0;

					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					//The padding type i have to apply...
					var padPos = [ 'padding',
						/ne|nw|n/.test(i) ? 'Top' :
						/se|sw|s/.test(i) ? 'Bottom' :
						/^e$/.test(i) ? 'Right' : 'Left' ].join("");

					target.css(padPos, padWrapper);

					this._proportionallyResize();

				}

				//TODO: What's that good for? There's not anything to be executed left
				if(!$(this.handles[i]).length)
					continue;

			}
		};

		//TODO: make renderAxis a prototype function
		this._renderAxis(this.element);

		this._handles = $('.ui-resizable-handle', this.element)
			.disableSelection();

		//Matching axis name
		this._handles.mouseover(function() {
			if (!self.resizing) {
				if (this.className)
					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				//Axis, default = se
				self.axis = axis && axis[1] ? axis[1] : 'se';
			}
		});

		//If we want to auto hide the elements
		if (o.autoHide) {
			this._handles.hide();
			$(this.element)
				.addClass("ui-resizable-autohide")
				.hover(function() {
					$(this).removeClass("ui-resizable-autohide");
					self._handles.show();
				},
				function(){
					if (!self.resizing) {
						$(this).addClass("ui-resizable-autohide");
						self._handles.hide();
					}
				});
		}

		//Initialize the mouse interaction
		this._mouseInit();

	},

	destroy: function() {

		this._mouseDestroy();

		var _destroy = function(exp) {
			$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
				.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
		};

		//TODO: Unwrap at same DOM position
		if (this.elementIsWrapper) {
			_destroy(this.element);
			var wrapper = this.element;
			wrapper.parent().append(
				this.originalElement.css({
					position: wrapper.css('position'),
					width: wrapper.outerWidth(),
					height: wrapper.outerHeight(),
					top: wrapper.css('top'),
					left: wrapper.css('left')
				})
			).end().remove();
		}

		this.originalElement.css('resize', this.originalResizeStyle);
		_destroy(this.originalElement);

	},

	_mouseCapture: function(event) {

		var handle = false;
		for(var i in this.handles) {
			if($(this.handles[i])[0] == event.target) handle = true;
		}

		return this.options.disabled || !!handle;

	},

	_mouseStart: function(event) {

		var o = this.options, iniPos = this.element.position(), el = this.element;

		this.resizing = true;
		this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };

		// bugfix for http://dev.jquery.com/ticket/1749
		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
			el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left });
		}

		//Opera fixing relative position
		if ($.browser.opera && (/relative/).test(el.css('position')))
			el.css({ position: 'relative', top: 'auto', left: 'auto' });

		this._renderProxy();

		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft() || 0;
			curtop += $(o.containment).scrollTop() || 0;
		}

		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		//Aspect Ratio
		this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);

	    var cursor = $('.ui-resizable-' + this.axis).css('cursor');
	    $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);

		el.addClass("ui-resizable-resizing");
		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		//Increase performance, avoid regex
		var el = this.helper, o = this.options, props = {},
			self = this, smp = this.originalMousePosition, a = this.axis;

		var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
		var trigger = this._change[a];
		if (!trigger) return false;

		// Calculate the attrs that will be change
		var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;

		if (this._aspectRatio || event.shiftKey)
			data = this._updateRatio(data, event);

		data = this._respectSize(data, event);

		// plugins callbacks need to be called first
		this._propagate("resize", event);

		el.css({
			top: this.position.top + "px", left: this.position.left + "px",
			width: this.size.width + "px", height: this.size.height + "px"
		});

		if (!this._helper && this._proportionallyResizeElements.length)
			this._proportionallyResize();

		this._updateCache(data);

		// calling the user callback at the end
		this._trigger('resize', event, this.ui());

		return false;
	},

	_mouseStop: function(event) {

		this.resizing = false;
		var o = this.options, self = this;

		if(this._helper) {
			var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
						soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;

			var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
				left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
				top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

			if (!o.animate)
				this.element.css($.extend(s, { top: top, left: left }));

			self.helper.height(self.size.height);
			self.helper.width(self.size.width);

			if (this._helper && !o.animate) this._proportionallyResize();
		}

		$('body').css('cursor', 'auto');

		this.element.removeClass("ui-resizable-resizing");

		this._propagate("stop", event);

		if (this._helper) this.helper.remove();
		return false;

	},

	_updateCache: function(data) {
		var o = this.options;
		this.offset = this.helper.offset();
		if (isNumber(data.left)) this.position.left = data.left;
		if (isNumber(data.top)) this.position.top = data.top;
		if (isNumber(data.height)) this.size.height = data.height;
		if (isNumber(data.width)) this.size.width = data.width;
	},

	_updateRatio: function(data, event) {

		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;

		if (data.height) data.width = (csize.height * this.aspectRatio);
		else if (data.width) data.height = (csize.width / this.aspectRatio);

		if (a == 'sw') {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a == 'nw') {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function(data, event) {

		var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis,
				ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
					isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height);

		if (isminw) data.width = o.minWidth;
		if (isminh) data.height = o.minHeight;
		if (ismaxw) data.width = o.maxWidth;
		if (ismaxh) data.height = o.maxHeight;

		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);

		if (isminw && cw) data.left = dw - o.minWidth;
		if (ismaxw && cw) data.left = dw - o.maxWidth;
		if (isminh && ch)	data.top = dh - o.minHeight;
		if (ismaxh && ch)	data.top = dh - o.maxHeight;

		// fixing jump error on top/left - bug #2330
		var isNotwh = !data.width && !data.height;
		if (isNotwh && !data.left && data.top) data.top = null;
		else if (isNotwh && !data.top && data.left) data.left = null;

		return data;
	},

	_proportionallyResize: function() {

		var o = this.options;
		if (!this._proportionallyResizeElements.length) return;
		var element = this.helper || this.element;

		for (var i=0; i < this._proportionallyResizeElements.length; i++) {

			var prel = this._proportionallyResizeElements[i];

			if (!this.borderDif) {
				var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
					p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];

				this.borderDif = $.map(b, function(v, i) {
					var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
					return border + padding;
				});
			}

			if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length)))
				continue;

			prel.css({
				height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
				width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
			});

		};

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if(this._helper) {

			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');

			// fix ie6 offset TODO: This seems broken
			var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
			pxyoffset = ( ie6 ? 2 : -1 );

			this.helper.addClass(this._helper).css({
				width: this.element.outerWidth() + pxyoffset,
				height: this.element.outerHeight() + pxyoffset,
				position: 'absolute',
				left: this.elementOffset.left - ie6offset +'px',
				top: this.elementOffset.top - ie6offset +'px',
				zIndex: ++o.zIndex //TODO: Don't modify option
			});

			this.helper
				.appendTo("body")
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function(event, dx, dy) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this.ui()]);
		(n != "resize" && this._trigger(n, event, this.ui()));
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

}));

$.extend($.ui.resizable, {
	version: "1.7.1",
	eventPrefix: "resize",
	defaults: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		cancel: ":input,option",
		containment: false,
		delay: 0,
		distance: 1,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		zIndex: 1000
	}
});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "alsoResize", {

	start: function(event, ui) {

		var self = $(this).data("resizable"), o = self.options;

		_store = function(exp) {
			$(exp).each(function() {
				$(this).data("resizable-alsoresize", {
					width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
					left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
				});
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0];	_store(o.alsoResize); }
			else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		}
	},

	resize: function(event, ui){
		var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition;

		var delta = {
			height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
			top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
		},

		_alsoResize = function(exp, c) {
			$(exp).each(function() {
				var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];

				$.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
					var sum = (start[prop]||0) + (delta[prop]||0);
					if (sum && sum >= 0)
						style[prop] = sum || null;
				});

				//Opera fixing relative position
				if (/relative/.test(el.css('position')) && $.browser.opera) {
					self._revertToRelativePosition = true;
					el.css({ position: 'absolute', top: 'auto', left: 'auto' });
				}

				el.css(style);
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) {
			$.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},

	stop: function(event, ui){
		var self = $(this).data("resizable");

		//Opera fixing relative position
		if (self._revertToRelativePosition && $.browser.opera) {
			self._revertToRelativePosition = false;
			el.css({ position: 'relative' });
		}

		$(this).removeData("resizable-alsoresize-start");
	}
});

$.ui.plugin.add("resizable", "animate", {

	stop: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options;

		var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
					soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
						soffsetw = ista ? 0 : self.sizeDiff.width;

		var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
					left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
						top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

		self.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(self.element.css('width'), 10),
						height: parseInt(self.element.css('height'), 10),
						top: parseInt(self.element.css('top'), 10),
						left: parseInt(self.element.css('left'), 10)
					};

					if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height });

					// propagating resize, and updating values for each animation step
					self._updateCache(data);
					self._propagate("resize", event);

				}
			}
		);
	}

});

$.ui.plugin.add("resizable", "containment", {

	start: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options, el = self.element;
		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
		if (!ce) return;

		self.containerElement = $(ce);

		if (/document/.test(oc) || oc == document) {
			self.containerOffset = { left: 0, top: 0 };
			self.containerPosition = { left: 0, top: 0 };

			self.parentData = {
				element: $(document), left: 0, top: 0,
				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
			};
		}

		// i'm a node, so compute top, left, right, bottom
		else {
			var element = $(ce), p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });

			self.containerOffset = element.offset();
			self.containerPosition = element.position();
			self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };

			var co = self.containerOffset, ch = self.containerSize.height,	cw = self.containerSize.width,
						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);

			self.parentData = {
				element: ce, left: co.left, top: co.top, width: width, height: height
			};
		}
	},

	resize: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options,
				ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
				pRatio = self._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;

		if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;

		if (cp.left < (self._helper ? co.left : 0)) {
			self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left));
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
			self.position.left = o.helper ? co.left : 0;
		}

		if (cp.top < (self._helper ? co.top : 0)) {
			self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top);
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
			self.position.top = self._helper ? co.top : 0;
		}

		self.offset.left = self.parentData.left+self.position.left;
		self.offset.top = self.parentData.top+self.position.top;

		var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ),
					hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height );

		var isParent = self.containerElement.get(0) == self.element.parent().get(0),
		    isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position'));

		if(isParent && isOffsetRelative) woset -= self.parentData.left;

		if (woset + self.size.width >= self.parentData.width) {
			self.size.width = self.parentData.width - woset;
			if (pRatio) self.size.height = self.size.width / self.aspectRatio;
		}

		if (hoset + self.size.height >= self.parentData.height) {
			self.size.height = self.parentData.height - hoset;
			if (pRatio) self.size.width = self.size.height * self.aspectRatio;
		}
	},

	stop: function(event, ui){
		var self = $(this).data("resizable"), o = self.options, cp = self.position,
				co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;

		var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height;

		if (self._helper && !o.animate && (/relative/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

		if (self._helper && !o.animate && (/static/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function(event, ui) {

		var self = $(this).data("resizable"), o = self.options, cs = self.size;

		self.ghost = self.originalElement.clone();
		self.ghost
			.css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
			.addClass('ui-resizable-ghost')
			.addClass(typeof o.ghost == 'string' ? o.ghost : '');

		self.ghost.appendTo(self.helper);

	},

	resize: function(event, ui){
		var self = $(this).data("resizable"), o = self.options;
		if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });
	},

	stop: function(event, ui){
		var self = $(this).data("resizable"), o = self.options;
		if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey;
		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);

		if (/^(se|s|e)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
		}
		else if (/^(ne)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
		}
		else if (/^(sw)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.left = op.left - ox;
		}
		else {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
			self.position.left = op.left - ox;
		}
	}

});

var num = function(v) {
	return parseInt(v, 10) || 0;
};

var isNumber = function(value) {
	return !isNaN(parseInt(value, 10));
};

})(jQuery);

/*
 * jQuery UI Draggable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {

	_init: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.addClasses && this.element.addClass("ui-draggable"));
		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element
			.removeData("draggable")
			.unbind(".draggable")
			.removeClass("ui-draggable"
				+ " ui-draggable-dragging"
				+ " ui-draggable-disabled");
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._trigger("start", event);

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			this._trigger('drag', event, ui);
			this.position = ui.position;
		}

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			dropped = $.ui.ddmanager.drop(this, event);

		//if a drop comes from outside (a sortable)
		if(this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				self._trigger("stop", event);
				self._clear();
			});
		} else {
			this._trigger("stop", event);
			this._clear();
		}

		return false;
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
			var ce = $(o.containment)[0]; if(!ce) return;
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		} else if(o.containment.constructor == Array) {
			this.containment = o.containment;
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return $.widget.prototype._trigger.call(this, type, event, ui);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs, //deprecated
			offset: this.positionAbs
		};
	}

}));

$.extend($.ui.draggable, {
	version: "1.7.1",
	eventPrefix: "drag",
	defaults: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		cancel: ":input,option",
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		delay: 0,
		distance: 1,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false
	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, 'sortable');
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
				if(this.shouldRevert) this.instance.options.revert = true;

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper == 'original')
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {
			
			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;
			
			if(this.instance._intersectsWith(this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					
					//Prevent reverting on this forced stop
					this.instance.options.revert = false;
					
					// The out event needs to be triggered independently
					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
					
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), o = $(this).data('draggable').options;
		if (t.css("cursor")) o._cursor = t.css("cursor");
		t.css("cursor", o.cursor);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if (o._cursor) $('body').css("cursor", o._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		var o = $(this).data('draggable').options;
		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data('draggable').options;
		if(t.css("opacity")) o._opacity = t.css("opacity");
		t.css('opacity', o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("draggable");
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	drag: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if(!o.axis || o.axis != 'x') {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
			}

			if(!o.axis || o.axis != 'y') {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
			}

		} else {

			if(!o.axis || o.axis != 'x') {
				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}

			if(!o.axis || o.axis != 'y') {
				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options;
		i.snapElements = [];

		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != i.element[0]) i.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options;
		var d = o.snapTolerance;

		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(o.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
			}

			var first = (ts || bs || ls || rs);

			if(o.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {

		var o = $(this).data("draggable").options;

		var group = $.makeArray($(o.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || o.stack.min) - (parseInt($(b).css("zIndex"),10) || o.stack.min);
		});

		$(group).each(function(i) {
			this.style.zIndex = o.stack.min + i;
		});

		this[0].style.zIndex = o.stack.min + group.length;

	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("draggable").options;
		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
		t.css('zIndex', o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("draggable").options;
		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
	}
});

})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/**
    Javascript Repeater
    http://jsrepeater.devprog.com/
    Version 1.1
    
    Copyright (c) 2008 devprog.com 
    This code is licensed under the MIT Licence
    http://www.opensource.org/licenses/mit-license.php
    
    usage: $('#myDiv').fillTemplate(data);
    Please see the site for details on template formatting
    
**/

(function($) {
    $.fn.fillTemplate = function(obj){
        
        if ($.fn.fillTemplate.rptInstance == null) { 
            $.fn.fillTemplate.rptInstance = new $.fn.fillTemplate.jsRepeater(); 
        }
        
        return this.each(function() {

            if ((this.id == null) || (this.id == undefined)){
                this.innerHTML = "Error: id attribute required";
            } else {
                if (($.fn.fillTemplate.rptInstance.templaters[this.id] == null) || ($.fn.fillTemplate.rptInstance.templaters[this.id] == undefined)){
                    $.fn.fillTemplate.rptInstance.templaters[this.id] = new $.fn.fillTemplate.templater();
                    var node = this.cloneNode(true);
                    $.fn.fillTemplate.rptInstance.templaters[this.id].initialise(this.cloneNode(true));
                }
                this.innerHTML = $.fn.fillTemplate.rptInstance.templaters[this.id].parse(obj);
            }
 
        });
    };
    
    $.fn.fillTemplate.rptInstance = null;
    
    $.fn.fillTemplate.jsRepeater = function(){
        this.templaters = {}; 
    };
    
    $.fn.fillTemplate.templater = function(){
        this.templaters = {}; this.Context = null; this.template = "";
        this.isRoot = true; this.mirrorID = null;
    };
    
    var templater = $.fn.fillTemplate.templater;
    
    templater.prototype.initialise = function(rootNode){
        if ((rootNode.getAttribute) && (rootNode.getAttribute("context"))){
            this.Context = rootNode.getAttributeNode("context").nodeValue;
        }
        for (var i=0; i<rootNode.childNodes.length; i++){
            this.extractSubTemplates(rootNode, rootNode.childNodes[i]);
        }
        if (!this.isRoot){
            var tempNode = document.createElement("div");
            tempNode.appendChild(rootNode.cloneNode(true));
            this.template = tempNode.innerHTML;
        } else { this.template = rootNode.innerHTML; }
        this.template = this.template.replace(/%7B/g, "{");
        this.template = this.template.replace(/%7D/g,"}");
    };
    templater.prototype.initialiseMirror = function(rootNode){
        var tempNode = document.createElement("div");
        tempNode.appendChild(rootNode.cloneNode(false));
        var Marker = document.createTextNode("STATIC");
        tempNode.childNodes[0].appendChild(Marker);
        this.template = tempNode.innerHTML;
    };
    templater.prototype.parseOrdering = function(template, ordinal, total){
        template = template.replace(/%{([^}]*)}/g,
            function(match, group1){
                var first = null; 
                var alternates = null;
                var last = null;
                
                if (group1.indexOf("|") > -1){
                    var ary = group1.split("|");
                    first = ary[0];
                    alternates = ary[1];
                    if (ary.length > 2) { last = ary[2]; }
                } else {
                    alternates = group1;
                }
                alternates = alternates.split(":");
                
                if ((ordinal == 0) && (first != null)) { return first; }
                if ((ordinal == total - 1) && (last != null)) { return last; }
                return alternates[ordinal % alternates.length];
            });
            return template;
    };
    templater.prototype.parseRecursionOrdering = function(template, data, recursionCount, ob){
        template = template.replace(/!%{([^}]*)}/g,
            function(match, group1){
                var first = null; 
                var alternates = null;
                var last = null;
                
                if (group1.indexOf("|") > -1){
                    var ary = group1.split("|");
                    first = ary[0];
                    alternates = ary[1];
                    if (ary.length > 2) { last = ary[2]; }
                } else {
                    alternates = group1;
                }
                alternates = alternates.split(":");
                
                if ((recursionCount == 0) && (first != null)) { return first; }
                //if ((ordinal == total - 1) && (last != null)) { return last; }
                return alternates[recursionCount % alternates.length];
            });
            return template;
    };
    templater.prototype.parseNumbering = function(template, ordinal, total){    
        template = template.replace(/#{([^}]*)}/g,
            function(match, group1){
                return ordinal + 1;
            });
            return template;
    };
    templater.prototype.parseRecursive = function(template, data, recursionCount, ob){

    template = template.replace(/!{([^}]*)}/g,
        function(match, group1){
            if (group1 > recursionCount){
                if (ob.Context == null) { return ""; }
                var contextData = data[ob.Context];
                if ((contextData == null) || (contextData == undefined)) { return ""; }
                return ob.parse(data, recursionCount + 1);
            } else { return ""; }
        });
        return template;
    };
    templater.prototype.parse = function(data, recursionCount){
        var result = ""; 
        var self = this;
        if (this.mirrorID){
            result += this.template.replace(/(STATIC)/g,                
                    function(match, group1) {    
                        return document.getElementById(self.mirrorID).innerHTML;    
                             
                    } ); 
            return result;
        }
        if ((recursionCount == null) || (recursionCount == undefined)) { recursionCount = 0; }
        var contextData = null;
        if (this.Context) { contextData = data[this.Context]; } else { contextData = data; }
        if ((contextData == null) || (contextData == undefined)) {   contextData = {}; }
        if (contextData instanceof Array) {    
            for(var i = 0; i < contextData.length; i++){
                var obj = contextData[i];
                result += this.template.replace(/\$\{([^}]*)\}/g,                
                    function(match, group1) { 
                        var outer = group1.split(":");
                        var val = outer[0];
                        var f = null;
                        if (outer.length > 1) { f = outer[1]; }
                        var ary = val.split(".");
                        var newObj = obj;
                        
                        for(var j=0; j<ary.length; j++){
                            newObj = newObj[ary[j]];
                            
                            if (newObj == undefined) { 
                                if (f != null) { return eval(f + '(newObj);'); }
                                else { return newObj; }   
                            }
                        }  
                        if (f != null) { return eval(f + '(newObj);'); }
                        else { return newObj; }               
                    } ); 
                 var self = this;   
                    result = this.parseNumbering(result, i, contextData.length);
                    result = this.parseRecursionOrdering(result, contextData[i], recursionCount, this);
                    result = this.parseOrdering(result, i, contextData.length);
                    
                    result = this.parseRecursive(result, contextData[i], recursionCount, this);
                    
                
                result = result.replace(/\~\{([^}]*)\}/g,            
                        function(match, group1) {      
                                    return self.templaters[group1].parse(contextData[i]);       
                                } );                            
            }
        } else {
            var obj = contextData; 

            result += this.template.replace(/\$\{([^}]*)\}/g,                
                    function(match, group1) { 
                        var outer = group1.split(":");
                        var val = outer[0];
                        var f = null;
                        if (outer.length > 1) { f = outer[1]; }
                             
                        ary = val.split(".");
                        var newObj = obj;
                        
                        for(var j=0; j<ary.length; j++){
                            newObj = newObj[ary[j]];
                            
                            if (newObj == undefined) { 
                                if (f != null) { return eval(f + '(newObj);'); }
                                else { return newObj; }
                             }
                        }  
                        if (f != null) { return eval(f + '(newObj);'); }
                                else { return newObj; }         
                    } );
              var self = this;      
                    result = this.parseNumbering(result, i, contextData.length);
                    result = this.parseRecursionOrdering(result, contextData, recursionCount, this);
                    result = this.parseOrdering(result, 0, 1);
                    
                    result = this.parseRecursive(result, contextData, recursionCount, this);
                    
            
            result = result.replace(/\~\{([^}]*)\}/g,            
            function(match, group1) {      
                        return self.templaters[group1].parse(contextData);       
                    } );  
        }  
        
        return result; 
    };
    templater.prototype.extractSubTemplates = function(sourceTree, node){
        var plucked = null;
        var markerID = null;
        var markerNode = null;
        var Subtemplater = null;
        if ((node.getAttribute) && (node.getAttribute("template"))){
            plucked = node;
            markerID = this.newGuid();
            markerNode = document.createTextNode("~{" + markerID + "}");
            sourceTree.replaceChild(markerNode, node);
            Subtemplater = new $.fn.fillTemplate.templater();
            Subtemplater.isRoot = false;
            Subtemplater.mirrorID = node.getAttributeNode("ID").nodeValue;
            this.templaters[markerID] = Subtemplater;
            Subtemplater.initialiseMirror(plucked);
            return;
        }
        if ((node.getAttribute) && (node.getAttribute("context"))){

        plucked = node;
        markerID = this.newGuid();
        markerNode = document.createTextNode("~{" + markerID + "}");

        sourceTree.replaceChild(markerNode, node);
        
        Subtemplater = new $.fn.fillTemplate.templater();
        Subtemplater.isRoot = false;
        this.templaters[markerID] = Subtemplater;
        Subtemplater.initialise(plucked);
        }
        else {
            for (var i=0; i<node.childNodes.length; i++){
                this.extractSubTemplates(node, node.childNodes[i]);
            }
        }
    };
    templater.prototype.S4 = function(){
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };  
    templater.prototype.newGuid = function(){
        return (this.S4()+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+this.S4()+this.S4()).toUpperCase();
    };
    

})(jQuery);
/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Buk�is-Haberkorns
 */

(function($) {

function History()
{
	this._curHash = '';
	this._callback = function(hash){};
};

$.extend(History.prototype, {

	init: function(callback) {
		this._callback = callback;
		this._curHash = location.hash;

		if($.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (this._curHash == '') {
				this._curHash = '#';
			}

			// add hidden iframe for IE
			$('body').prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var iframe = $('#jQuery_history')[0].contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = this._curHash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			this._historyBackStack = [];
			this._historyBackStack.length = history.length;
			this._historyForwardStack = [];
			this._isFirst = true;
			this._dontCheck = false;
		}
		this._callback(this._curHash.replace(/^#/, ''));
		setInterval(this._check, 100);
	},

	add: function(hash) {
		// This makes the looping function do something
		this._historyBackStack.push(hash);
		
		this._historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this._isFirst = true;
	},
	
	_check: function() {
		if($.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $('#jQuery_history')[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != $.history._curHash) {
			
				location.hash = current_hash;
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
				
			}
		} else if ($.browser.safari) {
			if (!$.history._dontCheck) {
				var historyDelta = history.length - $.history._historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					$.history._isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) $.history._historyForwardStack.unshift($.history._historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) $.history._historyBackStack.push($.history._historyForwardStack.shift());
					}
					var cachedHash = $.history._historyBackStack[$.history._historyBackStack.length - 1];
					if (cachedHash != undefined) {
						$.history._curHash = location.hash;
						$.history._callback(cachedHash);
					}
				} else if ($.history._historyBackStack[$.history._historyBackStack.length - 1] == undefined && !$.history._isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (location.hash.indexOf('#') >= 0) {
						$.history._callback(location.hash.split('#')[1]);
					} else {
						$.history._callback('');
					}
					$.history._isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != $.history._curHash) {
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
			}
		}
	},

        isKonqueror: function() {
		return /KHTML|Konqueror/.test(navigator.userAgent);
	},
	load: function(hash) {
		var newhash;

		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = (this.isKonqueror() ? '' : '#') + hash;
			location.hash = newhash;
		}

		this._curHash = newhash;
		
		if ($.browser.msie) {
			var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			// Manually keep track of the history values for Safari
			this.add(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {$.history._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	},
	value: function(hash) {
	    if (typeof hash != 'undefined') {
	        this.load(hash);
	    }
	    else {
	        var value = $.history._curHash.replace(/^#/, '');
	        return value;
	    }
	},
	path: function() {
        var value = this.value();
        return (value.indexOf('?') != -1) ? value.split('?')[0] : value;
	},
	pathNames: function() {
	    var path = this.path();
        var names = path.split('/');
        if (path.substr(0, 1) == '/' || path.length == 0)
            names.splice(0, 1);
        if (path.substr(path.length - 1, 1) == '/')
            names.splice(names.length - 1, 1);
        return names;
	},
	queryString: function() {
        var value = this.value();
        var index = value.indexOf('?');
        return (index != -1 && index < value.length) ? value.substr(index + 1) : '';
    },
    parameter: function(param) {
        var value = this.value();
        var index = value.indexOf('?');
        if (index != -1) {
            value = value.substr(index + 1);
            var params = value.split('&');
            var p, i = params.length;
            while(i--) {
                p = params[i].split('=');
                if (p[0] == param)
                return p[1];
            }
        }
    },
    parameterNames: function() {
        var value = this.value();
        var index = value.indexOf('?');
        var names = [];
        if (index != -1) {
            value = value.substr(index + 1);
            if (value != '' && value.indexOf('=') != -1) {
                var params = value.split('&');
                var i = 0;
                while(i < params.length) {
                    names.push(params[i].split('=')[0]);
                    i++;
                }
            }
        }
        return names;
    }
});

$(document).ready(function() {
	$.history = new History(); // singleton instance
});

})(jQuery);
// written by matthias [dot] jaeggli [at] orange8 [dot] com
// v1.2.1
//
// changelog:
//
// 1.2.1	
// height:0 fix for the original form element
//
// 1.2
// speed and loading-optimization
// rewrite of some parts

var allDms = [];
var closeAllDms = function(){
	$(allDms).each(function(){
		this.dmsTitle.close();
	});
} 

$.fn.extend({
	reverse: [].reverse,
	dropMultiselect: function(options){	
		var config = $.extend({
			maxHeight: 179,
			width: false,
			selectedCorr: 20,
			defaultTitle: "Bitte wählen",
			tracking : true
		}, options);
		this.tracking = {
			start: (config.tracking? new Date().getTime() : 0),
			stop: 0,
			laps: [],
			duration: 0,
			lap: function(msg){ if(config.tracking){ this.laps.push({msg: msg, time:( new Date().getTime() - this.start )}); } },
			terminate: function(){ this.stop = new Date().getTime(); this.duration = this.stop - this.start; }
		};
		var tracking = this.tracking;
	
		$(this).each(function(index){
		
			//create the html-replacement
			if(this.dms){ return $(this); }
			
			var dms = $("<div class='dms'/>")
				.click(function(e){
					//prevent closing droptown from a click inside the dropdown
					e.stopPropagation();
				})[0];
			dms.dmsIsMultiple = $(this).attr("multiple")? true : false;
			dms.dmsList = $("<ul"+(dms.dmsIsMultiple? '' : ' class="simple"')+" />")[0];
			dms.dmsTitle = $("<div class='title'/>")[0];
			dms.dmsDrop = $("<div class='drop'/>")
				.append(dms.dmsTitle)
				.append(dms.dmsList)[0];
			dms.dmsOriginal = this;
			this.dms = dms;
			$(dms).append(dms.dmsDrop);		
			allDms.push(dms);	
			
			//insert the fake select into DOM
			$(this).before(dms); 
			
			//set a fix width, if desired
			if(config.width){
				$(dms.dmsList).width(config.width - config.selectedCorr);
			}			
						
			dms.dmsFakeOptions = [];
			$(this).children()
				.each(function(){
					var tagName = $(this).hasClass("heading")? "span" : "a href='#'";
					var opt = $("<li class='" + $(this).attr("class") + "'>" +
									"<" + tagName + ">" +
										$.trim($(this).text()).replace(/\s/gi, "&nbsp;") +
									"</" + tagName + ">" +
								"</li>")[0];
					opt.partner = this;
					this.partner = opt;
					dms.dmsFakeOptions.push(opt);					
					$(dms.dmsList).append(opt);
				});	

			tracking.lap("html done element "+index);
			
			var group = "";
			$(dms.dmsFakeOptions).each(function(){
			
				//make a multiple-select or a single-select?
				if(dms.dmsIsMultiple){
					//create groups
					if($(this.partner).hasClass("group")){
						group = {head: this, children: []};
					}
					else if(group != ""){
						group.children.push(this);
					}
					this.group = group;
					
					//set the checkbox
					this.activate = function(noRecursion){
						$(this).addClass("active");	
						$(this.partner).attr("selected", "selected");
						
						if(!noRecursion){
							$(this.partner).change();
						
							if(this.group && $(this).hasClass("group")){
								$(this.group.children).each(function(){
									this.activate(true);
								});
							}
							else if(this.group && this.group.children.length == $(this.group.children).filter(".active").length){
								this.group.head.activate(true);
							}
						}
					}

					//remove checkbox
					this.deactivate = function(noRecursion){
						$(this).removeClass("active");
						$(this.partner).removeAttr("selected")
						
						if(!noRecursion){
							$(this.partner).change();
						
							if(this.group && $(this).hasClass("group")){
								$(this.group.children).each(function(){
									this.deactivate(true);
								});
							}
							else if(this.group){
								this.group.head.deactivate(true);
							}
						}
					}
				}
				//single-select
				else{
					//select the clicked value
					this.activate = function(noRecursion){
						$(dms.dmsOriginal)
							.children().each(function(){
								this.partner.deactivate(true);
							});
						$(this.partner).attr("selected", "selected")
						dms.dmsTitle.refresh().close();
						if(!noRecursion){
							$(this.partner).change();
						}
					}
					
					this.deactivate = function(noRecursion){
						$(this.partner).removeAttr("selected");
						if(!noRecursion){
							$(this.partner).change();
						}
					}
				}
				
				//enable an option for selection
				this.enable = function(noRecursion){
					$(this).removeClass("disabled");
					$(this.partner).removeAttr("disabled");
					
					if(this.group && this.group.head && !noRecursion){
						var foundActive = 0;
						$(this.group.head.children).each(function(){
							foundActive += $(this).hasClass("disabled")? 0 : 1;
						});
						if(foundActive > 0){
							this.group.head.enable(true);
						}
					}
				}
				
				//disable an option for selection
				this.disable = function(noRecursion){
					$(this).addClass("disabled");
					$(this.partner).attr("disabled", "disabled");
					this.deactivate(true);
					
					if(this.group && this.group.head && !noRecursion){
						if($(this).hasClass("group")){ //this is a head
							$(this.group.children).each(function(){
								this.disable(true);
							});
						}
						else{
							var foundActive = 0;
							$(this.group.head.children).each(function(){
								foundActive += $(this).hasClass("disabled")? 0 : 1;
							});
							if(foundActive == 0){
								this.group.head.disable(true);
							}
						}
					}
				}
				
				//children handlers
				$(this).children("a")
					.click(function(e){
						e.preventDefault();
						e.stopPropagation();
						if(!$(this).parent().is(".disabled")){
							var chb = $(this).parent();			
							if(chb = chb.get(0)){
								if($(chb).hasClass("active")){
									chb.deactivate();
								}
								else{
									chb.activate();
								}		
							}
							dms.dmsTitle.refresh();
						}
					})
					.keypress(function(e){
						switch(e.which){
							case 32:
								e.preventDefault();
								$(this).click();
								break;
						}
					});	
			});			
			
			tracking.lap("options done element "+index);
			
			//open and close
			dms.dmsTitle.refresh = function(){
				if(dms.dmsIsMultiple){
					var text = config.defaultTitle;
					var actives = $(dms.dmsList).find(".active");
					switch(actives.length){
						case 0: break;
						case 1:
							text = $(actives[0]).text();
							break;
						default:
							text = $(actives[0]).text() + ", ...";
							break;
					}
					$(this).text(text);
				}
				else{
					$(this).text($(dms.dmsOriginal).find(":selected").text());
				}
				return this;
			}	
			var title = $(dms.dmsTitle)
				.click(function(e){
						if(!$(this).hasClass("close")){
							this.close();
						}
						else{
							this.open();
						}
						e.stopPropagation();
					});
			dms.dmsTitle.close = function(){
				title
					.addClass("close")
					.parent().addClass("close");
				title.next()
					.css("top", -9999)
					.parents().css("z-index", "");	
				return this;
			}
			dms.dmsTitle.open = function(ignoreOthers){
				if(!title.hasClass("close")){
					return;
				}
				closeAllDms();
				title
					.removeClass("close")
					.parent()
						.removeClass("close");
				var ul = title.next();
				ul.parents().css("z-index", 100);
						
				//check if up or down
				var titlePos = $(this).offset().top;
				var titleHeight = $(this).outerHeight();
				var menuHeight = $(ul).outerHeight();
				
				var scrolledHeight = $(document).scrollTop();
				var viewPortHeight = $(window).height();					
				
				if(titlePos+titleHeight+menuHeight > scrolledHeight+viewPortHeight){	
					ul
						.css("top", -1*(menuHeight+titleHeight-1))
						.css("max-height", config.maxHeight)
						.css("overflow", "auto");
				}
				else{
					ul.css("top", -1);
					
					if(!($.browser.msie && parseInt($.browser.version)<7)){
						ul
							.css("max-height", 0)
							.css("overflow", "hidden")
							.animate({maxHeight: config.maxHeight}, 150, function(){
								$(this).css("overflow", "auto");
							});
					}
				}
				
				//IE6 special, max height fix
				if($.browser.msie && parseInt($.browser.version)<7 && ul.height()>config.maxHeight){
					ul
						.css("height", config.maxHeight)
						.css("overflow", "auto");
				}
			}	
			
			tracking.lap("open close done element "+index);
			
			//adjust width & height aka fix the float
			var dmsOriginal = $(dms.dmsOriginal);
			var floatFix = $("<div/>")
				.css("float", dmsOriginal.css("float"))
				.css("position", "relative")
				.height($(dms.dmsTitle).outerHeight());
			$(dms).before(floatFix);
			dmsOriginal.width(1).height(0).css("overflow", "hidden");
			$(floatFix)
				.append(dms.dmsOriginal)
				.prepend(dms);
				
			var list = $(dms.dmsList);
			var desiredWidth = list.outerWidth()+config.selectedCorr;			
			list
				.width(desiredWidth)
				.css("max-height", config.maxHeight)
				.prev()
					.width(desiredWidth-5);
			$(this).width(list.outerWidth());
			dms.dmsTitle.close();
			
			//initializing function
			dms.dmsOriginal.sync = function(){
				$(this).children().reverse().each(function(){
					if($(this).is(":selected")){ this.partner.activate(true); }
					else{ this.partner.deactivate(true); }
					
					//has to stay after the :selected check, because of dis-selection of disabled options
					if($(this).is(":disabled")){ this.partner.disable(true); 	}
					else{ this.partner.enable(true); }
					$(this.partner).children()
						.html($.trim($(this).text()).replace(/\s/gi, "&nbsp;"));
				});			
				dms.dmsTitle.refresh();
			}
			dms.dmsOriginal.sync();							
			
			//IE6 specials
			if($.browser.msie && parseInt($.browser.version)<8){
				try{
				var floatFixFloat = floatFix.css("float");
				if( (floatFixFloat == "none") || (floatFixFloat == "auto")){
					floatFix.css("float", "left");
				}
				floatFix.css("zoom", 1);
				$(dms.dmsTitle).click(function(){
					floatFix.css("zoom", 1);
				});
				$(dms.dmsOriginal).wrap(
					"<div style='overflow:hidden; width:"+$(dms).outerWidth()+"px; height:"+$(dms).outerHeight()+"px; margin-right:"+$(dms.dmsOriginal).css("margin-right")+"; '/>");
				$(dms.dmsFakeOptions)
					.each(function(){
						$(this)
							.click(function(e){
								e.preventDefault();
								e.stopPropagation();
								$("a", this).click();
							})
							.mouseover(function(e){
								e.preventDefault();
								e.stopPropagation();
								//$("a", this).addClass("hover"); // strage scrollbar bug 
							})
							.mouseout(function(e){
								e.preventDefault();
								e.stopPropagation();
								//$("a", this).removeClass("hover");  // strage scrollbar bug 
							});
					});
					
				dms.dmsTitle.open();
				dms.dmsTitle.close();
				}catch(e){
					alert(e.description);
				}
			}
						
			tracking.lap("finished element "+index);
		});
		
		this.tracking.terminate();
		
		return this;
	}
});

$(function(){	
	$(window).click(function(){
		closeAllDms();
	})
	$(document).click(function(){
		closeAllDms();
	})
});
/*
* jQuery pager plugin
* Version 1.0 (12/22/2008), modified by orange8 (04/08/2009)
* @requires jQuery v1.2.6 or later
*
* Example at: http://jonpauldavies.github.com/JQuery/Pager/PagerDemo.html
*
* Copyright (c) 2008-2009 Jon Paul Davies
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* 
* Read the related blog post and contact the author at http://www.j-dee.com/2008/12/22/jquery-pager-plugin/
*
* This version is far from perfect and doesn't manage it's own state, therefore contributions are more than welcome!
*
* Usage: .pager({ pageNumber: 1, pageCount: 15, buttonClickCallback: PagerClickTest });
*
* Where pageNumber is the visible page number
*       pageCount is the total number of pages to display
*       buttonClickCallback is the method to fire when a pager button is clicked.
*
* buttonClickCallback signiture is PagerClickTest = function(pageclickednumber) 
* Where pageclickednumber is the number of the page clicked in the control.
*
* The included Pager.CSS file is a dependancy but can obviously tweaked to your wishes
* Tested in IE6 IE7 Firefox & Safari. Any browser strangeness, please report.
*/
(function($) {

    $.fn.pager = function(options) {

        var opts = $.extend({}, $.fn.pager.defaults, options);

        return this.each(function() {
			// empty out the destination element and then render out the pager with the supplied options
            $(this).empty().append(renderpager(opts));
            
            // specify correct cursor activity
            $('.pages li').mouseover(function() { document.body.style.cursor = "pointer"; }).mouseout(function() { document.body.style.cursor = "auto"; });
        });
    };

    // render and return the pager with the supplied options
    function renderpager(opts) {
		var pageNumber = parseInt(opts.pageNumber);
		var pageCount = parseInt(opts.pageCount);
		var buttonClickCallback = opts.buttonClickCallback;

        // setup $pager to hold render
        var $pager = $('<ul class="pages"></ul>');

        // add in the previous and next buttons
        $pager.append(renderButton(opts.navStringFirst, opts)).append(renderButton(opts.navStringPrev, opts));

        // pager currently only handles 10 viewable pages ( could be easily parameterized, maybe in next version ) so handle edge cases
        var startPoint = 1;
        var endPoint = 9;

        if (pageNumber > 4) {
            startPoint = pageNumber - 4;
            endPoint = pageNumber + 4;
        }

        if (endPoint > pageCount) {
            startPoint = pageCount - 8;
            endPoint = pageCount;
        }

        if (startPoint < 1) {
            startPoint = 1;
        }

        // loop thru visible pages and render buttons
        for (var page = startPoint; page <= endPoint; page++) {

            var currentButton = $('<li class="page-number">' + (page) + '</li>');

            page == pageNumber ? currentButton.addClass('pgCurrent') : currentButton.click(function() { buttonClickCallback(this.firstChild.data); });
            currentButton.appendTo($pager);
        }

        // render in the next and last buttons before returning the whole rendered control back.
        $pager.append(renderButton(opts.navStringNext, opts)).append(renderButton(opts.navStringLast, opts));

        return $pager;
    }

    // renders and returns a 'specialized' button, ie 'next', 'previous' etc. rather than a page number button
    function renderButton(buttonLabel, opts) {
		var pageNumber = parseInt(opts.pageNumber);
		var pageCount = parseInt(opts.pageCount);
		var buttonClickCallback = opts.buttonClickCallback;

        var $Button = $('<li class="pgNext">' + buttonLabel + '</li>');

        var destPage = 1;

        // work out destination page for required button type
        switch (buttonLabel) {
            case opts.navStringFirst:
                destPage = 1;
                break;
            case opts.navStringPrev:
                destPage = pageNumber - 1;
                break;
            case opts.navStringNext:
                destPage = pageNumber + 1;
                break;
            case opts.navStringLast:
                destPage = pageCount;
                break;
        }

        // disable and 'grey' out buttons if not needed.
        if (buttonLabel == opts.navStringFirst || buttonLabel == opts.navStringPrev) {
            pageNumber <= 1 ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); });
        }
        else {
            pageNumber >= pageCount ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); });
        }

        return $Button;
    }

    // pager defaults. hardly worth bothering with in this case but used as placeholder for expansion in the next version
    $.fn.pager.defaults = {
        pageNumber: 1,
        pageCount: 1,
        navStringFirst: '|<',
        navStringPrev: '<',
        navStringLast: '>|',
        navStringNext: '>'
    };

})(jQuery);






//tiny plugins
$.fn.reverse = [].reverse;
$.shitbrowser = ($.browser.msie && parseInt($.browser.version) < 7);
var offeringSorting = window.configIsWinterTime ? "wa" : "sa";

(function($) {

    $.requestBubbleIcons = function(options) {
        options = options || {};
        options.callback = options.callback || function() { };
        options.url = options.url || "";
        options.queryPath = options.queryPath || "";

        $.ajax({
            type: "POST",
            url: options.url,
            data: "{ 'filters': ['/Angebots-Finder/Was'" + (options.queryPath ? ", '" + options.queryPath + "'" : "") + "] }",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: options.callback
        });
    }

    //bubble plugin
    $.fn.makeBubbles = function(options) {
        $(this).each(function() {
            if (this.hasBubbles) {
                options.callback();
                return;
            }
            this.hasBubbles = true;

            //init
            options = options || {};
            options.callback = options.callback || function() { };
            options.boubbleData = options.boubbleData || [];
            options.standardTitle = options.standardTitle || "";

            var locationCategoryList = [];
            var bubbleContainers = [];
            var rwCont = $(this);
            $(options.boubbleData).each(function() {
                var myBubbleData = this;
                var head = $('<span class="head">' + options.standardTitle + '</span>');
                var icons = {};
                $('<span class="icons"/>')
					.each(function() {
					    icons = this;
					    icons.loaded = false;
					});
                var bubble = {};
                $('<span class="bubble bubble-' + this.bubble + '"/>')
					.append(head)
					.append(icons)
					.each(function() {
					    this.head = head;
					    this.headText = $(head).text();
					    bubble = this;
					    bubble.icons = icons;
					    bubble.data = myBubbleData;
					})
					.mouseover(function(e) {
					    e.stopPropagation();
					});

                var station = {};
                $('<div class="imgreplace station ' + this.cssClass + '" style="top:' + this.top + 'px; left:' + this.left + 'px;"/>')
					.append(bubble)
					.each(function() {

					    //opens the bubble
					    var myStation = this;
					    this.open = function() {
					        var openMyBubble = function() {	//shit because IE7 popup blocker					
					            $(bubbleContainers).each(function() {
					                this.close();
					            });
					            $(myStation).addClass("open");
					        }

					        if (!this.bubble.icons.loaded) {
					            //load icons first
					            this.requestBubbleIcons({
					                callback: function(data) {
					                    //generate icons
					                    if (!data) { return; }

					                    //get my name
					                    data.LocationCategoryList = data.LocationCategoryList || [];
					                    var myAliasPath = myStation.bubble.data.aliasPath + "/" + myStation.bubble.data.name;
					                    var myAliasPathRailwayStation = myStation.bubble.data.aliasPath;
					                    var foundName = myStation.bubble.data.name;
					                    $(data.LocationCategoryList).each(function(i, val) {
					                        if (val.AliasPath == myAliasPath) {
					                            foundName = val.Name;
					                        }
					                    });

					                    //set title										
					                    myStation.bubble.headText += " (" + data.OfferingCount + ")";
					                    $(myStation.bubble.head).text(myStation.bubble.headText)
					                    if (data.OfferingCount) {
					                        $(myStation.bubble.head).click(function() {
					                            // temporarily set search criteria and redirect to the result page
					                            var allAliasPaths = [myAliasPathRailwayStation];
					                            $("[id*='_listBoxWh'] > option").removeAttr('selected');
					                            for (var i = 0; i < allAliasPaths.length; i++) {
					                                $("[id*='_listBoxWh'] > option:[value='" + allAliasPaths[i] + "']").attr('selected', 'selected');
					                            }
					                            $('#loe-of-tagsearch').val('');
					                            var encodedCriteria = getTinySearchUrl();
					                            var targetUrl = '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1';
					                            window.location.href = targetUrl;
					                        });
					                    }
					                    else {
					                        $(myStation.bubble.icons).addClass("empty");
					                        return;
					                    }

					                    //get icons
					                    $(data.CategoryList).each(function(i, val) {
					                        if (!val.OfferingCount) { return; }


					                        var nimage = $('<img alt=""/>').attr("src", val.IconBw);
					                        var nlink = $('<a href="' + val.AliasPath + '" title="' + val.Name + '" name="Raodmap_' + val.Name + '"/>')
												.mouseover(function() {
												    myStation.bubble.head.text($(this).attr("title"));
												    $(nimage).attr("src", val.Icon);
												})
												.mouseout(function(e) {
												    e.stopPropagation();
												    myStation.bubble.head.text(myStation.bubble.headText);
												    $(nimage).attr("src", val.IconBw);
												})
												.append(nimage)
												.click(function(e) {
												    e.preventDefault();

												    // temporarily set search criteria and redirect to the result page
												    var allAliasPaths = [val.AliasPath, myAliasPath, val.AliasPathWinter];
												    $("[id*='_listBoxWh'] > option").removeAttr('selected');
												    for (var i = 0; i < allAliasPaths.length; i++) {
												        $("[id*='_listBoxWh'] > option:[value='" + allAliasPaths[i] + "']").attr('selected', 'selected');
												    }
												    $('#loe-of-tagsearch').val('');

												    var encodedCriteria = getTinySearchUrl();
												    var targetUrl = '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1';
												    window.location.href = targetUrl;
												})
												.appendTo(myStation.bubble.icons);

					                        if (myStation.bubble.data.cssClass && myStation.bubble.data.cssClass == "dot-link" && !myStation.hasFlag) {
					                            myStation.hasFlag = true;

					                            //set my name into flag
					                            $(myStation).prepend(
													$("<span class='flag flag-" + myBubbleData.bubble + "'>" + foundName + "</span>")
														.click(function() {
														    setSearchCookieData(
																[],
																[],
																[myStation.bubble.data.aliasPath + "/" + myStation.bubble.data.name],
																[foundName],
																"");
														    window.location.href = '/suchuebersicht.aspx';
														})
												)
					                        }
					                    });

					                    //open the bubble
					                    openMyBubble();
					                },
					                url: "/Loetschberger/OfferingService.asmx/GetOfferingCategories",
					                queryPath: bubble.data.aliasPath + "/" + bubble.data.name
					            });
					            this.bubble.icons.loaded = true;
					        }
					        else {
					            openMyBubble();
					        }

					    }

					    //closes the bubble
					    this.close = function() {
					        $(myStation).removeClass("open");
					    }

					    //loads the icons inside the bubble
					    this.requestBubbleIcons = $.requestBubbleIcons;

					    this.bubble = bubble;
					    station = this;
					})
					.mouseover(function(e) {
					    this.open();
					    e.stopPropagation();
					})
					.click(function(e) {
					    e.stopPropagation();
					});

                rwCont.append(station);
                bubbleContainers.push(station);
            });

            var closeAllBubbles = function() {
                $(bubbleContainers).each(function() {
                    this.close();
                });
            }

            $(rwCont).click(function() {
                closeAllBubbles();
            });

            $("body").click(function() {
                closeAllBubbles();
            });

            if (options.callback) {
                options.callback();
            }
        });
    }

    //map bubbles plugin
    $.fn.mapBubbles = function(options) {
        $(this).each(function() {
            if (this.hasBubbles) {
                options.callback();
                return;
            }
            this.hasBubbles = true;
            var map = this;

            //init
            options = options || {};
            options.callback = options.callback || function() { };
            options.bubbleData = options.bubbleData || [];

            var locationCategoryList = [];
            var bubbleContainers = [];
            var rwCont = $(this);
            $(options.bubbleData).each(function() {
                var myBubbleData = this;
                var head = $('<strong class="head"></strong>').append($("<a href='" + myBubbleData.url + "' name='" + myBubbleData.name + "'></a>").text(myBubbleData.title).click(function(e) { e.stopPropagation(); }));
                var icons = {};
                $('<span class="icons"></span>')
					.text(myBubbleData.text + " ")
					.each(function() {
					    icons = this;
					})
					.append($("<span class='location'/>").text(myBubbleData.location));
                var bubble = {};
                $('<span class="bubble bubble-' + this.bubble + '"/>')
					.append(head)
					.append(icons)
					.each(function() {
					    this.head = head;
					    this.headText = $(head).text();
					    bubble = this;
					    bubble.icons = icons;
					    bubble.data = myBubbleData;
					})
					.mouseover(function(e) {
					    e.stopPropagation();
					})
					.mousedown(function(e) {
					    e.stopPropagation();
					})
					.click(function(e) {
					    e.stopPropagation();
					});
                var getCenterBonus = function(bubble) {
                    var bonus = 60;
                    switch (bubble) {
                        case "tr": return { left: bonus, top: -1 * bonus };
                        case "tl": return { left: -1 * bonus, top: -1 * bonus };
                        case "br": return { left: bonus, top: bonus };
                        case "bl": return { left: -1 * bonus, top: bonus };
                        default: return { left: 0, top: 0 };
                    }
                }

                var station = {};
                $('<div title="' + myBubbleData.location + '" class="imgreplace station ' + this.cssClass + '" style="top:' + this.top + 'px; left:' + this.left + 'px;"/>')
					.append(bubble)
					.each(function() {

					    //opens the bubble
					    var myStation = this;
					    this.open = function() {
					        var openMyBubble = function() {	//shit because IE7 popup blocker					
					            $(bubbleContainers).each(function() {
					                this.close();
					            });
					            $(myStation).addClass("open");
					        }
					        openMyBubble();
					        var cb = getCenterBonus(myBubbleData.bubble);
					        map.tryToCenter(myBubbleData.left + cb.left, myBubbleData.top + cb.top, "fast");
					    }

					    //closes the bubble
					    this.close = function() {
					        $(myStation).removeClass("open");
					    }

					    //loads the icons inside the bubble
					    this.requestBubbleIcons = $.requestBubbleIcons;

					    this.bubble = bubble;
					    station = this;
					})
					.click(function(e) {
					    e.stopPropagation();
					    if ($(this).hasClass("open")) {
					        this.close();
					    }
					    else {
					        this.open();
					    }
					})
					.mousedown(function(e) {
					    e.stopPropagation();
					});

                rwCont.append(station);
                bubbleContainers.push(station);
            });

            if (options.callback) {
                options.callback();
            }

            var closeAllBubbles = function() {
                $(bubbleContainers).each(function() {
                    this.close();
                });
            }

            $(rwCont).mousedown(function() {
                closeAllBubbles();
            });
        });
    }

    //dot links plugin
    $.fn.makeDotLinks = function(options) {
        $(this).each(function() {
            if (this.hasDots) {
                options.callback();
                return;
            }
            this.hasDots = true;

            //init
            options = options || {};
            options.callback = options.callback || function() { };
            options.data = options.data || [];

            //place the links
            var rwCont = $(this);
            $(options.bubbleData).each(function() {
                var linkData = this;

                var nlink = {};
                $('<a href="' + this.aliasPath + '" class="' + this.cssClass + '" style="top:' + this.top + 'px; left:' + this.left + 'px;"/>')
					.each(function() {
					    this.linkData = linkData;
					    nlink = this;
					});

                rwCont.append(nlink);
            });

            if (options.callback) {
                options.callback();
            }
        });
    }

    //easymap plugin
    $.fn.easymap = function(options) {
        var conf = $.extend({
            startX: 983,
            startY: 740,
            extremaX: 1013,
            extremaY: 770,
            borderWidth: 30,
            locations: [],
            isWinter: false
        }, options);

        this.each(function() {
            if (this.isEasyMap) { return; }
            this.isEasyMap = true;
            var map = this;

            //create map
            var dragOpts = {
                containment: 'parent',
                drag: function() {
                    map.mapUpdateMapAdditions();
                },
                scroll: false
            }
            $(map)
				.draggable(dragOpts)
				.css("left", conf.startX)
				.css("top", conf.startY)
				.mousedown(function() { $(this).addClass("dragging"); })
				.mouseup(function() { $(this).removeClass("dragging"); });


            //create buttons
            map.mapButtons = [];
            map.mapMove = function(params, speed) {
                $(map).stop(true, false).animate(params, speed, "linear", function() {
                    map.mapUpdateMapAdditions ? map.mapUpdateMapAdditions() : "";
                });
            }
            map.mapAddNavButton = function(btn, params) {
                params = params || {};
                btn.easymap = map;
                btn.animateTopValue = params.top === 0 ? 0 : (params.top || "-");
                btn.animateLeftValue = params.left === 0 ? 0 : (params.left || "-");
                btn.animateSpeed = params.speed || 250; //pixel per second
                $(btn)
					.mouseover(function() {
					    $(this).stop(true, true);
					})
					.mouseout(function() {
					    $(this).stop(true, true);
					    map.mapUpdateMapAdditions();
					})
					.mousedown(function(e) {
					    e.preventDefault();
					    e.stopPropagation();
					    if (btn.animateTopValue != "-" && btn.animateLeftValue != "-") {
					        var actualTop = parseInt($(map).css("top"));
					        var actualLeft = parseInt($(map).css("left"));
					        var newSpeedTop = Math.round((Math.abs(btn.animateTopValue - actualTop) * 1000) / (btn.animateSpeed));
					        var newSpeedLeft = Math.round((Math.abs(btn.animateLeftValue - actualLeft) * 1000) / (btn.animateSpeed));
					        var newSpeed = Math.round(Math.sqrt(newSpeedTop * newSpeedTop + newSpeedLeft * newSpeedLeft));
					        map.mapMove({ top: btn.animateTopValue, left: btn.animateLeftValue }, newSpeed);
					    }
					    else if (btn.animateTopValue != "-") {
					        var actualTop = parseInt($(map).css("top"));
					        var newSpeed = Math.round((Math.abs(btn.animateTopValue - actualTop) * 1000) / (btn.animateSpeed));
					        map.mapMove({ top: btn.animateTopValue }, newSpeed);
					    }
					    else if (btn.animateLeftValue != "-") {
					        var actualLeft = parseInt($(map).css("left"));
					        var newSpeed = Math.round((Math.abs(btn.animateLeftValue - actualLeft) * 1000) / (btn.animateSpeed));
					        map.mapMove({ left: btn.animateLeftValue }, newSpeed);
					    }
					})
					.mouseup(function() {
					    $(map).stop(true, false);
					    map.mapUpdateMapAdditions();
					});
                map.mapButtons.push(btn);
                $(map).parents(".easymap").append(btn);
                return btn;
            }
            var extremeTop = $(map).height() - $(map).parents(".easymap").height() + 2 * conf.borderWidth;
            var topLeft = map.mapAddNavButton($("<div class='mapbutton topleft'>&nbsp;</div>")[0], { top: extremeTop, left: 1013 });
            var top = map.mapAddNavButton($("<div class='mapbutton top'>&nbsp;</div>")[0], { top: extremeTop });
            var topRight = map.mapAddNavButton($("<div class='mapbutton topright'>&nbsp;</div>")[0], { top: extremeTop, left: 0 });
            var right = map.mapAddNavButton($("<div class='mapbutton right'>&nbsp;</div>")[0], { left: 0 });
            var bottomRight = map.mapAddNavButton($("<div class='mapbutton bottomright'>&nbsp;</div>")[0], { top: 0, left: 0 });
            var bottom = map.mapAddNavButton($("<div class='mapbutton bottom'>&nbsp;</div>")[0], { top: 0 });
            var bottomLeft = map.mapAddNavButton($("<div class='mapbutton bottomleft'>&nbsp;</div>")[0], { top: 0, left: 1013 });
            var left = map.mapAddNavButton($("<div class='mapbutton left'>&nbsp;</div>")[0], { left: 1013 });

            //display
            var cursor = $('<div class="cursor"><div class="border"><div class="bg"></div></div></div>')[0];
            $(cursor).find(".bg").fadeTo(0, 0.3);
            var display = $('<div class="easymap-display' + (conf.isWinter ? " easymap-display-winter" : "") + '"></div>').append(cursor)[0];
            //$(map).parents(".easymap").(display);
            $("#map-disp-containter").prepend(display);

            if (conf.isWinter) {
                $("#map-disp-containter").parent().addClass("panorama-list-winter")
            }

            var mapHeight = parseInt($(map).height()) + conf.borderWidth * 2;
            var mapWidth = parseInt($(map).width()) + conf.borderWidth * 2;
            var curHeight = parseInt($(cursor).height());
            var curWidth = parseInt($(cursor).width());
            var dispHeight = parseInt($(display).height());
            var dispWidth = parseInt($(display).width());
            $(cursor)
				.draggable({ containment: 'parent',
				    drag: function() {
				        var curTop = parseInt($(cursor).css("top"));
				        var curLeft = parseInt($(cursor).css("left"));

				        var newPosLeft = curLeft + curWidth == dispWidth ? 0 : conf.extremaX - Math.round(curLeft * mapWidth / dispWidth);
				        var newPosTop = curTop + curHeight == dispHeight ? 0 : conf.extremaY - Math.round(curTop * mapHeight / dispHeight);

				        $(map).css("top", newPosTop).css("left", newPosLeft);

				        map.mapUpdateButtons();
				    }
				})
				.mousedown(function() { $(this).css("cursor", "move"); })
				.mouseup(function() { $(this).css("cursor", "default"); });

            map.mapUpdateMapAdditions = function() {
                map.mapUpdateCursor();
                map.mapUpdateButtons();
            }
            map.mapUpdateCursor = function() {
                var mapTop = parseInt($(map).css("top"));
                var mapLeft = parseInt($(map).css("left"));
                var newPosLeft = Math.round((conf.extremaX - mapLeft) / (mapWidth / dispWidth));
                var newPosTop = Math.round((conf.extremaY - mapTop) / (mapHeight / dispHeight));
                newPosLeft = newPosLeft + curWidth > dispWidth ? dispWidth - curWidth : newPosLeft;
                newPosTop = newPosTop + curHeight > dispHeight ? dispHeight - curHeight : newPosTop;

                //$(cursor).stop().animate({top: newPosTop, left:newPosLeft}, "fast", "linear");
                $(cursor)
					.css("top", newPosTop)
					.css("left", newPosLeft);
            }
            map.mapUpdateButtons = function() {
                var mapTop = parseInt($(map).css("top"));
                var mapLeft = parseInt($(map).css("left"));
                $(map.mapButtons).each(function() {
                    if ((mapTop === this.animateTopValue && mapLeft === this.animateLeftValue) ||
						(mapTop === this.animateTopValue && this.animateLeftValue === "-") ||
						(this.animateTopValue === "-" && mapLeft === this.animateLeftValue)
							) {
                        $(this).hide();
                    }
                    else {
                        $(this).show();
                    }
                });
            }

            //centering		
            var winHeight = parseInt($(map).parents(".easymap").innerHeight());
            var winWidth = parseInt($(map).parents(".easymap").innerWidth());
            map.tryToCenter = function(x, y, speed) {

                var mapTop = parseInt($(map).css("top"));
                var mapLeft = parseInt($(map).css("left"));
                x = parseInt(x);
                y = parseInt(y);
                var newPosLeft = Math.round(mapLeft + ((mapWidth + conf.borderWidth - winWidth / 2) - (mapLeft + x)));
                var newPosTop = Math.round(mapTop + ((mapHeight + conf.borderWidth - winHeight / 2) - (mapTop + y)));
                newPosLeft = newPosLeft < 0 ? 0 : (newPosLeft > conf.extremaX ? conf.extremaX : newPosLeft - 2 * conf.borderWidth);
                newPosTop = newPosTop < 0 ? 0 : (newPosTop > conf.extremaY ? conf.extremaY : newPosTop - 2 * conf.borderWidth);

                map.mapMove({ left: newPosLeft, top: newPosTop }, "fast");
            }
            map.tryToCenter(Math.round((conf.extremaX + winWidth) / 2), Math.round((conf.extremaY + winHeight) / 2), 0);
            map.mapUpdateCursor();
        });

        return $(this);
    }


})(jQuery);


// onload
$(function() {
    $("#headContainer .headpart").not(":first").hide();
    $(".items-hold .item:first").hide();

    if ($("#hRoadway, #hPanorama").length) {
        //preload all icons
        $.requestBubbleIcons({
            callback: function(data) {
                //generate icons
                var preloader = $("<div/>");
                $(data.CategoryList).each(function(i, val) {
                    //colorfull
                    preloader.append($('<img/>').attr("src", val.Icon));
                    //black and white
                    preloader.append($('<img/>').attr("src", val.IconBw));
                });

            },
            url: "/Loetschberger/OfferingService.asmx/GetOfferingCategories"
        });
    }

    //animate and init header items
    var panoramaBubbleData = false;
    var items = $(".items-hold .item")
		.reverse()
		.each(function(i, val) {
		    var item = this;
		    $(this)
				.append(
					$("<div style='position:absolute; left:0; top:0; cursor:pointer; zoom:1; background:#fff;'/>")
						.fadeTo(1, 0.01)
						.css("width", $(this).width() + 20)
						.css("height", $(this).height() + 10)
						.mouseover(function() {
						    var p = $(item);
						    if (p.is(":animated")) {
						        return false;
						    }
						    $(p)
								.animate({ bottom: 5 }, 50, "linear", function() {
								    $(this).animate({ bottom: -2 }, 50, "linear", function() {
								        $(this).animate({ bottom: 0 }, 50, "linear");
								    });
								});
						})
						.click(function() {
						    //$("a", $(this).parent()).click();

						    //0. check if any animation is on
						    $(items).each(function() {
						        if ($(this).is(":animated")) {
						            return;
						        }
						    });

						    //1. slide out items
						    slideOut($(".items-hold"), 0, 200, function() {
						        $(items).each(function() { $(this).css("bottom", 0).show(); });
						        $(item).hide();
						        slideIn($(".items-hold"), 0, 200);
						    });

						    //2. hide actual head part
						    $("#headContainer .headpart:visible").fadeOut("fast");

						    //3. load desired content, if not already loaded									
						    var showNext = $($("a", $(this).parent()).attr("href") || "");
						    var afterLoad = function() {
						        showNext.fadeIn("slow");
						    }
						    switch (showNext.attr("id")) {
						        case "hRoadway":
						            showNext
									.each(function() {
									    var img = $("img", this);
									    img.attr("src", img.attr("rel"));
									})
									.makeBubbles({
									    callback: function() {
									        afterLoad();

									        //add links
									        //$(this) // == append links

									    },
									    standardTitle: "Aktivit&auml;ten",
									    boubbleData: [
											{ name: "Bern", left: 20, top: 72, bubble: "br", aliasPath: "/Angebots-Finder/WO/Aaretal/Bern-(1)", cssClass: "big-station" },
											{ name: "Muensingen", left: 98, top: 53, bubble: "br", aliasPath: "/Angebots-Finder/WO/Aaretal/Munsingen", cssClass: "" },
											{ name: "Thun", left: 175, top: 65, bubble: "br", aliasPath: "/Angebots-Finder/WO/Thunersee/Thun-(1)", cssClass: "" },
											{ name: "Spiez", left: 251, top: 73, bubble: "br", aliasPath: "/Angebots-Finder/WO/Thunersee/Spiez-(1)", cssClass: "big-station" },
											{ name: "Wimmis", left: 253, top: 145, bubble: "br", aliasPath: "/Angebots-Finder/WO/Simmental/Wimmis-(1)", cssClass: "" },
											{ name: "Muelenen", left: 332, top: 63, bubble: "br", aliasPath: "/Angebots-Finder/WO/Kandertal/Mulenen", cssClass: "" },
											{ name: "Oey-Diemtigen", left: 331, top: 180, bubble: "br", aliasPath: "/Angebots-Finder/WO/Simmental/Oey-Diemtigen-(1)", cssClass: "" },
											{ name: "Reichenbach", left: 409, top: 61, bubble: "br", aliasPath: "/Angebots-Finder/WO/Kandertal/Reichenbach-(1)", cssClass: "" },
											{ name: "Erlenbach", left: 409, top: 180, bubble: "br", aliasPath: "/Angebots-Finder/WO/Simmental/Erlenbach-im-Simmental", cssClass: "" },
											{ name: "Darstetten", left: 475, top: 179, bubble: "br", aliasPath: "/Angebots-Finder/WO/Simmental/Darstetten-(1)", cssClass: "" },
											{ name: "Frutigen", left: 546, top: 54, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Kandertal/Frutigen-(1)", cssClass: "" },
											{ name: "Weissenburg", left: 552, top: 191, bubble: "tl", aliasPath: "/Angebots-Finder/WO/Simmenta/Weissenburg-(1)", cssClass: "" },
											{ name: "Kandersteg", left: 622, top: 75, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Kandertal/Kandersteg-(1)", cssClass: "" },
											{ name: "Oberwil", left: 622, top: 191, bubble: "tl", aliasPath: "/Angebots-Finder/WO/Simmental/Oberwil-im-Simmental", cssClass: "" },
											{ name: "Goppenstein", left: 677, top: 52, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Lotschberger-Sudrampe/Goppenstein-(1)", cssClass: "" },
											{ name: "Boltigen", left: 693, top: 174, bubble: "tl", aliasPath: "/Angebots-Finder/WO/Simmental/Boltigen-(1)", cssClass: "" },
											{ name: "Hohtenn", left: 726, top: 43, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Lotschberger-Sudrampe/Hohtenn-(1)", cssClass: "" },
											{ name: "Ausserberg", left: 777, top: 51, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Lotschberger-Sudrampe/Ausserberg-(1)", cssClass: "" },
											{ name: "Weissenbach", left: 764, top: 183, bubble: "tl", aliasPath: "/Angebots-Finder/WO/Simmental/Weissenbach-(1)", cssClass: "" },
											{ name: "Eggerberg", left: 830, top: 59, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Lotschberger-Sudrampe/Eggerberg-(1)", cssClass: "" },
											{ name: "Zweisimmen", left: 843, top: 176, bubble: "tl", aliasPath: "/Angebots-Finder/WO/Simmental/Zweisimmen-(1)", cssClass: "big-station" },
											{ name: "Lalden", left: 893, top: 69, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Lotschberger-Sudrampe/Lalden-(1)", cssClass: "" },
											{ name: "Brig", left: 926, top: 72, bubble: "bl", aliasPath: "/Angebots-Finder/WO/Lotschberger-Sudrampe/Brig-(1)", cssClass: "big-station" }
										]
									});
						            if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('roadMapItem', 'link');
						            break;

						        case "hPanorama":
						            showNext.show();

						            var mapConfig = {
						                startX: 983,
						                startY: 740,
						                extremaX: 1013,
						                extremaY: 770,
						                borderWidth: 30
						            }

						            //check for winter
						            var isWinter = false;
						            if ($(item).is(".winter")) {
						                isWinter = true;
						                mapConfig.isWinter = true;
						                mapConfig.extremaY = 1017;
						                $("#hPanorama .easymap .mapcontainer").addClass("mapcontainer-winter");
						                $("#hPanorama .easymap .mapcontainer .mapholder").addClass("mapholder-winter");
						            }

						            var panoramaMap = $("#hPanorama .easymap .mapcontainer .mapholder").easymap(mapConfig);

						            //load bubbles if not already loaded
						            if (!panoramaBubbleData) {
						                panoramaBubbleData = [];
						                var url = !isWinter ?
											"/App_Themes/Loetschberger/csv/angebote_panoramakarte.csv" :
											"/App_Themes/Loetschberger/csv/angebote_panoramakarte_winter.csv";

						                $.get(url, function(data) {
						                    //make bubble data object
						                    if (!data) { return; }
						                    data = data
												.replace(/\r/g, "\n")
												.replace(/\n\n/g, "\n")
												.split("\n");
						                    $(data)
												.each(function() {
												    var b = this.split(";");
												    if (!parseInt(b[0] || "")) { return; }
												    panoramaBubbleData.push({
												        title: b[1] || "",
												        text: b[2] || "",
												        location: b[3] || "",
												        url: b[4] || "",
												        left: parseInt(b[5]),
												        top: parseInt(b[6]),
												        bubble: b[7] || "tr",
												        cssClass: "map-bubble",
												        name: "Panorama_Header",
												        id: parseInt(b[0])
												    });
												});

						                    //insert Bubbles
						                    panoramaMap.mapBubbles({ bubbleData: panoramaBubbleData });
						                });
						            }
						            if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('panoramaMapItem', 'link');
						            break;

						        default:
						            if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('impressionMapItem', 'link');
						            afterLoad();
						            break;
						    }
						})
				)
		});

    var index = 0;
    //slides in Header Items
    var slideIn = function(elems, index, speed, endCall) {
        if (!elems || !elems.length) { return; }
        index = index || 0;
        speed = speed || 200;
        speed = endCall || function() { };
        var callback = function() { }
        if (elems.length > index + 1) {
            callback = function() {
                slideIn(elems, index + 1, speed, endCall);
            }
        }
        else {
            callback = endCall;
        }
        $(elems[index]).animate({ bottom: 0 }, speed, "swing", callback);
    }
    slideIn(items.not(":hidden"), 0, 500);

    //slides Out Header Items
    var slideOut = function(elems, index, speed, endCall) {
        if (!elems || !elems.length) { return; }
        index = index || 0;
        speed = speed || 200;
        speed = endCall || function() { };
        var callback = function() { }
        if (elems.length > index + 1) {
            callback = function() {
                slideOut(elems, index + 1, speed, endCall);
            }
        }
        else {
            callback = endCall;
        }
        $(elems[index]).animate({ bottom: -100 }, speed, "swing", callback);
    }

    if ($.shitbrowser) {
        //$("body").prepend("<a href='http://www.microsoft.com/windows/internet-explorer/' target='_blank' id='oldbrowser'><strong>Alter Browser</strong> Sie benutzen ein &uuml;ber "+((new Date()).getYear()-2001)+" Jahre alter Browser, klicken Sie hier um das Problem zu beheben.</a>");
        //$("#oldbrowser").show().hide().slideDown("slow");
    }

    var kkeys = [], lolwut = "38,38,40,40,37,39,37,39,66,65";
    $(document).keydown(function(e) {
        kkeys.push(e.keyCode);
        if (kkeys.toString().indexOf(lolwut) >= 0) {
            $(document).unbind('keydown', arguments.callee);
            $("#main").append(
				$("<img/>").css("position", "absolute").css("bottom", 0).css("right", 0)
					.load(function() {
					    $(this).fadeTo("fast", 0.7, function() {
					        this.s = (this.s + 1) % 2;
					        $(this).attr("src", this.u[this.s]);
					    });
					})
					.each(function() {
					    this.s = 1;
					    this.n = unescape("%68%74%74%70%3A%2F%2F%37%38%2E%34%36%2E%38%30%2E%32%30%34%2F");
					    this.r = unescape("%2E%70%6E%67");
					    this.u = [this.n + 0 + this.r, this.n + 1 + this.r]
					})
					.load()
					.click(function() { $(this).remove(); })
			);
        }
    });


    try {
        $(".items-hold .item:first div").click();
    }
    catch (e) {
        //ERROR not handled
    }

});

$(document).ready(function(){
	
	//get all radio groupnames of perfect radios
	var radioGroupNames = new Array();	
	$("input.perfectradio").each(function(){
		if((","+radioGroupNames.toString()).indexOf(this.name)<1){
			radioGroupNames.push(this.name);
		}
	});
	
	//this function updates the label-class according the checked-state of the relative 
	var updateLabels = function(){
		$(this.group).each(function(){
			if(this.checked){
				$(this.label).addClass("perfectradio-checked");
			}
			else{
				$(this.label).removeClass("perfectradio-checked");
			}
		});
	}
	
	//create radio groups and init the states
	for(var i=0; i<radioGroupNames.length; i++){
		var grp = $("input[name='"+radioGroupNames[i]+"']").filter("input[type='radio']");
		grp.each(function(){
			this.group = grp;
			this.label = $("label[for='"+this.id+"']").get(0);
			this.label.radio = this;
			$(this)
			.change(updateLabels)
			.click(updateLabels)	//IE6 hack -> wrong event firing
			.focus(function(){
				$(this.label).addClass("perfectradio-focus");
			})
			.blur(function(){
				$(this.label).removeClass("perfectradio-focus");
			});
		})
		.each(updateLabels);		//initialize 
	}
});

$(document).ready(function(){
	
	var updateCbLabel = function(){
		if(this.checked){
			$(this.label).addClass("perfectcheckbox-checked");
		}
		else{
			$(this.label).removeClass("perfectcheckbox-checked");
		}
	}	
	$("label.perfectcheckbox").each(function(){
		var chbx = $("#"+$(this).attr("for")).get(0);
		chbx.label = this;
		this.checkbox = chbx;
		
		$(chbx)
		.change(updateCbLabel)
		.click(updateCbLabel)				//IE6 hack -> wrong event firing
		.focus(function(){
			$(this.label).addClass("perfectcheckbox-focus");
		})
		.blur(function(){
			$(this.label).removeClass("perfectcheckbox-focus");
		})
 		.each(updateCbLabel);				//initialize		
		
		if($.shitbrowser){
			$(this).css("zoom", 1);
		}
		
	});
});

/**
    This script implements the google analytics tracking capabilities. By default
    every pageview (either postback or not) is logged by this framework. Form
    submissions to the same page url (postbacks) may poison the analytics results.
    In order to circumvent this limitation we use a simple trick with a well known
    hidden input field "analyticsTrackPageviewLink". By using this hidden field
    it's possible to track the state after a postback occured (i.e. in a order
    process). Therefore use the following code in the different event handlers
    in the code behind:
    <code>
        protected void btnRegister(object sender, EventArgs e)
        {
            string analyticsLink = this.Request.RawUrl + "/Registered";
            Page.ClientScript.RegisterHiddenField("analyticsTrackPageviewLink", analyticsLink);
        }
    </code>
    
    Integration examples:
    
    <code>
        $(document).ready(function() {
            // alwasy init first!
            $.analyticsInit({ accountId: 'UA-XXXXXXX-X' });
            
            // this tracks external links
            $('a[href^="http"]').analyticsTrackPageview();
            // another approach to track external links
            $('a[rel*="external"]').analyticsTrackPageview();
            // the most reliable method is as follows
            $("a[href^='http:'], a[rel='external']").not("[href*='" + window.location.hostname + "']").analyticsTrackPageview();
            
            // track postback event
            $('a[href^="javascript:__"]').analyticsTrackEvent();
        });
    </code> 
*/

(function($){
    // intializes the tracker
    $.analyticsInit = function(options) {
        // load the google analytics script
        var _gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); 
        var _url = _gaJsHost + "google-analytics.com/ga.js";
        var opt = $.extend({			
			    accountId: 'UA-1234567-0'
			}, options);
			
		// turn on caching, otherwise google script won't be cached
        $.ajaxSetup({ cache: true }); 
        jQuery.getScript(_url, function() {
            $.pageTracker = _gat._getTracker(opt.accountId);
            $.pageTracker._initData();
            // set user segmentation
            //$.pageTracker._setVar('test1');
            //$.pageTracker._setVar('test2');          
            // determine postback state
            var trackLink = $('#analyticsTrackPageviewLink').attr('value');      
            if(trackLink) {
                $.pageTracker._trackPageview(trackLink);
            }
            else {
                // track default pageview
                $.pageTracker._trackPageview();
            }                  
        });
        $.ajaxSetup({ cache: false });
    }
 

	// adds click tracking to elements
	$.fn.analyticsTrackPageview = function(options) {
				var opt = $.extend({
		        eventName: 'click',			
			    label: function(element) {
			                element = $(element).get(0);
			                if(element.hostname != window.location.hostname) {
			                    return '/outgoing/' + $(element).attr('href');
			                }
			                else {
			                    var tmpHref = $(element).attr('href');
			                    tmpHref = tmpHref.replace(new RegExp('http[s]{0,1}://' + window.location.hostname), '');
			                    return tmpHref;
			                }		                
			           },
			     useLiveEvents: true
			}, options);
						
		function evaluate(element, text_or_function) {
			if(typeof text_or_function == 'function') {
				text_or_function = text_or_function(element);
			}
			return text_or_function;
		};

        if(opt.useLiveEvents) {
		    $(this.selector).live(opt.eventName, function() {
			    var element = $(this);
			    var label = evaluate(element, opt.label);
			    //alert('tracking live: ' + label);
			    try {
			        $.pageTracker._trackPageview(label);
			    } catch(Exception) { }
		    })
    		
		    return $(this);
		}
		else {
		    // add click handler to all matching elements
		    return this.each(function() {
			    var element = $(this);
			    var label = evaluate(element, opt.label);
                element.bind(opt.eventName, function() {
                    //alert('tracking: ' + label);
                    try {
			            $.pageTracker._trackPageview(label);
			        } catch(Exception) { }
                });
		    });
		}
	};


	// adds click tracking to elements
	$.fn.analyticsTrackEvent = function(options) {
		var opt = $.extend({
		    eventName: 'click',
			category: 'default',
			action: 'click',
			label: function(element) { return element.attr('href') },
			value: null }, options);
			
		var postBackRegex = /javascript:__doPostBack\('(.*?)','(.*?)'\)/;
			
		// if second parameter is a string: returns the value of the second
		// parameter. If the second parameter is a function: passes the
		// element to the function and returns function's return value.
		function evaluate(element, text_or_function) {
			if(typeof text_or_function == 'function') {
				text_or_function = text_or_function(element);
			}
			return text_or_function;
		};

		// add click handler to all matching elements
		return this.each(function() {
			var element = $(this);
			// use default options, if necessary
			var category = evaluate(element, opt.category);
			var action = evaluate(element, opt.action);
			var label = evaluate(element, opt.label);
			var value = evaluate(element, opt.value);
			if(postBackRegex.test(label)) {
			    action = postBackRegex.exec(label)[1];
			    value = postBackRegex.exec(label)[2];
			    label = '';			    
			}
					
			var message = "category:'" + category + "' action:'" + action + "' label:'" + label + "' value:'" + value + "'";

		    element.bind(opt.eventName, function() {
                //alert('Tracked ' + message);
                try {
			        $.pageTracker._trackEvent(category, action, label, value);
			    } catch(Exception) { }
			    return true;
            });
		});
	};
})(jQuery);
var MEMO_COOKIE_NAME = 'lb_memoboard';
var SEARCH_COOKIE_KEY = 'lb_search_key';
var SEARCH_ITEMS_PER_PAGE = 6;
var NO_SEARCH_CRITERIA_SELECTED = 'Bitte wählen Sie mindestens ein Suchkriterium aus.';
var OFFERING_COUNT_REGEX = new RegExp('\([0-9]+\)');
var TIME_REGEX = new RegExp('[0-2][0-9]\:[0-5][0-9]\:[0-5][0-9]');
var TINY_SEARCH_URL_SELECTORS = ["[id$='_listBoxWhat']", "[id$='_listBoxWho']", "[id$='_listBoxWhere']", "#loe-of-tagsearch", "#altDateField", "[id$='_listBoxSimpleDifficulty']", "[id$='_listBoxClimbingDifficulty']"];

var offeringResults;
var offeringResultsHash;
var offeringResultsTotal;
var selectedDateWhen = '';
var gisGooglemapInitialized = false;
var offeringSorting = window.configIsWinterTime ? "wa" : "sa";

$(document).ready(function() {
    offeringSorting = window.configIsWinterTime ? "wa" : "sa";
});

// prevent jQuery from adding random stuff to the urls
$(document).ready(function() {
    $.ajaxSetup({ cache: true });
});


// external window
$(document).ready(function() {
    $("a[href^='http:'], a[rel='external']").live('click', function(e) {
        $(this).not("[href*='" + window.location.hostname + "']").attr('target', '_blank');
    });
});


// ga tracking
$(document).ready(function() {
    $.analyticsInit({ accountId: 'UA-8171201-1' });
    // this tracks external links
    $("a[href^='http:'], a[rel='external'],a.loe-of-detail-link").analyticsTrackPageview();
    $('a.ico-pdf, a.ico-print, a.ico-email, a.loe-of-addmemo').analyticsTrackPageview();
});


// replacing transparent png-image, when we detect IE6
$(document).ready(function() {
    if ($.shitbrowser) {
        $('#loe-of-find').attr('src', ($('#loe-of-find').attr('src') || "").replace(/.png/, '-ie.gif'));
    }
});

//Tipps tracking
$(document).ready(function() {
    var PageClick = function(pageclickednumber) {
        $("#commentpager")
            .pager({ pageNumber: pageclickednumber,
                pageCount: $("#loe-tipps-pagercontainer").attr("rel") % 5,
                buttonClickCallback: PageClick
            });
        $(".loe-com-tipps").hide();
        $(".loe-com-page" + pageclickednumber).show();
    }
    $(".loe-com-page1").show();

    $("#commentpager")
        .pager({ pageNumber: 1,
            pageCount: $("#loe-tipps-pagercontainer").attr("rel") % 5,
            buttonClickCallback: PageClick
        });

    $(".loe-tipps-fullcomment").live('click', function(e) {
        e.preventDefault();
        $(".loe-tipps-intro" + $(this).attr("rel")).hide();
        $(".loe-tipps-fulltext" + $(this).attr("rel")).show();
    });

    $(".loe-tipps-introcomment").live('click', function(e) {
        e.preventDefault();
        $(".loe-tipps-intro" + $(this).attr("rel")).show();
        $(".loe-tipps-fulltext" + $(this).attr("rel")).hide();
    });
});

//IE6 margin wettbewerb korrektur
$(document).ready(function() {
    $("#loe-contest-termslink").live('click', function(e) {
        $("#loe-Contest-Terms").each(function() {
            $(this).css("display", "inline");
        });
    });
});

// extend the dropdowns
$(document).ready(function() {
    $('.dms-hidden-original').not('.nosync').dropMultiselect();

    // *** (un)comment the following lines to enable/disable the WHEN-dropdown (datepicker) and the difficulty-dropdowns

    // setting WHEN-dropdown visible if we're on the searchoveviewpage
    if ($('#loe-of-resultheader').length > 0) {
        //$('#selectorWhen').slideDown(200);	//uncomment to enable when drop down		
        $('#hiddenDifficulty').show();
        $('#selectorSimpleDifficulty').css('width', '234px');
        $('#selectorSimpleDifficulty').css('clear', 'left');
        $('#selectorSimpleDifficulty').css('visibility', 'visible');
        $('#selectorClimbingDifficulty').css('width', '234px');
        $('#selectorClimbingDifficulty').css('clear', 'left');
        $('#selectorClimbingDifficulty').css('visibility', 'visible');
    }

    // setting the width for the WHEN-textfield, which depends on the width of WHAT-dropdown
    $('#textfieldWhen').width(($("[id$='_listBoxWhat']").width() - 6));
    $('#selectorWhen').width($("[id$='_listBoxWhat']").width());

    // adding datepicker to the WHEN-textfield (width of the datepicker depends on the width of the WHEN-textfield)
    //	$('#textfieldWhen').datepicker( {           //uncomment to enable when drop dow & delete display:none in offeringFinder.aspx & write visibility : hidden
    //		nextText: '', 
    //		prevText: '', 
    //		dateFormat: 'DD, dd. MM yy', 
    //		minDate: new Date(), 
    //		maxDate: '+1y',
    //		showAnim: 'slideDown',
    //		altField: '#altDateField',
    //		width: $('#textfieldWhen').width()
    //	}, $.datepicker.setDefaults($.datepicker.regional['de']));		

    // initializing the DIFFICULTY-dropdowns (with the width of the WHO-dropdown)		
    $("[id$='_listBoxSimpleDifficulty']").dropMultiselect({ width: ($("[id$='_listBoxWho']").width() - 4) }).each(function() {
        if (!this.initialHideSimpleDifficulty) {
            $(this).parents("li").hide();
        }
        this.initialHideSimpleDifficulty = 1;
    });
    $("[id$='_listBoxSimpleDifficulty']").each(function() { this.sync() });

    $("[id$='_listBoxClimbingDifficulty']").dropMultiselect({ width: $("[id$='_listBoxWho']").width() - 4 }).each(function() {
        if (!this.initialHideClimbingDifficulty) {
            $(this).parents("li").hide();
        }
        this.initialHideClimbingDifficulty = 1;
    });
    $("[id$='_listBoxClimbingDifficulty']").each(function() { this.sync() });
});


// simple slideshow
$(document).ready(function() {
    var imgPreloader = $("<img/>").load(function() {
        $('#loe-of-gallery-img').fadeOut(200, function() {
            $(this).attr('title', $(imgPreloader).attr('title'));
            $(this).attr('src', $(imgPreloader).attr('src')).fadeIn(200);
        });
    });

    $('.loe-of-gallery-thumb').live('click', function(e) {
        e.preventDefault();
        // reset highlighted item
        $('li', $(this).parent().parent()).removeClass('active');
        $(this).parent().addClass('active');
        // set new image url
        var imgUrl = $('img', this).attr('src');
        var imgTitle = $('img', this).attr('title');
        imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('width=') - 1);
        if ($(imgPreloader).attr('src') != imgUrl) {
            $(imgPreloader).attr('src', imgUrl);
            $(imgPreloader).attr('title', imgTitle);
        }
    });
});


// collapsible panels
$(document).ready(function() {
    $('.comments h2, .loe-of-colpanel, .morepartner h2').live('click', function() {
        var headline = $(this).html();
        if (headline.indexOf('+') > 0) {
            $(this).html(headline.replace('(+)', '(-)'));
        }
        else {
            $(this).html(headline.replace('(-)', '(+)'));
        }

        $(this).next().slideToggle(300);
    });
});


//All Events
$(document).ready(function() {
    $(".news .allEvents").live('click', function() {
        $("[id$='loe_of_reset']").click();
        if (window.configIsWinterTime) {
            $("[id$='_listBoxWhat'] option").each(function() {
                if ($(this).attr('value') == "/Angebots-Finder/WAS/Winter/Veranstaltungen") {
                    $(this).attr('selected', true);
                }
            });
        }
        else {
            $("[id$='_listBoxWhat'] option").each(function() {
                if ($(this).attr('value') == "/Angebots-Finder/WAS/Sommer/Veranstaltungen") {
                    $(this).attr('selected', true);
                }
            });
        }
        $('#loe-of-find').click();
    });
});


// icon handlers
$(document).ready(function() {
    $('.ico-pdf').live('click', function(e) {
        e.preventDefault();

        var self = $(this);
        // mediaplex tracking
        var mpt = new Date();
        var timeStamp = mpt.getTime();
        //webtrekk tracking
        if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('pdfIco', 'link');
        $('body').append('<img id="mp-AD-' + timeStamp + '" src="http://altfarm.mediaplex.com/ad/bk/12612-77826-3840-0?Landingpage_AusfluegeDrucken=1&mpuid=' + timeStamp + '-' + mpt.getTimezoneOffset() + '" border="0">');

        $("#mp-AD-" + timeStamp).load(function() {
            var pdfLink = '/Loetschberger/ExportToPdf.aspx?url=' + encodeURIComponent(self.attr('href').replace('?pdf', ''));
            window.location.href = pdfLink;
        });
        
        return false;
    });

    $('.ico-print').live('click', function(e) {
        e.preventDefault();
        //webtrekk tracking
        if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('printIco', 'link');
        // mediaplex tracking
        var mpt = new Date();
        //$('body').append("<img src=\"http://altfarm.mediaplex.com/ad/bk/12612-77826-3840-0?Landingpage_AusfluegeDrucken=1&mpuid=" + mpt.getTime() + "-" + mpt.getTimezoneOffset() + "\" border=\"0\">");
        $('body').append("<img src=\"http://altfarm.mediaplex.com/ad/bk/12612-77826-3840-0?Lead_AusfluegeDrucken=1&amp;mpuid=" + mpt.getTime() + "-" + mpt.getTimezoneOffset() + "\" height=\"1\" width=\"1\" alt=\"Mediaplex_tag\" border=\"0\">");

        window.print();
        return false;
    });

    $('.ico-email').live('click', function(e) {
        e.preventDefault();

        var self = $(this);
        //webtrekk tracking
        if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('mailIco', 'link');
        // mediaplex tracking
        var mpt = new Date();
        var timeStamp = mpt.getTime();
        //$('body').append('<img id="mp-' + timeStamp + '" src="http://altfarm.mediaplex.com/ad/bk/12612-77826-3840-0?Landingpage_AusfluegeDrucken=1&mpuid=' + timeStamp + '-' + mpt.getTimezoneOffset() + '" border="0">');
        $('body').append('<img id="mp-LW-' + timeStamp + '" src="http://altfarm.mediaplex.com/ad/bk/12612-77826-3840-0?Lead_Weiterempfehlen=1&amp;mpuid=' + timeStamp + '-' + mpt.getTimezoneOffset() + '" height="1" width="1" alt="Mediaplex_tag" border="0">');

        $('#mp-LW-' + timeStamp).load(function() {
            window.location.href = '/Weiterempfehlen.aspx?nodeid=' + self.attr('nodeID');
        });
        return false;
    });

    $('.ico-comment').live('click', function(e) {
        e.preventDefault();
        //webtrekk tracking
        if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('commentIco', 'link');
        window.location.href = '/TippAbgeben.aspx?nodeid=' + $(this).attr('nodeID');
        return false;
    });
});

$(document).ready(function() {
    $("#loe-offering-gmapshowhide").live("click", function(e) {
        e.preventDefault();
        if ($(this).html() == "(-) Lageplan") {
            $("#loe-offering-mapcontainer").hide();
            $(this).empty();
            $(this).append("(+) Lageplan");
        }
        else {
            $("#loe-offering-mapcontainer").show();
            $(this).empty();
            $(this).append("(-) Lageplan");
        }
    });
});

// subnavi handlers
$(document).ready(function() {
    $('.loe-nav-sub-dd').change(function() {
        var docLink = $('option:selected', this).val();
        if ((docLink == '') || (docLink == '-')) {
            return;
        }

        document.location.href = docLink;
    });

    $('.info-service').click(function() {
        window.location.href = $('a', this).attr('href');
    });
});


$(document).ready(function() {
    $('.loe-cam-location').change(function() {
        window.location.href = $(".loe-cam-location OPTION:selected").val();
    });
});


$(document).ready(function() {
    $('a#allEvents').attr('href', '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/2048@0@0@@@1@1/list/' + offeringSorting + '/1');
});


// google map
$(document).ready(function() {
    // disable google map for the moment
    // return;

    // check, if map container is available
    if ($('#loe-gmap-hold').length == 0) {
        return;
    }

    $('#loe-item-impression').hide();
    $('#loe-item-google-map').click(function() {
        $('#loe-gmap-hold').css("left", "0px");
        $('#loe-item-google-map').hide();
        $('#loe-item-impression').show();
        if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('googleMapItem', 'link');
    });

    $('#loe-item-impression').click(function() {
        $('#loe-gmap-hold').css("left", "-2000px");
        $('#loe-item-google-map').show();
        $('#loe-item-impression').hide();
        if (typeof (wt_sendinfo) != "undefined") wt_sendinfo('impressionItem', 'link');
    });

    $('#loe-item-google-map').click(function() {
        if (gisGooglemapInitialized) { return; }
        gisGooglemapInitialized = true;

        function layoutMapControls(instance) {
            // add map controls 
            instance.lmc = new GLargeMapControl();
            instance.addControl(instance.lmc, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(30, 7)));
            instance.addControl(new GMapTypeControl());

            var defaultIcon = new GIcon(G_DEFAULT_ICON);

            var markerIcons = [];
            markerIcons['default'] = new GIcon(G_DEFAULT_ICON);
            markerIcons['house'] = new GIcon(defaultIcon, 'house.png');
            markerIcons['castle'] = new GIcon(defaultIcon, 'castle.png');
            markerIcons['webcam'] = [];
            markerIcons['webcam']['default'] = new GIcon();
            markerIcons['webcam']['default'].image = "/App_Themes/Loetschberger/images/icon_webcams.png";
            markerIcons['webcam']['default'].iconSize = new GSize(23, 26);
            markerIcons['webcam']['default'].iconAnchor = new GPoint(11, 26);
            markerIcons['webcam']['default'].infoWindowAnchor = new GPoint(11, 26);
            markerIcons['webcam']['cluster'] = markerIcons['webcam']['default'];

            var layers_morebutton = [
                { name: " Webcams", iconUrl: null, obj: new o8.Gis.MapLayer('webcams', markerIcons['webcam']) }
            ];

            // add map layer control
            instance.addControl(new o8.Gis.LayerControl(layers_morebutton));

            var sidebar_layers = [];
            var layerDefs = o8.Gis.fetchDataFromServiceSync('GetLayers', '{}');
            if (layerDefs) {
                for (var i = 0; i < layerDefs.length; i++) {
                    var layerId = layerDefs[i].LayerId;
                    var layerName = layerDefs[i].Name;
                    var layerIconUrl = layerDefs[i].IconUrl;

                    var layerMarkerIcons = [];
                    layerMarkerIcons['default'] = new GIcon();
                    layerMarkerIcons['default'].image = '/App_Themes/Loetschberger/images/icon_aktivitaeten.png';
                    layerMarkerIcons['default'].iconSize = new GSize(23, 26);
                    layerMarkerIcons['default'].iconAnchor = new GPoint(11, 26);
                    layerMarkerIcons['default'].infoWindowAnchor = new GPoint(11, 26);
                    layerMarkerIcons['cluster'] = layerMarkerIcons['default'];

                    sidebar_layers.push({ name: layerName, iconUrl: layerIconUrl, obj: new o8.Gis.MapLayer(layerId, layerMarkerIcons) });
                }
            }

            // add map layer control
            instance.addControl(new o8.Gis.SidebarControl(instance, sidebar_layers));

            $(".gis-sidebar-ctl-tgl-btn").click();
        }

        function markerInfoHtmlContentProvider(markerId, markerType, properties) {
            var tmpString = '<div id="loe-gmap-testinfo" style="width:200px;">';
            tmpString += '<h3 style="font-size:12px;color:#788c0b;margin:0 0 8px 0;padding:0;"><a href="' + properties.Url + '">' + properties.Title + '</a></h3>';
            if (properties.CategoryIcons) {
                for (var i = 0; i < properties.CategoryIcons.length; i++) {
                    tmpString += '<img src="' + properties.CategoryIcons[i] + '" alt="" style="float:left;margin:0 4px 4px 0;" name=GoogleMap_"' + properties.Title + '" />';
                }
                tmpString += '<br style="clear:both;" />';
            }
            tmpString += '<img src="' + properties.Image + '" alt="" style="height:89px;" /><br />';
            if (properties.Text != '') {
                tmpString += properties.Text + '<br />';
            }
            if (properties.CamLocation) {
                tmpString += 'Standort: ' + properties.CamLocation + '<br />';
            }
            if (properties.CamAltitude) {
                tmpString += 'Höhe: ' + properties.CamAltitude + '<br />';
            }
            tmpString += '</div>';
            return tmpString;
        }

        // instantiate and initialize the google map
        var gisMap = new o8.Gis.Map(layoutMapControls, markerInfoHtmlContentProvider);
        gisMap.initialize('loe-gmap-hold', { 'Lat': 46.70633, 'Lon': 7.53043 }, 9);
        gisMap.setBounds({ 'Lat': 46.05989, 'Lon': 6.35696 }, { 'Lat': 47.7730, 'Lon': 8.70391 });
        gisMap.setAllowedZoomLevels(8, 18);

        // ensure that the allocated memory will be freed
        $(window).unload(function() { GUnload(); });

        $(".gis-layer-checkbox-0").click().each(function() {
            this.mapUpdateLayer();
        });
    });
});


// issuu embedding
$(document).ready(function() {
    if ($('#issuu-container').length == 0) {
        return;
    }

    var hostAndProto = document.location.protocol + '//' + document.location.host;
    var fileUrl = 'http://static.issuu.com/webembed/viewers/style1/v1/IssuuViewer.swf';
    var swfId = 'issuu-container';
    var flashvars = {};
    flashvars.mode = 'embed';
    //flashvars.layout = 'http://skin.issuu.com/v/light/layout.xml';
    flashvars.layout = hostAndProto + '/App_Themes/Loetschberger/swf/issuu/layout.xml';
    flashvars.documentId = '100415152713-a539de8c89974e65828af96d7266c7ce';
    flashvars.docName = 'travelguide2010';
    flashvars.username = 'loetschberger-TravelGuide';
    flashvars.loadingInfoText = 'Travel Guide 2010';

    var params = {};
    params.allowfullscreen = 'true';
    params.wmode = 'transparent';
    params.menu = 'false';

    var attributes = {};
    attributes.id = swfId;
    attributes.name = swfId;

    swfobject.embedSWF(fileUrl, swfId, 965, 340, '9.0', false, flashvars, params, attributes);
});


// sidebar controls
//
// weather
$(document).ready(function() {

    $('.loe-weather-location').ready(function() {
        var locationId = $(".loe-weather-location OPTION:selected").val();
        $.ajax({
            type: "POST",
            url: "/Loetschberger/WeatherService.asmx/GetCurrentWeather",
            data: "{ locationId:'" + locationId + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: parseCurrentWeatherResponse
        });
    });


    $('.loe-weather-location').change(function() {
        var locationId = $("OPTION:selected", this).val();
        $.ajax({
            type: 'POST',
            url: '/Loetschberger/WeatherService.asmx/GetCurrentWeather',
            data: "{ locationId:'" + locationId + "' }",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: parseCurrentWeatherResponse
        });
    });
});


// random offering
$(document).ready(function() {
    function getRandomFeaturedOffering() {
        if ($('#loe-of-featured').length == 0) {
            return;
        }

        $.ajax({
            type: "POST",
            url: "/Loetschberger/OfferingService.asmx/GetRandomOfferings",
            data: "{ count:'1'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                if (msg == null) {
                    $('#loe-of-featured').hide();
                    return;
                }

                $('#loe-of-featured').show();
                $('.selected-event-hold').fadeOut(500, function() {
                    msg[0].Image = msg[0].Image.replace('width=67', 'width=132');
                    // adding offerings to the jsrepeater template and make it visible
                    $('#loe-of-featured').fillTemplate(msg);
                    $('#loe-of-featured img').each(function() {
                        $(this).attr('src', $(this).attr('rel'));
                    });
                    $('.selected-event-hold').fadeIn(500);
                });
            }
        });
    }

    getRandomFeaturedOffering();
    // we use a timer to change the random offerings periodically
    var timer = window.setInterval(getRandomFeaturedOffering, 10000);
});


// location mouseover weather div
$(document).ready(function() {
    var pos = $("#page-holder").position();
    $(".loe-divweather").hide();
    $(".loe-divweather").mouseover(function(e) {
        e.stopPropagation();
    });
    $(".loe-divweather").mouseout(function(e) {
        e.stopPropagation();
    });
    $("#content .location-hold .loe-location-listalllocation li").hover(function() {
        $(".loe-divweather").show();
        $(".loe-divweather").css("top", $(this).position().top - pos.top);
        $(".loe-divweather").css("margin-left", $(this).position().left - 10);
        var locationId = $(this).attr("locationid");

        $.ajax({
            type: 'POST',
            url: '/Loetschberger/WeatherService.asmx/GetCurrentWeather',
            data: "{ locationId:'" + locationId + "' }",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(msg) {
                if (msg == null) {
                    $('#loe-divweather-temp').html("-.-");
                    $('#loe-divweather-icon').attr('src', '/App_Themes/Loetschberger/images/symbols_crop/null.png');
                }
                else {
                    $('#loe-divweather-temp').html(msg.Temperature);
                    if (msg.WeatherSymbol.length > 0) {
                        $('#loe-divweather-icon').attr('src', '/App_Themes/Loetschberger/images/symbols_crop/' + msg.WeatherSymbol + '.png');
                    }
                    else {
                        $('#loe-divweather-icon').attr('src', '/App_Themes/Loetschberger/images/symbols_crop/null.png');
                    }
                }
            }
        });
    }, function(e) {
        e.stopPropagation();
        $(".loe-divweather").hide();
    })
	.children().mouseout(function(e) {
	    e.stopPropagation();
	});
});


// offering finder
$(document).ready(function() {
    // restore previous search criteria
    var encodedCriteria = $.cookie(SEARCH_COOKIE_KEY) == null ? null : unescape($.cookie(SEARCH_COOKIE_KEY));
    if ($('#loe-of-resultheader').length > 0) {
        var pathParts = $.history.pathNames();
        encodedCriteria = pathParts[1];
    }

    if (encodedCriteria) {
        restoreCurrentSearchCriteria(encodedCriteria);
    }

    $('.loe-of-taglink').live('click', function() {
        var encodedCriteria = '0@0@0@' + $(this).text();

        if ($('#loe-of-resultheader').length == 0) {
            var targetUrl = '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1';
            window.location.href = targetUrl;
            return false;
        }
        else {
            // we're on the search results page, init search via indirect call
            $.history.value('s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1');
            return false;
        }
    });

    $("[id$='_listBoxWhat'],[id$='_listBoxWho'],[id$='_listBoxWhere']").change(function() {
        var encodedCriteria = getTinySearchUrl();
        // writing values to search-cookie		
        $.cookie(SEARCH_COOKIE_KEY, escape(encodedCriteria), { expires: 3, path: '/' });

        var searchCriteria = getCriteriaFromTinyUrl(encodedCriteria);
        updateMatchingOfferingCounts(searchCriteria[0], searchCriteria[1], searchCriteria[2], true);
    });
    //IE Enter handler bug fix
    $('#loe-of-tagsearch').keypress(function(e) {
        if (e.keyCode == 13 && $("div.ui-autocomplete-results").css("display") != 'block' && $.cookie(SEARCH_COOKIE_KEY) != null) {
            $('#loe-of-find').click();
            e.stopPropagation();
        }
    });
    // click-handler for find-button
    $('#loe-of-find').click(function() {
        //closing all dropdowns
        closeAllDms();

        var tempTagSearch = $("#loe-of-tagsearch").val();
        tempTagSearch = tempTagSearch.replace('oe', 'ö');
        tempTagSearch = tempTagSearch.replace('ae', 'ä');
        tempTagSearch = tempTagSearch.replace('ue', 'ü');
        $("#loe-of-tagsearch").val(tempTagSearch);
        
        if ($('#textfieldWhen').val() == '') {
            $('#altDateField').val('');
        }

        var encodedCriteria = getTinySearchUrl();
        if (isEncodedCriteriaEmpty(encodedCriteria)) {
            alert(NO_SEARCH_CRITERIA_SELECTED);
            return false;
        }

        // writing values to search-cookie		
        $.cookie(SEARCH_COOKIE_KEY, escape(encodedCriteria), { expires: 3, path: '/' });

        // only redirecting if we are not already on searchoverview page
        if ($('#loe-of-resultheader').length == 0) {
            var targetUrl = '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1';
            window.location.href = targetUrl;
            return false;
        }
        else {
            // we're on the search results page, init search via indirect call
            $.history.value('/s-' + new Date().getTime() + '/' + getTinySearchUrl() + '/list/' + offeringSorting + '/1');
            return false;
        }
    });

    // show detail functionality
    $('.loe-of-detail-link').live('click', function(e) {
        e.preventDefault();

        var nodeId = parseInt($(this).attr('rel'));
        var offeringName = $(this).attr('title') || $(this).attr('alt');
        var pathParts = $.history.pathNames();
        $.history.load('/' + pathParts[0] + '/' + pathParts[1] + '/id/' + nodeId);

        // update viewcount
        $.ajax({
            type: "POST",
            url: "/Loetschberger/OfferingService.asmx/UpdateOfferingViewCount",
            data: "{ nodeID:'" + nodeId + "', offeringName:'" + offeringName + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    });

    // sorting functionality by views
    $('#loe-of-viewsort').live('click', function(e) {
        e.preventDefault();

        var pathParts = $.history.pathNames();
        $.history.value('/' + pathParts[0] + '/' + pathParts[1] + '/list/v/1');
    });

    // sorting functionality by activity
    $('#loe-of-activitysort').live('click', function(e) {
        e.preventDefault();

        var pathParts = $.history.pathNames();
        $.history.value('/' + pathParts[0] + '/' + pathParts[1] + '/list/sa/1');
    });

    // sorting functionality by activity winter
    $('#loe-of-winteractivitysort').live('click', function(e) {
        e.preventDefault();

        var pathParts = $.history.pathNames();
        $.history.value('/' + pathParts[0] + '/' + pathParts[1] + '/list/wa/1');
    });

    // sorting functionality by date
    $('#loe-of-actualitysort').live('click', function(e) {
        e.preventDefault();

        var pathParts = $.history.pathNames();
        $.history.value('/' + pathParts[0] + '/' + pathParts[1] + '/list/d/1');
    });

    // tag search auto complete
    $('#loe-of-tagsearch').autocomplete({ source: function(term) {
        var querys = "{query:'" + term + "'}";
        var response;
        $.ajax({
            async: false,
            type: "POST",
            url: '/Loetschberger/OfferingService.asmx/GetSuggestedTags',
            data: querys,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                response = data;
            }
        });
        return response;
    },
        parse: function(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: row[0]
                    };
                }
            }
            return parsed;
        }
    });

    // click handler for 'reset search criteria'
    $("[id$='loe_of_reset']").click(function() {

        // resetting the dropdowns
        $("[id*='_listBoxWh'] > option").removeAttr('selected');

        // resetting tagSearch and datepicker
        $('#loe-of-tagsearch').val('');
        $('input#textfieldWhen').val('');
        $('#altDateField').val('');

        updateMatchingOfferingCounts([], [], [], true);

        // writing values to search-cookie
        var encodedCriteria = getTinySearchUrl();
        $.cookie(SEARCH_COOKIE_KEY, escape(encodedCriteria), { expires: 3, path: '/' });
        return false;
    });
});

//SBB - CFF functionality
$(document).ready(function() {
    var time = new Date();
    var yy = time.getFullYear();
    var mm = time.getMonth() + 1; mm = (mm < 10) ? '0' + mm : mm;
    var dd = time.getDate(); dd = (dd < 10) ? '0' + dd : dd;
    var travelDate = dd + '.' + mm + '.' + yy;
    $('input[name="REQ0JourneyDate"]').val(travelDate);
    $('.loe-of-detail-link').live('click', function(e) {
        $.ajax({
            type: "POST",
            url: "/Loetschberger/OfferingService.asmx/GetOfferingStopInfo",
            data: "{ nodeID:'" + $(this).attr('rel') + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('input[name="REQ0JourneyStopsZG"]').val(msg);
            }
        });
    });
});

$(document).ready(function() {
    // what single box search (on home)
    $('#loe-of-find-singlebox-what').live('click', function() {
        var encodedCriteria = getTinySearchUrl(["[id$='_singleListBoxWhat']"]);
        encodedCriteria += '@0@0@';
        if (isEncodedCriteriaEmpty(encodedCriteria)) {
            alert(NO_SEARCH_CRITERIA_SELECTED);
            return false;
        }

        var targetUrl = '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1';
        window.location.href = targetUrl;
        return false;
    });

    // who single box search (on home)
    $('#loe-of-find-singlebox-who').live('click', function() {
        var encodedCriteria = getTinySearchUrl(["[id$='_singleListBoxWho']"]);
        encodedCriteria = '0@' + encodedCriteria + '@0@';
        if (isEncodedCriteriaEmpty(encodedCriteria)) {
            alert(NO_SEARCH_CRITERIA_SELECTED);
            return false;
        }

        var targetUrl = '/Suchuebersicht.aspx#/s-' + new Date().getTime() + '/' + encodedCriteria + '/list/' + offeringSorting + '/1';
        window.location.href = targetUrl;
        return false;
    });
});


// memo functionality
$(document).ready(function() {
    function getMemos(offeringNodeID, remove) {
        var valueString = $.cookie(MEMO_COOKIE_NAME) ? $.cookie(MEMO_COOKIE_NAME) : '-1';
        var values = valueString.split(',');

        if (remove) {
            values = $.grep(values, function(val) { return val != offeringNodeID.toString(); });
        }
        else {
            if (!values.contains(offeringNodeID)) {
                values.push(offeringNodeID.toString());
            }
        }

        valueString = values.join(',');

        // (re)writing values to cookie	
        $.cookie(MEMO_COOKIE_NAME, valueString, { expires: 3, path: '/' });

        // invoking scriptService to recieve information about the offerings on memoboard
        $.ajax({
            type: "POST",
            async: false,
            url: "/loetschberger/OfferingService.asmx/GetMemos",
            data: "{ cookieValue:'" + valueString + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                if (msg.length > 0) {
                    // displaying memo intro message
                    $('#loe-memo-introtext').hide();

                    // adding offerings to memoboard
                    $('#loe-memo-template').fillTemplate(msg);
                    $('#loe-memo-list').show();
                    $('.loe-memo-memopagelink').show();
                }
                else {
                    $('#loe-memo-introtext').show();
                    $('#loe-memo-list').hide();
                    $('.loe-memo-memopagelink').hide();
                }

                // setting number of offerings on memoboard		
                $('#loe-memo-count').text('(' + msg.length + ')');
            }
        });
    }

    // always get the memos by default
    getMemos(-1);

    $('#loe-gmap-testinfo').live('click', function(event) {
        var $target = $(event.target);
        if ($target.is('a.loe-of-addmemo')) {
            //alert( 'W00t!' );
            //return false;
        }
    });

    // adds a memo to the memo list
    $('a.loe-of-addmemo').live('click', function(e) {
        e.preventDefault();
        
        var mpt = new Date();
        var timeStamp = mpt.getTime();
        $('body').append('<img id="mp-LM-' + timeStamp + '" src="http://altfarm.mediaplex.com/ad/bk/12612-77826-3840-0?Lead_Merkzettel=1&amp;mpuid=' + timeStamp + '-' + mpt.getTimezoneOffset() + '" height="1" width="1" alt="Mediaplex_tag" border="0">');

        var offeringNodeID = $(this).attr('rel');
        if (offeringNodeID) {
            getMemos(offeringNodeID, false);
        }
    });

    // removes a memo from the list
    $('a.loe-of-removememo').live('click', function(e) {
        e.preventDefault();

        var offeringNodeID = $(this).attr('rel');
        if (offeringNodeID) {
            getMemos(offeringNodeID, true);
        }
    });

    // shows a memo
    $('a.loe-of-showmemo').live('click', function(e) {
        e.preventDefault();

        var offLiveUrl = $(this).attr('href');
        var locationId = $(this).attr("locationID");

        $(".conbookmark li.active").removeClass("active");
        $(this).closest("li").addClass("active");

        $.ajaxSetup({ cache: true });
        $('#content').load(offLiveUrl + ' #content .place', null, function() {
            // set pdf download link correctly
            $('a.ico-pdf').attr('href', offLiveUrl + '?pdf');
            $('a.ico-print').attr('href', offLiveUrl + '?print');

            //Weather update Function Call
            $.ajax({
                type: "POST",
                url: "/Loetschberger/WeatherService.asmx/GetCurrentWeather",
                data: "{ locationId:'" + locationId + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    parseCurrentWeatherResponse(msg);
                    $('.weather').show();
                }
            });
        });

        return false;
    });

    // open the first memo, preventdefault is necessary because ie will
    // navigate to offering instead
    $('a.loe-of-showmemo :first').click(function(e) { e.preventDefault(); });
    $('a.loe-of-showmemo :first').trigger('click');
});


//news Control
$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "/Loetschberger/OfferingService.asmx/GetLatestEvents",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $(".loe-offering-template").fillTemplate(msg);
        }
    });
});

function loeWebTrekk() {

    webtrekk = new Object();

    webtrekk.trackDomain = "loetschberger01.webtrekk.net"; // track url
    webtrekk.trackId = "117817120242968"; // webtrekk id(s)
    webtrekk.domain = "www.loetschberger.com"; // list or regexp of your domains
    webtrekk.contentId = $("head > title:first").text(); // content id
    webtrekk.sendinfo = "1"; // optional: starts wt_sendinfo() automatically

    ////// OPTIONAL
    //// content group(s)
    webtrekk.contentGroup = new Array();
    webtrekk.contentGroup[1] = $("#webtrekkContentGrp1").attr("name");
    webtrekk.contentGroup[2] = $("#webtrekkContentGrp2").attr("name");
    webtrekk.contentGroup[3] = $("#webtrekkContentGrp3").attr("name");

    //// click tracking										
    webtrekk.linkTrack = "link"; // click tracking: (standard|link)
    webtrekk.linkTrackAttribute = "";   // optional: for "standard" only
    webtrekk.linkTrackParams = "name"; // optional: for "link" only

    webtrekk.heatmap = "";

    //// form tracking
    webtrekk.form = ""; // activate form tracking
    webtrekk.formAnonymous = ""; // anonymous data

    //// products
    webtrekk.product = ""; // products
    webtrekk.productCategory = new Array();

    //// order
    webtrekk.orderValue = ""; // order value

    //// campaigns
    webtrekk.mediaCode = ""; // mediacode
    webtrekk.linkPosition = ""; // link position (wt_lp in url)
    webtrekk.keyword = ""; // keyword (wt_kw in url)

    //// custom page parameter
    webtrekk.customParameter = new Array(); // custom parameter page context

    //// custom click parameter
    webtrekk.customClickParameter = new Array(); // custom parameter click context

    //// custom session parameter
    webtrekk.customSessionParameter = new Array(); // custom parameter session context

    //// custom time parameter
    webtrekk.customTimeParameter = new Array(); // custom parameter time context

    //// custom campaign parameter
    webtrekk.customCampaignParameter = new Array();

    //// custom e-commerce parameter
    webtrekk.customEcommerceParameter = new Array(); // custom Parameter e-commerce context

    //// customer id
    webtrekk.customerId = "";

    //// internal search
    var pathParts = $.history.pathNames();
    if ((pathParts != null) && (pathParts.length != 0)) {
        var searchCriteria = getCriteriaFromTinyUrl(pathParts[1]);
        webtrekk.internalSearch = "What : " + searchCriteria[0] + "//Who : " + searchCriteria[1] + "//Where : " + searchCriteria[2] + "//Text : " + searchCriteria[3] + "//When : " + searchCriteria[4];
    }
    else {
        webtrekk.internalSearch = "";
    }

    // turn on caching, otherwise google script won't be cached
    $.ajaxSetup({ cache: true });
    $.getScript("http://www.loetschberger.ch/Loetschberger/js/webtrekk.js");
    $.ajaxSetup({ cache: false });
}


//weather Module update Function
function parseCurrentWeatherResponse(msg) {
    if (msg) {
        $('.loe-weather-temp').html(msg.Temperature);
        $('.loe-weather-forecast').attr('href', msg.CityPath);
        // setting image link
        $('#loe-weather-image-link').attr('href', msg.CityPath);
        // setting image attributes
        $('#loe-weather-image').attr('alt', msg.City);
        $('#loe-weather-image').attr('title', msg.City);
        if (msg.WebCams) {
            if (msg.WebCams[0] == undefined) {
                $('#loe-weather-image').attr('src', '/App_Themes/Loetschberger/images/nocam.jpg');
            }
            else {
                $('#loe-weather-image').attr('src', '/Loetschberger/WebCamProxy.aspx?camUrl=' + encodeURIComponent(msg.WebCams[0]) + '&height=70&width=132');
            }
        }
        $('#loe-weather-icon').attr('src', '/App_Themes/Loetschberger/images/symbols_crop/' + msg.WeatherSymbol + '.png');
        $('#loe-weather-webCam-date').html(msg.ServerDate);
        if (msg.WeatherDate != null) {
            $('#loe-weather-date').html(msg.WeatherDate.substring(8, 10) + ':' + msg.WeatherDate.substring(10, 12));
        }
    }
}


Array.prototype.contains = function(element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
};


function updateMatchingOfferingCounts(whatPaths, whoPaths, wherePaths, updateOfferingCount) {
    $.ajax({
        type: "POST",
        url: "/Loetschberger/OfferingService.asmx/GetInvalidItemsAndOfferingCount",
        data: "{ csvSelectedAliasPathsWhat:'" + whatPaths.join(',') + "', csvSelectedAliasPathsWho:'" + whoPaths.join(',') + "', csvSelectedAliasPathsWhere:'" + wherePaths.join(',') + "', selectedDateWhen:'" + selectedDateWhen + "'  }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {

            // getting number of offerings
            offeringResultsTotal = msg.OfferingCount;
            if (updateOfferingCount) {
                // update page offering counter				
                $("[id$='_lblOfferingCounter']").text(offeringResultsTotal + (offeringResultsTotal > 1 ? ' Ausflüge' : ' Ausflug'));
            }

            // setting new header image		
            if ($('img#loe-visual-impression').attr('src') != msg.HeaderImage) {
                $('<img/>').attr('src', msg.HeaderImage).load(function() {
                    $('img#loe-visual-impression').stop().fadeTo(200, 0, function() {
                        $('img#loe-visual-impression').attr('src', msg.HeaderImage);
                    }).fadeTo(200, 1);
                });
            }

            // build a map containing all criteria alias paths and count		
            var aliasPathOfferingCountHashMap = [];
            for (var i = 0; i < msg.CategoryList.length; i++) {
                aliasPathOfferingCountHashMap[msg.CategoryList[i].AliasPath] = msg.CategoryList[i].OfferingCount;
            }

            var dropDownSelectors = ['_listBoxWhat', '_listBoxWho', '_singleListBoxWhat', '_singleListBoxWho'];
            for (var i = 0; i < dropDownSelectors.length; i++) {
                $("[id$='" + dropDownSelectors[i] + "'] > option").not('.heading').each(function() {
                    if (aliasPathOfferingCountHashMap[$(this).val()]) {
                        // removing 'disabled' attribute from 'option' tag
                        $(this).removeAttr('disabled');

                        // updating offeringCount for current element									
                        updateItemOfferingCounter($(this), aliasPathOfferingCountHashMap[$(this).val()]);
                    }
                    else {
                        // no offerings for current category: adding 'disabled' attribute to option tag and setting offeringCount to zero
                        $(this).attr('disabled', 'disabled');
                        updateItemOfferingCounter($(this), 0);
                    }
                });
            }

            $("[id$='_listBoxWhere'] > option").not('.group').each(function(index) {
                if (aliasPathOfferingCountHashMap[$(this).val()]) {
                    // removing 'disabled' attribute from 'option' tag
                    if (this.partner) {
                        this.partner.enable();
                    }

                    // updating offeringCount for current element				
                    updateItemOfferingCounter($(this), aliasPathOfferingCountHashMap[$(this).val()]);
                }
                else {

                    // no offerings for current category: adding 'disabled' attribute to option tag and setting offeringCount to zero					
                    if (this.partner) {
                        this.partner.disable();
                    }
                    updateItemOfferingCounter($(this), 0);
                }
            });

            // sync extended drop downs
            $('.dms-hidden-original').not('.nosync').each(function() { this.sync() });

            // checking if difficulty-selector dropdown should be visible	
            //if($('#selectorWhen:visible').length > 0)
            if ($('#hiddenDifficulty').css("display") != 'none') {
                switch (whatPaths.toString()) {
                    case '/Angebots-Finder/WAS/Sommer/Wandern':
                        $('#selectorClimbingDifficulty').hide();
                        $('#selectorSimpleDifficulty').slideDown(500);
                        break;

                    case '/Angebots-Finder/WAS/Sommer/Mountainbike-und-Fahrrad':
                        $('#selectorClimbingDifficulty').hide();
                        $('#selectorSimpleDifficulty').slideDown(500);
                        break;

                    case '/Angebots-Finder/WAS/Sommer/Verschiedenes':
                        $('#selectorClimbingDifficulty').hide();
                        $('#selectorSimpleDifficulty').slideDown(500);
                        break;

                    case '/Angebots-Finder/WAS/Sommer/Klettern':
                        $('#selectorSimpleDifficulty').hide();
                        $('#selectorClimbingDifficulty').slideDown(500);
                        break;

                    default:
                        $('#selectorSimpleDifficulty').slideUp(500);
                        $('#selectorClimbingDifficulty').slideUp(500);
                }
            }

        }
    });
}


function updateItemOfferingCounter(itemElement, numOfItems) {
    if (itemElement.html().match(OFFERING_COUNT_REGEX)) {
        var matching = OFFERING_COUNT_REGEX.exec(itemElement.html());
        var newText = itemElement.html().substring(0, (matching.index - 1)) + '(' + numOfItems + ')';
        itemElement.html(newText);
    }
    // we don't need the 'else'-clause because we're adding the itemCount to the
    // offerings initially in 'BindDropdown'-method (c# codebehind), so we can be
    // sure that every offering already comes with an itemCount addition						
}


function filterOfferingsByDifficulty(offeringList) {
    offeringResults = [];
    if ($('#selectorSimpleDifficulty:visible').length > 0) {
        var difficultyLevel = $("[id$='_listBoxSimpleDifficulty'] > option:selected").val();
        if (difficultyLevel == 'choose') {
            offeringResults = offeringList;
        }
        else {
            for (var i = 0; i < offeringList.length; i++) {
                if (offeringList[i].Difficulty == difficultyLevel) {
                    offeringResults.push(offeringList[i]);
                }
            }
        }
    }
    else {
        if ($('#selectorClimbingDifficulty:visible').length > 0) {
            var difficultyLevel = $("[id$='_listBoxClimbingDifficulty'] > option:selected").val();
            if (difficultyLevel == 'choose') {
                offeringResults = offeringList;
            }
            else {
                for (var i = 0; i < offeringList.length; i++) {
                    if (offeringList[i].Difficulty == difficultyLevel) {
                        offeringResults.push(offeringList[i]);
                    }
                }
            }
        }
        else {
            offeringResults = offeringList;
        }
    }
    return offeringResults;
}


// don't initialize jquery address in document.ready as it's too late for ff 3!!!
$(document).ready(function() {
    $.history.init(function(hash) {

        var pathParts = $.history.pathNames();
        loeWebTrekk();
        if ((pathParts == null) || (pathParts.length == 0)) {
            return;
        }

        if (pathParts[0].indexOf('s-') == 0) {
            var encodedCriteria = pathParts[1];
            prepareOfferingListView(encodedCriteria);

            if (pathParts[2] === 'id') {
                // detail view
                var nodeId = pathParts[3];
                prepareOfferingDetailView(nodeId);
            }
            else if (pathParts[2] === 'list') {
                // result list view
                var sortMethod = pathParts[3];
                var listPage = parseInt(pathParts[4]);
                // clone the array
                var sortedOfferings = offeringResults.slice();

                // un-highlight the sorting term
                $('#loe-of-activitysort').removeClass('active');
                $('#loe-of-winteractivitysort').removeClass('active');
                $('#loe-of-viewsort').removeClass('active');
                $('#loe-of-actualitysort').removeClass('active');

                if (sortMethod === 'd') {
                    // highlight the sorting term
                    $('#loe-of-actualitysort').addClass('active');
                    // sorting offeringList by creation date (newest first)
                    sortedOfferings.sort(function(a, b) {
                        var timeA = new Date(parseInt(a.Created.substr(6, 13)));
                        var timeB = new Date(parseInt(b.Created.substr(6, 13)));
                        return timeB - timeA;
                    });
                }
                else if (sortMethod === 'v') {
                    // highlight the sorting term
                    $('#loe-of-viewsort').addClass('active');
                    // sorting offeringList by number of views, descending
                    sortedOfferings.sort(function(a, b) { return b.Views - a.Views; });
                }
                else if (sortMethod === 'wa') {
                    // highlight the sorting term
                    $('#loe-of-winteractivitysort').addClass('active');
                    // sorting offeringList alphabetically by offeringName
                    sortedOfferings.sort(function(a, b) {
                        if (a.IsWinterOffering === b.IsWinterOffering) {
                            return (a.Name >= b.Name ? 1 : -1);
                        }
                        else {
                            return a.IsWinterOffering ? -1 : 1;
                        }
                    });
                }
                else if (sortMethod === 'sa') {
                    // highlight the sorting term
                    $('#loe-of-activitysort').addClass('active');
                    // sorting offeringList alphabetically by offeringName
                    sortedOfferings.sort(function(a, b) {
                        if (a.IsWinterOffering === b.IsWinterOffering) {
                            return (a.Name >= b.Name ? 1 : -1);
                        }
                        else {
                            return a.IsWinterOffering ? 1 : -1;
                        }
                    });
                }
                else {
                    // highlight the sorting term
                    $('#loe-of-activitysort').addClass('active');
                    // sorting offeringList alphabetically by offeringName
                    sortedOfferings.sort(function(a, b) { return (a.Name >= b.Name ? 1 : -1); });
                }

                // init pager with the sorted results
                initSearchResultPager(sortedOfferings, listPage, SEARCH_ITEMS_PER_PAGE);
            }
            else {
                alert('cannot handle');
            }
        }
    });
});



function restoreCurrentSearchCriteria(encodedCriteria) {
    // check, if we have a finder
    if ($('#finder').length == 0) {
        return;
    }

    // retrieve the current search filter items
    var searchCriteria = getCriteriaFromTinyUrl(encodedCriteria);
    // restore selected items in the dropdowns
    var allAliasPaths = searchCriteria[0];
    allAliasPaths = allAliasPaths.concat(searchCriteria[1]);
    allAliasPaths = allAliasPaths.concat(searchCriteria[2]);

    // update dropdowns with the preselected values
    $("[id*='_listBoxWh'] > option").removeAttr('selected');
    for (var i = 0; i < allAliasPaths.length; i++) {
        $("[id*='_listBoxWh'] > option:[value='" + allAliasPaths[i] + "']").attr('selected', 'selected');
    }

    // update tagsearch
    if (searchCriteria.length > 3) {
        var tempTagSearch = searchCriteria[3];
        tempTagSearch = tempTagSearch.replace('oe', 'ö');
        tempTagSearch = tempTagSearch.replace('ae', 'ä');
        tempTagSearch = tempTagSearch.replace('ue', 'ü');
        $("#loe-of-tagsearch").val(tempTagSearch);
        searchCriteria[3] = tempTagSearch;
    }

    // update datepicker
    $('#textfieldWhen').val(getFriendlyDateFromTimestamp(searchCriteria[4]));

    // restore the matching offering count
    updateMatchingOfferingCounts(searchCriteria[0], searchCriteria[1], searchCriteria[2], true);
}


function prepareOfferingListView(encodedCriteria) {
    //reload offerings, if required
    if (offeringResultsHash == encodedCriteria) {
        return;
    }

    var searchCriteria = getCriteriaFromTinyUrl(encodedCriteria);
    var tagSearchText = '';
    if (searchCriteria.length > 3) {
        var tempTagSearch = searchCriteria[3];
        tempTagSearch = tempTagSearch.replace('oe', 'ö');
        tempTagSearch = tempTagSearch.replace('ae', 'ä');
        tempTagSearch = tempTagSearch.replace('ue', 'ü');
        searchCriteria[3] = tempTagSearch;
        tagSearchText = searchCriteria[3];
    }
    // ensure the correct preselected search criteria
    restoreCurrentSearchCriteria(encodedCriteria);
    // retrieve the matching offerings
    offeringResults = getMatchingOfferings(searchCriteria[0], searchCriteria[1], searchCriteria[2], tagSearchText, searchCriteria[4]);
    offeringResultsHash = encodedCriteria;

    var offeringResultsTotal = offeringResults.length;
    if (offeringResultsTotal == 0) {
        // get random offerings instead
        offeringResults = getRandomOfferings(SEARCH_ITEMS_PER_PAGE);
        offeringResultsTotal = offeringResults.length;

        // fill and show result header
        var currentSearchCriteriaString = getCurrentSearchCriteriaString();
        $('#loe-of-resultheader').fillTemplate({
            selectedItems: currentSearchCriteriaString.replace(/,/g, ', '),
            offeringsTotal: offeringResultsTotal
        });
        // adding 'nothing found' message AR: move to the template			 		      
        $('div.tools').append('<br /><div id="loe-of-nothing-found"><p>Zu Ihren Wünschen können wir Ihnen leider keinen Ausflug vorschlagen. Unten stehend finden Sie mögliche Alternativen.<br />Oder starten Sie eine neue Abfrage mit einem anderen Stichwort.</p><br /></div>');
        $('#loe-of-nothing-found').show();
        $('#loe-of-resultheader').show();

        // setting difficulty message (if one of the DIFFICULTY-dropdowns is visible and a difficulty-level
        // is selected
        if ($('li#selectorSimpleDifficulty:visible').length > 0 &&
		    $("[id$='_listBoxSimpleDifficulty']").attr("selectedIndex") > 0) {
            $('#loe-filter-difficulty-overviewpage').text($("[id$='_listBoxSimpleDifficulty'] > option:selected").text());
            $('#loe-filter-difficulty-message-overviewpage').show();
        }
        if ($('li#selectorClimbingDifficulty:visible').length > 0 &&
		    $("[id$='_listBoxClimbingDifficulty']").attr("selectedIndex") > 0) {
            $('#loe-filter-difficulty-overviewpage').text($("[id$='_listBoxClimbingDifficulty'] > option:selected").text());
            $('#loe-filter-difficulty-message-overviewpage').show();
        }
    }
    else {
        // fill and show result header
        var currentSearchCriteriaString = getCurrentSearchCriteriaString();
        $('#loe-of-resultheader').fillTemplate({
            selectedItems: currentSearchCriteriaString.replace(/,/g, ', '),
            offeringsTotal: offeringResultsTotal
        });
        $('#loe-of-nothing-found').hide();
        $('#loe-of-resultheader').show();

        //alert('datestring: ' +$('#textfieldWhen').val());
        // setting filter date message if filterDate string is valid
        $.ajax({
            type: "POST",
            url: "/Loetschberger/OfferingService.asmx/IsSelectedDateValid",
            data: "{ selectedDate:'" + $('#altDateField').val() + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                if (msg) {
                    $('#loe-filter-date-overviewpage').text($('#textfieldWhen').val());
                    $('#loe-filter-date-message-overviewpage').show();
                    $('#loe-filter-date-message-overviewpage').css('display', 'block');
                }
            }
        });

        // setting difficulty message (if one of the DIFFICULTY-dropdowns is visible and a difficulty-level
        // is selected
        if ($('li#selectorSimpleDifficulty:visible').length > 0 &&
		    $("[id$='_listBoxSimpleDifficulty']").attr("selectedIndex") > 0) {
            $('#loe-filter-difficulty-overviewpage').text($("[id$='_listBoxSimpleDifficulty'] > option:selected").text());
            $('#loe-filter-difficulty-message-overviewpage').show();
        }
        if ($('li#selectorClimbingDifficulty:visible').length > 0 &&
		    $("[id$='_listBoxClimbingDifficulty']").attr("selectedIndex") > 0) {
            $('#loe-filter-difficulty-overviewpage').text($("[id$='_listBoxClimbingDifficulty'] > option:selected").text());
            $('#loe-filter-difficulty-message-overviewpage').show();
        }
    }

    // setting number of offerings											
    $("[id$='_lblOfferingCounter']").text(offeringResultsTotal + (offeringResultsTotal == 1 ? ' Ausflug' : ' Ausflüge'));
}


function getMatchingOfferings(whatPaths, whoPaths, wherePaths, tagSearchText, selectedDateWhen) {
    var matchingOfferings = [];

    $.ajax({
        type: "POST",
        async: false,
        url: "/Loetschberger/OfferingService.asmx/GetOfferings",
        data: "{ aliasPathsWhat:'" + whatPaths.join(',') + "', aliasPathsWho:'" + whoPaths.join(',') + "', aliasPathsWhere:'" + wherePaths.join(',') + "', tagSearchText:'" + tagSearchText + "', selectedDateWhen:'" + selectedDateWhen + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // filtering offerings depending on selected value of difficulty dropdown
            // this method sets the global offeringResults variable
            matchingOfferings = filterOfferingsByDifficulty(msg);
            //matchingOfferings = msg;
        }
    });

    return matchingOfferings;
}


function getRandomOfferings(offeringCount) {
    var randomOfferings = [];

    // no offerings found, we get some random ones
    $.ajax({
        type: "POST",
        async: false,
        url: "/Loetschberger/OfferingService.asmx/GetRandomOfferings",
        data: "{ count:'" + offeringCount + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            randomOfferings = msg;
        }
    });

    return randomOfferings;
}


function initSearchResultPager(searchResults, pageNumber, itemsPerPage) {
    // calculating number of searchresult pages	
    var pageCount = (searchResults.length + itemsPerPage - 1) / itemsPerPage;

    // always reinit search result pager, the pager doesn't maintain state
    $("#pager").pager({ pageNumber: pageNumber,
        pageCount: pageCount,
        buttonClickCallback: function(pageNumber) {
            var pathParts = $.history.pathNames();
            $.history.value('/' + pathParts[0] + '/' + pathParts[1] + '/' + pathParts[2] + '/' + pathParts[3] + '/' + pageNumber);
            //initSearchResultPager(searchResults, pageNumber, itemsPerPage); 
        } 
    });

    // switch display results			
    var startIndex = (pageNumber - 1) * itemsPerPage;
    var endIndex = Math.min(startIndex + itemsPerPage, searchResults.length);
    var offeringListSubset = [];
    for (var i = startIndex; i < endIndex; i++) {
        offeringListSubset.push(searchResults[i]);
    }

    // adding offerings to the jsrepeater template
    $('#loe-of-list').fillTemplate(offeringListSubset);

    // trimming the image titles (used for the tooltips)
    $('div.loe-of-item > span > img').each(function() {
        $(this).attr('title', $.trim($(this).attr('title')))
    });
    $('a.loe-of-detail-link > img.bord').each(function() {
        $(this).attr('title', $.trim($(this).attr('title')))
    });

    // updating indices in the result-header
    $('#startIndex').html(startIndex + 1);
    $('#endIndex').html(endIndex);

    $('#loe-of-detail').hide();
    $('#loe-of-resultheader').show();
    $('#loe-of-list').show();
}

function prepareOfferingDetailView(nodeId) {
    var liveUrl = null;
    var locationID = null;
    var locationPicture = null;

    // search corresponding offering
    for (var i = 0; i < offeringResults.length; i++) {
        if (offeringResults[i].LinkedNodeID == nodeId) {
            liveUrl = offeringResults[i].LiveURL;
            locationID = offeringResults[i].LocationID;
            locationPicture = offeringResults[i].LocationPicture;
        }
    }

    $.ajaxSetup({ cache: true });
    // prevent jquery from adding alert random number at the end of the url
    $('#loe-of-detail').load(liveUrl + ' #content', null, function() {
        // setting tipps visible
        $(".loe-com-page1").show();

        // adding 'Sie haben gesucht nach: ...' text
        var currentSearchCriteriaString = getCurrentSearchCriteriaString();
        $('label#loe-search-items-detailpage').text(currentSearchCriteriaString.replace(/,/g, ', '));

        // setting filter date message if filterDate string is valid
        $.ajax({
            type: "POST",
            url: "/Loetschberger/OfferingService.asmx/IsSelectedDateValid",
            data: "{ selectedDate:'" + $('#textfieldWhen').val() + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                if (msg) {
                    $('#loe-filter-date-detailpage').text($('#textfieldWhen').val());
                    $('#loe-filter-date-message-detailpage').show();
                    $('#loe-filter-date-message-detailpage').css('display', 'block');
                }
            }
        });

        // adding difficulty message (if one of the DIFFICULTY-dropdowns is visible and a difficulty-level
        // is selected
        if ($('li#selectorSimpleDifficulty:visible').length > 0 &&
			$("[id$='_listBoxSimpleDifficulty']").attr("selectedIndex") > 0) {
            $('#loe-filter-difficulty-detailpage').text($("[id$='_listBoxSimpleDifficulty'] > option:selected").text());
            $('#loe-filter-difficulty-message-detailpage').show();
        }
        if ($('li#selectorClimbingDifficulty:visible').length > 0 &&
			$("[id$='_listBoxClimbingDifficulty']").attr("selectedIndex") > 0) {
            $('#loe-filter-difficulty-detailpage').text($("[id$='_listBoxClimbingDifficulty'] > option:selected").text());
            $('#loe-filter-difficulty-message-detailpage').show();
        }

        // adding back icon (we only need the icon, if we are coming from the searchoverview page, so this is the place to add it)
        $('div.remember > ul').each(function() { $(this).prepend('<li><a class="ico-back" title="Zurück zu den Suchresultaten" onclick="javascript:history.back();">back</a></li>') });

        // show detail panel
        $('#loe-of-detail').show();
        $('#loe-of-resultheader').hide();
        $('#loe-of-list').hide();
    });


    // getting and setting header image (depending on the location of the offering)				
    if ($('img#loe-visual-impression').attr('src') != locationPicture) {
        $('<img/>').attr('src', locationPicture).load(function() {
            $('img#loe-visual-impression').stop().fadeTo(200, 0, function() {
                $('img#loe-visual-impression').attr('src', locationPicture);
            }).fadeTo(200, 1);
        });
    }

    $('.loe-weather-location').val(locationID);
    $('.loe-weather-location').each(function() { this.sync() });
    $('.loe-weather-location').trigger('change');
}


function getCurrentSearchCriteriaString() {
    var searchCriteriaStrings = [];

    var dropDownSelectors = ['_listBoxWhat', '_listBoxWho', '_listBoxWhere'];
    for (var i = 0; i < dropDownSelectors.length; i++) {
        $("[id$='" + dropDownSelectors[i] + "'] > option:selected").each(function() {
            var searchCriteriaString = $(this).html();
            if (searchCriteriaString.match(OFFERING_COUNT_REGEX)) {
                // removing the offeringCount from the string
                var matching = OFFERING_COUNT_REGEX.exec(searchCriteriaString);
                var newText = searchCriteriaString.substring(0, (matching.index - 2));
                searchCriteriaString = newText;
            }
            searchCriteriaStrings.push(searchCriteriaString);
        });
    }

    if ($.trim($("#loe-of-tagsearch").val()).length > 0) {
        searchCriteriaStrings.push($.trim($("#loe-of-tagsearch").val()));
    }

    return searchCriteriaStrings.join(',');
}

function getTinySearchUrl(elementSelectors) {
    function getSelectedIndices(dropDownSelector) {
        var indices = [];
        var i = 0;
        $(dropDownSelector + ' > option').each(function() {
            if ($(this).attr('selected')) {
                indices.push(i);
            }
            i++;
        });

        return indices;
    }

    // set default dd selectors
    if (elementSelectors == null) {
        elementSelectors = TINY_SEARCH_URL_SELECTORS;
    }

    var pathParts = [];
    for (var i = 0; i < elementSelectors.length; i++) {
        var currentSelector = elementSelectors[i];
        if ($(currentSelector + ' > option').length > 0) {
            // it's a dropdown
            var indices = getSelectedIndices(currentSelector);
            var binSumGrps = [0];
            for (var j = 0; j < indices.length; j++) {
                var currGrp = Math.floor(indices[j] / 32);
                for (var k = 0; k <= currGrp; k++) {
                    if (!binSumGrps[k]) {
                        binSumGrps[k] = 0;
                    }

                    binSumGrps[k] += (k == currGrp ? Math.pow(2, indices[j] % 32) : 0);
                }
            }

            pathParts.push(binSumGrps.join('.'));
        }
        else {
            // it's another element (tagsearch or datepicker)
            var value = $.trim($(currentSelector).val());
            pathParts.push(value);
        }
    }

    return pathParts.join('@');
}

function getCriteriaFromTinyUrl(tinyUrl) {
    var filterCriteria = [];
    var elementSelectors = TINY_SEARCH_URL_SELECTORS;
    var pathParts = tinyUrl.split('@');
    for (var i = 0; i < elementSelectors.length; i++) {
        var currentSelector = elementSelectors[i];
        var pathPart = pathParts[i];

        if ($(currentSelector + ' > option').length > 0) {
            var indices = [];

            if (pathPart) {
                var binSumGrps = pathPart.split('.');
                for (var j = 0; j < binSumGrps.length; j++) {
                    for (var k = 31; k >= 0; k--) {
                        var tmp = Math.pow(2, k);
                        if (tmp <= binSumGrps[j]) {
                            indices.push((j * 32) + k);
                            binSumGrps[j] -= tmp;
                        }
                    }
                }
            }

            var aliasPaths = [];
            var k = 0;
            $(currentSelector + ' > option').each(function() {
                if (indices.contains(k)) {
                    aliasPaths.push($(this).val());
                }
                k++;
            });

            filterCriteria.push(aliasPaths);
        }
        else {
            filterCriteria.push(pathPart);
        }
    }

    return filterCriteria;
}


function isEncodedCriteriaEmpty(encodedCriteria) {
    return ($.trim(encodedCriteria) == '0@0@0@@');
}


function getFriendlyDateFromTimestamp(timestamp) {
    try {
        var dateTimeString = $.datepicker.parseDate($.datepicker.TIMESTAMP, timestamp).toLocaleString();
        // removing the time-part 
        if (dateTimeString.match(TIME_REGEX)) {
            var matching = TIME_REGEX.exec(dateTimeString);
            var dateString = $.trim(dateTimeString.substring(0, (matching.index)));
        }
        return dateString
    }
    catch (Exception) { }
    return '';
}


// fixup form1, the use of jquery address prevents postbacks!!
$(document).ready(function() {
    window.setTimeout(function() { window.theForm = document.forms['form1']; }, 100);
});

//SBB  - CFF Function
function SearchConnection() {
    var url = 'http://fahrplan.sbb.ch/bin/query.exe/dn?externalCall=yes';
    url += '&queryPageDisplayed=yes';
    url += '&REQ0JourneyStopsSA=' + $('select[name="REQ0JourneyStopsSA"]').val();
    url += '&REQ0JourneyStopsSG=' + $('input[name="REQ0JourneyStopsSG"]').val();
    url += '&REQ0JourneyStopsSID=' + $('input[name="REQ0JourneyStopsSID"]').val();
    url += '&REQ0JourneyStopsZA=' + $('select[name="REQ0JourneyStopsZA"]').val();
    url += '&REQ0JourneyStopsZG=' + $('input[name="REQ0JourneyStopsZG"]').val();
    url += '&REQ0JourneyStopsZID=' + $('input[name="REQ0JourneyStopsZID"]').val();
    url += '&REQ0JourneyDate=' + $('input[name="REQ0JourneyDate"]').val();
    url += '&REQ0JourneyTime=' + $('input[name="REQ0JourneyTime"]').val();

    url += '&REQ0HafasSearchForw=' + $('input[name="REQ0HafasSearchForw"]:checked').val();
    url += '&start=Suchen'
    var w = window.open(url, 'sbb');
    w.focus();
}
/* generated: 9/7/2010 6:40:49 PM */
