/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/*
 * Wicket Ajax Support 
 *
 * @author Igor Vaynberg
 * @author Matej Knopp 
 */

if (Function.prototype.bind == null) {
	Function.prototype.bind = function(object) {
		var __method = this;
		return function() {
			return __method.apply(object, arguments);
		}
	}
}

// Wicket Namespace

if (typeof(Wicket) == "undefined")
	Wicket = { };



/**
 * Browser types
 */
if (typeof(Wicket.Browser) == "undefined") {
	Wicket.Browser = { 
		isKHTML: function() {
			return /Konqueror|KHTML/.test(navigator.userAgent) && !/Apple/.test(navigator.userAgent);
		},
		
		isSafari: function() {
			return /KHTML/.test(navigator.userAgent) && /Apple/.test(navigator.userAgent);
		},
		
		isOpera: function() {
			return !Wicket.Browser.isSafari() && typeof(window.opera) != "undefined";
		},
	
		isIE: function() {
			return !Wicket.Browser.isSafari() && typeof(document.all) != "undefined" && typeof(window.opera) == "undefined";
		},
		
		isIEQuirks: function() {
			// is the browser internet explorer in quirks mode (we could use document.compatMode too)		
			return Wicket.Browser.isIE() && document.documentElement.clientHeight == 0;
		},		
		
		isIELessThan7: function() {
			var index = navigator.userAgent.indexOf("MSIE");
			var version = parseFloat(navigator.userAgent.substring(index + 5));
			return Wicket.Browser.isIE() && version < 7;
		},
		
		isIE7: function() {
			var index = navigator.userAgent.indexOf("MSIE");
			var version = parseFloat(navigator.userAgent.substring(index + 5));
			return Wicket.Browser.isIE() && version >= 7;
		},
		
		isGecko: function() {
			return /Gecko/.test(navigator.userAgent) && !Wicket.Browser.isSafari();
		}
	};
}




/**
 * Events related code
 * Based on code from Mootools (http://mootools.net)
 */

if (typeof(Wicket.Event) == "undefined") {
	Wicket.Event = {
		idCounter: 0,
		
		getId: function(element) {
			var current = element.getAttribute("id");
			if (typeof(current) == "string" && current.length > 0) {
				return current;
			} else {
				current = "wicket-generated-id-" + Wicket.Event.idCounter++;
				element.setAttribute("id", current);
				return current;
			}
		},
		
		handler: function() {
			var id = this[0];
			var original = this[1];
			var element = Wicket.$(id);
			original.bind(element)();
		},
	
		fire: function(element, event) {
			if (document.createEvent) {
				var e=document.createEvent("Event");
				e.initEvent(event, true, true);
				return element.dispatchEvent(e);
			} else {
				return element.fireEvent("on"+event);
			}
		},
		
		// adds an event of specified type to the element
		// also supports the domready event on window
		// domready is event fired when the DOM is complete, but before loading external resources (images, ...)
		add: function(element, type, fn) {
			// is the event domready?
			if (element == window && type == "domready") {
				Wicket.Event.addDomReadyEvent(fn);
			} else {
				if (element.addEventListener){
					element.addEventListener((type == 'mousewheel' && Wicket.Browser.isGecko()) ? 'DOMMouseScroll' : type, fn, false);
				} else {
					if (element == window || element == document)   {
						fn = fn.bind(element);
					}
					else {
						fn = Wicket.Event.handler.bind([Wicket.Event.getId(element), fn]);					
					}				
					// Because of the fn.bind (returning a new function object)
					// you can't detach the event first to be sure that there are no doubles :(
					//element.detachEvent('on'+type, fn);
					element.attachEvent('on'+type, fn);
				}
			}
			return element;
		},
		
		// handlers that will be fired on dom ready event
		domReadyHandlers : new Array(),
		
		// fires the dom ready event and cleanup the handlers
		fireDomReadyHandlers : function() {
			var h = Wicket.Event.domReadyHandlers;
			while (h.length > 0) {
				var c = h.shift();
				c();
			}
			Wicket.Event.domReadyHandlers = null;
		},
		
		// adds the dom ready event 
		addDomReadyEvent : function(fn) {
			// is the window already loaded?
			if (window.loaded)  {
				fn();
			} else if (!window.events || !window.events.domready) {
				// register the handler
				Wicket.Event.domReadyHandlers.push(fn);
			
				// callback
				var domReady = function() {
					if (window.loaded) 
						return;
					window.loaded = true;
					
					// invoke the handlers
					Wicket.Event.fireDomReadyHandlers();
				}.bind(this);
				
				if (document.readyState && (Wicket.Browser.isKHTML() || Wicket.Browser.isSafari())) { 
				  //safari and konqueror don't support the event - simulate it through a timeout
					var domCheck = function() {
						if (document.readyState == "loaded" ||
						    document.readyState == "complete") {
						    domReady();
						} else {
							// dom not yet ready, set timer to check later
							window.setTimeout(domCheck, 10);
						}
					}
					window.setTimeout(domCheck, 10);
				} else if (document.readyState && Wicket.Browser.isIE()) { 
					if (document.getElementById('ie_ready') == null) {
						// for internet explorer we need to load a "dummy" scrip from ::/ to get the 
						// readystatechangeevernt - that means the main page being loaded and now the browser
						// is loading dependencies
						var src = (window.location.protocol == 'https:') ? '\/\/:' : 'javascript:void(0)';
						document.write('<script id="ie_ready" defer src="' + src + '"><\/script>');
						document.getElementById('ie_ready').onreadystatechange = function() {
							if (this.readyState == 'complete') domReady();
						};
					}
				} else { 
					// other browsers
					Wicket.Event.add(document, "DOMContentLoaded", domReady);
				}
			} else {
				window.addEventListener("domready", fn, false);
			}
		}
	};
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/*
 * Wicket Ajax Support 
 *
 * @author Igor Vaynberg
 * @author Matej Knopp 
 */

if (Function.prototype.bind == null) {
	Function.prototype.bind = function(object) {
		var __method = this;
		return function() {
			return __method.apply(object, arguments);
		}
	}
}

// Wicket Namespace

if (typeof(Wicket) == "undefined")
	Wicket = { };


Wicket.$ = function(arg) {
	if (arg == null || typeof(arg) == "undefined") {
		return null;
	}
	if (arguments.length > 1) {
		var e=[];
		for (var i=0; i<arguments.length; i++) {
			e.push(Wicket.$(arguments[i]));
		}
		return e;
	} else if (typeof arg == 'string') {
		return document.getElementById(arg);
	} else {
		return arg;
	}
}

// returns if the element belongs to current document
// if the argument is not element, function returns true
Wicket.$$ = function(element) {	
	if (typeof(element) == "string") {		
		element = Wicket.$(element);
	}	
	if (element == null || typeof(element) == "undefined" ||
	    element.tagName == null || typeof(element.tagName) == "undefined") {
	    return true;
	}
	
	var id = element.getAttribute('id');
	if (typeof(id) == "undefined" || id == null || id == "")
		return element.ownerDocument == document;
	else
		return document.getElementById(id) == element;
}

Wicket.isPortlet = function() {
	return Wicket.portlet == true;
}

Wicket.emptyFunction = function() { };

Wicket.Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}

/**
 * Add a check for old Safari. It should not be our responsibility to check the 
 * browser's version, but it's a minor version that makes a difference here,
 * so we try to be at least user friendly.  
 */
if (typeof DOMParser == "undefined" && Wicket.Browser.isSafari()) {
   DOMParser = function () {}

   DOMParser.prototype.parseFromString = function (str, contentType) {
   		alert('You are using an old version of Safari.\nTo be able to use this page you need at least version 2.0.1.');
   }
}


/**
 * Logging functionality. 
 */

Wicket.Log = { 

	enabled: function() {
		return wicketAjaxDebugEnabled();
	},
	
	info: function(msg) {
	    if (Wicket.Log.enabled())
			WicketAjaxDebug.logInfo(msg);
	},
	
	error: function(msg) {
		if (Wicket.Log.enabled())
			WicketAjaxDebug.logError(msg);
	},  

	log: function(msg) {
		if(Wicket.Log.enabled())
			WicketAjaxDebug.log(msg);
	}
},

/**
 * Functions executer takes array of functions and executes them. Each function gets
 * the notify object, which needs to be called for the next function to be executed.
 * This way the functions can be executed synchronously. Each function has to call
 * the notify object at some point, otherwise the functions after it wont be executed.
 * After the FunctionExecuter is initiatialized, the start methods triggers the
 * first function.
 */
Wicket.FunctionsExecuter = Wicket.Class.create();

Wicket.FunctionsExecuter.prototype = {
	initialize: function(functions) {
		this.functions = functions;
		this.current = 0;
		this.depth = 0; // we need to limit call stack depth
	},
	
	processNext: function() {
		if (this.current < this.functions.length) {
			var f = this.functions[this.current];
			var run = function() {
				f(this.notify.bind(this));
			}.bind(this);
			this.current++;
						
			if (this.depth > 50 || Wicket.Browser.isKHTML() || Wicket.Browser.isSafari()) {
				// to prevent khtml bug that crashes entire browser
				// or to prevent stack overflow (safari has small call stack)
				this.depth = 0;
				window.setTimeout(run, 1);
			} else {
				this.depth ++;
				run();
			}				
		}
	},	
	
	start: function() {
		this.processNext();
	},
	
	notify: function() {
		this.processNext();
	}
}

Wicket.replaceOuterHtmlIE = function(element, text) {						

	// replaces all <iframe references with <__WICKET_JS_REMOVE_X9F4A__iframe text
	var marker = "__WICKET_JS_REMOVE_X9F4A__"; 					
	function markIframe(text) {
		var t = text;
		var r = /<\s*iframe/i;
		while ((m = t.match(r)) != null) {			
			t = Wicket.replaceAll(t, m[0], "<" + marker + m[0].substring(1));            
		}
        return t;
	}
	
	function removeIframeMark(text) {
		return Wicket.replaceAll(text, marker, "");
	}
							
	if (element.tagName == "SCRIPT") {
		// we need to get the javascript content, so we create an invalid DOM structure,
		// (that is necessary for IE to let us see the innerHTML of the script tag	
		var tempDiv = document.createElement("div");
		tempDiv.innerHTML = "<table>" + text + "</table>";		
		var script = tempDiv.childNodes[0].childNodes[0].innerHTML;
		
		element.outerHtml = text;
		try {
			eval(script);
		} catch (e) {
			Wicket.Log.error("Wicket.replaceOuterHtmlIE: " + e + ": eval -> " + script);
		}
		return;
	}  
	
	var parent = element.parentNode;
	var tn = element.tagName;
				
					
	var tempDiv = document.createElement("div");
	var tempParent;
	
	// array for javascripts that were in the text
	var scripts = new Array();				
	
	if (window.parent == window || window.parent == null) {
		document.body.appendChild(tempDiv);
	}
		
	if (tn != 'TBODY' && tn != 'TR' && tn != "TD" && tn != "THEAD" && tn != "TFOOT" && tn != "TH") {
		
		// in case the element is not any of these																									
						
		// this is not exactly nice, but we need to get invalid markup inside innerHTML,
		// because otherwise IE just swallows the <script> tags (sometimes)		
		tempDiv.innerHTML = '<table style="display:none">' + markIframe(text) + '</table>';
						
		// now copy the script tags to array (needed later for script execution)
		var s = tempDiv.getElementsByTagName("script");				
						
		for (var i = 0; i < s.length; ++i) {			
			scripts.push(s[i]);
		}						
						
		// now use regular div so that we won't mess the DOM
		tempDiv.innerHTML = '<div style="display:none">' + text + '</div>'; 

		// set the outer <div> as parent
		tempParent = tempDiv.childNodes[0];
		
		tempParent.parentNode.removeChild(tempParent);								
						
	} else {
	
		// same trick as with before, this time we need a div to to create invalid markup
		// (otherwise we wouldn't be able to get the script tags)
		tempDiv.innerHTML = '<div style="display:none">' + markIframe(text) + '</div>';
	
		// now copy the script tags to array (needed later for script execution)
		var s = tempDiv.getElementsByTagName("script");
						
		for (var i = 0; i < s.length; ++i) {
			scripts.push(s[i]);
		}		
		
		// hack to get around the fact that IE doesn't allow to replace table elements
		tempDiv.innerHTML = '<table style="display: none">' + text + '</table>';
		
		// get the parent element of new elements
		tempParent = tempDiv.getElementsByTagName(tn).item(0).parentNode;					
	}	

	// place all newly created elements before the old element	
	while(tempParent.childNodes.length > 0) {
		var tempElement = tempParent.childNodes[0];
		parent.insertBefore(tempElement, element);
		tempElement = null;
	}

    // remove the original element
	if(element.style.backgroundImage)
		element.style.backgroundImage = "";
	parent.removeChild(element);
	element.outerHTML = "";	
	element = "";
	
	if (window.parent == window || window.parent == null) {
		if(tempDiv.style.backgroundImage)
			tempDiv.style.backgroundImage = "";
		document.body.removeChild(tempDiv);
	}	
	
	tempDiv.outerHTML = "";

	parent = null;
	tempDiv = null;
	tempParent = null;
      		
	for (i = 0; i < scripts.length; ++i) {
		Wicket.Head.addJavascripts(scripts[i], removeIframeMark); 
	}									
}

Wicket.replaceOuterHtmlSafari = function(element, text) {
	// if we are replacing a single <script> element
	if (element.tagName == "SCRIPT") {
		// create temporal div and add script as inner HTML		
		var tempDiv = document.createElement("div");
		tempDiv.innerHTML = text;

		// try to get script content
		var script = tempDiv.childNodes[0].innerHTML;
		if (typeof(script) != "string") {
			script = tempDiv.childNodes[0].text;
		}
		
		element.outerHTML = text;
		try {
			eval(script);
		} catch (e) {
			Wicket.Log.error("Wicket.replaceOuterHtmlSafari: " + e + ": eval -> " + script);
		}
		return;
	}
	var parent = element.parentNode;
	var next = element.nextSibling;
	
	var index = 0;
	while (parent.childNodes[index] != element) {
		++index;
	}
	
	element.outerHTML = text;	
		
	element = parent.childNodes[index];	
	
	// go through newly added elements and try to find javascripts that 
	// need to be executed	
	while (element != next) {
		try {
			Wicket.Head.addJavascripts(element);
		} catch (ignore) {
		}
		element = element.nextSibling;
	}	
}

/**
 * A cross-browser method that replaces the markup of an element. The behavior
 * is similar to calling element.outerHtml=text in internet explorer. However
 * this method also takes care of executing javascripts within the markup on
 * browsers that don't do that automatically.
 * Also this method takes care of replacing table elements (tbody, tr, td, thead)
 * on browser where it's not supported when using outerHTML (IE).
 */
Wicket.replaceOuterHtml = function(element, text) {	

	if (Wicket.Browser.isIE()|| Wicket.Browser.isOpera()) {		
		Wicket.replaceOuterHtmlIE(element, text);				
    } else if (Wicket.Browser.isSafari() ) {
    	Wicket.replaceOuterHtmlSafari(element, text);    	
    } else /* GECKO */ {
    	// create range and fragment
        var range = element.ownerDocument.createRange();
        range.selectNode(element);
		var fragment = range.createContextualFragment(text);
		
        element.parentNode.replaceChild(fragment, element);        
    }		
}	

/**
 * Decoding functionality
 *
 * Wicket sends rendered components and javascript as CDATA section of XML document. When the 
 * component body itself contains a CDATA section, Wicket needs to escape it properly. 
 */
Wicket.decode = function(encoding, text) {
    if (encoding == "wicket1") {
        return Wicket.decode1(text);
    }
}

Wicket.decode1 = function(text) {
    return Wicket.replaceAll(text, "]^", "]");
}

Wicket.replaceAll = function(str, from, to) {
	eval('var regex = /' + from.replace( /\W/g ,'\\$&' ) + '/g ;');
	return str.replace(regex,to);
}

/** shows element */
Wicket.show=function(e) {
    var e=Wicket.$(e);
    if (e!=null) {
	    e.style.display = "";
	}
}
/** hides element */
Wicket.hide=function(e) {
    var e=Wicket.$(e);
    if (e!=null) {
	    e.style.display = "none";
	}
}
/** call-counting implementation of Wicket.show() */
Wicket.showIncrementally=function(e) {
	var e=Wicket.$(e);
	if (e==null) return;
	var count=e.getAttribute("showIncrementallyCount");
	count=parseInt((count==null)?0:count);
	if (count>=0) Wicket.show(e);
	e.setAttribute("showIncrementallyCount", count+1);

}
/** call-counting implementation of Wicket.hide() */
Wicket.hideIncrementally=function(e) {
	var e=Wicket.$(e);
	if (e==null) return;
	var count=e.getAttribute("showIncrementallyCount");
	count=parseInt((count==null)?0:count-1);
	if (count<=0) Wicket.hide(e);
	e.setAttribute("showIncrementallyCount", count);
}


/**
 * Form serialization
 *
 * To post a form using Ajax Wicket first needs to serialize it, which means composing a string
 * from form elments names and values. The string will then be set as body of POST request.
 */

Wicket.Form = { }

Wicket.Form.encode = function(text) {
    if (encodeURIComponent) {
        return encodeURIComponent(text);
    } else {
        return escape(text);
    }
}

Wicket.Form.serializeSelect = function(select){
	// if it is a non-multiple select, iterating on each element is not required (WICKET-389)
	if (select.multiple == false){
		return Wicket.Form.encode(select.name) + "=" + Wicket.Form.encode(select.value) + "&";
	}

    //else
    var result = "";
    for (var i = 0; i < select.options.length; ++i) {
        var option = select.options[i];
        if (option.selected) {
            result += Wicket.Form.encode(select.name) + "=" + Wicket.Form.encode(option.value) + "&";
        }
    }
    return result;
}

// this function intentionally ignores image and submit inputs
Wicket.Form.serializeInput = function(input) {
    var type = input.type.toLowerCase();
    if ((type == "checkbox" || type == "radio") && input.checked) {
        return Wicket.Form.encode(input.name) + "=" + Wicket.Form.encode(input.value) + "&";
    } else if (type == "text" || type == "password" || type == "hidden" || type == "textarea" || type == "search") {
		return Wicket.Form.encode(input.name) + "=" + Wicket.Form.encode(input.value) + "&";
	} else {
		return "";
    }
}

//list of item to exclude from serialization
Wicket.Form.excludeFromAjaxSerialization = {};

// Returns url/post-body fragment representing element (e) 
Wicket.Form.serializeElement = function(e) {

	if (Wicket.Form.excludeFromAjaxSerialization && e.id && Wicket.Form.excludeFromAjaxSerialization[e.id] == "true") {
		return "";
	}

    var tag = e.tagName.toLowerCase();
    if (tag == "select") {
        return Wicket.Form.serializeSelect(e);
    } else if (tag == "input" || tag == "textarea") {
        return Wicket.Form.serializeInput(e);
    } else {
    	return "";
    }
}
   
   
Wicket.Form.doSerialize = function(form) {
    var result = "";
    for (var i = 0; i < form.elements.length; ++i) {
        var e = form.elements[i];
        if (e.name && e.name != "" && !e.disabled) {
            result += Wicket.Form.serializeElement(e);
        }
    }
    return result;
}

Wicket.Form.serialize = function(element, dontTryToFindRootForm) {
	if (element.tagName.toLowerCase() == "form") {		
		return Wicket.Form.doSerialize(element);
	} else {
		// try to find a form in DOM parents
		var elementBck = element;
		
		if (dontTryToFindRootForm != true) {
			do {
				element = element.parentNode;
			} while(element.tagName.toLowerCase() != "form" && element.tagName.toLowerCase() != "body")
		}
		
		if (element.tagName.toLowerCase() == "form"){
			// We found a form : serialize it
			return Wicket.Form.doSerialize(element);
		} else {
			// there is not form in dom hierarchy
			// simulate it  
			var form = document.createElement("form");
			var parent = elementBck.parentNode;

			parent.replaceChild(form, elementBck);
			form.appendChild(elementBck);
			var result = Wicket.Form.doSerialize(form);
			parent.replaceChild(elementBck, form);
			
			return result
		}
	}
}

/**
 * DOM nodes serialization functionality
 *
 * The purpose of these methods is to return a string representation
 * of the DOM tree.
 */
 
Wicket.DOM = { }

// Method for serializing DOM nodes to string
// original taken from Tacos (http://tacoscomponents.jot.com)
Wicket.DOM.serializeNodeChildren = function(node) {
	if (node == null) { 
		return "" 
	}
	var result = "";
	
	for (var i = 0; i < node.childNodes.length; i++) {
		var thisNode = node.childNodes[i];
		switch (thisNode.nodeType) {
			case 1: // ELEMENT_NODE
			case 5: // ENTITY_REFERENCE_NODE
				result += Wicket.DOM.serializeNode(thisNode);
				break;
			case 8: // COMMENT
				result += "<!--" + thisNode.nodeValue + "-->";
				break;
			case 4: // CDATA_SECTION_NODE
				result += "<![CDATA[" + thisNode.nodeValue + "]]>";
				break;				
			case 3: // TEXT_NODE
			case 2: // ATTRIBUTE_NODE
				result += thisNode.nodeValue;
				break;
			default:
				break;
		}
	}
	return result;	
}


Wicket.DOM.serializeNode = function(node){
	if (node == null) { 
		return "" 
	}
	var result = "";
	result += '<' + node.nodeName;
	
	if (node.attributes && node.attributes.length > 0) {
				
		for (var i = 0; i < node.attributes.length; i++) {
			result += " " + node.attributes[i].name 
				+ "=\"" + node.attributes[i].value + "\"";	
		}
	}
	
	result += '>';
	result += Wicket.DOM.serializeNodeChildren(node);
	result += '</' + node.nodeName + '>';
	return result;
}

// Utility function that determines whether given element is part of the current document
Wicket.DOM.containsElement = function(element) {
	var id = element.getAttribute("id");
	if (id != null)
		return Wicket.$(id) != null;
	else
		return false;
}

/**
 * Channel management
 *
 * Wicket Ajax requests are organized in channels. A channel maintain the order of 
 * requests and determines, what should happen when a request is fired while another 
 * one is being processed. The default behavior (stack) puts the all subsequent requests 
 * in a queue, while the drop behavior limits queue size to one, so only the most
 * recent of subsequent requests is executed.
 * The name of channel determines the policy. E.g. channel with name foochannel|s is 
 * a stack channel, while barchannel|d is a drop channel.
 *
 * The Channel class is supposed to be used through the ChannelManager.
 */
Wicket.Channel = Wicket.Class.create();
Wicket.Channel.prototype = {
	initialize: function(name) {
		var res = name.match(/^([^|]+)\|(d|s)$/)
		if (res == null)
			this.type ='s'; // default to stack 
		else
			this.type = res[2];
		this.callbacks = new Array();
		this.busy = false;
	},	
	
	schedule: function(callback) {
		if (this.busy == false) {
			this.busy = true;			
			return callback();
		} else {
			Wicket.Log.info("Channel busy - postponing...");
			if (this.type == 's') // stack 
				this.callbacks.push(callback);
			else /* drop */
				this.callbacks[0] = callback;
			return null;				
		}
	},
	
	done: function() {
		var c = null;
		
		if (this.callbacks.length > 0) {
			c = this.callbacks.shift();
		}
			
		if (c != null && typeof(c) != "undefined") {
			Wicket.Log.info("Calling posponed function...");
			// we can't call the callback from this call-stack
			// therefore we set it on timer event
			window.setTimeout(c, 1);			
		} else {
			this.busy = false;
		}
	}
};

/**
 * Channel manager maintains a map of channels. 
 */
Wicket.ChannelManager = Wicket.Class.create();
Wicket.ChannelManager.prototype = {
	initialize: function() {
		this.channels = new Array();
	},
  
	// Schedules the callback to channel with given name.
	schedule: function(channel, callback) {
		var c = this.channels[channel];
		if (c == null) {
			c = new Wicket.Channel(channel);
			this.channels[channel] = c;
		}
		return c.schedule(callback);
	},
	
	// Tells the ChannelManager that the current callback in channel with given name 
	// has finished processing and another scheduled callback can be executed (if any).
	done: function(channel) {
		var c = this.channels[channel];
		if (c != null)
			c.done();
	}
};

// Default channel manager instance
Wicket.channelManager = new Wicket.ChannelManager();

/**
 * The Ajax class handles low level details of creating and pooling XmlHttpRequest objects,
 * as well as registering and execution of pre-call, post-call and failure handlers.
 */
 Wicket.Ajax = { 
 	// Creates a new instance of a XmlHttpRequest
	createTransport: function() {
	    var transport = null;
	    if (window.ActiveXObject) {
	        transport = new ActiveXObject("Microsoft.XMLHTTP");
	        Wicket.Log.info("Using ActiveX transport");
	    } else if (window.XMLHttpRequest) {
	        transport = new XMLHttpRequest();
	        Wicket.Log.info("Using XMLHttpRequest transport");
	    } 
	    
	    if (transport == null) {
	        Wicket.Log.error("Wicket.Ajax.createTransport: Could not locate ajax transport. Your browser does not support the required XMLHttpRequest object or wicket could not gain access to it.");
	    }    
	    return transport;
	},
	
	transports: [],
	
	// Returns a transport from pool if any of them is not being used, or creates new instance
	getTransport: function() {
		var t = Wicket.Ajax.transports;
		for (var i = 0; i < t.length; ++i) {
			if (t[i].readyState == 0) {
				return t[i];
			}
		}
		t.push(Wicket.Ajax.createTransport());
		return t[t.length-1];		
	},
	
	preCallHandlers: [],
	postCallHandlers: [],	
	failureHandlers: [],
	
	registerPreCallHandler: function(handler) {
		var h = Wicket.Ajax.preCallHandlers;
		h.push(handler);
	},
	
	registerPostCallHandler: function(handler) {
		var h = Wicket.Ajax.postCallHandlers;
		h.push(handler);
	},
	
	registerFailureHandler: function(handler) {
		var h = Wicket.Ajax.failureHandlers;
		h.push(handler);
	},
	
	invokePreCallHandlers: function() {
		var h = Wicket.Ajax.preCallHandlers;
		if (h.length > 0) {
			Wicket.Log.info("Invoking pre-call handler(s)...");
		}
		for (var i = 0; i < h.length; ++i) {
			h[i]();
		}
	},
	
	invokePostCallHandlers: function() {
		var h = Wicket.Ajax.postCallHandlers;
		if (h.length > 0) {
			Wicket.Log.info("Invoking post-call handler(s)...");
		}
		for (var i = 0; i < h.length; ++i) {
			h[i]();
		}
	},

	invokeFailureHandlers: function() {
		var h = Wicket.Ajax.failureHandlers;
		if (h.length > 0) {
			Wicket.Log.info("Invoking failure handler(s)...");
		}
		for (var i = 0; i < h.length; ++i) {
			h[i]();
		}
	}
}

/**
 * The Ajax.Request class encapsulates a XmlHttpRequest. 
 */
Wicket.Ajax.Request = Wicket.Class.create();

Wicket.Ajax.Request.prototype = {
    // Creates a new request object.
	initialize: function(url, loadedCallback, parseResponse, randomURL, failureHandler, channel, successHandler) {
		this.url = url;
		this.loadedCallback = loadedCallback;
		// whether we should give the loadedCallback parsed response (DOM tree) or the raw string
		this.parseResponse = parseResponse != null ? parseResponse : true; 
		this.randomURL = randomURL != null ? randomURL : true;
		this.failureHandler = failureHandler != null ? failureHandler : function() { };
		this.successHandler = successHandler != null ? successHandler : function() { };
		this.async = true;
		this.channel = channel;
		this.precondition = function() { return true; } // allow a condition to block request 

		// when suppressDone is set, the loadedCallback is responsible for calling
		// Ajax.Request.done() to process possibly pendings requests in the channel.
		this.suppressDone = false;
		this.instance = Math.random();
		this.debugContent = true;
	},
	
	done: function() {
		Wicket.channelManager.done(this.channel);
	},
	
	createUrl: function() {
		if (this.randomURL == false)
			return this.url;
		else
			return this.url + (this.url.indexOf("?")>-1 ? "&" : "?") + "random=" + Math.random();
	},
	
	log: function(method, url) {
		var log = Wicket.Log.info;
		log("");
		log("Initiating Ajax "+method+" request on " + url);
	},
	
	failure: function() {
		this.failureHandler();
   		Wicket.Ajax.invokePostCallHandlers();
   		Wicket.Ajax.invokeFailureHandlers();
	},
	
	// Executes a get request
	get: function() {
		if (Wicket.isPortlet()) {
	        // first check if a query string is provided
	        var qs = this.url.indexOf('?');
	        if (qs==-1) {
	            qs = this.url.indexOf('&');
	        }
	        if (qs>-1) {
	            var query = this.url.substring(qs+1);
	            // ensure the query is not empty
	            if (query && query.length > 0) {
	                // cut off query part from original url
	                this.url = this.url.substring(0,qs);
	                // ensure query ends with &
	                if (query.charAt(query.length-1)!='&') {
	                    query += "&";
	                }
	                // post the query string instead to support portlets
	                // for which you cannot modify/append to the url
	                return this.post(query);
	            }
	        }
	    }
		if (this.channel != null) {
			var res = Wicket.channelManager.schedule(this.channel, this.doGet.bind(this));
			return res != null ? res : true;
		} else {
			return this.doGet();
		}
	},
	
	// The actual get request implementation
	doGet: function() {
		if (this.precondition()) {
	
			this.transport = Wicket.Ajax.getTransport();
		
			var url = this.createUrl();
			this.log("GET", url);
			
			Wicket.Ajax.invokePreCallHandlers();
			
			var t = this.transport;
			if (t != null) {
				t.open("GET", url, this.async);
				t.onreadystatechange = this.stateChangeCallback.bind(this);
				// set a special flag to allow server distinguish between ajax and non-ajax requests
				t.setRequestHeader("Wicket-Ajax", "true");
				if (typeof(Wicket.Focus.lastFocusId) != "undefined" && Wicket.Focus.lastFocusId != "" && Wicket.Focus.lastFocusId != null)
				    t.setRequestHeader("Wicket-FocusedElementId", Wicket.Focus.lastFocusId);				
				t.setRequestHeader("Accept", "text/xml");
				t.send(null);
				return true;
			} else {
				this.failure();
	       		return false;
			}
		} else {
			Wicket.Log.info("Ajax GET stopped because of precondition check, url:" + this.url);
			this.done();
			return true;
		}
	},
	
	// Posts the given string
	post: function(body) {
		if (this.channel != null) {
			var res = Wicket.channelManager.schedule(this.channel, function() { this.doPost(body); }.bind(this));
			return res != null ? res: true;
		} else {
			return this.doPost(body);
		}
	},
	
	// The actual post implementation
	doPost: function(body) {
		
		if (this.precondition()) {
			this.transport = Wicket.Ajax.getTransport();	
		
			var url = this.createUrl();			
			
			this.log("POST", url);
			
			Wicket.Ajax.invokePreCallHandlers();
			
			var t = this.transport;
			if (t != null) {
				// we allow body to be a method - to lazily evaluate itself
				if (typeof(body) == "function") {
					body = body();
				}				
				t.open("POST", url, this.async);
				t.onreadystatechange = this.stateChangeCallback.bind(this);
				t.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				// set a special flag to allow server distinguish between ajax and non-ajax requests
				t.setRequestHeader("Wicket-Ajax", "true");
				if (typeof(Wicket.Focus.lastFocusId) != "undefined" && Wicket.Focus.lastFocusId != "" && Wicket.Focus.lastFocusId != null)
				    t.setRequestHeader("Wicket-FocusedElementId", Wicket.Focus.lastFocusId);				
				t.setRequestHeader("Accept", "text/xml");
				t.send(body);
				return true;
			} else {
	       		this.failure();
	       		return false;
			}
		} else {
			Wicket.Log.info("Ajax POST stopped because of precondition check, url:" + this.url);
			this.done();
			return true;
		}
	},
	
	// Method that processes the request states
	stateChangeCallback: function() {	
		var t = this.transport;
		var status;
		
		if (t != null && t.readyState == 4) {
			try {
				status = t.status;
			}
			catch (e) {
				Wicket.Log.error("Wicket.Ajax.Request.stateChangeCallback: Exception evaluating AJAX status: " + e);
				status = "unavailable";
			}
			if (status == 200 || status == "") { // as stupid as it seems, IE7 sets status to "" on ok
				// response came without error
				var responseAsText = t.responseText;
				
				// first try to get the redirect header
				var redirectUrl;
				try {
					redirectUrl = t.getResponseHeader('Ajax-Location');
				} catch (ignore) { // might happen in older mozilla
				}
				
				// the redirect header was set, go to new url
				if (typeof(redirectUrl) != "undefined" && redirectUrl != null && redirectUrl != "") {
					t.onreadystatechange = Wicket.emptyFunction;
					
					// In case the page isn't really redirected. For example say the redirect is to an octet-stream.
					// A file download popup will appear but the page in the browser won't change.					
					this.done();
					this.successHandler();
					
                    // support/check for non-relative redirectUrl like as provided and needed in a portlet context
					if (redirectUrl.charAt(0)==('/')||redirectUrl.match("^http://")=="http://"||redirectUrl.match("^https://")=="https://") {
					    window.location = redirectUrl;
					}
					else {
					    var urlDepth = 0;
					    while (redirectUrl.substring(0, 3) == "../") {
						    urlDepth++;
						    redirectUrl = redirectUrl.substring(3);
					    }
					    // Make this a string.
					    var calculatedRedirect = window.location.pathname;
					    while (urlDepth > -1) {
						    urlDepth--;
						    i = calculatedRedirect.lastIndexOf("/");
						    if (i > -1) {
							    calculatedRedirect = calculatedRedirect.substring(0, i);
						    }
					    }
					    calculatedRedirect += "/" + redirectUrl;
					    
					    if (Wicket.Browser.isGecko()) {					    
					    	// firefox 3 has problem with window.location setting relative url
					    	calculatedRedirect = window.location.protocol + "//" + window.location.host + calculatedRedirect;					    	
					    }
					    
					    window.location = calculatedRedirect;
					}
				}
				else {
					// no redirect, just regular response
					var log = Wicket.Log.info;				
					log("Received ajax response (" + responseAsText.length + " characters)");
					if (this.debugContent != false) {
						log("\n" + responseAsText);
					}
	        		
	        		// parse the response if the callback needs a DOM tree
	        		if (this.parseResponse == true) {
						var xmldoc;					
						if (typeof(window.XMLHttpRequest) != "undefined" && typeof(DOMParser) != "undefined") {						
							var parser = new DOMParser();
							xmldoc = parser.parseFromString(responseAsText, "text/xml");						
						} else if (window.ActiveXObject) {
							xmldoc = t.responseXML;
						}
						// invoke the loaded callback with an xml document
						this.loadedCallback(xmldoc); 
					} else {
						// invoke the loaded callback with raw string
						this.loadedCallback(responseAsText);
					}        		
					if (this.suppressDone == false)
						this.done();
				}
        	} else {
        		// when an error happened
        		var log = Wicket.Log.error;
        		log("Received Ajax response with code: " + status);
        		if (status == 500) {
					log("500 error had text: " + t.responseText);
				}
		   		this.done();        		
        		this.failure();
        	}    	
        	t.onreadystatechange = Wicket.emptyFunction;
        	t.abort();
        	this.transport = null;       
        }        
	}
};

/**
 * Ajax call fires a Wicket Ajax request and processes the response. 
 * The response can contain 
 *   - javascript that should be invoked
 *   - body of components being replaced
 *   - header contributions of components
 */
Wicket.Ajax.Call = Wicket.Class.create();

Wicket.Ajax.Call.prototype = {
	// Initializes the Call
	initialize: function(url, successHandler, failureHandler, channel) {
		this.successHandler = successHandler != null ? successHandler : function() { };
		this.failureHandler = failureHandler != null ? failureHandler : function() { };

		var c = channel != null ? channel : "0|s"; // set the default channel if not specified
		// initialize the internal Ajax request
		this.request = new Wicket.Ajax.Request(url, this.loadedCallback.bind(this), true, true, failureHandler, c, successHandler);
		this.request.suppressDone = true;
	},
	
	// On ajax request failure
	failure: function(message) {
		if (message != null)
			Wicket.Log.error("Wicket.Ajax.Call.failure: Error while parsing response: " + message);
		this.request.done();
		this.failureHandler();
   		Wicket.Ajax.invokePostCallHandlers();
   		Wicket.Ajax.invokeFailureHandlers();
	},	
	
	// Fires a get request
	call: function() {	
		return this.request.get();
	},
	
	// Fires a post request
	post: function(body) {
		return this.request.post(body);
	},

	// Submits a form using ajax
	submitFormById: function(formId, submitButton) {
		var form = Wicket.$(formId);
		if (form == null || typeof (form) == "undefined")
			Wicket.Log.error("Wicket.Ajax.Call.submitFormById: Trying to submit form with id '"+formId+"' that is not in document.");
		return this.submitForm(form, submitButton);
	},
	
	// Submits a form using ajax.
	// This method serializes a form and sends it as POST body.
	submitForm: function(form, submitButton) {
		if (form.onsubmit) {	
			if (!form.onsubmit()) return;
		}
	    
	    if (this.handleMultipart(form, submitButton)) {
	    	return true;
	    }
	    var body = function() {
	    	var s = Wicket.Form.serialize(form);
	    	if (submitButton != null) {
		        s += Wicket.Form.encode(submitButton) + "=1";
		    }
		    return s;		    
	    }	    
	    return this.request.post(body);
	},


	// If the form contains multipart content this function will post 
	// the form using an iframe instead of the regular ajax call
	// and bridge the output - transparently making this work  as if it was an ajax call
	handleMultipart: function (form, submitButton) {
		
		var multipart=false;
		
		// find root form
		if (form.tagName.toLowerCase() != "form") {
			do {
				// check if any inner forms are multipart
				if (multipart==false&&Wicket!=undefined&&Wicket.Forms!=undefined) {
					var meta=Wicket.Forms[form.id];
					if (meta!=undefined) {
						if (meta["multipart"]!=undefined) {
							multipart=multipart||meta["multipart"];
						}
					}
				}
				form = form.parentNode;
			} while(form.tagName.toLowerCase() != "form" && form.tagName.toLowerCase() != "body")
		}	

		
		if (form.tagName.toLowerCase() != "form") {
			// no form in the hierarchy, cant handle multipart
			return false;
		}
		
		multipart=multipart||form.enctype=="multipart/form-data";
		
		if (multipart==false) {
			// nothing to handle
			return false;
		}
		
		var originalFormAction=form.action;
		var originalFormTarget=form.target;
		var originalFormMethod=form.method;
		var originalFormEnctype=form.enctype;
		var originalFormEncoding=form.encoding;
		
		var iframeName="wicket-submit-"+(""+Math.random()).substr(2);
		
		try {
    		var iframe = document.createElement("<iframe name='"+iframeName+"' id='"+iframeName+"' src='about:blank'/>");
		} catch (ex) {
		    var iframe = document.createElement("iframe");
			iframe.name=iframeName;
			iframe.id=iframe.name;
			iframe.src="about:blank";
		}
		
		iframe.style.display="none";
		iframe.style.visibility="hidden";
		
		document.body.appendChild(iframe);
		
		// reconfigure the form
		form.target=iframe.name;
		form.action=this.request.url + "&wicket:ajax=true";
		form.method="post";
		form.enctype="multipart/form-data";
		form.encoding="multipart/form-data";
		
		// create submitting button element
		if (submitButton!=null) {
			try {
	    		var btn = document.createElement("<input type='hidden' name='"+submitButton+"' id='"+iframe.id+"-btn' value='1'/>");
			} catch (ex) {
			    var btn = document.createElement("input");
			    btn.type="hidden";
				btn.name=submitButton;
				btn.id=iframe.id+"-btn";
				btn.value="1";
			}
			form.appendChild(btn);
		}
		
		// invoke pre call handlers
		Wicket.Ajax.invokePreCallHandlers();
		
		//submit the form into the iframe, response will be handled by the onload callback
		form.submit();

		
		// install handler to deal with the ajax response
		// ... we add the onload event after form submit because chrome fires it prematurely
		Wicket.Event.add(iframe, "load", this.handleMultipartComplete.bind(this));

		// handled, restore state and return true
		form.action=originalFormAction;
		form.target=originalFormTarget;
		form.method=originalFormMethod;
		form.enctype=originalFormEnctype;
		form.encoding=originalFormEncoding;
		
 		return true;
 	},
 
 	// Completes the multipart ajax handling started via handleMultipart()
	handleMultipartComplete: function (event) {
		if (event==null) { event=window.event; }
		if (event.target!=null) {
			var iframe=event.target;
		} else {
			var iframe=event.srcElement
		};

		var envelope=iframe.contentWindow.document;
		if (envelope.XMLDocument!=null) { envelope=envelope.XMLDocument; }
	
		// process the response
		this.loadedCallback(envelope);

		// stop the event
		if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble=true; }

		// remove the event
		if (iframe.detachEvent)  
			iframe.detachEvent("onload", this.handleMultipartComplete);  
		else  
			iframe.removeEventListener("load", this.handleMultipartComplete, false);
		
		// remove the iframe and button elements
		setTimeout(function() {
			var e=document.getElementById(iframe.id+"-btn");
			if (e!=null) {
				e.parentNode.removeChild(e);
			}
			iframe.parentNode.removeChild(iframe);
		}, 250);
	},
	
	// Processes the response
	loadedCallback: function(envelope) {
		// To process the response, we go through the xml document and add a function for every action (step).
		// After this is done, a FunctionExecuter object asynchronously executes these functions.
		// The asynchronous execution is necessary, because some steps might involve loading external javascript,
		// which must be asynchronous, so that it doesn't block the browser, but we also have to maintain
		// the order in which scripts are loaded and we have to delay the next steps until the script is
		// loaded.
		try {			
			var root = envelope.getElementsByTagName("ajax-response")[0];
					
			// the root element must be <ajax-response	
		    if (root == null || root.tagName != "ajax-response") {
		    	this.failure("Could not find root <ajax-response> element");
		    	return;
		    }
						
			// iinitialize the array for steps (closures that execute each action)
		    var steps = new Array();

		   	// start it a bit later so that the browser does handle the next event 
		   // before the component is or can be replaced. We could do (if (!posponed))
		   // because if there is already something in the queue then we could execute that immedietly 
			steps.push(function(notify) {
			   window.setTimeout(notify,2);
			}.bind(this));
			
		    if (Wicket.Browser.isKHTML()) {
		    	// there's a nasty bug in KHTML that makes the browser crash
		    	// when the methods are delayed. Therefore we have to fire it
		    	// ASAP. The javascripts that would cause dependency problems are
		    	// loaded synchronously in konqueror.
			    steps.push = function(method) {
			    	method(function() { });
			    }
			}
			
			// go through the ajax response and for every action (component, js evaluation, header contribution)
			// ad the proper closure to steps
			var stepIndexOfLastReplacedComponent = -1;
		    for (var i = 0; i < root.childNodes.length; ++i) {
		    	var node = root.childNodes[i];				

		        if (node.tagName == "component") {
					if (stepIndexOfLastReplacedComponent == -1) {
						this.processFocusedComponentMark(steps);
					}
					stepIndexOfLastReplacedComponent = steps.length;
					this.processComponent(steps, node);
		        } else if (node.tagName == "evaluate") {
		           this.processEvaluation(steps, node);
		        } else if (node.tagName == "header-contribution") {
		           this.processHeaderContribution(steps, node);
		        } else if (node.tagName == "redirect") {
		           this.processRedirect(steps, node);
		        }
		        
		    }
			if (stepIndexOfLastReplacedComponent != -1) {
				this.processFocusedComponentReplaceCheck(steps, stepIndexOfLastReplacedComponent);
			}

			// add the last step, which should trigger the success call the done method on request
			this.success(steps);
		    
		    if (Wicket.Browser.isKHTML() == false) {
			    Wicket.Log.info("Response parsed. Now invoking steps...");		    		   		    
			    var executer = new Wicket.FunctionsExecuter(steps);
			    executer.start();		    
		    }		    
		} catch (e) {
			this.failure(e.message);
		}
	},
	
	// Adds a closure to steps that should be invoked after all other steps have been successfully executed
	success: function(steps) {
		steps.push(function(notify) {
			Wicket.Log.info("Response processed successfully.");			
			Wicket.Ajax.invokePostCallHandlers();
			// retach the events to the new components (a bit blunt method...)
			// This should be changed for IE See comments in wicket-event.js add (attachEvent/detachEvent)
			// IE this will cause double events for everything.. (mostly because of the Function.prototype.bind(element))
			Wicket.Focus.attachFocusEvent();
			
			this.request.done();
			this.successHandler();

			// set the focus to the last component
			setTimeout("Wicket.Focus.requestFocus();", 0);
			
			// continue to next step (which should make the processing stop, as success should be the final step)		
			notify();			
		}.bind(this));
	},

	// Adds a closure that replaces a component	
	processComponent: function(steps, node) {
		steps.push(function(notify) {
			// get the component id
			var compId = node.getAttribute("id");
			var text="";

			// get the new component body
			if (node.hasChildNodes()) {
				for( i=0 ; i < node.childNodes.length; i++ ) {
     				text = text + node.childNodes[i].nodeValue;
   				} 
			}

			// if the text was escaped, unascape it
			// (escaping is done when the component body contains a CDATA section)
			var encoding = node.getAttribute("encoding");
			if (encoding != null && encoding!="") {
				text = Wicket.decode(encoding, text);
			}
			
			// get existing component
			var element = Wicket.$(compId);

			if (element == null || typeof(element) == "undefined") {			
				Wicket.Log.error("Wicket.Ajax.Call.processComponent: Component with id [["+compId+"]] a was not found while trying to perform markup update. Make sure you called component.setOutputMarkupId(true) on the component whose markup you are trying to update.");
			} else {
				// replace the component
				Wicket.replaceOuterHtml(element, text);
			}
			// continue to next step
			notify();
		});
	},
	
	// Adds a closure that evaluates javascript code
	processEvaluation: function(steps, node) {
		steps.push(function(notify) {
			// get the javascript body
		    var text = node.firstChild.nodeValue;
		    
		    // unescape it if necessary
		    var encoding = node.getAttribute("encoding");
		    if (encoding != null) {
		        text = Wicket.decode(encoding, text);
		    }
		    
		    // test if the javascript is in form of identifier|code
		    // if it is, we allow for letting the javascript decide when the rest of processing will continue 
		    // by invoking identifier();
		    var res = text.match(new RegExp("^([a-z|A-Z_][a-z|A-Z|0-9_]*)\\|((.|\\n)*)$"));
		    		     
		    if (res != null) {

		    	text = "var f = function(" + res[1] + ") {" + res[2] +"};";
		    			    	
		    	try {
			   		// do the evaluation
			    	eval(text);
			    	f(notify);
			    } catch (exception) {
			    	Wicket.Log.error("Wicket.Ajax.Call.processEvaluation: Exception evaluating javascript: " + exception);
			    }
		    	
		    } else {
		    	// just evaluate the javascript
			    try {
			   		// do the evaluation
			    	eval(text);
			    } catch (exception) {
			    	Wicket.Log.error("Wicket.Ajax.Call.processEvaluation: Exception evaluating javascript: " + exception);
			    }
			    // continue to next step
				notify();
			}
		});		
	},
	
	// Adds a closure that processes a header contribution
	processHeaderContribution: function(steps, node) {
		var c = new Wicket.Head.Contributor();
		c.processContribution(steps, node);
	},

	// Adds a closure that processes a redirect
	processRedirect: function(steps, node) {
		var text = node.firstChild.nodeValue;
		Wicket.Log.info("Redirecting to: "+text);
		window.location=text;
	},


	// mark the focused component so that we know if it has been replaced by response
	processFocusedComponentMark: function(steps) {
		steps.push(function(notify) {
			Wicket.Focus.markFocusedComponent();

			// continue to next step
			notify();
		});
	},

	// detect if the focused component was replaced
	processFocusedComponentReplaceCheck: function(steps, lastReplaceComponentStep) {
		// add this step imediately after all components have been replaced
		steps.splice(lastReplaceComponentStep + 1, 0, function(notify) {
			Wicket.Focus.checkFocusedComponentReplaced();

			// continue to next step
			notify();
		});
	}
};

/**
 * Header contribution allows component to include custom javascript and stylesheet. 
 *
 * Header contributor takes the code component would render to page head and
 * interprets it just as browser would when loading a page. 
 * That means loading external javascripts and stylesheets, executing inline 
 * javascript and aplying inline styles. 
 *
 * Header contributor also filters duplicate entries, so that it doesn't load/process
 * resources that have been loaded.
 * For inline styles and javascript, element id is used to filter out duplicate entries.
 * For stylesheet and javascript references, url is used for filtering.
 */
Wicket.Head = { };

Wicket.Head.Contributor = Wicket.Class.create();

Wicket.Head.Contributor.prototype = {
	initialize: function() {
	},
	
	// Parses the header contribution element (returns a DOM tree with the contribution)
	parse: function(headerNode) {
		// the header contribution is stored as CDATA section in the header-contribution element.
		// even though we need to parse it (and we have aleady parsed the response), header
		// contribution needs to be treated separately. The reason for this is that
		// Konqueror crashes when it there is a <script element in the parsed string. So we
		// need to replace that first
		
		// get the header contribution text and unescape it if necessary
		var text = headerNode.firstChild.nodeValue;	
	    var encoding = headerNode.getAttribute("encoding");
	    
	    if (encoding != null && encoding != "") {
	        text = Wicket.decode(encoding, text);        
	    }       
	    
	    if (Wicket.Browser.isKHTML()) {
			// konqueror crashes if there is a <script element in the xml, but <SCRIPT is fine. 
			text = text.replace(/<script/g,"<SCRIPT");
			text = text.replace(/<\/script>/g,"</SCRIPT>");	
		}
				
		// build a DOM tree of the contribution
		var xmldoc;
		if (window.ActiveXObject) {
			xmldoc = new ActiveXObject("Microsoft.XMLDOM");
			if (!xmldoc.loadXML(text)) {
				Wicket.Log.error("Error parsing response: "+text);
			}
		} else {
		    var parser = new DOMParser();    
		    xmldoc = parser.parseFromString(text, "text/xml");	
		}	
		
		return xmldoc;	
	},
	
	// Processes the parsed header contribution
	processContribution: function(steps, headerNode) {
		var xmldoc = this.parse(headerNode);
		var rootNode = xmldoc.documentElement;

		// go through the individual elements and process them according to their type
		for (var i = 0; i < rootNode.childNodes.length; i++) {
			var node = rootNode.childNodes[i];			
			if (node.tagName != null) {
				var name = node.tagName.toLowerCase();
				
				// it is possible that a reference is surrounded by a <wicket:link
				// in that case, we need to find the inner element
				if (name == "wicket:link") {					
					for (var j = 0; j < node.childNodes.length; ++j) {
						var childNode = node.childNodes[j];
						// try to find a regular node inside wicket:link
						if (childNode.nodeType == 1) {
							node = childNode;
							name = node.tagName.toLowerCase();
							break;
						}					
					}					
				}
						
				// process the element
			    if (name == "link") {
					this.processLink(steps, node);
				} else if (name == "script") {
					this.processScript(steps, node);
				} else if (name == "style") {
					this.processStyle(steps, node);
				}
			}
		}	
	},
	
	// Process an external stylesheet element
	processLink: function(steps, node) {		
		steps.push(function(notify) {
			// if the element is already in head, skip it
			if (Wicket.Head.containsElement(node, "href")) {
				notify();
				return;
			}
			// create link element
			var css = Wicket.Head.createElement("link");

			// copy required attributes
			css.id = node.getAttribute("id");
			css.rel = node.getAttribute("rel");
			css.href = node.getAttribute("href");
			css.type = node.getAttribute("type");
			
			// add element to head
			Wicket.Head.addElement(css);
			
			// continue to next step
			notify();
		});
	},
	
	// Process an inline style element
	processStyle: function(steps, node) {
		steps.push(function(notify) {
			// if element with same id is already in document, skip it
			if (Wicket.DOM.containsElement(node)) {
				notify();
				return;
			}	
			// serialize the style to string
			var content = Wicket.DOM.serializeNodeChildren(node);
			
			// create style element
			var style = Wicket.Head.createElement("style");
			
			// copy id attribute
			style.id = node.getAttribute("id");										
				
			// create stylesheet
			if (Wicket.Browser.isIE()) {
				try  {
					document.createStyleSheet().cssText = content;
				}
				catch(ignore) {
					var run = function() {
						try {
							document.createStyleSheet().cssText = content;
						}
						catch(e) {
							Wicket.Log.error("Wicket.Head.Contributor.processStyle: " + e);
						}
					}
					window.setTimeout(run, 1);
				}
			} else {			
				var textNode = document.createTextNode(content);
				style.appendChild(textNode);
			} 		
			Wicket.Head.addElement(style);
			
			// continue to next step
			notify();
		});
	},
	
	// Process a script element (both inline and external)
	processScript: function(steps, node) {
		steps.push(function(notify) {		
			// if element in same id is already in document, 
			// or element with same src attribute is in document, skip it
			if (Wicket.DOM.containsElement(node) ||
				Wicket.Head.containsElement(node, "src")) {
				notify(); 
				return;
			}
			
			// determine whether it is external javascript (has src attribute set)
			var src = node.getAttribute("src");
			
			if (src != null && src != "") {
				// load the external javascript using Wicket.Ajax.Request
				
				// callback when script is loaded
				var onLoad = function(content) {					
					Wicket.Head.addJavascript(content, null, src);
					Wicket.Ajax.invokePostCallHandlers();

					// continue to next step
					notify();
				}
				// we need to schedule the request as timeout
				// calling xml http request from another request call stack doesn't work
				window.setTimeout(function() {
					var req = new Wicket.Ajax.Request(src, onLoad, false, false);
					req.debugContent = false;
					if (Wicket.Browser.isKHTML())
						// konqueror can't process the ajax response asynchronously, therefore the 
						// javascript loading must be also synchronous
						req.async = false;
					// get the javascript
					req.get();					
				},1);
			} else {
				// serialize the element content to string
				var text = Wicket.DOM.serializeNodeChildren(node);
				// get rid of prefix and suffix, they are not eval-d correctly
				text = text.replace(/^<!--\/\*--><!\[CDATA\[\/\*><!--\*\//, "");
				text = text.replace(/\/\*-->]]>\*\/$/, "");
				
				var id = node.getAttribute("id");
				
				if (typeof(id) == "string" && id.length > 0) {					
					// add javascript to document head
					Wicket.Head.addJavascript(text, id);
				} else {
					try {
						eval(text);
					} catch (e) {
						Wicket.Log.error("Wicket.Head.Contributor.processScript: " + e + ": eval -> " + text);
					}
				}
				
				// continue to next step
				notify();
			}
		});					
	}	
};

/**
 * Head manipulation
 */

// Creates an element in document
Wicket.Head.createElement = function(name) {
	return document.createElement(name);
}

// Adds the element to page head
Wicket.Head.addElement = function(element) {
	var head = document.getElementsByTagName("head");

	if (head[0]) {
		head[0].appendChild(element);
	}
}

// Returns true, if the page head contains element that has attribute with
// name mandatoryAttribute same as the given element and their names match.
//
// e.g. Wicket.Head.containsElement(myElement, "src") return true, if there
// is an element in head that is of same type as myElement, and whose src
// attribute is same as myElement.src.
Wicket.Head.containsElement = function(element, mandatoryAttribute) {
	var attr = element.getAttribute(mandatoryAttribute);
	if (attr == null || attr == "" || typeof(attr) == "undefined")
		return false;

	var head = document.getElementsByTagName("head")[0];
	
	if (element.tagName == "script")
		head = document;
	
	var nodes = head.getElementsByTagName(element.tagName);
	
	for (var i = 0; i < nodes.length; ++i) {
		var node = nodes[i];				
		
		// check node names and mandatory attribute values
		// we also have to check for attribute name that is suffixed by "_".
		// this is necessary for filtering script references
		if (node.tagName.toLowerCase() == element.tagName.toLowerCase() &&
			(node.getAttribute(mandatoryAttribute) == attr ||
		     node.getAttribute(mandatoryAttribute+"_") == attr)) {
		    return true;
		}
	}
	return false;
}

// Adds a javascript element to page header. 
// The fakeSrc attribute is used to filter out duplicate javascript references.
// External javascripts are loaded using xmlhttprequest. Then a javascript element is created and the
// javascript body is used as text for the element. For javascript references, wicket uses the src 
// attribute to filter out duplicates. However, since we set the body of the element, we can't assign
// also a src value. Therefore we put the url to the src_ (notice the underscore)  attribute.
// Wicket.Head.containsElement is aware of that and takes also the underscored attributes into account.
Wicket.Head.addJavascript = function(content, id, fakeSrc) {
	var script = Wicket.Head.createElement("script");
	script.id = id;
	script.setAttribute("src_", fakeSrc);
	
	// set the javascript as element content
	if (null == script.canHaveChildren || script.canHaveChildren) {
		var textNode = document.createTextNode(content);			
		script.appendChild(textNode);
	} else {
		script.text = content;
	} 		
	Wicket.Head.addElement(script);	
}

// Goes through all script elements contained by the element and add them to head
Wicket.Head.addJavascripts = function(element, contentFilter) {	
	function add(element) {
		var src = element.getAttribute("src");
		
		// if it is a reference, just add it to head				
		if (src != null && src.length > 0) {			
			var e = document.createElement("script");
			e.setAttribute("type","text/javascript");
			e.setAttribute("src", src);
			Wicket.Head.addElement(e);											
		} else {	
			var content = Wicket.DOM.serializeNodeChildren(element);		
			if (content == null || content == "")
				content = element.text;
			
			if (typeof(contentFilter) == "function") {
				content = contentFilter(content);
			}
			
			Wicket.Head.addJavascript(content);
		}		
	}
	if (typeof(element) != "undefined" &&
	    typeof(element.tagName) != "undefined" &&
	    element.tagName.toLowerCase() == "script") {
		add(element);
	} else {
		// we need to check if there are any children, because Safari
		// aborts when the element is a text node			
		if (element.childNodes.length > 0) {			
			var scripts = element.getElementsByTagName("script");
			for (var i = 0; i < scripts.length; ++i) {
				add(scripts[i]);
			}
		}
	}
}

/**
 * Throttler's purpose is to make sure that ajax requests wont be fired too often.
 */

Wicket.ThrottlerEntry = Wicket.Class.create();
Wicket.ThrottlerEntry.prototype = {
	initialize: function(func) {
		this.func = func;
		this.timestamp = new Date().getTime();
		this.timeoutVar = undefined;
	},
	
	getTimestamp: function() {
		return this.timestamp;
	},
	
	getFunc: function() {
		return this.func;
	},
	
	setFunc: function(func) {
		this.func = func;
	},

	getTimeoutVar: function() {
        return this.timeoutVar;
	},

	setTimeoutVar: function(timeoutVar) {
        this.timeoutVar = timeoutVar;
	}
};

Wicket.Throttler = Wicket.Class.create();
Wicket.Throttler.prototype = {

    /* "postponeTimerOnUpdate" is an optional parameter. If it is set to true, then the timer is
       reset each time the throttle function gets called. Use this behaviour if you want something
       to happen at X milliseconds after the *last* call to throttle.
       If the parameter is not set, or set to false, then the timer is not reset. */
	initialize: function(postponeTimerOnUpdate) {
		this.entries = new Array();
		if (postponeTimerOnUpdate != undefined)
            this.postponeTimerOnUpdate = postponeTimerOnUpdate;
        else
            this.postponeTimerOnUpdate = false;
	},
	
	throttle: function(id, millis, func) {
		var entry = this.entries[id];
		var me = this;
		if (entry == undefined) {
			entry = new Wicket.ThrottlerEntry(func);
			entry.setTimeoutVar(window.setTimeout(function() { me.execute(id); }, millis));
			this.entries[id] = entry;
		} else {
			entry.setFunc(func);
            if (this.postponeTimerOnUpdate == true)
            {
                window.clearTimeout(entry.getTimeoutVar());
                entry.setTimeoutVar(window.setTimeout(function() { me.execute(id); }, millis));
            }
		}	
	},
	
	execute: function(id) {
		var entry = this.entries[id];
		if (entry != undefined) {
			var func = entry.getFunc();
            this.entries[id] = undefined;	
			var tmp = func();
		}
	}
};

Wicket.throttler = new Wicket.Throttler();

/**
 * Prevent event from bubbling up in the element hierarchy.
 */
Wicket.stopEvent = function(e) {
	e=Wicket.fixEvent(e);		
	e.cancelBubble = true;
	if (e.stopPropagation)
		e.stopPropagation();
}

/**
 * If no event is given as argument (IE), window.event is returned. 
 */
Wicket.fixEvent = function(e) {
	if (typeof e == 'undefined') 
		e = window.event;
	return e;		
}

/**
 * Flexible dragging support.
 */
Wicket.Drag = {
		
	/**
	 * Initializes the dragging on the specified element.
	 * Element's onmousedown will be replaced by generated handler.
	 *
	 * @param {Element} element - element clicking on which the drag should begin 
	 * @param {Function} onDragBegin - handler called at the begin on dragging - passed element as first parameter
	 * @param {Function} onDragEnd - handler called at the end of dragging - passed element as first parameter
	 * @param {Function} onDrag - handler called during dragging - passed element and mouse deltas	 
	 */
	init: function(element, onDragBegin, onDragEnd, onDrag) {		
		
		if (typeof(onDragBegin) == "undefined")
			onDragBegin = Wicket.emptyFunction;
		if (typeof(onDragEnd) == "undefined")
			onDragEnd = Wicket.emptyFunction;
		if (typeof(onDrag) == "undefined")
			onDrag = Wicket.emptyFunction;

		element.wicketOnDragBegin = onDragBegin;
		element.wicketOnDrag = onDrag;
		element.wicketOnDragEnd = onDragEnd;

		
		// set the mousedown handler 
		Wicket.Event.add(element, "mousedown", Wicket.Drag.mouseDownHandler);									
	},
	
	mouseDownHandler: function(e) {
		e = Wicket.fixEvent(e);
	
		var element = this;
	
		// HACK - for safari stopPropagation doesn't work well because
		// it also prevents scrollbars and form components getting the
		// event. Therefore for safari the 'ignore' flag is set on event. 
		if (typeof(e.ignore) == "undefined") {
			
			Wicket.stopEvent(e);
			
			if (e.preventDefault) {
				e.preventDefault();
			}

			element.wicketOnDragBegin(element);		
			
			element.lastMouseX = e.clientX;
			element.lastMouseY = e.clientY;
			
			element.old_onmousemove = document.onmousemove;
			element.old_onmouseup = document.onmouseup;
			element.old_onselectstart = document.onselectstart;	
			element.old_onmouseout = document.onmouseout;		
			
			document.onselectstart = function() { return false; }
			document.onmousemove = Wicket.Drag.mouseMove;
			document.onmouseup = Wicket.Drag.mouseUp;
			document.onmouseout = Wicket.Drag.mouseOut;				
						
			Wicket.Drag.current = element;
						
			return false;
		} 			
			
	},
	
	/**
	 * Deinitializes the dragging support on given element. 
	 */
	clean: function(element) {
		element.onmousedown = null;
	},

	/**
	 * Called when mouse is moved. This method fires the onDrag event
	 * with element instance, deltaX and deltaY (the distance
	 * between this call and the previous one).
	 
	 * The onDrag handler can optionally return an array of two integers 
	 * - the delta correction. This is used, for example, if there is
	 * element being resized and the size limit has been reached (but the
	 * mouse can still move).
	 * 
	 * @param {Event} e
	 */	
	mouseMove: function(e) {
		e = Wicket.fixEvent(e);
		var o = Wicket.Drag.current;

		// this happens sometimes in Safari 
		if (e.clientX < 0 || e.clientY < 0) {
			return;
		}		

		if (o != null) {		
			var deltaX = e.clientX - o.lastMouseX;
			var deltaY = e.clientY - o.lastMouseY;
				
			var res = o.wicketOnDrag(o, deltaX, deltaY, e);
			
			if (res == null)
				res = [0, 0];
			
			o.lastMouseX = e.clientX + res[0];
			o.lastMouseY = e.clientY + res[1];
		}
		
		return false;
	},

	/**
	 * Called when the mouse button is released.
	 * Cleans all temporary variables and callback methods.
	 * 
	 * @param {Event} e
	 */	
	mouseUp: function(e) {		
		e = Wicket.fixEvent(e);
		var o = Wicket.Drag.current;
		
		if (o != null && typeof(o) != "undefined") {
			o.wicketOnDragEnd(o);		
			
			o.lastMouseX = null;
			o.lastMouseY = null;
			
			document.onmousemove = o.old_onmousemove;
			document.onmouseup = o.old_onmouseup;		
			document.onselectstart = o.old_onselectstart;
					
			document.onmouseout = o.old_onmouseout;
			
			o.old_mousemove = null;		
			o.old_mouseup = null;
			o.old_onselectstart = null;
			o.old_onmouseout = null;
			
			Wicket.Drag.current = null;
		}
	},
	
	/**
	 * Called when mouse leaves an element. We need this for firefox, as otherwise
	 * the dragging would continue after mouse leaves the document.
	 * Unfortunately this break dragging in firefox immediately after the mouse leaves
	 * page. 
	 */
	mouseOut: function(e) {
		if (false && Wicket.Browser.isGecko()) {
			// other browsers handle this more gracefully		
			e = Wicket.fixEvent(e);
			
			if (e.target.tagName == "HTML") {
				Wicket.Drag.mouseUp(e);				
			}
		}
	}
	
	
};

Wicket.ChangeHandler=function(elementId){
    var KEY_BACKSPACE=8;
    var KEY_TAB=9;
    var KEY_ENTER=13;
    var KEY_ESC=27;
    var KEY_LEFT=37;
    var KEY_UP=38;
    var KEY_RIGHT=39;
    var KEY_DOWN=40;
    var KEY_SHIFT=16;
    var KEY_CTRL=17;
    var KEY_ALT=18;

	var obj = Wicket.$(elementId);
	obj.setAttribute("autocomplete", "off");
	obj.onchangeoriginal = obj.onchange;
	
	if (Wicket.Browser.isIE() || Wicket.Browser.isKHTML() || Wicket.Browser.isSafari()) {
	
		var objonchange = obj.onchange;

		obj.onkeyup = function(event) {		
			switch (wicketKeyCode(Wicket.fixEvent(event))) {
				case KEY_ENTER:
				case KEY_UP:
				case KEY_DOWN:
				case KEY_ESC:
				case KEY_TAB:
				case KEY_RIGHT:
				case KEY_LEFT:
				case KEY_SHIFT:
				case KEY_ALT:
				case KEY_CTRL:
					return Wicket.stopEvent(event);
					break;
				default:
					if (typeof objonchange == "function")objonchange();
			}
			return null;
		}
		
		obj.onpaste = function(event) {
			if (typeof objonchange == "function"){
				setTimeout(function() {
	   			  objonchange();
			     }, 10);
			}
			return null;
		}
		
		obj.oncut = function(event) {
			if (typeof objonchange == "function"){
				setTimeout(function() {
	   			  objonchange();
			     }, 10);
			}
			return null;
		}
	} else {
		obj.addEventListener('input', obj.onchange, true);
	}

	obj.onchange = function(event) {
		Wicket.stopEvent(event);
	}
} 

/*
 * Compatibility layer to maintain the original wicket-ajax API.
 */

var wicketThrottler = Wicket.throttler;

function wicketAjaxGet(url, successHandler, failureHandler, precondition, channel) {

	var call = new Wicket.Ajax.Call(url, successHandler, failureHandler, channel);
	
	if (typeof(precondition) != "undefined" && precondition != null) {
		call.request.precondition = precondition;
	}
	
	return call.call();
}

function wicketAjaxPost(url, body, successHandler, failureHandler, precondition, channel) {
	var call = new Wicket.Ajax.Call(url, successHandler, failureHandler, channel);
	
	if (typeof(precondition) != "undefined" && precondition != null) {		
		call.request.precondition = precondition;
	}
	
	return call.post(body);
}

function wicketSubmitForm(form, url, submitButton, successHandler, failureHandler, precondition, channel) {
	var call = new Wicket.Ajax.Call(url, successHandler, failureHandler, channel);
	
	if (typeof(precondition) != "undefined" && precondition != null) {
		call.request.precondition = precondition;
	}
	
	return call.submitForm(form, submitButton);
}

function wicketSubmitFormById(formId, url, submitButton, successHandler, failureHandler, precondition, channel) {
	var call = new Wicket.Ajax.Call(url, successHandler, failureHandler, channel);
	
	if (typeof(precondition) != "undefined" && precondition != null) {
		call.request.precondition = precondition;
	}
	
	return call.submitFormById(formId, submitButton);
}

wicketSerialize = Wicket.Form.serializeElement;

wicketSerializeForm = Wicket.Form.serialize;

wicketEncode = Wicket.Form.encode;

wicketDecode = Wicket.decode;

wicketAjaxGetTransport = Wicket.Ajax.getTransport;

// Global handlers stubs

Wicket.Ajax.registerPreCallHandler(function() {
	if (typeof(window.wicketGlobalPreCallHandler) != "undefined") {
	    var global=wicketGlobalPreCallHandler;
	    if (global!=null) {
	    	global();
	    }
	}    
});

Wicket.Ajax.registerPostCallHandler(function() {
	if (typeof(window.wicketGlobalPostCallHandler) != "undefined") {
	    var global=wicketGlobalPostCallHandler;
	    if (global!=null) {
	    	global();
	    }
	}    
});

Wicket.Ajax.registerFailureHandler(function() {
	if (typeof(window.wicketGlobalFailureHandler) != "undefined") {
	    var global=wicketGlobalFailureHandler;
	    if (global!=null) {
	    	global();
	    }
	}    
});

// FOCUS FUNCTIONS

Wicket.Focus = {
	lastFocusId : "",
	refocusLastFocusedComponentAfterResponse : false,
	focusSetFromServer : false,

	setFocus: function(event)
	{ 
		event = Wicket.fixEvent(event);		
	
	    // IE doesn't have the property "target".
	    // Use "srcElement" instead.
	    var target = event.target ? event.target : event.srcElement;
	    if (target) {
			Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
			Wicket.Focus.lastFocusId=target.id;
			Wicket.Log.info("focus set on " + Wicket.Focus.lastFocusId);
		}
	},
	
	blur: function(event)
	{ 
		event = Wicket.fixEvent(event);		
	
	    // IE doesn't have the property "target".
	    // Use "srcElement" instead.
	    var target = event.target ? event.target : event.srcElement;
	    if (target && Wicket.Focus.lastFocusId==target.id) {
			if (Wicket.Focus.refocusLastFocusedComponentAfterResponse) {
				// replaced components seem to blur when replaced only on Safari - so do not modify lastFocusId so it gets refocused
				Wicket.Log.info("focus removed from " + target.id + " but ignored because of component replacement");
			} else {
				Wicket.Focus.lastFocusId=null;
				Wicket.Log.info("focus removed from " + target.id);
			}
		}
	},
	
	getFocusedElement: function()
	{
		if (typeof(Wicket.Focus.lastFocusId) != "undefined" && Wicket.Focus.lastFocusId != "" && Wicket.Focus.lastFocusId != null)
		{
			Wicket.Log.info("returned focused element: " + Wicket.$(Wicket.Focus.lastFocusId)); 
			return Wicket.$(Wicket.Focus.lastFocusId);
		}
		return;
	},

	setFocusOnId: function(id)
	{
		if (typeof(id) != "undefined" && id != "" && id != null) {
			Wicket.Focus.refocusLastFocusedComponentAfterResponse = true;
			Wicket.Focus.focusSetFromServer = true;
			Wicket.Focus.lastFocusId=id;
			Wicket.Log.info("focus set on " + Wicket.Focus.lastFocusId + " from serverside");
		} else {
			Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
			Wicket.Log.info("refocus focused component after request stopped from serverside");
		}
	},
	
	// mark the focused component so that we know if it has been replaced or not by response
	markFocusedComponent: function()
	{
		var focusedElement = Wicket.Focus.getFocusedElement();
		if (typeof(focusedElement) != "undefined" && focusedElement != null) {
			focusedElement.wasFocusedBeforeComponentReplacements = true; // create a property of the focused element that would not remain there if component is replaced
			Wicket.Focus.refocusLastFocusedComponentAfterResponse = true;
			Wicket.Focus.focusSetFromServer = false;
		} else {
			Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
		}
	},

	// detect if the focused component was replaced
	checkFocusedComponentReplaced: function()
	{
		var focusedElement = Wicket.Focus.getFocusedElement();
		if (Wicket.Focus.refocusLastFocusedComponentAfterResponse == true)
		{
			if (typeof(focusedElement) != "undefined" && focusedElement != null) {
				if (typeof(focusedElement.wasFocusedBeforeComponentReplacements) != "undefined")
				{
					// focus component was not replaced - no need to refocus it
					Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
				}
			} else {
				// focused component dissapeared completely - no use to try to refocus it
				Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
				Wicket.Focus.lastFocusId = "";
			}
		}
	},
	
	requestFocus: function()
	{
		// if the focused component is replaced by the ajax response, a re-focus might be needed (if focus was not changed from server)
		// but if not, and the focus component should remain the same, do not re-focus - fixes problem on IE6 for combos that have the popup open (refocusing closes popup)
		if (Wicket.Focus.refocusLastFocusedComponentAfterResponse && typeof(Wicket.Focus.lastFocusId) != "undefined" && Wicket.Focus.lastFocusId != "" && Wicket.Focus.lastFocusId != null)
		{ 
			var toFocus = Wicket.$(Wicket.Focus.lastFocusId);
			
			if (toFocus != null && typeof(toFocus) != "undefined") {
				Wicket.Log.info("Calling focus on " + Wicket.Focus.lastFocusId);
				try {
					if (Wicket.Focus.focusSetFromServer) {
						toFocus.focus();
					} else {
						// avoid loops like - onfocus triggering an event the modifies the tag => refocus => the event is triggered again
						var temp = toFocus.onfocus;
						toFocus.onfocus = null;
						toFocus.focus();
						setTimeout(function() { toFocus.onfocus = temp; }, 0);	// IE needs setTimeout (it seems not to call onfocus sync. when focus() is called
					}
				} catch (ignore) {
				}
			}
			else
			{
				Wicket.Focus.lastFocusId = "";
				Wicket.Log.info("Couldn't set focus on " + Wicket.Focus.lastFocusId + " not on the page anymore");
			}
		}
		else if (Wicket.Focus.refocusLastFocusedComponentAfterResponse)
		{
			Wicket.Log.info("last focus id was not set");
		}
		else
		{
			Wicket.Log.info("refocus last focused component not needed/allowed");
		}
		Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
	},
	
	setFocusOnElements: function (elements)
	{
		// we need to cache array length because IE will try to recalculate 
		// the collection of elements every time length() is called which can be quiet expensive
		// if the collection is a result of getElementsByTagName or a similar function.
		var len=elements.length;
		for (var i=0; i< len; i++)
		{
		    if (elements[i].wicketFocusSet != true)
		    {
		         Wicket.Event.add(elements[i],'focus',Wicket.Focus.setFocus);
		         Wicket.Event.add(elements[i],'blur',Wicket.Focus.blur);		         
		         elements[i].wicketFocusSet = true;
		    }
		}
	},
	
	attachFocusEvent: function()
	{
		Wicket.Focus.setFocusOnElements(document.getElementsByTagName("input"));
		Wicket.Focus.setFocusOnElements(document.getElementsByTagName("select"));
		Wicket.Focus.setFocusOnElements(document.getElementsByTagName("textarea"));
		Wicket.Focus.setFocusOnElements(document.getElementsByTagName("button"));
		Wicket.Focus.setFocusOnElements(document.getElementsByTagName("a"));
	}
}
Wicket.Event.addDomReadyEvent(Wicket.Focus.attachFocusEvent);


// DEBUG FUNCTIONS
function wicketAjaxDebugEnabled() {
    if (typeof(wicketAjaxDebugEnable)=="undefined") {
        return false;
    } else {
        return wicketAjaxDebugEnable==true;
    }
}

// MISC FUNCTIONS
function wicketKeyCode(event) {
    if (typeof(event.keyCode)=="undefined") {
        return event.which;
    } else {
        return event.keyCode;
    }
}

function wicketGet(id) {
    return Wicket.$(id);
}

function wicketShow(id) {
    var e=wicketGet(id);
    if (e!=null) {
	    e.style.display = "";
	}
}

function wicketHide(id) {
    var e=wicketGet(id);
	if (e!=null) {
	    e.style.display = "none";
	}
}


(function(){var W=this,ab,F=W.jQuery,S=W.$,T=W.jQuery=W.$=function(b,a){return new T.fn.init(b,a)},M=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,ac=/^.[^:#\[\.,]*$/;T.fn=T.prototype={init:function(e,b){e=e||document;if(e.nodeType){this[0]=e;this.length=1;this.context=e;return this}if(typeof e==="string"){var c=M.exec(e);if(c&&(c[1]||!b)){if(c[1]){e=T.clean([c[1]],b)}else{var a=document.getElementById(c[3]);if(a&&a.id!=c[3]){return T().find(e)}var d=T(a||[]);d.context=document;d.selector=e;return d}}else{return T(b).find(e)}}else{if(T.isFunction(e)){return T(document).ready(e)}}if(e.selector&&e.context){this.selector=e.selector;this.context=e.context}return this.setArray(T.isArray(e)?e:T.makeArray(e))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(a){return a===ab?Array.prototype.slice.call(this):this[a]},pushStack:function(c,a,d){var b=T(c);b.prevObject=this;b.context=this.context;if(a==="find"){b.selector=this.selector+(this.selector?" ":"")+d}else{if(a){b.selector=this.selector+"."+a+"("+d+")"}}return b},setArray:function(a){this.length=0;Array.prototype.push.apply(this,a);return this},each:function(a,b){return T.each(this,a,b)},index:function(a){return T.inArray(a&&a.jquery?a[0]:a,this)},attr:function(c,a,b){var d=c;if(typeof c==="string"){if(a===ab){return this[0]&&T[b||"attr"](this[0],c)}else{d={};d[c]=a}}return this.each(function(e){for(c in d){T.attr(b?this.style:this,c,T.prop(this,d[c],b,e,c))}})},css:function(b,a){if((b=="width"||b=="height")&&parseFloat(a)<0){a=ab}return this.attr(b,a,"curCSS")},text:function(a){if(typeof a!=="object"&&a!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(a))}var b="";T.each(a||this,function(){T.each(this.childNodes,function(){if(this.nodeType!=8){b+=this.nodeType!=1?this.nodeValue:T.fn.text([this])}})});return b},wrapAll:function(b){if(this[0]){var a=T(b,this[0].ownerDocument).clone();if(this[0].parentNode){a.insertBefore(this[0])}a.map(function(){var c=this;while(c.firstChild){c=c.firstChild}return c}).append(this)}return this},wrapInner:function(a){return this.each(function(){T(this).contents().wrapAll(a)})},wrap:function(a){return this.each(function(){T(this).wrapAll(a)})},append:function(){return this.domManip(arguments,true,function(a){if(this.nodeType==1){this.appendChild(a)}})},prepend:function(){return this.domManip(arguments,true,function(a){if(this.nodeType==1){this.insertBefore(a,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(a){this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,false,function(a){this.parentNode.insertBefore(a,this.nextSibling)})},end:function(){return this.prevObject||T([])},push:[].push,sort:[].sort,splice:[].splice,find:function(b){if(this.length===1){var a=this.pushStack([],"find",b);a.length=0;T.find(b,this[0],a);return a}else{return this.pushStack(T.unique(T.map(this,function(c){return T.find(b,c)})),"find",b)}},clone:function(b){var d=this.map(function(){if(!T.support.noCloneEvent&&!T.isXMLDoc(this)){var f=this.outerHTML;if(!f){var e=this.ownerDocument.createElement("div");e.appendChild(this.cloneNode(true));f=e.innerHTML}return T.clean([f.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(b===true){var a=this.find("*").andSelf(),c=0;d.find("*").andSelf().each(function(){if(this.nodeName!==a[c].nodeName){return}var g=T.data(a[c],"events");for(var e in g){for(var f in g[e]){T.event.add(this,e,g[e][f],g[e][f].data)}}c++})}return d},filter:function(a){return this.pushStack(T.isFunction(a)&&T.grep(this,function(b,c){return a.call(b,c)})||T.multiFilter(a,T.grep(this,function(b){return b.nodeType===1})),"filter",a)},closest:function(c){var a=T.expr.match.POS.test(c)?T(c):null,b=0;return this.map(function(){var d=this;while(d&&d.ownerDocument){if(a?a.index(d)>-1:T(d).is(c)){T.data(d,"closest",b);return d}d=d.parentNode;b++}})},not:function(b){if(typeof b==="string"){if(ac.test(b)){return this.pushStack(T.multiFilter(b,this,true),"not",b)}else{b=T.multiFilter(b,this)}}var a=b.length&&b[b.length-1]!==ab&&!b.nodeType;return this.filter(function(){return a?T.inArray(this,b)<0:this!=b})},add:function(a){return this.pushStack(T.unique(T.merge(this.get(),typeof a==="string"?T(a):T.makeArray(a))))},is:function(a){return !!a&&T.multiFilter(a,this).length>0},hasClass:function(a){return !!a&&this.is("."+a)},val:function(c){if(c===ab){var i=this[0];if(i){if(T.nodeName(i,"option")){return(i.attributes.value||{}).specified?i.value:i.text}if(T.nodeName(i,"select")){var e=i.selectedIndex,b=[],a=i.options,f=i.type=="select-one";if(e<0){return null}for(var h=f?e:0,d=f?e+1:a.length;h<d;h++){var g=a[h];if(g.selected){c=T(g).val();if(f){return c}b.push(c)}}return b}return(i.value||"").replace(/\r/g,"")}return ab}if(typeof c==="number"){c+=""}return this.each(function(){if(this.nodeType!=1){return}if(T.isArray(c)&&/radio|checkbox/.test(this.type)){this.checked=(T.inArray(this.value,c)>=0||T.inArray(this.name,c)>=0)}else{if(T.nodeName(this,"select")){var j=T.makeArray(c);T("option",this).each(function(){this.selected=(T.inArray(this.value,j)>=0||T.inArray(this.text,j)>=0)});if(!j.length){this.selectedIndex=-1}}else{this.value=c}}})},html:function(a){return a===ab?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(a)},replaceWith:function(a){return this.after(a).remove()},eq:function(a){return this.slice(a,+a+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(a){return this.pushStack(T.map(this,function(b,c){return a.call(b,c,b)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(d,a,b){if(this[0]){var e=(this[0].ownerDocument||this[0]).createDocumentFragment(),h=T.clean(d,(this[0].ownerDocument||this[0]),e),f=e.firstChild;if(f){for(var g=0,i=this.length;g<i;g++){b.call(c(this[g],f),this.length>1||g>0?e.cloneNode(true):e)}}if(h){T.each(h,E)}}return this;function c(k,j){return a&&T.nodeName(k,"table")&&T.nodeName(j,"tr")?(k.getElementsByTagName("tbody")[0]||k.appendChild(k.ownerDocument.createElement("tbody"))):k}}};T.fn.init.prototype=T.fn;function E(b,a){if(a.src){T.ajax({url:a.src,async:false,dataType:"script"})}else{T.globalEval(a.text||a.textContent||a.innerHTML||"")}if(a.parentNode){a.parentNode.removeChild(a)}}function ad(){return +new Date}T.extend=T.fn.extend=function(){var c=arguments[0]||{},e=1,d=arguments.length,h=false,f;if(typeof c==="boolean"){h=c;c=arguments[1]||{};e=2}if(typeof c!=="object"&&!T.isFunction(c)){c={}}if(d==e){c=this;--e}for(;e<d;e++){if((f=arguments[e])!=null){for(var g in f){var b=c[g],a=f[g];if(c===a){continue}if(h&&a&&typeof a==="object"&&!a.nodeType){c[g]=T.extend(h,b||(a.length!=null?[]:{}),a)}else{if(a!==ab){c[g]=a}}}}}return c};var ag=/z-?index|font-?weight|opacity|zoom|line-?height/i,Q=document.defaultView||{},L=Object.prototype.toString;T.extend({noConflict:function(a){W.$=S;if(a){W.jQuery=F}return T},isFunction:function(a){return L.call(a)==="[object Function]"},isArray:function(a){return L.call(a)==="[object Array]"},isXMLDoc:function(a){return a.nodeType===9&&a.documentElement.nodeName!=="HTML"||!!a.ownerDocument&&T.isXMLDoc(a.ownerDocument)},globalEval:function(a){if(a&&/\S/.test(a)){var b=document.getElementsByTagName("head")[0]||document.documentElement,c=document.createElement("script");c.type="text/javascript";if(T.support.scriptEval){c.appendChild(document.createTextNode(a))}else{c.text=a}b.insertBefore(c,b.firstChild);b.removeChild(c)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()==b.toUpperCase()},each:function(e,a,f){var g,d=0,c=e.length;if(f){if(c===ab){for(g in e){if(a.apply(e[g],f)===false){break}}}else{for(;d<c;){if(a.apply(e[d++],f)===false){break}}}}else{if(c===ab){for(g in e){if(a.call(e[g],g,e[g])===false){break}}}else{for(var b=e[0];d<c&&a.call(b,d,b)!==false;b=e[++d]){}}}return e},prop:function(b,a,c,d,e){if(T.isFunction(a)){a=a.call(b,d)}return typeof a==="number"&&c=="curCSS"&&!ag.test(e)?a+"px":a},className:{add:function(b,a){T.each((a||"").split(/\s+/),function(d,c){if(b.nodeType==1&&!T.className.has(b.className,c)){b.className+=(b.className?" ":"")+c}})},remove:function(b,a){if(b.nodeType==1){b.className=a!==ab?T.grep(b.className.split(/\s+/),function(c){return !T.className.has(a,c)}).join(" "):""}},has:function(a,b){return a&&T.inArray(b,(a.className||a).toString().split(/\s+/))>-1}},swap:function(b,c,a){var e={};for(var d in c){e[d]=b.style[d];b.style[d]=c[d]}a.call(b);for(var d in c){b.style[d]=e[d]}},css:function(e,g,c,h){if(g=="width"||g=="height"){var a,f={position:"absolute",visibility:"hidden",display:"block"},b=g=="width"?["Left","Right"]:["Top","Bottom"];function d(){a=g=="width"?e.offsetWidth:e.offsetHeight;if(h==="border"){return}T.each(b,function(){if(!h){a-=parseFloat(T.curCSS(e,"padding"+this,true))||0}if(h==="margin"){a+=parseFloat(T.curCSS(e,"margin"+this,true))||0}else{a-=parseFloat(T.curCSS(e,"border"+this+"Width",true))||0}})}if(e.offsetWidth!==0){d()}else{T.swap(e,f,d)}return Math.max(0,Math.round(a))}return T.curCSS(e,g,c)},curCSS:function(e,h,g){var b,i=e.style;if(h=="opacity"&&!T.support.opacity){b=T.attr(i,"opacity");return b==""?"1":b}if(h.match(/float/i)){h=H}if(!g&&i&&i[h]){b=i[h]}else{if(Q.getComputedStyle){if(h.match(/float/i)){h="float"}h=h.replace(/([A-Z])/g,"-$1").toLowerCase();var a=Q.getComputedStyle(e,null);if(a){b=a.getPropertyValue(h)}if(h=="opacity"&&b==""){b="1"}}else{if(e.currentStyle){var d=h.replace(/\-(\w)/g,function(k,j){return j.toUpperCase()});b=e.currentStyle[h]||e.currentStyle[d];if(!/^\d+(px)?$/i.test(b)&&/^\d/.test(b)){var f=i.left,c=e.runtimeStyle.left;e.runtimeStyle.left=e.currentStyle.left;i.left=b||0;b=i.pixelLeft+"px";i.left=f;e.runtimeStyle.left=c}}}}return b},clean:function(g,b,d){b=b||document;if(typeof b.createElement==="undefined"){b=b.ownerDocument||b[0]&&b[0].ownerDocument||document}if(!d&&g.length===1&&typeof g[0]==="string"){var e=/^<(\w+)\s*\/?>$/.exec(g[0]);if(e){return[b.createElement(e[1])]}}var f=[],h=[],a=b.createElement("div");T.each(g,function(l,i){if(typeof i==="number"){i+=""}if(!i){return}if(typeof i==="string"){i=i.replace(/(<(\w+)[^>]*?)\/>/g,function(q,p,r){return r.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?q:p+"></"+r+">"});var m=i.replace(/^\s+/,"").substring(0,10).toLowerCase();var k=!m.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!m.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||m.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!m.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!m.indexOf("<td")||!m.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!m.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!T.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];a.innerHTML=k[1]+i+k[2];while(k[0]--){a=a.lastChild}if(!T.support.tbody){var j=/<tbody/i.test(i),n=!m.indexOf("<table")&&!j?a.firstChild&&a.firstChild.childNodes:k[1]=="<table>"&&!j?a.childNodes:[];for(var o=n.length-1;o>=0;--o){if(T.nodeName(n[o],"tbody")&&!n[o].childNodes.length){n[o].parentNode.removeChild(n[o])}}}if(!T.support.leadingWhitespace&&/^\s/.test(i)){a.insertBefore(b.createTextNode(i.match(/^\s*/)[0]),a.firstChild)}i=T.makeArray(a.childNodes)}if(i.nodeType){f.push(i)}else{f=T.merge(f,i)}});if(d){for(var c=0;f[c];c++){if(T.nodeName(f[c],"script")&&(!f[c].type||f[c].type.toLowerCase()==="text/javascript")){h.push(f[c].parentNode?f[c].parentNode.removeChild(f[c]):f[c])}else{if(f[c].nodeType===1){f.splice.apply(f,[c+1,0].concat(T.makeArray(f[c].getElementsByTagName("script"))))}d.appendChild(f[c])}}return h}return f},attr:function(c,f,b){if(!c||c.nodeType==3||c.nodeType==8){return ab}var e=!T.isXMLDoc(c),a=b!==ab;f=e&&T.props[f]||f;if(c.tagName){var g=/href|src|style/.test(f);if(f=="selected"&&c.parentNode){c.parentNode.selectedIndex}if(f in c&&e&&!g){if(a){if(f=="type"&&T.nodeName(c,"input")&&c.parentNode){throw"type property can't be changed"}c[f]=b}if(T.nodeName(c,"form")&&c.getAttributeNode(f)){return c.getAttributeNode(f).nodeValue}if(f=="tabIndex"){var d=c.getAttributeNode("tabIndex");return d&&d.specified?d.value:c.nodeName.match(/(button|input|object|select|textarea)/i)?0:c.nodeName.match(/^(a|area)$/i)&&c.href?0:ab}return c[f]}if(!T.support.style&&e&&f=="style"){return T.attr(c.style,"cssText",b)}if(a){c.setAttribute(f,""+b)}var h=!T.support.hrefNormalized&&e&&g?c.getAttribute(f,2):c.getAttribute(f);return h===null?ab:h}if(!T.support.opacity&&f=="opacity"){if(a){c.zoom=1;c.filter=(c.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(b)+""=="NaN"?"":"alpha(opacity="+b*100+")")}return c.filter&&c.filter.indexOf("opacity=")>=0?(parseFloat(c.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}f=f.replace(/-([a-z])/ig,function(j,i){return i.toUpperCase()});if(a){c[f]=b}return c[f]},trim:function(a){return(a||"").replace(/^\s+|\s+$/g,"")},makeArray:function(a){var c=[];if(a!=null){var b=a.length;if(b==null||typeof a==="string"||T.isFunction(a)||a.setInterval){c[0]=a}else{while(b){c[--b]=a[b]}}}return c},inArray:function(b,a){for(var d=0,c=a.length;d<c;d++){if(a[d]===b){return d}}return -1},merge:function(b,e){var d=0,c,a=b.length;if(!T.support.getAll){while((c=e[d++])!=null){if(c.nodeType!=8){b[a++]=c}}}else{while((c=e[d++])!=null){b[a++]=c}}return b},unique:function(a){var f=[],g={};try{for(var e=0,d=a.length;e<d;e++){var b=T.data(a[e]);if(!g[b]){g[b]=true;f.push(a[e])}}}catch(c){f=a}return f},grep:function(e,a,f){var d=[];for(var c=0,b=e.length;c<b;c++){if(!f!=!a(e[c],c)){d.push(e[c])}}return d},map:function(f,a){var e=[];for(var d=0,c=f.length;d<c;d++){var b=a(f[d],d);if(b!=null){e[e.length]=b}}return e.concat.apply([],e)}});var O=navigator.userAgent.toLowerCase();T.browser={version:(O.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(O),opera:/opera/.test(O),msie:/msie/.test(O)&&!/opera/.test(O),mozilla:/mozilla/.test(O)&&!/(compatible|webkit)/.test(O)};T.each({parent:function(a){return a.parentNode},parents:function(a){return T.dir(a,"parentNode")},next:function(a){return T.nth(a,2,"nextSibling")},prev:function(a){return T.nth(a,2,"previousSibling")},nextAll:function(a){return T.dir(a,"nextSibling")},prevAll:function(a){return T.dir(a,"previousSibling")},siblings:function(a){return T.sibling(a.parentNode.firstChild,a)},children:function(a){return T.sibling(a.firstChild)},contents:function(a){return T.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:T.makeArray(a.childNodes)}},function(b,a){T.fn[b]=function(d){var c=T.map(this,a);if(d&&typeof d=="string"){c=T.multiFilter(d,c)}return this.pushStack(T.unique(c),b,d)}});T.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(b,a){T.fn[b]=function(h){var e=[],c=T(h);for(var d=0,g=c.length;d<g;d++){var f=(d>0?this.clone(true):this).get();T.fn[a].apply(T(c[d]),f);e=e.concat(f)}return this.pushStack(e,b,h)}});T.each({removeAttr:function(a){T.attr(this,a,"");if(this.nodeType==1){this.removeAttribute(a)}},addClass:function(a){T.className.add(this,a)},removeClass:function(a){T.className.remove(this,a)},toggleClass:function(a,b){if(typeof b!=="boolean"){b=!T.className.has(this,a)}T.className[b?"add":"remove"](this,a)},remove:function(a){if(!a||T.filter(a,[this]).length){T("*",this).add([this]).each(function(){T.event.remove(this);T.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){T(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(b,a){T.fn[b]=function(){return this.each(a,arguments)}});function Y(b,a){return b[0]&&parseInt(T.curCSS(b[0],a,true),10)||0}var aa="jQuery"+ad(),I=0,R={};T.extend({cache:{},data:function(c,d,b){c=c==W?R:c;var a=c[aa];if(!a){a=c[aa]=++I}if(d&&!T.cache[a]){T.cache[a]={}}if(b!==ab){T.cache[a][d]=b}return d?T.cache[a][d]:a},removeData:function(c,d){c=c==W?R:c;var a=c[aa];if(d){if(T.cache[a]){delete T.cache[a][d];d="";for(d in T.cache[a]){break}if(!d){T.removeData(c)}}}else{try{delete c[aa]}catch(b){if(c.removeAttribute){c.removeAttribute(aa)}}delete T.cache[a]}},queue:function(c,d,a){if(c){d=(d||"fx")+"queue";var b=T.data(c,d);if(!b||T.isArray(a)){b=T.data(c,d,T.makeArray(a))}else{if(a){b.push(a)}}}return b},dequeue:function(a,b){var d=T.queue(a,b),c=d.shift();if(!b||b==="fx"){c=d[0]}if(c!==ab){c.call(a)}}});T.fn.extend({data:function(d,b){var a=d.split(".");a[1]=a[1]?"."+a[1]:"";if(b===ab){var c=this.triggerHandler("getData"+a[1]+"!",[a[0]]);if(c===ab&&this.length){c=T.data(this[0],d)}return c===ab&&a[1]?this.data(a[0]):c}else{return this.trigger("setData"+a[1]+"!",[a[0],b]).each(function(){T.data(this,d,b)})}},removeData:function(a){return this.each(function(){T.removeData(this,a)})},queue:function(b,a){if(typeof b!=="string"){a=b;b="fx"}if(a===ab){return T.queue(this[0],b)}return this.each(function(){var c=T.queue(this,b,a);if(b=="fx"&&c.length==1){c[0].call(this)}})},dequeue:function(a){return this.each(function(){T.dequeue(this,a)})}});(function(){var b=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,h=0,l=Object.prototype.toString;var n=function(r,v,ai,D){ai=ai||[];v=v||document;if(v.nodeType!==1&&v.nodeType!==9){return[]}if(!r||typeof r!=="string"){return ai}var q=[],t,A,x,w,C,u,s=true;b.lastIndex=0;while((t=b.exec(r))!==null){q.push(t[1]);if(t[2]){u=RegExp.rightContext;break}}if(q.length>1&&g.exec(r)){if(q.length===2&&k.relative[q[0]]){A=j(q[0]+q[1],v)}else{A=k.relative[q[0]]?[v]:n(q.shift(),v);while(q.length){r=q.shift();if(k.relative[r]){r+=q.shift()}A=j(r,A)}}}else{var B=D?{expr:q.pop(),set:o(D)}:n.find(q.pop(),q.length===1&&v.parentNode?v.parentNode:v,c(v));A=n.filter(B.expr,B.set);if(q.length>0){x=o(A)}else{s=false}while(q.length){var y=q.pop(),z=y;if(!k.relative[y]){y=""}else{z=q.pop()}if(z==null){z=v}k.relative[y](x,z,c(v))}}if(!x){x=A}if(!x){throw"Syntax error, unrecognized expression: "+(y||r)}if(l.call(x)==="[object Array]"){if(!s){ai.push.apply(ai,x)}else{if(v.nodeType===1){for(var p=0;x[p]!=null;p++){if(x[p]&&(x[p]===true||x[p].nodeType===1&&i(v,x[p]))){ai.push(A[p])}}}else{for(var p=0;x[p]!=null;p++){if(x[p]&&x[p].nodeType===1){ai.push(A[p])}}}}}else{o(x,ai)}if(u){n(u,v,ai,D);if(m){hasDuplicate=false;ai.sort(m);if(hasDuplicate){for(var p=1;p<ai.length;p++){if(ai[p]===ai[p-1]){ai.splice(p--,1)}}}}}return ai};n.matches=function(q,p){return n(q,null,null,p)};n.find=function(p,w,x){var q,s;if(!p){return[]}for(var t=0,u=k.order.length;t<u;t++){var r=k.order[t],s;if((s=k.match[r].exec(p))){var v=RegExp.leftContext;if(v.substr(v.length-1)!=="\\"){s[1]=(s[1]||"").replace(/\\/g,"");q=k.find[r](s,w,x);if(q!=null){p=p.replace(k.match[r],"");break}}}}if(!q){q=w.getElementsByTagName("*")}return{set:q,expr:p}};n.filter=function(C,D,z,t){var u=C,x=[],p=D,r,w,q=D&&D[0]&&c(D[0]);while(C&&D.length){for(var ai in k.filter){if((r=k.match[ai].exec(C))!=null){var v=k.filter[ai],y,A;w=false;if(p==x){x=[]}if(k.preFilter[ai]){r=k.preFilter[ai](r,p,z,x,t,q);if(!r){w=y=true}else{if(r===true){continue}}}if(r){for(var s=0;(A=p[s])!=null;s++){if(A){y=v(A,r,s,p);var B=t^!!y;if(z&&y!=null){if(B){w=true}else{p[s]=false}}else{if(B){x.push(A);w=true}}}}}if(y!==ab){if(!z){p=x}C=C.replace(k.match[ai],"");if(!w){return[]}break}}}if(C==u){if(w==null){throw"Syntax error, unrecognized expression: "+C}else{break}}u=C}return p};var k=n.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(p){return p.getAttribute("href")}},relative:{"+":function(p,w,q){var s=typeof w==="string",x=s&&!/\W/.test(w),r=s&&!x;if(x&&!q){w=w.toUpperCase()}for(var t=0,u=p.length,v;t<u;t++){if((v=p[t])){while((v=v.previousSibling)&&v.nodeType!==1){}p[t]=r||v&&v.nodeName===w?v||false:v===w}}if(r){n.filter(w,p,true)}},">":function(u,r,t){var w=typeof r==="string";if(w&&!/\W/.test(r)){r=t?r:r.toUpperCase();for(var q=0,s=u.length;q<s;q++){var v=u[q];if(v){var p=v.parentNode;u[q]=p.nodeName===r?p:false}}}else{for(var q=0,s=u.length;q<s;q++){var v=u[q];if(v){u[q]=w?v.parentNode:v.parentNode===r}}if(w){n.filter(r,u,true)}}},"":function(p,r,t){var q=h++,s=a;if(!r.match(/\W/)){var u=r=t?r:r.toUpperCase();s=d}s("parentNode",r,q,p,u,t)},"~":function(p,r,t){var q=h++,s=a;if(typeof r==="string"&&!r.match(/\W/)){var u=r=t?r:r.toUpperCase();s=d}s("previousSibling",r,q,p,u,t)}},find:{ID:function(r,q,p){if(typeof q.getElementById!=="undefined"&&!p){var s=q.getElementById(r[1]);return s?[s]:[]}},NAME:function(q,u,t){if(typeof u.getElementsByName!=="undefined"){var r=[],v=u.getElementsByName(q[1]);for(var p=0,s=v.length;p<s;p++){if(v[p].getAttribute("name")===q[1]){r.push(v[p])}}return r.length===0?null:r}},TAG:function(q,p){return p.getElementsByTagName(q[1])}},preFilter:{CLASS:function(p,r,q,s,u,t){p=" "+p[1].replace(/\\/g,"")+" ";if(t){return p}for(var w=0,v;(v=r[w])!=null;w++){if(v){if(u^(v.className&&(" "+v.className+" ").indexOf(p)>=0)){if(!q){s.push(v)}}else{if(q){r[w]=false}}}}return false},ID:function(p){return p[1].replace(/\\/g,"")},TAG:function(q,r){for(var p=0;r[p]===false;p++){}return r[p]&&c(r[p])?q[1]:q[1].toUpperCase()},CHILD:function(q){if(q[1]=="nth"){var p=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(q[2]=="even"&&"2n"||q[2]=="odd"&&"2n+1"||!/\D/.test(q[2])&&"0n+"+q[2]||q[2]);q[2]=(p[1]+(p[2]||1))-0;q[3]=p[3]-0}q[0]=h++;return q},ATTR:function(v,r,q,s,u,t){var p=v[1].replace(/\\/g,"");if(!t&&k.attrMap[p]){v[1]=k.attrMap[p]}if(v[2]==="~="){v[4]=" "+v[4]+" "}return v},PSEUDO:function(u,r,q,s,t){if(u[1]==="not"){if(u[3].match(b).length>1||/^\w/.test(u[3])){u[3]=n(u[3],null,null,r)}else{var p=n.filter(u[3],r,q,true^t);if(!q){s.push.apply(s,p)}return false}}else{if(k.match.POS.test(u[0])||k.match.CHILD.test(u[0])){return true}}return u},POS:function(p){p.unshift(true);return p}},filters:{enabled:function(p){return p.disabled===false&&p.type!=="hidden"},disabled:function(p){return p.disabled===true},checked:function(p){return p.checked===true},selected:function(p){p.parentNode.selectedIndex;return p.selected===true},parent:function(p){return !!p.firstChild},empty:function(p){return !p.firstChild},has:function(p,q,r){return !!n(r[3],p).length},header:function(p){return/h\d/i.test(p.nodeName)},text:function(p){return"text"===p.type},radio:function(p){return"radio"===p.type},checkbox:function(p){return"checkbox"===p.type},file:function(p){return"file"===p.type},password:function(p){return"password"===p.type},submit:function(p){return"submit"===p.type},image:function(p){return"image"===p.type},reset:function(p){return"reset"===p.type},button:function(p){return"button"===p.type||p.nodeName.toUpperCase()==="BUTTON"},input:function(p){return/input|select|textarea|button/i.test(p.nodeName)}},setFilters:{first:function(p,q){return q===0},last:function(q,r,s,p){return r===p.length-1},even:function(p,q){return q%2===0},odd:function(p,q){return q%2===1},lt:function(p,q,r){return q<r[3]-0},gt:function(p,q,r){return q>r[3]-0},nth:function(p,q,r){return r[3]-0==q},eq:function(p,q,r){return r[3]-0==q}},filter:{PSEUDO:function(u,q,p,t){var r=q[1],w=k.filters[r];if(w){return w(u,p,q,t)}else{if(r==="contains"){return(u.textContent||u.innerText||"").indexOf(q[3])>=0}else{if(r==="not"){var v=q[3];for(var p=0,s=v.length;p<s;p++){if(v[p]===u){return false}}return true}}}},CHILD:function(w,t){var q=t[1],v=w;switch(q){case"only":case"first":while(v=v.previousSibling){if(v.nodeType===1){return false}}if(q=="first"){return true}v=w;case"last":while(v=v.nextSibling){if(v.nodeType===1){return false}}return true;case"nth":var u=t[2],x=t[3];if(u==1&&x==0){return true}var r=t[0],y=w.parentNode;if(y&&(y.sizcache!==r||!w.nodeIndex)){var s=0;for(v=y.firstChild;v;v=v.nextSibling){if(v.nodeType===1){v.nodeIndex=++s}}y.sizcache=r}var p=w.nodeIndex-x;if(u==0){return p==0}else{return(p%u==0&&p/u>=0)}}},ID:function(p,q){return p.nodeType===1&&p.getAttribute("id")===q},TAG:function(p,q){return(q==="*"&&p.nodeType===1)||p.nodeName===q},CLASS:function(p,q){return(" "+(p.className||p.getAttribute("class"))+" ").indexOf(q)>-1},ATTR:function(u,p){var q=p[1],s=k.attrHandle[q]?k.attrHandle[q](u):u[q]!=null?u[q]:u.getAttribute(q),t=s+"",v=p[2],r=p[4];return s==null?v==="!=":v==="="?t===r:v==="*="?t.indexOf(r)>=0:v==="~="?(" "+t+" ").indexOf(r)>=0:!r?t&&s!==false:v==="!="?t!=r:v==="^="?t.indexOf(r)===0:v==="$="?t.substr(t.length-r.length)===r:v==="|="?t===r||t.substr(0,r.length+1)===r+"-":false},POS:function(u,r,q,t){var s=r[2],p=k.setFilters[s];if(p){return p(u,q,r,t)}}}};var g=k.match.POS;for(var e in k.match){k.match[e]=RegExp(k.match[e].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var o=function(p,q){p=Array.prototype.slice.call(p);if(q){q.push.apply(q,p);return q}return p};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(f){o=function(t,p){var r=p||[];if(l.call(t)==="[object Array]"){Array.prototype.push.apply(r,t)}else{if(typeof t.length==="number"){for(var q=0,s=t.length;q<s;q++){r.push(t[q])}}else{for(var q=0;t[q];q++){r.push(t[q])}}}return r}}var m;if(document.documentElement.compareDocumentPosition){m=function(q,r){var p=q.compareDocumentPosition(r)&4?-1:q===r?0:1;if(p===0){hasDuplicate=true}return p}}else{if("sourceIndex" in document.documentElement){m=function(q,r){var p=q.sourceIndex-r.sourceIndex;if(p===0){hasDuplicate=true}return p}}else{if(document.createRange){m=function(p,r){var q=p.ownerDocument.createRange(),s=r.ownerDocument.createRange();q.selectNode(p);q.collapse(true);s.selectNode(r);s.collapse(true);var t=q.compareBoundaryPoints(Range.START_TO_END,s);if(t===0){hasDuplicate=true}return t}}}}(function(){var q=document.createElement("form"),p="script"+(new Date).getTime();q.innerHTML="<input name='"+p+"'/>";var r=document.documentElement;r.insertBefore(q,r.firstChild);if(!!document.getElementById(p)){k.find.ID=function(v,u,t){if(typeof u.getElementById!=="undefined"&&!t){var s=u.getElementById(v[1]);return s?s.id===v[1]||typeof s.getAttributeNode!=="undefined"&&s.getAttributeNode("id").nodeValue===v[1]?[s]:ab:[]}};k.filter.ID=function(t,s){var u=typeof t.getAttributeNode!=="undefined"&&t.getAttributeNode("id");return t.nodeType===1&&u&&u.nodeValue===s}}r.removeChild(q)})();(function(){var p=document.createElement("div");p.appendChild(document.createComment(""));if(p.getElementsByTagName("*").length>0){k.find.TAG=function(s,t){var u=t.getElementsByTagName(s[1]);if(s[1]==="*"){var q=[];for(var r=0;u[r];r++){if(u[r].nodeType===1){q.push(u[r])}}u=q}return u}}p.innerHTML="<a href='#'></a>";if(p.firstChild&&typeof p.firstChild.getAttribute!=="undefined"&&p.firstChild.getAttribute("href")!=="#"){k.attrHandle.href=function(q){return q.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var q=n,p=document.createElement("div");p.innerHTML="<p class='TEST'></p>";if(p.querySelectorAll&&p.querySelectorAll(".TEST").length===0){return}n=function(u,v,s,r){v=v||document;if(!r&&v.nodeType===9&&!c(v)){try{return o(v.querySelectorAll(u),s)}catch(t){}}return q(u,v,s,r)};n.find=q.find;n.filter=q.filter;n.selectors=q.selectors;n.matches=q.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var p=document.createElement("div");p.innerHTML="<div class='test e'></div><div class='test'></div>";if(p.getElementsByClassName("e").length===0){return}p.lastChild.className="e";if(p.getElementsByClassName("e").length===1){return}k.order.splice(1,0,"CLASS");k.find.CLASS=function(s,r,q){if(typeof r.getElementsByClassName!=="undefined"&&!q){return r.getElementsByClassName(s[1])}}})()}function d(v,q,r,x,p,y){var z=v=="previousSibling"&&!y;for(var t=0,u=x.length;t<u;t++){var w=x[t];if(w){if(z&&w.nodeType===1){w.sizcache=r;w.sizset=t}w=w[v];var s=false;while(w){if(w.sizcache===r){s=x[w.sizset];break}if(w.nodeType===1&&!y){w.sizcache=r;w.sizset=t}if(w.nodeName===q){s=w;break}w=w[v]}x[t]=s}}}function a(v,q,r,x,p,y){var z=v=="previousSibling"&&!y;for(var t=0,u=x.length;t<u;t++){var w=x[t];if(w){if(z&&w.nodeType===1){w.sizcache=r;w.sizset=t}w=w[v];var s=false;while(w){if(w.sizcache===r){s=x[w.sizset];break}if(w.nodeType===1){if(!y){w.sizcache=r;w.sizset=t}if(typeof q!=="string"){if(w===q){s=true;break}}else{if(n.filter(q,[w]).length>0){s=w;break}}}w=w[v]}x[t]=s}}}var i=document.compareDocumentPosition?function(p,q){return p.compareDocumentPosition(q)&16}:function(p,q){return p!==q&&(p.contains?p.contains(q):true)};var c=function(p){return p.nodeType===9&&p.documentElement.nodeName!=="HTML"||!!p.ownerDocument&&c(p.ownerDocument)};var j=function(s,u){var p=[],w="",v,q=u.nodeType?[u]:u;while((v=k.match.PSEUDO.exec(s))){w+=v[0];s=s.replace(k.match.PSEUDO,"")}s=k.relative[s]?s+"*":s;for(var t=0,r=q.length;t<r;t++){n(s,q[t],p)}return n.filter(w,p)};T.find=n;T.filter=n.filter;T.expr=n.selectors;T.expr[":"]=T.expr.filters;n.selectors.filters.hidden=function(p){return p.offsetWidth===0||p.offsetHeight===0};n.selectors.filters.visible=function(p){return p.offsetWidth>0||p.offsetHeight>0};n.selectors.filters.animated=function(p){return T.grep(T.timers,function(q){return p===q.elem}).length};T.multiFilter=function(p,r,q){if(q){p=":not("+p+")"}return n.matches(p,r)};T.dir=function(q,r){var s=[],p=q[r];while(p&&p!=document){if(p.nodeType==1){s.push(p)}p=p[r]}return s};T.nth=function(t,s,q,p){s=s||1;var r=0;for(;t;t=t[q]){if(t.nodeType==1&&++r==s){break}}return t};T.sibling=function(p,q){var r=[];for(;p;p=p.nextSibling){if(p.nodeType==1&&p!=q){r.push(p)}}return r};return;W.Sizzle=n})();T.event={add:function(c,f,d,a){if(c.nodeType==3||c.nodeType==8){return}if(c.setInterval&&c!=W){c=W}if(!d.guid){d.guid=this.guid++}if(a!==ab){var e=d;d=this.proxy(e);d.data=a}var g=T.data(c,"events")||T.data(c,"events",{}),b=T.data(c,"handle")||T.data(c,"handle",function(){return typeof T!=="undefined"&&!T.event.triggered?T.event.handle.apply(arguments.callee.elem,arguments):ab});b.elem=c;T.each(f.split(/\s+/),function(k,j){var i=j.split(".");j=i.shift();d.type=i.slice().sort().join(".");var h=g[j];if(T.event.specialAll[j]){T.event.specialAll[j].setup.call(c,a,i)}if(!h){h=g[j]={};if(!T.event.special[j]||T.event.special[j].setup.call(c,a,i)===false){if(c.addEventListener){c.addEventListener(j,b,false)}else{if(c.attachEvent){c.attachEvent("on"+j,b)}}}}h[d.guid]=d;T.event.global[j]=true});c=null},guid:1,global:{},remove:function(b,e,c){if(b.nodeType==3||b.nodeType==8){return}var f=T.data(b,"events"),g,h;if(f){if(e===ab||(typeof e==="string"&&e.charAt(0)==".")){for(var d in f){this.remove(b,d+(e||""))}}else{if(e.type){c=e.handler;e=e.type}T.each(e.split(/\s+/),function(m,k){var i=k.split(".");k=i.shift();var l=RegExp("(^|\\.)"+i.slice().sort().join(".*\\.")+"(\\.|$)");if(f[k]){if(c){delete f[k][c.guid]}else{for(var j in f[k]){if(l.test(f[k][j].type)){delete f[k][j]}}}if(T.event.specialAll[k]){T.event.specialAll[k].teardown.call(b,i)}for(g in f[k]){break}if(!g){if(!T.event.special[k]||T.event.special[k].teardown.call(b,i)===false){if(b.removeEventListener){b.removeEventListener(k,T.data(b,"handle"),false)}else{if(b.detachEvent){b.detachEvent("on"+k,T.data(b,"handle"))}}}g=null;delete f[k]}}})}for(g in f){break}if(!g){var a=T.data(b,"handle");if(a){a.elem=null}T.removeData(b,"events");T.removeData(b,"handle")}}},trigger:function(d,b,e,h){var f=d.type||d;if(!h){d=typeof d==="object"?d[aa]?d:T.extend(T.Event(f),d):T.Event(f);if(f.indexOf("!")>=0){d.type=f=f.slice(0,-1);d.exclusive=true}if(!e){d.stopPropagation();if(this.global[f]){T.each(T.cache,function(){if(this.events&&this.events[f]){T.event.trigger(d,b,this.handle.elem)}})}}if(!e||e.nodeType==3||e.nodeType==8){return ab}d.result=ab;d.target=e;b=T.makeArray(b);b.unshift(d)}d.currentTarget=e;var c=T.data(e,"handle");if(c){c.apply(e,b)}if((!e[f]||(T.nodeName(e,"a")&&f=="click"))&&e["on"+f]&&e["on"+f].apply(e,b)===false){d.result=false}if(!h&&e[f]&&!d.isDefaultPrevented()&&!(T.nodeName(e,"a")&&f=="click")){this.triggered=true;try{e[f]()}catch(a){}}this.triggered=false;if(!d.isPropagationStopped()){var g=e.parentNode||e.ownerDocument;if(g){T.event.trigger(d,b,g,true)}}},handle:function(b){var c,h;b=arguments[0]=T.event.fix(b||W.event);b.currentTarget=this;var a=b.type.split(".");b.type=a.shift();c=!a.length&&!b.exclusive;var d=RegExp("(^|\\.)"+a.slice().sort().join(".*\\.")+"(\\.|$)");h=(T.data(this,"events")||{})[b.type];for(var f in h){var e=h[f];if(c||d.test(e.type)){b.handler=e;b.data=e.data;var g=e.apply(this,arguments);if(g!==ab){b.result=g;if(g===false){b.preventDefault();b.stopPropagation()}}if(b.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(c){if(c[aa]){return c}var e=c;c=T.Event(e);for(var d=this.props.length,a;d;){a=this.props[--d];c[a]=e[a]}if(!c.target){c.target=c.srcElement||document}if(c.target.nodeType==3){c.target=c.target.parentNode}if(!c.relatedTarget&&c.fromElement){c.relatedTarget=c.fromElement==c.target?c.toElement:c.fromElement}if(c.pageX==null&&c.clientX!=null){var b=document.documentElement,f=document.body;c.pageX=c.clientX+(b&&b.scrollLeft||f&&f.scrollLeft||0)-(b.clientLeft||0);c.pageY=c.clientY+(b&&b.scrollTop||f&&f.scrollTop||0)-(b.clientTop||0)}if(!c.which&&((c.charCode||c.charCode===0)?c.charCode:c.keyCode)){c.which=c.charCode||c.keyCode}if(!c.metaKey&&c.ctrlKey){c.metaKey=c.ctrlKey}if(!c.which&&c.button){c.which=(c.button&1?1:(c.button&2?3:(c.button&4?2:0)))}return c},proxy:function(a,b){b=b||function(){return a.apply(this,arguments)};b.guid=a.guid=a.guid||b.guid||this.guid++;return b},special:{ready:{setup:P,teardown:function(){}}},specialAll:{live:{setup:function(b,a){T.event.add(this,a[0],af)},teardown:function(a){if(a.length){var c=0,b=RegExp("(^|\\.)"+a[0]+"(\\.|$)");T.each((T.data(this,"events").live||{}),function(){if(b.test(this.type)){c++}});if(c<1){T.event.remove(this,a[0],af)}}}}}};T.Event=function(a){if(!this.preventDefault){return new T.Event(a)}if(a&&a.type){this.originalEvent=a;this.type=a.type}else{this.type=a}this.timeStamp=ad();this[aa]=true};function X(){return false}function J(){return true}T.Event.prototype={preventDefault:function(){this.isDefaultPrevented=J;var a=this.originalEvent;if(!a){return}if(a.preventDefault){a.preventDefault()}a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=J;var a=this.originalEvent;if(!a){return}if(a.stopPropagation){a.stopPropagation()}a.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=J;this.stopPropagation()},isDefaultPrevented:X,isPropagationStopped:X,isImmediatePropagationStopped:X};var ah=function(b){var c=b.relatedTarget;while(c&&c!=this){try{c=c.parentNode}catch(a){c=this}}if(c!=this){b.type=b.data;T.event.handle.apply(this,arguments)}};T.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(a,b){T.event.special[b]={setup:function(){T.event.add(this,a,ah,b)},teardown:function(){T.event.remove(this,a,ah)}}});T.fn.extend({bind:function(b,a,c){return b=="unload"?this.one(b,a,c):this.each(function(){T.event.add(this,b,c||a,c&&a)})},one:function(b,a,c){var d=T.event.proxy(c||a,function(e){T(this).unbind(e,d);return(c||a).apply(this,arguments)});return this.each(function(){T.event.add(this,b,d,c&&a)})},unbind:function(a,b){return this.each(function(){T.event.remove(this,a,b)})},trigger:function(b,a){return this.each(function(){T.event.trigger(b,a,this)})},triggerHandler:function(c,a){if(this[0]){var b=T.Event(c);b.preventDefault();b.stopPropagation();T.event.trigger(b,a,this[0]);return b.result}},toggle:function(a){var c=arguments,b=1;while(b<c.length){T.event.proxy(a,c[b++])}return this.click(T.event.proxy(a,function(d){this.lastToggle=(this.lastToggle||0)%b;d.preventDefault();return c[this.lastToggle++].apply(this,arguments)||false}))},hover:function(b,a){return this.mouseenter(b).mouseleave(a)},ready:function(a){P();if(T.isReady){a.call(document,T)}else{T.readyList.push(a)}return this},live:function(a,b){var c=T.event.proxy(b);c.guid+=this.selector+a;T(document).bind(Z(a,this.selector),this.selector,c);return this},die:function(a,b){T(document).unbind(Z(a,this.selector),b?{guid:b.guid+this.selector+a}:null);return this}});function af(a){var d=RegExp("(^|\\.)"+a.type+"(\\.|$)"),b=true,c=[];T.each(T.data(this,"events").live||[],function(g,f){if(d.test(f.type)){var e=T(a.target).closest(f.data)[0];if(e){c.push({elem:e,fn:f})}}});c.sort(function(e,f){return T.data(e.elem,"closest")-T.data(f.elem,"closest")});T.each(c,function(){if(this.fn.call(this.elem,a,this.fn.data)===false){return(b=false)}});return b}function Z(a,b){return["live",a,b.replace(/\./g,"`").replace(/ /g,"|")].join(".")}T.extend({isReady:false,readyList:[],ready:function(){if(!T.isReady){T.isReady=true;if(T.readyList){T.each(T.readyList,function(){this.call(document,T)});T.readyList=null}T(document).triggerHandler("ready")}}});var G=false;function P(){if(G){return}G=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);T.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);T.ready()}});if(document.documentElement.doScroll&&W==W.top){(function(){if(T.isReady){return}try{document.documentElement.doScroll("left")}catch(a){setTimeout(arguments.callee,0);return}T.ready()})()}}}T.event.add(W,"load",T.ready)}T.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(a,b){T.fn[b]=function(c){return c?this.bind(b,c):this.trigger(b)}});T(W).bind("unload",function(){for(var a in T.cache){if(a!=1&&T.cache[a].handle){T.event.remove(T.cache[a].handle.elem)}}});(function(){T.support={};var f=document.documentElement,e=document.createElement("script"),a=document.createElement("div"),b="script"+(new Date).getTime();a.style.display="none";a.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 d=a.getElementsByTagName("*"),g=a.getElementsByTagName("a")[0];if(!d||!d.length||!g){return}T.support={leadingWhitespace:a.firstChild.nodeType==3,tbody:!a.getElementsByTagName("tbody").length,objectAll:!!a.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/red/.test(g.getAttribute("style")),hrefNormalized:g.getAttribute("href")==="/a",opacity:g.style.opacity==="0.5",cssFloat:!!g.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};e.type="text/javascript";try{e.appendChild(document.createTextNode("window."+b+"=1;"))}catch(c){}f.insertBefore(e,f.firstChild);if(W[b]){T.support.scriptEval=true;delete W[b]}f.removeChild(e);if(a.attachEvent&&a.fireEvent){a.attachEvent("onclick",function(){T.support.noCloneEvent=false;a.detachEvent("onclick",arguments.callee)});a.cloneNode(true).fireEvent("onclick")}T(function(){var h=document.createElement("div");h.style.width=h.style.paddingLeft="1px";document.body.appendChild(h);T.boxModel=T.support.boxModel=h.offsetWidth===2;document.body.removeChild(h).style.display="none"})})();var H=T.support.cssFloat?"cssFloat":"styleFloat";T.props={"for":"htmlFor","class":"className","float":H,cssFloat:H,styleFloat:H,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};T.fn.extend({_load:T.fn.load,load:function(e,b,a){if(typeof e!=="string"){return this._load(e)}var c=e.indexOf(" ");if(c>=0){var g=e.slice(c,e.length);e=e.slice(0,c)}var d="GET";if(b){if(T.isFunction(b)){a=b;b=null}else{if(typeof b==="object"){b=T.param(b);d="POST"}}}var f=this;T.ajax({url:e,type:d,dataType:"html",data:b,complete:function(i,h){if(h=="success"||h=="notmodified"){f.html(g?T("<div/>").append(i.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(g):i.responseText)}if(a){f.each(a,[i.responseText,h,i])}}});return this},serialize:function(){return T.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?T.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(c,b){var a=T(this).val();return a==null?null:T.isArray(a)?T.map(a,function(d,e){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});T.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(b,a){T.fn[a]=function(c){return this.bind(a,c)}});var N=ad();T.extend({get:function(d,b,a,c){if(T.isFunction(b)){a=b;b=null}return T.ajax({type:"GET",url:d,data:b,success:a,dataType:c})},getScript:function(b,a){return T.get(b,null,a,"script")},getJSON:function(c,b,a){return T.get(c,b,a,"json")},post:function(d,b,a,c){if(T.isFunction(b)){a=b;b={}}return T.ajax({type:"POST",url:d,data:b,success:a,dataType:c})},ajaxSetup:function(a){T.extend(T.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return W.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:"*/*"}},lastModified:{},ajax:function(k){k=T.extend(true,k,T.extend(true,{},T.ajaxSettings,k));var a,r=/=\?(&|$)/g,f,b,q=k.type.toUpperCase();if(k.data&&k.processData&&typeof k.data!=="string"){k.data=T.param(k.data)}if(k.dataType=="jsonp"){if(q=="GET"){if(!k.url.match(r)){k.url+=(k.url.match(/\?/)?"&":"?")+(k.jsonp||"callback")+"=?"}}else{if(!k.data||!k.data.match(r)){k.data=(k.data?k.data+"&":"")+(k.jsonp||"callback")+"=?"}}k.dataType="json"}if(k.dataType=="json"&&(k.data&&k.data.match(r)||k.url.match(r))){a="jsonp"+N++;if(k.data){k.data=(k.data+"").replace(r,"="+a+"$1")}k.url=k.url.replace(r,"="+a+"$1");k.dataType="script";W[a]=function(u){b=u;o();l();W[a]=ab;try{delete W[a]}catch(t){}if(p){p.removeChild(d)}}}if(k.dataType=="script"&&k.cache==null){k.cache=false}if(k.cache===false&&q=="GET"){var s=ad();var c=k.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+s+"$2");k.url=c+((c==k.url)?(k.url.match(/\?/)?"&":"?")+"_="+s:"")}if(k.data&&q=="GET"){k.url+=(k.url.match(/\?/)?"&":"?")+k.data;k.data=null}if(k.global&&!T.active++){T.event.trigger("ajaxStart")}var g=/^(\w+:)?\/\/([^\/?#]+)/.exec(k.url);if(k.dataType=="script"&&q=="GET"&&g&&(g[1]&&g[1]!=location.protocol||g[2]!=location.host)){var p=document.getElementsByTagName("head")[0];var d=document.createElement("script");d.src=k.url;if(k.scriptCharset){d.charset=k.scriptCharset}if(!a){var i=false;d.onload=d.onreadystatechange=function(){if(!i&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){i=true;o();l();d.onload=d.onreadystatechange=null;p.removeChild(d)}}}p.appendChild(d);return ab}var m=false;var n=k.xhr();if(k.username){n.open(q,k.url,k.async,k.username,k.password)}else{n.open(q,k.url,k.async)}try{if(k.data){n.setRequestHeader("Content-Type",k.contentType)}if(k.ifModified){n.setRequestHeader("If-Modified-Since",T.lastModified[k.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}n.setRequestHeader("X-Requested-With","XMLHttpRequest");n.setRequestHeader("Accept",k.dataType&&k.accepts[k.dataType]?k.accepts[k.dataType]+", */*":k.accepts._default)}catch(e){}if(k.beforeSend&&k.beforeSend(n,k)===false){if(k.global&&!--T.active){T.event.trigger("ajaxStop")}n.abort();return false}if(k.global){T.event.trigger("ajaxSend",[n,k])}var j=function(v){if(n.readyState==0){if(h){clearInterval(h);h=null;if(k.global&&!--T.active){T.event.trigger("ajaxStop")}}}else{if(!m&&n&&(n.readyState==4||v=="timeout")){m=true;if(h){clearInterval(h);h=null}f=v=="timeout"?"timeout":!T.httpSuccess(n)?"error":k.ifModified&&T.httpNotModified(n,k.url)?"notmodified":"success";if(f=="success"){try{b=T.httpData(n,k.dataType,k)}catch(t){f="parsererror"}}if(f=="success"){var u;try{u=n.getResponseHeader("Last-Modified")}catch(t){}if(k.ifModified&&u){T.lastModified[k.url]=u}if(!a){o()}}else{T.handleError(k,n,f)}l();if(v){n.abort()}if(k.async){n=null}}}};if(k.async){var h=setInterval(j,13);if(k.timeout>0){setTimeout(function(){if(n&&!m){j("timeout")}},k.timeout)}}try{n.send(k.data)}catch(e){T.handleError(k,n,null,e)}if(!k.async){j()}function o(){if(k.success){k.success(b,f)}if(k.global){T.event.trigger("ajaxSuccess",[n,k])}}function l(){if(k.complete){k.complete(n,f)}if(k.global){T.event.trigger("ajaxComplete",[n,k])}if(k.global&&!--T.active){T.event.trigger("ajaxStop")}}return n},handleError:function(c,a,d,b){if(c.error){c.error(a,d,b)}if(c.global){T.event.trigger("ajaxError",[a,c,b])}},active:0,httpSuccess:function(a){try{return !a.status&&location.protocol=="file:"||(a.status>=200&&a.status<300)||a.status==304||a.status==1223}catch(b){}return false},httpNotModified:function(b,d){try{var a=b.getResponseHeader("Last-Modified");return b.status==304||a==T.lastModified[d]}catch(c){}return false},httpData:function(a,c,d){var e=a.getResponseHeader("content-type"),f=c=="xml"||!c&&e&&e.indexOf("xml")>=0,b=f?a.responseXML:a.responseText;if(f&&b.documentElement.tagName=="parsererror"){throw"parsererror"}if(d&&d.dataFilter){b=d.dataFilter(b,c)}if(typeof b==="string"){if(c=="script"){T.globalEval(b)}if(c=="json"){b=W["eval"]("("+b+")")}}return b},param:function(d){var b=[];function a(f,e){b[b.length]=encodeURIComponent(f)+"="+encodeURIComponent(e)}if(T.isArray(d)||d.jquery){T.each(d,function(){a(this.name,this.value)})}else{for(var c in d){if(T.isArray(d[c])){T.each(d[c],function(){a(c,this)})}else{a(c,T.isFunction(d[c])?d[c]():d[c])}}}return b.join("&").replace(/%20/g,"+")}});var V={},U,ae=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function K(b,c){var a={};T.each(ae.concat.apply([],ae.slice(0,c)),function(){a[this]=b});return a}T.fn.extend({show:function(c,a){if(c){return this.animate(K("show",3),c,a)}else{for(var e=0,g=this.length;e<g;e++){var h=T.data(this[e],"olddisplay");this[e].style.display=h||"";if(T.css(this[e],"display")==="none"){var f=this[e].tagName,b;if(V[f]){b=V[f]}else{var d=T("<"+f+" />").appendTo("body");b=d.css("display");if(b==="none"){b="block"}d.remove();V[f]=b}T.data(this[e],"olddisplay",b)}}for(var e=0,g=this.length;e<g;e++){this[e].style.display=T.data(this[e],"olddisplay")||""}return this}},hide:function(b,a){if(b){return this.animate(K("hide",3),b,a)}else{for(var c=0,d=this.length;c<d;c++){var e=T.data(this[c],"olddisplay");if(!e&&e!=="none"){T.data(this[c],"olddisplay",T.css(this[c],"display"))}}for(var c=0,d=this.length;c<d;c++){this[c].style.display="none"}return this}},_toggle:T.fn.toggle,toggle:function(a,b){var c=typeof a==="boolean";return T.isFunction(a)&&T.isFunction(b)?this._toggle.apply(this,arguments):a==null||c?this.each(function(){var d=c?a:T(this).is(":hidden");T(this)[d?"show":"hide"]()}):this.animate(K("toggle",3),a,b)},fadeTo:function(c,a,b){return this.animate({opacity:a},c,b)},animate:function(a,d,b,c){var e=T.speed(d,b,c);return this[e.queue===false?"each":"queue"](function(){var g=T.extend({},e),i,f=this.nodeType==1&&T(this).is(":hidden"),h=this;for(i in a){if(a[i]=="hide"&&f||a[i]=="show"&&!f){return g.complete.call(this)}if((i=="height"||i=="width")&&this.style){g.display=T.css(this,"display");g.overflow=this.style.overflow}}if(g.overflow!=null){this.style.overflow="hidden"}g.curAnim=T.extend({},a);T.each(a,function(o,k){var l=new T.fx(h,g,o);if(/toggle|show|hide/.test(k)){l[k=="toggle"?f?"show":"hide":k](a)}else{var m=k.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),j=l.cur(true)||0;if(m){var p=parseFloat(m[2]),n=m[3]||"px";if(n!="px"){h.style[o]=(p||1)+n;j=((p||1)/l.cur(true))*j;h.style[o]=j+n}if(m[1]){p=((m[1]=="-="?-1:1)*p)+j}l.custom(j,p,n)}else{l.custom(j,k,"")}}});return true})},stop:function(b,c){var a=T.timers;if(b){this.queue([])}this.each(function(){for(var d=a.length-1;d>=0;d--){if(a[d].elem==this){if(c){a[d](true)}a.splice(d,1)}}});if(!c){this.dequeue()}return this}});T.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(b,a){T.fn[b]=function(d,c){return this.animate(a,d,c)}});T.extend({speed:function(b,a,c){var d=typeof b==="object"?b:{complete:c||!c&&a||T.isFunction(b)&&b,duration:b,easing:c&&a||a&&!T.isFunction(a)&&a};d.duration=T.fx.off?0:typeof d.duration==="number"?d.duration:T.fx.speeds[d.duration]||T.fx.speeds._default;d.old=d.complete;d.complete=function(){if(d.queue!==false){T(this).dequeue()}if(T.isFunction(d.old)){d.old.call(this)}};return d},easing:{linear:function(b,a,d,c){return d+c*b},swing:function(b,a,d,c){return((-Math.cos(b*Math.PI)/2)+0.5)*c+d}},timers:[],fx:function(b,c,a){this.options=c;this.elem=b;this.prop=a;if(!c.orig){c.orig={}}}});T.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(T.fx.step[this.prop]||T.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var b=parseFloat(T.css(this.elem,this.prop,a));return b&&b>-10000?b:parseFloat(T.curCSS(this.elem,this.prop))||0},custom:function(a,b,c){this.startTime=ad();this.start=a;this.end=b;this.unit=c||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;function d(f){return e.step(f)}d.elem=this.elem;if(d()&&T.timers.push(d)&&!U){U=setInterval(function(){var f=T.timers;for(var g=0;g<f.length;g++){if(!f[g]()){f.splice(g--,1)}}if(!f.length){clearInterval(U);U=ab}},13)}},show:function(){this.options.orig[this.prop]=T.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());T(this.elem).show()},hide:function(){this.options.orig[this.prop]=T.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(c){var d=ad();if(c||d>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var f=true;for(var e in this.options.curAnim){if(this.options.curAnim[e]!==true){f=false}}if(f){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(T.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){T(this.elem).hide()}if(this.options.hide||this.options.show){for(var b in this.options.curAnim){T.attr(this.elem.style,b,this.options.orig[b])}}this.options.complete.call(this.elem)}return false}else{var a=d-this.startTime;this.state=a/this.options.duration;this.pos=T.easing[this.options.easing||(T.easing.swing?"swing":"linear")](this.state,a,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};T.extend(T.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){T.attr(a.elem.style,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null){a.elem.style[a.prop]=a.now+a.unit}else{a.elem[a.prop]=a.now}}}});if(document.documentElement.getBoundingClientRect){T.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return T.offset.bodyOffset(this[0])}var f=this[0].getBoundingClientRect(),c=this[0].ownerDocument,g=c.body,h=c.documentElement,a=h.clientTop||g.clientTop||0,b=h.clientLeft||g.clientLeft||0,d=f.top+(self.pageYOffset||T.boxModel&&h.scrollTop||g.scrollTop)-a,e=f.left+(self.pageXOffset||T.boxModel&&h.scrollLeft||g.scrollLeft)-b;return{top:d,left:e}}}else{T.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return T.offset.bodyOffset(this[0])}T.offset.initialized||T.offset.initialize();var f=this[0],i=f.offsetParent,j=f,a=f.ownerDocument,c,h=a.documentElement,e=a.body,d=a.defaultView,k=d.getComputedStyle(f,null),b=f.offsetTop,g=f.offsetLeft;while((f=f.parentNode)&&f!==e&&f!==h){c=d.getComputedStyle(f,null);b-=f.scrollTop,g-=f.scrollLeft;if(f===i){b+=f.offsetTop,g+=f.offsetLeft;if(T.offset.doesNotAddBorder&&!(T.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(f.tagName))){b+=parseInt(c.borderTopWidth,10)||0,g+=parseInt(c.borderLeftWidth,10)||0}j=i,i=f.offsetParent}if(T.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"){b+=parseInt(c.borderTopWidth,10)||0,g+=parseInt(c.borderLeftWidth,10)||0}k=c}if(k.position==="relative"||k.position==="static"){b+=e.offsetTop,g+=e.offsetLeft}if(k.position==="fixed"){b+=Math.max(h.scrollTop,e.scrollTop),g+=Math.max(h.scrollLeft,e.scrollLeft)}return{top:b,left:g}}}T.offset={initialize:function(){if(this.initialized){return}var c=document.body,i=document.createElement("div"),g,h,a,f,b,j,e=c.style.marginTop,d='<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>';b={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(j in b){i.style[j]=b[j]}i.innerHTML=d;c.insertBefore(i,c.firstChild);g=i.firstChild,h=g.firstChild,f=g.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(h.offsetTop!==5);this.doesAddBorderForTableAndCells=(f.offsetTop===5);g.style.overflow="hidden",g.style.position="relative";this.subtractsBorderForOverflowNotVisible=(h.offsetTop===-5);c.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(c.offsetTop===0);c.style.marginTop=e;c.removeChild(i);this.initialized=true},bodyOffset:function(c){T.offset.initialized||T.offset.initialize();var a=c.offsetTop,b=c.offsetLeft;if(T.offset.doesNotIncludeMarginInBodyOffset){a+=parseInt(T.curCSS(c,"marginTop",true),10)||0,b+=parseInt(T.curCSS(c,"marginLeft",true),10)||0}return{top:a,left:b}}};T.fn.extend({position:function(){var b=0,c=0,e;if(this[0]){var d=this.offsetParent(),a=this.offset(),f=/^body|html$/i.test(d[0].tagName)?{top:0,left:0}:d.offset();a.top-=Y(this,"marginTop");a.left-=Y(this,"marginLeft");f.top+=Y(d,"borderTopWidth");f.left+=Y(d,"borderLeftWidth");e={top:a.top-f.top,left:a.left-f.left}}return e},offsetParent:function(){var a=this[0].offsetParent||document.body;while(a&&(!/^body|html$/i.test(a.tagName)&&T.css(a,"position")=="static")){a=a.offsetParent}return T(a)}});T.each(["Left","Top"],function(b,c){var a="scroll"+c;T.fn[a]=function(d){if(!this[0]){return null}return d!==ab?this.each(function(){this==W||this==document?W.scrollTo(!b?d:T(W).scrollLeft(),b?d:T(W).scrollTop()):this[a]=d}):this[0]==W||this[0]==document?self[b?"pageYOffset":"pageXOffset"]||T.boxModel&&document.documentElement[a]||document.body[a]:this[0][a]}});T.each(["Height","Width"],function(b,d){var f=b?"Left":"Top",c=b?"Right":"Bottom",e=d.toLowerCase();T.fn["inner"+d]=function(){return this[0]?T.css(this[0],e,false,"padding"):null};T.fn["outer"+d]=function(g){return this[0]?T.css(this[0],e,false,g?"margin":"border"):null};var a=d.toLowerCase();T.fn[a]=function(g){return this[0]==W?document.compatMode=="CSS1Compat"&&document.documentElement["client"+d]||document.body["client"+d]:this[0]==document?Math.max(document.documentElement["client"+d],document.body["scroll"+d],document.documentElement["scroll"+d],document.body["offset"+d],document.documentElement["offset"+d]):g===ab?(this.length?T.css(this[0],a):null):this.css(a,typeof g==="string"?g:g+"px")}})})();

jQuery.fn.center=function(){this.css("position","absolute");this.css("top",(jQuery(window).height()-this.height())/2+jQuery(window).scrollTop()+"px");this.css("left",(jQuery(window).width()-this.width())/2+jQuery(window).scrollLeft()+"px");return this};

jQuery.bt={version:"0.9.5-rc1"};(function($){jQuery.fn.bt=function(content,options){if(typeof content!="string"){var contentSelect=true;options=content;content=false}else{var contentSelect=false}if(jQuery.fn.hoverIntent&&jQuery.bt.defaults.trigger=="hover"){jQuery.bt.defaults.trigger="hoverIntent"}return this.each(function(index){var opts=jQuery.extend(false,jQuery.bt.defaults,jQuery.bt.options,options);opts.spikeLength=numb(opts.spikeLength);opts.spikeGirth=numb(opts.spikeGirth);opts.overlap=numb(opts.overlap);var ajaxTimeout=false;if(opts.killTitle){$(this).find("[title]").andSelf().each(function(){if(!$(this).attr("bt-xTitle")){$(this).attr("bt-xTitle",$(this).attr("title")).attr("title","")}})}if(typeof opts.trigger=="string"){opts.trigger=[opts.trigger]}if(opts.trigger[0]=="hoverIntent"){var hoverOpts=jQuery.extend(opts.hoverIntentOpts,{over:function(){this.btOn()},out:function(){this.btOff()}});$(this).hoverIntent(hoverOpts)}else{if(opts.trigger[0]=="hover"){$(this).hover(function(){this.btOn()},function(){this.btOff()})}else{if(opts.trigger[0]=="now"){if($(this).hasClass("bt-active")){this.btOff()}else{this.btOn()}}else{if(opts.trigger[0]=="none"){}else{if(opts.trigger.length>1&&opts.trigger[0]!=opts.trigger[1]){$(this).bind(opts.trigger[0],function(){this.btOn()}).bind(opts.trigger[1],function(){this.btOff()})}else{$(this).bind(opts.trigger[0],function(){if($(this).hasClass("bt-active")){this.btOff()}else{this.btOn()}})}}}}}this.btOn=function(){if(typeof $(this).data("bt-box")=="object"){this.btOff()}opts.preBuild.apply(this);$(jQuery.bt.vars.closeWhenOpenStack).btOff();$(this).addClass("bt-active "+opts.activeClass);if(contentSelect&&opts.ajaxPath==null){if(opts.killTitle){$(this).attr("title",$(this).attr("bt-xTitle"))}content=$.isFunction(opts.contentSelector)?opts.contentSelector.apply(this):eval(opts.contentSelector);if(opts.killTitle){$(this).attr("title","")}}if(opts.ajaxPath!=null&&content==false){if(typeof opts.ajaxPath=="object"){var url=eval(opts.ajaxPath[0]);url+=opts.ajaxPath[1]?" "+opts.ajaxPath[1]:""}else{var url=opts.ajaxPath}var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off)}var cacheData=opts.ajaxCache?$(document.body).data("btCache-"+url.replace(/\./g,"")):null;if(typeof cacheData=="string"){content=selector?$("<div/>").append(cacheData.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):cacheData}else{var target=this;var ajaxOpts=jQuery.extend(false,{type:opts.ajaxType,data:opts.ajaxData,cache:opts.ajaxCache,url:url,complete:function(XMLHttpRequest,textStatus){if(textStatus=="success"||textStatus=="notmodified"){if(opts.ajaxCache){$(document.body).data("btCache-"+url.replace(/\./g,""),XMLHttpRequest.responseText)}ajaxTimeout=false;content=selector?$("<div/>").append(XMLHttpRequest.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):XMLHttpRequest.responseText}else{if(textStatus=="timeout"){ajaxTimeout=true}content=opts.ajaxError.replace(/%error/g,XMLHttpRequest.statusText)}if($(target).hasClass("bt-active")){target.btOn()}}},opts.ajaxOpts);jQuery.ajax(ajaxOpts);content=opts.ajaxLoading}}var shadowMarginX=0;var shadowMarginY=0;var shadowShiftX=0;var shadowShiftY=0;if(opts.shadow&&!shadowSupport()){opts.shadow=false;jQuery.extend(opts,opts.noShadowOpts)}if(opts.shadow){if(opts.shadowBlur>Math.abs(opts.shadowOffsetX)){shadowMarginX=opts.shadowBlur*2}else{shadowMarginX=opts.shadowBlur+Math.abs(opts.shadowOffsetX)}shadowShiftX=(opts.shadowBlur-opts.shadowOffsetX)>0?opts.shadowBlur-opts.shadowOffsetX:0;if(opts.shadowBlur>Math.abs(opts.shadowOffsetY)){shadowMarginY=opts.shadowBlur*2}else{shadowMarginY=opts.shadowBlur+Math.abs(opts.shadowOffsetY)}shadowShiftY=(opts.shadowBlur-opts.shadowOffsetY)>0?opts.shadowBlur-opts.shadowOffsetY:0}if(opts.offsetParent){var offsetParent=$(opts.offsetParent);var offsetParentPos=offsetParent.offset();var pos=$(this).offset();var top=numb(pos.top)-numb(offsetParentPos.top)+numb($(this).css("margin-top"))-shadowShiftY;var left=numb(pos.left)-numb(offsetParentPos.left)+numb($(this).css("margin-left"))-shadowShiftX}else{var offsetParent=($(this).css("position")=="absolute")?$(this).parents().eq(0).offsetParent():$(this).offsetParent();var pos=$(this).btPosition();var top=numb(pos.top)+numb($(this).css("margin-top"))-shadowShiftY;var left=numb(pos.left)+numb($(this).css("margin-left"))-shadowShiftX}var width=$(this).btOuterWidth();var height=$(this).outerHeight();if(typeof content=="object"){var original=content;var clone=$(original).clone(true).show();var origClones=$(original).data("bt-clones")||[];origClones.push(clone);$(original).data("bt-clones",origClones);$(clone).data("bt-orig",original);$(this).data("bt-content-orig",{original:original,clone:clone});content=clone}if(typeof content=="null"||content==""){return}var $text=$('<div class="bt-content"></div>').append(content).css({padding:opts.padding,position:"absolute",width:(opts.shrinkToFit?"auto":opts.width),zIndex:opts.textzIndex,left:shadowShiftX,top:shadowShiftY}).css(opts.cssStyles);var $box=$('<div class="bt-wrapper"></div>').append($text).addClass(opts.cssClass).css({position:"absolute",width:opts.width,zIndex:opts.wrapperzIndex,visibility:"hidden"}).appendTo(offsetParent);if(jQuery.fn.bgiframe){$text.bgiframe();$box.bgiframe()}$(this).data("bt-box",$box);var scrollTop=numb($(document).scrollTop());var scrollLeft=numb($(document).scrollLeft());var docWidth=numb($(window).width());var docHeight=numb($(window).height());var winRight=scrollLeft+docWidth;var winBottom=scrollTop+docHeight;var space=new Object();var thisOffset=$(this).offset();space.top=thisOffset.top-scrollTop;space.bottom=docHeight-((thisOffset+height)-scrollTop);space.left=thisOffset.left-scrollLeft;space.right=docWidth-((thisOffset.left+width)-scrollLeft);var textOutHeight=numb($text.outerHeight());var textOutWidth=numb($text.btOuterWidth());if(opts.positions.constructor==String){opts.positions=opts.positions.replace(/ /,"").split(",")}if(opts.positions[0]=="most"){var position="top";for(var pig in space){position=space[pig]>space[position]?pig:position}}else{for(var x in opts.positions){var position=opts.positions[x];if((position=="left"||position=="right")&&space[position]>textOutWidth+opts.spikeLength){break}else{if((position=="top"||position=="bottom")&&space[position]>textOutHeight+opts.spikeLength){break}}}}var horiz=left+((width-textOutWidth)*0.5);var vert=top+((height-textOutHeight)*0.5);var points=new Array();var textTop,textLeft,textRight,textBottom,textTopSpace,textBottomSpace,textLeftSpace,textRightSpace,crossPoint,textCenter,spikePoint;switch(position){case"top":$text.css("margin-bottom",opts.spikeLength+"px");$box.css({top:(top-$text.outerHeight(true))+opts.overlap,left:horiz});textRightSpace=(winRight-opts.windowMargin)-($text.offset().left+$text.btOuterWidth(true));var xShift=shadowShiftX;if(textRightSpace<0){$box.css("left",(numb($box.css("left"))+textRightSpace)+"px");xShift-=textRightSpace}textLeftSpace=($text.offset().left+numb($text.css("margin-left")))-(scrollLeft+opts.windowMargin);if(textLeftSpace<0){$box.css("left",(numb($box.css("left"))-textLeftSpace)+"px");xShift+=textLeftSpace}textTop=$text.btPosition().top+numb($text.css("margin-top"));textLeft=$text.btPosition().left+numb($text.css("margin-left"));textRight=textLeft+$text.btOuterWidth();textBottom=textTop+$text.outerHeight();textCenter={x:textLeft+($text.btOuterWidth()*opts.centerPointX),y:textTop+($text.outerHeight()*opts.centerPointY)};points[points.length]=spikePoint={y:textBottom+opts.spikeLength,x:((textRight-textLeft)*0.5)+xShift,type:"spike"};crossPoint=findIntersectX(spikePoint.x,spikePoint.y,textCenter.x,textCenter.y,textBottom);crossPoint.x=crossPoint.x<textLeft+opts.spikeGirth/2+opts.cornerRadius?textLeft+opts.spikeGirth/2+opts.cornerRadius:crossPoint.x;crossPoint.x=crossPoint.x>(textRight-opts.spikeGirth/2)-opts.cornerRadius?(textRight-opts.spikeGirth/2)-opts.CornerRadius:crossPoint.x;points[points.length]={x:crossPoint.x-(opts.spikeGirth/2),y:textBottom,type:"join"};points[points.length]={x:textLeft,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:textTop,type:"corner"};points[points.length]={x:textRight,y:textTop,type:"corner"};points[points.length]={x:textRight,y:textBottom,type:"corner"};points[points.length]={x:crossPoint.x+(opts.spikeGirth/2),y:textBottom,type:"join"};points[points.length]=spikePoint;break;case"left":$text.css("margin-right",opts.spikeLength+"px");$box.css({top:vert+"px",left:((left-$text.btOuterWidth(true))+opts.overlap)+"px"});textBottomSpace=(winBottom-opts.windowMargin)-($text.offset().top+$text.outerHeight(true));var yShift=shadowShiftY;if(textBottomSpace<0){$box.css("top",(numb($box.css("top"))+textBottomSpace)+"px");yShift-=textBottomSpace}textTopSpace=($text.offset().top+numb($text.css("margin-top")))-(scrollTop+opts.windowMargin);if(textTopSpace<0){$box.css("top",(numb($box.css("top"))-textTopSpace)+"px");yShift+=textTopSpace}textTop=$text.btPosition().top+numb($text.css("margin-top"));textLeft=$text.btPosition().left+numb($text.css("margin-left"));textRight=textLeft+$text.btOuterWidth();textBottom=textTop+$text.outerHeight();textCenter={x:textLeft+($text.btOuterWidth()*opts.centerPointX),y:textTop+($text.outerHeight()*opts.centerPointY)};points[points.length]=spikePoint={x:textRight+opts.spikeLength,y:((textBottom-textTop)*0.5)+yShift,type:"spike"};crossPoint=findIntersectY(spikePoint.x,spikePoint.y,textCenter.x,textCenter.y,textRight);crossPoint.y=crossPoint.y<textTop+opts.spikeGirth/2+opts.cornerRadius?textTop+opts.spikeGirth/2+opts.cornerRadius:crossPoint.y;crossPoint.y=crossPoint.y>(textBottom-opts.spikeGirth/2)-opts.cornerRadius?(textBottom-opts.spikeGirth/2)-opts.cornerRadius:crossPoint.y;points[points.length]={x:textRight,y:crossPoint.y+opts.spikeGirth/2,type:"join"};points[points.length]={x:textRight,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:textTop,type:"corner"};points[points.length]={x:textRight,y:textTop,type:"corner"};points[points.length]={x:textRight,y:crossPoint.y-opts.spikeGirth/2,type:"join"};points[points.length]=spikePoint;break;case"bottom":$text.css("margin-top",opts.spikeLength+"px");$box.css({top:(top+height)-opts.overlap,left:horiz});textRightSpace=(winRight-opts.windowMargin)-($text.offset().left+$text.btOuterWidth(true));var xShift=shadowShiftX;if(textRightSpace<0){$box.css("left",(numb($box.css("left"))+textRightSpace)+"px");xShift-=textRightSpace}textLeftSpace=($text.offset().left+numb($text.css("margin-left")))-(scrollLeft+opts.windowMargin);if(textLeftSpace<0){$box.css("left",(numb($box.css("left"))-textLeftSpace)+"px");xShift+=textLeftSpace}textTop=$text.btPosition().top+numb($text.css("margin-top"));textLeft=$text.btPosition().left+numb($text.css("margin-left"));textRight=textLeft+$text.btOuterWidth();textBottom=textTop+$text.outerHeight();textCenter={x:textLeft+($text.btOuterWidth()*opts.centerPointX),y:textTop+($text.outerHeight()*opts.centerPointY)};points[points.length]=spikePoint={x:((textRight-textLeft)*0.5)+xShift,y:shadowShiftY,type:"spike"};crossPoint=findIntersectX(spikePoint.x,spikePoint.y,textCenter.x,textCenter.y,textTop);crossPoint.x=crossPoint.x<textLeft+opts.spikeGirth/2+opts.cornerRadius?textLeft+opts.spikeGirth/2+opts.cornerRadius:crossPoint.x;crossPoint.x=crossPoint.x>(textRight-opts.spikeGirth/2)-opts.cornerRadius?(textRight-opts.spikeGirth/2)-opts.cornerRadius:crossPoint.x;points[points.length]={x:crossPoint.x+opts.spikeGirth/2,y:textTop,type:"join"};points[points.length]={x:textRight,y:textTop,type:"corner"};points[points.length]={x:textRight,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:textTop,type:"corner"};points[points.length]={x:crossPoint.x-(opts.spikeGirth/2),y:textTop,type:"join"};points[points.length]=spikePoint;break;case"right":$text.css("margin-left",(opts.spikeLength+"px"));$box.css({top:vert+"px",left:((left+width)-opts.overlap)+"px"});textBottomSpace=(winBottom-opts.windowMargin)-($text.offset().top+$text.outerHeight(true));var yShift=shadowShiftY;if(textBottomSpace<0){$box.css("top",(numb($box.css("top"))+textBottomSpace)+"px");yShift-=textBottomSpace}textTopSpace=($text.offset().top+numb($text.css("margin-top")))-(scrollTop+opts.windowMargin);if(textTopSpace<0){$box.css("top",(numb($box.css("top"))-textTopSpace)+"px");yShift+=textTopSpace}textTop=$text.btPosition().top+numb($text.css("margin-top"));textLeft=$text.btPosition().left+numb($text.css("margin-left"));textRight=textLeft+$text.btOuterWidth();textBottom=textTop+$text.outerHeight();textCenter={x:textLeft+($text.btOuterWidth()*opts.centerPointX),y:textTop+($text.outerHeight()*opts.centerPointY)};points[points.length]=spikePoint={x:shadowShiftX,y:((textBottom-textTop)*0.5)+yShift,type:"spike"};crossPoint=findIntersectY(spikePoint.x,spikePoint.y,textCenter.x,textCenter.y,textLeft);crossPoint.y=crossPoint.y<textTop+opts.spikeGirth/2+opts.cornerRadius?textTop+opts.spikeGirth/2+opts.cornerRadius:crossPoint.y;crossPoint.y=crossPoint.y>(textBottom-opts.spikeGirth/2)-opts.cornerRadius?(textBottom-opts.spikeGirth/2)-opts.cornerRadius:crossPoint.y;points[points.length]={x:textLeft,y:crossPoint.y-opts.spikeGirth/2,type:"join"};points[points.length]={x:textLeft,y:textTop,type:"corner"};points[points.length]={x:textRight,y:textTop,type:"corner"};points[points.length]={x:textRight,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:textBottom,type:"corner"};points[points.length]={x:textLeft,y:crossPoint.y+opts.spikeGirth/2,type:"join"};points[points.length]=spikePoint;break}var canvas=document.createElement("canvas");$(canvas).attr("width",(numb($text.btOuterWidth(true))+opts.strokeWidth*2+shadowMarginX)).attr("height",(numb($text.outerHeight(true))+opts.strokeWidth*2+shadowMarginY)).appendTo($box).css({position:"absolute",zIndex:opts.boxzIndex});if(typeof G_vmlCanvasManager!="undefined"){canvas=G_vmlCanvasManager.initElement(canvas)}if(opts.cornerRadius>0){var newPoints=new Array();var newPoint;for(var i=0;i<points.length;i++){if(points[i].type=="corner"){newPoint=betweenPoint(points[i],points[(i-1)%points.length],opts.cornerRadius);newPoint.type="arcStart";newPoints[newPoints.length]=newPoint;newPoints[newPoints.length]=points[i];newPoint=betweenPoint(points[i],points[(i+1)%points.length],opts.cornerRadius);newPoint.type="arcEnd";newPoints[newPoints.length]=newPoint}else{newPoints[newPoints.length]=points[i]}}points=newPoints}var ctx=canvas.getContext("2d");if(opts.shadow&&opts.shadowOverlap!==true){var shadowOverlap=numb(opts.shadowOverlap);switch(position){case"top":if(opts.shadowOffsetX+opts.shadowBlur-shadowOverlap>0){$box.css("top",(numb($box.css("top"))-(opts.shadowOffsetX+opts.shadowBlur-shadowOverlap)))}break;case"right":if(shadowShiftX-shadowOverlap>0){$box.css("left",(numb($box.css("left"))+shadowShiftX-shadowOverlap))}break;case"bottom":if(shadowShiftY-shadowOverlap>0){$box.css("top",(numb($box.css("top"))+shadowShiftY-shadowOverlap))}break;case"left":if(opts.shadowOffsetY+opts.shadowBlur-shadowOverlap>0){$box.css("left",(numb($box.css("left"))-(opts.shadowOffsetY+opts.shadowBlur-shadowOverlap)))}break}}drawIt.apply(ctx,[points],opts.strokeWidth);ctx.fillStyle=opts.fill;if(opts.shadow){ctx.shadowOffsetX=opts.shadowOffsetX;ctx.shadowOffsetY=opts.shadowOffsetY;ctx.shadowBlur=opts.shadowBlur;ctx.shadowColor=opts.shadowColor}ctx.closePath();ctx.fill();if(opts.strokeWidth>0){ctx.shadowColor="rgba(0, 0, 0, 0)";ctx.lineWidth=opts.strokeWidth;ctx.strokeStyle=opts.strokeStyle;ctx.beginPath();drawIt.apply(ctx,[points],opts.strokeWidth);ctx.closePath();ctx.stroke()}opts.preShow.apply(this,[$box[0]]);$box.css({display:"none",visibility:"visible"});opts.showTip.apply(this,[$box[0]]);if(opts.overlay){var overlay=$('<div class="bt-overlay"></div>').css({position:"absolute",backgroundColor:"blue",top:top,left:left,width:width,height:height,opacity:".2"}).appendTo(offsetParent);$(this).data("overlay",overlay)}if((opts.ajaxPath!=null&&opts.ajaxCache==false)||ajaxTimeout){content=false}if(opts.clickAnywhereToClose){jQuery.bt.vars.clickAnywhereStack.push(this);$(document).click(jQuery.bt.docClick)}if(opts.closeWhenOthersOpen){jQuery.bt.vars.closeWhenOpenStack.push(this)}opts.postShow.apply(this,[$box[0]])};this.btOff=function(){var box=$(this).data("bt-box");opts.preHide.apply(this,[box]);var i=this;i.btCleanup=function(){var box=$(i).data("bt-box");var contentOrig=$(i).data("bt-content-orig");var overlay=$(i).data("bt-overlay");if(typeof box=="object"){$(box).remove();$(i).removeData("bt-box")}if(typeof contentOrig=="object"){var clones=$(contentOrig.original).data("bt-clones");$(contentOrig).data("bt-clones",arrayRemove(clones,contentOrig.clone))}if(typeof overlay=="object"){$(overlay).remove();$(i).removeData("bt-overlay")}jQuery.bt.vars.clickAnywhereStack=arrayRemove(jQuery.bt.vars.clickAnywhereStack,i);jQuery.bt.vars.closeWhenOpenStack=arrayRemove(jQuery.bt.vars.closeWhenOpenStack,i);$(i).removeClass("bt-active "+opts.activeClass);opts.postHide.apply(i)};opts.hideTip.apply(this,[box,i.btCleanup])};var refresh=this.btRefresh=function(){this.btOff();this.btOn()}});function drawIt(points,strokeWidth){this.moveTo(points[0].x,points[0].y);for(i=1;i<points.length;i++){if(points[i-1].type=="arcStart"){this.quadraticCurveTo(round5(points[i].x,strokeWidth),round5(points[i].y,strokeWidth),round5(points[(i+1)%points.length].x,strokeWidth),round5(points[(i+1)%points.length].y,strokeWidth));i++}else{this.lineTo(round5(points[i].x,strokeWidth),round5(points[i].y,strokeWidth))}}}function round5(num,strokeWidth){var ret;strokeWidth=numb(strokeWidth);if(strokeWidth%2){ret=num}else{ret=Math.round(num-0.5)+0.5}return ret}function numb(num){return parseInt(num)||0}function arrayRemove(arr,elem){var x,newArr=new Array();for(x in arr){if(arr[x]!=elem){newArr.push(arr[x])}}return newArr}function canvasSupport(){var canvas_compatible=false;try{canvas_compatible=!!(document.createElement("canvas").getContext("2d"))}catch(e){canvas_compatible=!!(document.createElement("canvas").getContext)}return canvas_compatible}function shadowSupport(){try{var userAgent=navigator.userAgent.toLowerCase();if(/webkit/.test(userAgent)){return true}else{if(/gecko|mozilla/.test(userAgent)&&parseFloat(userAgent.match(/firefox\/(\d+(?:\.\d+)+)/)[1])>=3.1){return true}}}catch(err){}return false}function betweenPoint(point1,point2,dist){var y,x;if(point1.x==point2.x){y=point1.y<point2.y?point1.y+dist:point1.y-dist;return{x:point1.x,y:y}}else{if(point1.y==point2.y){x=point1.x<point2.x?point1.x+dist:point1.x-dist;return{x:x,y:point1.y}}}}function centerPoint(arcStart,corner,arcEnd){var x=corner.x==arcStart.x?arcEnd.x:arcStart.x;var y=corner.y==arcStart.y?arcEnd.y:arcStart.y;var startAngle,endAngle;if(arcStart.x<arcEnd.x){if(arcStart.y>arcEnd.y){startAngle=(Math.PI/180)*180;endAngle=(Math.PI/180)*90}else{startAngle=(Math.PI/180)*90;endAngle=0}}else{if(arcStart.y>arcEnd.y){startAngle=(Math.PI/180)*270;endAngle=(Math.PI/180)*180}else{startAngle=0;endAngle=(Math.PI/180)*270}}return{x:x,y:y,type:"center",startAngle:startAngle,endAngle:endAngle}}function findIntersect(r1x1,r1y1,r1x2,r1y2,r2x1,r2y1,r2x2,r2y2){if(r2x1==r2x2){return findIntersectY(r1x1,r1y1,r1x2,r1y2,r2x1)}if(r2y1==r2y2){return findIntersectX(r1x1,r1y1,r1x2,r1y2,r2y1)}var r1m=(r1y1-r1y2)/(r1x1-r1x2);var r1b=r1y1-(r1m*r1x1);var r2m=(r2y1-r2y2)/(r2x1-r2x2);var r2b=r2y1-(r2m*r2x1);var x=(r2b-r1b)/(r1m-r2m);var y=r1m*x+r1b;return{x:x,y:y}}function findIntersectY(r1x1,r1y1,r1x2,r1y2,x){if(r1y1==r1y2){return{x:x,y:r1y1}}var r1m=(r1y1-r1y2)/(r1x1-r1x2);var r1b=r1y1-(r1m*r1x1);var y=r1m*x+r1b;return{x:x,y:y}}function findIntersectX(r1x1,r1y1,r1x2,r1y2,y){if(r1x1==r1x2){return{x:r1x1,y:y}}var r1m=(r1y1-r1y2)/(r1x1-r1x2);var r1b=r1y1-(r1m*r1x1);var x=(y-r1b)/r1m;return{x:x,y:y}}};jQuery.fn.btPosition=function(){function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0}var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,"marginTop");offset.left-=num(this,"marginLeft");parentOffset.top+=num(offsetParent,"borderTopWidth");parentOffset.left+=num(offsetParent,"borderLeftWidth");results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left}}return results};jQuery.fn.btOuterWidth=function(margin){function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0}return this["innerWidth"]()+num(this,"borderLeftWidth")+num(this,"borderRightWidth")+(margin?num(this,"marginLeft")+num(this,"marginRight"):0)};jQuery.fn.btOn=function(){return this.each(function(index){if(jQuery.isFunction(this.btOn)){this.btOn()}})};jQuery.fn.btOff=function(){return this.each(function(index){if(jQuery.isFunction(this.btOff)){this.btOff()}})};jQuery.bt.vars={clickAnywhereStack:[],closeWhenOpenStack:[]};jQuery.bt.docClick=function(e){if(!e){var e=window.event}if(!$(e.target).parents().andSelf().filter(".bt-wrapper, .bt-active").length&&jQuery.bt.vars.clickAnywhereStack.length){$(jQuery.bt.vars.clickAnywhereStack).btOff();$(document).unbind("click",jQuery.bt.docClick)}};jQuery.bt.defaults={trigger:"hover",clickAnywhereToClose:true,closeWhenOthersOpen:false,shrinkToFit:false,width:"200px",padding:"10px",spikeGirth:10,spikeLength:15,overlap:0,overlay:false,killTitle:true,textzIndex:9999,boxzIndex:9998,wrapperzIndex:9997,offsetParent:null,positions:["most"],fill:"rgb(255, 255, 102)",windowMargin:10,strokeWidth:1,strokeStyle:"#000",cornerRadius:5,centerPointX:0.5,centerPointY:0.5,shadow:false,shadowOffsetX:2,shadowOffsetY:2,shadowBlur:3,shadowColor:"#000",shadowOverlap:false,noShadowOpts:{strokeStyle:"#999"},cssClass:"",cssStyles:{},activeClass:"bt-active",contentSelector:"$(this).attr('title')",ajaxPath:null,ajaxError:"<strong>ERROR:</strong> <em>%error</em>",ajaxLoading:"<blink>Loading...</blink>",ajaxData:{},ajaxType:"GET",ajaxCache:true,ajaxOpts:{},preBuild:function(){},preShow:function(box){},showTip:function(box){$(box).show()},postShow:function(box){},preHide:function(box){},hideTip:function(box,callback){$(box).hide();callback()},postHide:function(){},hoverIntentOpts:{interval:300,timeout:500}};jQuery.bt.options={}})(jQuery);

var visural_inputHints=[];function VisuralInputHint(a,d,b,c){this.inputId=a;this.hintText=d;this.hintStyle=b;this.entryStyle=c;this.handleFocus=function(){if(jQuery("#"+this.inputId).val()===this.hintText){jQuery("#"+this.inputId).attr("style",this.entryStyle);jQuery("#"+this.inputId).val("")}};this.handleBlur=function(){if(!jQuery("#"+this.inputId).val()){jQuery("#"+this.inputId).attr("style",this.hintStyle);jQuery("#"+this.inputId).val(this.hintText)}}};
