; // semicolon to terminate inline code before this block
/*!
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){

var 
	// Will speed up references to window, and allows munging its name.
	window = this,
	// Will speed up references to undefined, and allows munging its name.
	undefined,
	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,
	// Map over the $ in case of overwrite
	_$ = window.$,

	jQuery = window.jQuery = window.$ = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context );
	},

	// A simple way to check for HTML strings or ID strings
	// (both of which we optimize for)
	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
	// Is it a simple selector
	isSimple = /^.[^:#\[\.,]*$/;

jQuery.fn = jQuery.prototype = {
	init: function( selector, context ) {
		// Make sure that a selection was provided
		selector = selector || document;

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this[0] = selector;
			this.length = 1;
			this.context = selector;
			return this;
		}
		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			var match = quickExpr.exec( selector );

			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] )
					selector = jQuery.clean( [ match[1] ], context );

				// HANDLE: $("#id")
				else {
					var elem = document.getElementById( match[3] );

					// Handle the case where IE and Opera return items
					// by name instead of ID
					if ( elem && elem.id != match[3] )
						return jQuery().find( selector );

					// Otherwise, we inject the element directly into the jQuery object
					var ret = jQuery( elem || [] );
					ret.context = document;
					ret.selector = selector;
					return ret;
				}

			// HANDLE: $(expr, [context])
			// (which is just equivalent to: $(content).find(expr)
			} else
				return jQuery( context ).find( selector );

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) )
			return jQuery( document ).ready( selector );

		// Make sure that old selector state is passed along
		if ( selector.selector && selector.context ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return this.setArray(jQuery.isArray( selector ) ?
			selector :
			jQuery.makeArray(selector));
	},

	// Start with an empty selector
	selector: "",

	// The current version of jQuery being used
	jquery: "1.3.2",

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num === undefined ?

			// Return a 'clean' array
			Array.prototype.slice.call( this ) :

			// Return just the object
			this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {
		// Build a new jQuery matched element set
		var ret = jQuery( elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		ret.context = this.context;

		if ( name === "find" )
			ret.selector = this.selector + (this.selector ? " " : "") + selector;
		else if ( name )
			ret.selector = this.selector + "." + name + "(" + selector + ")";

		// Return the newly-formed element set
		return ret;
	},

	// Force the current matched set of elements to become
	// the specified array of elements (destroying the stack in the process)
	// You should use pushStack() in order to do this, but maintain the stack
	setArray: function( elems ) {
		// Resetting the length to 0, then using the native Array push
		// is a super-fast way to populate an object with array-like properties
		this.length = 0;
		Array.prototype.push.apply( this, elems );

		return this;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem && elem.jquery ? elem[0] : elem
		, this );
	},

	attr: function( name, value, type ) {
		var options = name;

		// Look for the case where we're accessing a style value
		if ( typeof name === "string" )
			if ( value === undefined )
				return this[0] && jQuery[ type || "attr" ]( this[0], name );

			else {
				options = {};
				options[ name ] = value;
			}

		// Check to see if we're setting style values
		return this.each(function(i){
			// Set all the styles
			for ( name in options )
				jQuery.attr(
					type ?
						this.style :
						this,
					name, jQuery.prop( this, options[ name ], type, i, name )
				);
		});
	},

	css: function( key, value ) {
		// ignore negative width and height values
		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
			value = undefined;
		return this.attr( key, value, "curCSS" );
	},

	text: function( text ) {
		if ( typeof text !== "object" && text != null )
			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

		var ret = "";

		jQuery.each( text || this, function(){
			jQuery.each( this.childNodes, function(){
				if ( this.nodeType != 8 )
					ret += this.nodeType != 1 ?
						this.nodeValue :
						jQuery.fn.text( [ this ] );
			});
		});

		return ret;
	},

	wrapAll: function( html ) {
		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).clone();

			if ( this[0].parentNode )
				wrap.insertBefore( this[0] );

			wrap.map(function(){
				var elem = this;

				while ( elem.firstChild )
					elem = elem.firstChild;

				return elem;
			}).append(this);
		}

		return this;
	},

	wrapInner: function( html ) {
		return this.each(function(){
			jQuery( this ).contents().wrapAll( html );
		});
	},

	wrap: function( html ) {
		return this.each(function(){
			jQuery( this ).wrapAll( html );
		});
	},

	append: function() {
		return this.domManip(arguments, true, function(elem){
			if (this.nodeType == 1)
				this.appendChild( elem );
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, function(elem){
			if (this.nodeType == 1)
				this.insertBefore( elem, this.firstChild );
		});
	},

	before: function() {
		return this.domManip(arguments, false, function(elem){
			this.parentNode.insertBefore( elem, this );
		});
	},

	after: function() {
		return this.domManip(arguments, false, function(elem){
			this.parentNode.insertBefore( elem, this.nextSibling );
		});
	},

	end: function() {
		return this.prevObject || jQuery( [] );
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: [].push,
	sort: [].sort,
	splice: [].splice,

	find: function( selector ) {
		if ( this.length === 1 ) {
			var ret = this.pushStack( [], "find", selector );
			ret.length = 0;
			jQuery.find( selector, this[0], ret );
			return ret;
		} else {
			return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
				return jQuery.find( selector, elem );
			})), "find", selector );
		}
	},

	clone: function( events ) {
		// Do the clone
		var ret = this.map(function(){
			if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
				// IE copies events bound via attachEvent when
				// using cloneNode. Calling detachEvent on the
				// clone will also remove the events from the orignal
				// In order to get around this, we use innerHTML.
				// Unfortunately, this means some modifications to
				// attributes in IE that are actually only stored
				// as properties will not be copied (such as the
				// the name attribute on an input).
				var html = this.outerHTML;
				if ( !html ) {
					var div = this.ownerDocument.createElement("div");
					div.appendChild( this.cloneNode(true) );
					html = div.innerHTML;
				}

				return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
			} else
				return this.cloneNode(true);
		});

		// Copy the events from the original to the clone
		if ( events === true ) {
			var orig = this.find("*").andSelf(), i = 0;

			ret.find("*").andSelf().each(function(){
				if ( this.nodeName !== orig[i].nodeName )
					return;

				var events = jQuery.data( orig[i], "events" );

				for ( var type in events ) {
					for ( var handler in events[ type ] ) {
						jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
					}
				}

				i++;
			});
		}

		// Return the cloned set
		return ret;
	},

	filter: function( selector ) {
		return this.pushStack(
			jQuery.isFunction( selector ) &&
			jQuery.grep(this, function(elem, i){
				return selector.call( elem, i );
			}) ||

			jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
				return elem.nodeType === 1;
			}) ), "filter", selector );
	},

	closest: function( selector ) {
		var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
			closer = 0;

		return this.map(function(){
			var cur = this;
			while ( cur && cur.ownerDocument ) {
				if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
					jQuery.data(cur, "closest", closer);
					return cur;
				}
				cur = cur.parentNode;
				closer++;
			}
		});
	},

	not: function( selector ) {
		if ( typeof selector === "string" )
			// test special case where just one selector is passed in
			if ( isSimple.test( selector ) )
				return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
			else
				selector = jQuery.multiFilter( selector, this );

		var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
		return this.filter(function() {
			return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
		});
	},

	add: function( selector ) {
		return this.pushStack( jQuery.unique( jQuery.merge(
			this.get(),
			typeof selector === "string" ?
				jQuery( selector ) :
				jQuery.makeArray( selector )
		)));
	},

	is: function( selector ) {
		return !!selector && jQuery.multiFilter( selector, this ).length > 0;
	},

	hasClass: function( selector ) {
		return !!selector && this.is( "." + selector );
	},

	val: function( value ) {
		if ( value === undefined ) {			
			var elem = this[0];

			if ( elem ) {
				if( jQuery.nodeName( elem, 'option' ) )
					return (elem.attributes.value || {}).specified ? elem.value : elem.text;
				
				// We need to handle select boxes special
				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type == "select-one";

					// Nothing was selected
					if ( index < 0 )
						return null;

					// Loop through all the selected options
					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
						var option = options[ i ];

						if ( option.selected ) {
							// Get the specifc value for the option
							value = jQuery(option).val();

							// We don't need an array for one selects
							if ( one )
								return value;

							// Multi-Selects return an array
							values.push( value );
						}
					}

					return values;				
				}

				// Everything else, we just grab the value
				return (elem.value || "").replace(/\r/g, "");

			}

			return undefined;
		}

		if ( typeof value === "number" )
			value += '';

		return this.each(function(){
			if ( this.nodeType != 1 )
				return;

			if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
				this.checked = (jQuery.inArray(this.value, value) >= 0 ||
					jQuery.inArray(this.name, value) >= 0);

			else if ( jQuery.nodeName( this, "select" ) ) {
				var values = jQuery.makeArray(value);

				jQuery( "option", this ).each(function(){
					this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
						jQuery.inArray( this.text, values ) >= 0);
				});

				if ( !values.length )
					this.selectedIndex = -1;

			} else
				this.value = value;
		});
	},

	html: function( value ) {
		return value === undefined ?
			(this[0] ?
				this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
				null) :
			this.empty().append( value );
	},

	replaceWith: function( value ) {
		return this.after( value ).remove();
	},

	eq: function( i ) {
		return this.slice( i, +i + 1 );
	},

	slice: function() {
		return this.pushStack( Array.prototype.slice.apply( this, arguments ),
			"slice", Array.prototype.slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function(elem, i){
			return callback.call( elem, i, elem );
		}));
	},

	andSelf: function() {
		return this.add( this.prevObject );
	},

	domManip: function( args, table, callback ) {
		if ( this[0] ) {
			var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
				scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
				first = fragment.firstChild;

			if ( first )
				for ( var i = 0, l = this.length; i < l; i++ )
					callback.call( root(this[i], first), this.length > 1 || i > 0 ?
							fragment.cloneNode(true) : fragment );
		
			if ( scripts )
				jQuery.each( scripts, evalScript );
		}

		return this;
		
		function root( elem, cur ) {
			return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
				(elem.getElementsByTagName("tbody")[0] ||
				elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
				elem;
		}
	}
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

function evalScript( i, elem ) {
	if ( elem.src )
		jQuery.ajax({
			url: elem.src,
			async: false,
			dataType: "script"
		});

	else
		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );

	if ( elem.parentNode )
		elem.parentNode.removeChild( elem );
}

function now(){
	return +new Date;
}

jQuery.extend = jQuery.fn.extend = function() {
	// copy reference to target object
	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) )
		target = {};

	// extend jQuery itself if only one argument is passed
	if ( length == i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ )
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null )
			// Extend the base object
			for ( var name in options ) {
				var src = target[ name ], copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy )
					continue;

				// Recurse if we're merging object values
				if ( deep && copy && typeof copy === "object" && !copy.nodeType )
					target[ name ] = jQuery.extend( deep, 
						// Never move original objects, clone them
						src || ( copy.length != null ? [ ] : { } )
					, copy );

				// Don't bring in undefined values
				else if ( copy !== undefined )
					target[ name ] = copy;

			}

	// Return the modified object
	return target;
};

// exclude the following css properties to add px
var	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
	// cache defaultView
	defaultView = document.defaultView || {},
	toString = Object.prototype.toString;

jQuery.extend({
	noConflict: function( deep ) {
		window.$ = _$;

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return toString.call(obj) === "[object Function]";
	},

	isArray: function( obj ) {
		return toString.call(obj) === "[object Array]";
	},

	// check if an element is in a (or is an) XML document
	isXMLDoc: function( elem ) {
		return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
			!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
	},

	// Evalulates a script in a global context
	globalEval: function( data ) {
		if ( data && /\S/.test(data) ) {
			// Inspired by code by Andrea Giammarchi
			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
			var head = document.getElementsByTagName("head")[0] || document.documentElement,
				script = document.createElement("script");

			script.type = "text/javascript";
			if ( jQuery.support.scriptEval )
				script.appendChild( document.createTextNode( data ) );
			else
				script.text = data;

			// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
			// This arises when a base node is used (#2709).
			head.insertBefore( script, head.firstChild );
			head.removeChild( script );
		}
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
	},

	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0, length = object.length;

		if ( args ) {
			if ( length === undefined ) {
				for ( name in object )
					if ( callback.apply( object[ name ], args ) === false )
						break;
			} else
				for ( ; i < length; )
					if ( callback.apply( object[ i++ ], args ) === false )
						break;

		// A special, fast, case for the most common use of each
		} else {
			if ( length === undefined ) {
				for ( name in object )
					if ( callback.call( object[ name ], name, object[ name ] ) === false )
						break;
			} else
				for ( var value = object[0];
					i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
		}

		return object;
	},

	prop: function( elem, value, type, i, name ) {
		// Handle executable functions
		if ( jQuery.isFunction( value ) )
			value = value.call( elem, i );

		// Handle passing in a number to a CSS property
		return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
			value + "px" :
			value;
	},

	className: {
		// internal only, use addClass("class")
		add: function( elem, classNames ) {
			jQuery.each((classNames || "").split(/\s+/), function(i, className){
				if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
					elem.className += (elem.className ? " " : "") + className;
			});
		},

		// internal only, use removeClass("class")
		remove: function( elem, classNames ) {
			if (elem.nodeType == 1)
				elem.className = classNames !== undefined ?
					jQuery.grep(elem.className.split(/\s+/), function(className){
						return !jQuery.className.has( classNames, className );
					}).join(" ") :
					"";
		},

		// internal only, use hasClass("class")
		has: function( elem, className ) {
			return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};
		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( var name in options )
			elem.style[ name ] = old[ name ];
	},

	css: function( elem, name, force, extra ) {
		if ( name == "width" || name == "height" ) {
			var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];

			function getWH() {
				val = name == "width" ? elem.offsetWidth : elem.offsetHeight;

				if ( extra === "border" )
					return;

				jQuery.each( which, function() {
					if ( !extra )
						val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
					if ( extra === "margin" )
						val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
					else
						val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
				});
			}

			if ( elem.offsetWidth !== 0 )
				getWH();
			else
				jQuery.swap( elem, props, getWH );

			return Math.max(0, Math.round(val));
		}

		return jQuery.curCSS( elem, name, force );
	},

	curCSS: function( elem, name, force ) {
		var ret, style = elem.style;

		// We need to handle opacity special in IE
		if ( name == "opacity" && !jQuery.support.opacity ) {
			ret = jQuery.attr( style, "opacity" );

			return ret == "" ?
				"1" :
				ret;
		}

		// Make sure we're using the right name for getting the float value
		if ( name.match( /float/i ) )
			name = styleFloat;

		if ( !force && style && style[ name ] )
			ret = style[ name ];

		else if ( defaultView.getComputedStyle ) {

			// Only "float" is needed here
			if ( name.match( /float/i ) )
				name = "float";

			name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();

			var computedStyle = defaultView.getComputedStyle( elem, null );

			if ( computedStyle )
				ret = computedStyle.getPropertyValue( name );

			// We should always get a number back from opacity
			if ( name == "opacity" && ret == "" )
				ret = "1";

		} else if ( elem.currentStyle ) {
			var camelCase = name.replace(/\-(\w)/g, function(all, letter){
				return letter.toUpperCase();
			});

			ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];

			// From the awesome hack by Dean Edwards
			// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

			// If we're not dealing with a regular pixel number
			// but a number that has a weird ending, we need to convert it to pixels
			if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
				// Remember the original values
				var left = style.left, rsLeft = elem.runtimeStyle.left;

				// Put in the new values to get a computed value out
				elem.runtimeStyle.left = elem.currentStyle.left;
				style.left = ret || 0;
				ret = style.pixelLeft + "px";

				// Revert the changed values
				style.left = left;
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret;
	},

	clean: function( elems, context, fragment ) {
		context = context || document;

		// !context.createElement fails in IE with an error but returns typeof 'object'
		if ( typeof context.createElement === "undefined" )
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

		// If a single string is passed in and it's a single tag
		// just do a createElement and skip the rest
		if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
			var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
			if ( match )
				return [ context.createElement( match[1] ) ];
		}

		var ret = [], scripts = [], div = context.createElement("div");

		jQuery.each(elems, function(i, elem){
			if ( typeof elem === "number" )
				elem += '';

			if ( !elem )
				return;

			// Convert html string into DOM nodes
			if ( typeof elem === "string" ) {
				// Fix "XHTML"-style tags in all browsers
				elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
					return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
						all :
						front + "></" + tag + ">";
				});

				// Trim whitespace, otherwise indexOf won't work as expected
				var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();

				var wrap =
					// option or optgroup
					!tags.indexOf("<opt") &&
					[ 1, "<select multiple='multiple'>", "</select>" ] ||

					!tags.indexOf("<leg") &&
					[ 1, "<fieldset>", "</fieldset>" ] ||

					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
					[ 1, "<table>", "</table>" ] ||

					!tags.indexOf("<tr") &&
					[ 2, "<table><tbody>", "</tbody></table>" ] ||

				 	// <thead> matched above
					(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
					[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||

					!tags.indexOf("<col") &&
					[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||

					// IE can't serialize <link> and <script> tags normally
					!jQuery.support.htmlSerialize &&
					[ 1, "div<div>", "</div>" ] ||

					[ 0, "", "" ];

				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + elem + wrap[2];

				// Move to the right depth
				while ( wrap[0]-- )
					div = div.lastChild;

				// Remove IE's autoinserted <tbody> from table fragments
				if ( !jQuery.support.tbody ) {

					// String was a <table>, *may* have spurious <tbody>
					var hasBody = /<tbody/i.test(elem),
						tbody = !tags.indexOf("<table") && !hasBody ?
							div.firstChild && div.firstChild.childNodes :

						// String was a bare <thead> or <tfoot>
						wrap[1] == "<table>" && !hasBody ?
							div.childNodes :
							[];

					for ( var j = tbody.length - 1; j >= 0 ; --j )
						if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
							tbody[ j ].parentNode.removeChild( tbody[ j ] );

					}

				// IE completely kills leading whitespace when innerHTML is used
				if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
					div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
				
				elem = jQuery.makeArray( div.childNodes );
			}

			if ( elem.nodeType )
				ret.push( elem );
			else
				ret = jQuery.merge( ret, elem );

		});

		if ( fragment ) {
			for ( var i = 0; ret[i]; i++ ) {
				if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
				} else {
					if ( ret[i].nodeType === 1 )
						ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
					fragment.appendChild( ret[i] );
				}
			}
			
			return scripts;
		}

		return ret;
	},

	attr: function( elem, name, value ) {
		// don't set attributes on text and comment nodes
		if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
			return undefined;

		var notxml = !jQuery.isXMLDoc( elem ),
			// Whether we are setting (or getting)
			set = value !== undefined;

		// Try to normalize/fix the name
		name = notxml && jQuery.props[ name ] || name;

		// Only do all the following if this is a node (faster for style)
		// IE elem.getAttribute passes even for style
		if ( elem.tagName ) {

			// These attributes require special treatment
			var special = /href|src|style/.test( name );

			// Safari mis-reports the default selected property of a hidden option
			// Accessing the parent's selectedIndex property fixes it
			if ( name == "selected" && elem.parentNode )
				elem.parentNode.selectedIndex;

			// If applicable, access the attribute via the DOM 0 way
			if ( name in elem && notxml && !special ) {
				if ( set ){
					// We can't allow the type property to be changed (since it causes problems in IE)
					if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
						throw "type property can't be changed";

					elem[ name ] = value;
				}

				// browsers index elements by id/name on forms, give priority to attributes.
				if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
					return elem.getAttributeNode( name ).nodeValue;

				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				if ( name == "tabIndex" ) {
					var attributeNode = elem.getAttributeNode( "tabIndex" );
					return attributeNode && attributeNode.specified
						? attributeNode.value
						: elem.nodeName.match(/(button|input|object|select|textarea)/i)
							? 0
							: elem.nodeName.match(/^(a|area)$/i) && elem.href
								? 0
								: undefined;
				}

				return elem[ name ];
			}

			if ( !jQuery.support.style && notxml &&  name == "style" )
				return jQuery.attr( elem.style, "cssText", value );

			if ( set )
				// convert the value to a string (all browsers do this but IE) see #1070
				elem.setAttribute( name, "" + value );

			var attr = !jQuery.support.hrefNormalized && notxml && special
					// Some attributes require a special call on IE
					? elem.getAttribute( name, 2 )
					: elem.getAttribute( name );

			// Non-existent attributes return null, we normalize to undefined
			return attr === null ? undefined : attr;
		}

		// elem is actually elem.style ... set the style

		// IE uses filters for opacity
		if ( !jQuery.support.opacity && name == "opacity" ) {
			if ( set ) {
				// IE has trouble with opacity if it does not have layout
				// Force it by setting the zoom level
				elem.zoom = 1;

				// Set the alpha filter to set the opacity
				elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
					(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
			}

			return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
				(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
				"";
		}

		name = name.replace(/-([a-z])/ig, function(all, letter){
			return letter.toUpperCase();
		});

		if ( set )
			elem[ name ] = value;

		return elem[ name ];
	},

	trim: function( text ) {
		return (text || "").replace( /^\s+|\s+$/g, "" );
	},

	makeArray: function( array ) {
		var ret = [];

		if( array != null ){
			var i = array.length;
			// The window, strings (and functions) also have 'length'
			if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
				ret[0] = array;
			else
				while( i )
					ret[--i] = array[i];
		}

		return ret;
	},

	inArray: function( elem, array ) {
		for ( var i = 0, length = array.length; i < length; i++ )
		// Use === because on IE, window == document
			if ( array[ i ] === elem )
				return i;

		return -1;
	},

	merge: function( first, second ) {
		// We have to loop this way because IE & Opera overwrite the length
		// expando of getElementsByTagName
		var i = 0, elem, pos = first.length;
		// Also, we need to make sure that the correct elements are being returned
		// (IE returns comment nodes in a '*' query)
		if ( !jQuery.support.getAll ) {
			while ( (elem = second[ i++ ]) != null )
				if ( elem.nodeType != 8 )
					first[ pos++ ] = elem;

		} else
			while ( (elem = second[ i++ ]) != null )
				first[ pos++ ] = elem;

		return first;
	},

	unique: function( array ) {
		var ret = [], done = {};

		try {

			for ( var i = 0, length = array.length; i < length; i++ ) {
				var id = jQuery.data( array[ i ] );

				if ( !done[ id ] ) {
					done[ id ] = true;
					ret.push( array[ i ] );
				}
			}

		} catch( e ) {
			ret = array;
		}

		return ret;
	},

	grep: function( elems, callback, inv ) {
		var ret = [];

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ )
			if ( !inv != !callback( elems[ i ], i ) )
				ret.push( elems[ i ] );

		return ret;
	},

	map: function( elems, callback ) {
		var ret = [];

		// Go through the array, translating each of the items to their
		// new value (or values).
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			var value = callback( elems[ i ], i );

			if ( value != null )
				ret[ ret.length ] = value;
		}

		return ret.concat.apply( [], ret );
	}
});

// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
	safari: /webkit/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

jQuery.each({
	parent: function(elem){return elem.parentNode;},
	parents: function(elem){return jQuery.dir(elem,"parentNode");},
	next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
	prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
	nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
	prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
	siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
	children: function(elem){return jQuery.sibling(elem.firstChild);},
	contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
	jQuery.fn[ name ] = function( selector ) {
		var ret = jQuery.map( this, fn );

		if ( selector && typeof selector == "string" )
			ret = jQuery.multiFilter( selector, ret );

		return this.pushStack( jQuery.unique( ret ), name, selector );
	};
});

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function(name, original){
	jQuery.fn[ name ] = function( selector ) {
		var ret = [], insert = jQuery( selector );

		for ( var i = 0, l = insert.length; i < l; i++ ) {
			var elems = (i > 0 ? this.clone(true) : this).get();
			jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
			ret = ret.concat( elems );
		}

		return this.pushStack( ret, name, selector );
	};
});

jQuery.each({
	removeAttr: function( name ) {
		jQuery.attr( this, name, "" );
		if (this.nodeType == 1)
			this.removeAttribute( name );
	},

	addClass: function( classNames ) {
		jQuery.className.add( this, classNames );
	},

	removeClass: function( classNames ) {
		jQuery.className.remove( this, classNames );
	},

	toggleClass: function( classNames, state ) {
		if( typeof state !== "boolean" )
			state = !jQuery.className.has( this, classNames );
		jQuery.className[ state ? "add" : "remove" ]( this, classNames );
	},

	remove: function( selector ) {
		if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
			// Prevent memory leaks
			jQuery( "*", this ).add([this]).each(function(){
				jQuery.event.remove(this);
				jQuery.removeData(this);
			});
			if (this.parentNode)
				this.parentNode.removeChild( this );
		}
	},

	empty: function() {
		// Remove element nodes and prevent memory leaks
		jQuery(this).children().remove();

		// Remove any remaining nodes
		while ( this.firstChild )
			this.removeChild( this.firstChild );
	}
}, function(name, fn){
	jQuery.fn[ name ] = function(){
		return this.each( fn, arguments );
	};
});

// Helper function used by the dimensions and offset modules
function num(elem, prop) {
	return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};

jQuery.extend({
	cache: {},

	data: function( elem, name, data ) {
		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ];

		// Compute a unique ID for the element
		if ( !id )
			id = elem[ expando ] = ++uuid;

		// Only generate the data cache if we're
		// trying to access or manipulate it
		if ( name && !jQuery.cache[ id ] )
			jQuery.cache[ id ] = {};

		// Prevent overriding the named cache with undefined values
		if ( data !== undefined )
			jQuery.cache[ id ][ name ] = data;

		// Return the named cache data, or the ID for the element
		return name ?
			jQuery.cache[ id ][ name ] :
			id;
	},

	removeData: function( elem, name ) {
		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ];

		// If we want to remove a specific section of the element's data
		if ( name ) {
			if ( jQuery.cache[ id ] ) {
				// Remove the section of cache data
				delete jQuery.cache[ id ][ name ];

				// If we've removed all the data, remove the element's cache
				name = "";

				for ( name in jQuery.cache[ id ] )
					break;

				if ( !name )
					jQuery.removeData( elem );
			}

		// Otherwise, we want to remove all of the element's data
		} else {
			// Clean up the element expando
			try {
				delete elem[ expando ];
			} catch(e){
				// IE has trouble directly removing the expando
				// but it's ok with using removeAttribute
				if ( elem.removeAttribute )
					elem.removeAttribute( expando );
			}

			// Completely remove the data cache
			delete jQuery.cache[ id ];
		}
	},
	queue: function( elem, type, data ) {
		if ( elem ){
	
			type = (type || "fx") + "queue";
	
			var q = jQuery.data( elem, type );
	
			if ( !q || jQuery.isArray(data) )
				q = jQuery.data( elem, type, jQuery.makeArray(data) );
			else if( data )
				q.push( data );
	
		}
		return q;
	},

	dequeue: function( elem, type ){
		var queue = jQuery.queue( elem, type ),
			fn = queue.shift();
		
		if( !type || type === "fx" )
			fn = queue[0];
			
		if( fn !== undefined )
			fn.call(elem);
	}
});

jQuery.fn.extend({
	data: function( key, value ){
		var parts = key.split(".");
		parts[1] = parts[1] ? "." + parts[1] : "";

		if ( value === undefined ) {
			var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

			if ( data === undefined && this.length )
				data = jQuery.data( this[0], key );

			return data === undefined && parts[1] ?
				this.data( parts[0] ) :
				data;
		} else
			return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
				jQuery.data( this, key, value );
			});
	},

	removeData: function( key ){
		return this.each(function(){
			jQuery.removeData( this, key );
		});
	},
	queue: function(type, data){
		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
		}

		if ( data === undefined )
			return jQuery.queue( this[0], type );

		return this.each(function(){
			var queue = jQuery.queue( this, type, data );
			
			 if( type == "fx" && queue.length == 1 )
				queue[0].call(this);
		});
	},
	dequeue: function(type){
		return this.each(function(){
			jQuery.dequeue( this, type );
		});
	}
});/*!
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
	done = 0,
	toString = Object.prototype.toString;

var Sizzle = function(selector, context, results, seed) {
	results = results || [];
	context = context || document;

	if ( context.nodeType !== 1 && context.nodeType !== 9 )
		return [];
	
	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	var parts = [], m, set, checkSet, check, mode, extra, prune = true;
	
	// Reset the position of the chunker regexp (start from head)
	chunker.lastIndex = 0;
	
	while ( (m = chunker.exec(selector)) !== null ) {
		parts.push( m[1] );
		
		if ( m[2] ) {
			extra = RegExp.rightContext;
			break;
		}
	}

	if ( parts.length > 1 && origPOS.exec( selector ) ) {
		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
			set = posProcess( parts[0] + parts[1], context );
		} else {
			set = Expr.relative[ parts[0] ] ?
				[ context ] :
				Sizzle( parts.shift(), context );

			while ( parts.length ) {
				selector = parts.shift();

				if ( Expr.relative[ selector ] )
					selector += parts.shift();

				set = posProcess( selector, set );
			}
		}
	} else {
		var ret = seed ?
			{ expr: parts.pop(), set: makeArray(seed) } :
			Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
		set = Sizzle.filter( ret.expr, ret.set );

		if ( parts.length > 0 ) {
			checkSet = makeArray(set);
		} else {
			prune = false;
		}

		while ( parts.length ) {
			var cur = parts.pop(), pop = cur;

			if ( !Expr.relative[ cur ] ) {
				cur = "";
			} else {
				pop = parts.pop();
			}

			if ( pop == null ) {
				pop = context;
			}

			Expr.relative[ cur ]( checkSet, pop, isXML(context) );
		}
	}

	if ( !checkSet ) {
		checkSet = set;
	}

	if ( !checkSet ) {
		throw "Syntax error, unrecognized expression: " + (cur || selector);
	}

	if ( toString.call(checkSet) === "[object Array]" ) {
		if ( !prune ) {
			results.push.apply( results, checkSet );
		} else if ( context.nodeType === 1 ) {
			for ( var i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
					results.push( set[i] );
				}
			}
		} else {
			for ( var i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
					results.push( set[i] );
				}
			}
		}
	} else {
		makeArray( checkSet, results );
	}

	if ( extra ) {
		Sizzle( extra, context, results, seed );

		if ( sortOrder ) {
			hasDuplicate = false;
			results.sort(sortOrder);

			if ( hasDuplicate ) {
				for ( var i = 1; i < results.length; i++ ) {
					if ( results[i] === results[i-1] ) {
						results.splice(i--, 1);
					}
				}
			}
		}
	}

	return results;
};

Sizzle.matches = function(expr, set){
	return Sizzle(expr, null, null, set);
};

Sizzle.find = function(expr, context, isXML){
	var set, match;

	if ( !expr ) {
		return [];
	}

	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
		var type = Expr.order[i], match;
		
		if ( (match = Expr.match[ type ].exec( expr )) ) {
			var left = RegExp.leftContext;

			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace(/\\/g, "");
				set = Expr.find[ type ]( match, context, isXML );
				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}

	if ( !set ) {
		set = context.getElementsByTagName("*");
	}

	return {set: set, expr: expr};
};

Sizzle.filter = function(expr, set, inplace, not){
	var old = expr, result = [], curLoop = set, match, anyFound,
		isXMLFilter = set && set[0] && isXML(set[0]);

	while ( expr && set.length ) {
		for ( var type in Expr.filter ) {
			if ( (match = Expr.match[ type ].exec( expr )) != null ) {
				var filter = Expr.filter[ type ], found, item;
				anyFound = false;

				if ( curLoop == result ) {
					result = [];
				}

				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

					if ( !match ) {
						anyFound = found = true;
					} else if ( match === true ) {
						continue;
					}
				}

				if ( match ) {
					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							var pass = not ^ !!found;

							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;
								} else {
									curLoop[i] = false;
								}
							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}

				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}

					expr = expr.replace( Expr.match[ type ], "" );

					if ( !anyFound ) {
						return [];
					}

					break;
				}
			}
		}

		// Improper expression
		if ( expr == old ) {
			if ( anyFound == null ) {
				throw "Syntax error, unrecognized expression: " + expr;
			} else {
				break;
			}
		}

		old = expr;
	}

	return curLoop;
};

var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],
	match: {
		ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
	},
	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},
	attrHandle: {
		href: function(elem){
			return elem.getAttribute("href");
		}
	},
	relative: {
		"+": function(checkSet, part, isXML){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !/\W/.test(part),
				isPartStrNotTag = isPartStr && !isTag;

			if ( isTag && !isXML ) {
				part = part.toUpperCase();
			}

			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

					checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
						elem || false :
						elem === part;
				}
			}

			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},
		">": function(checkSet, part, isXML){
			var isPartStr = typeof part === "string";

			if ( isPartStr && !/\W/.test(part) ) {
				part = isXML ? part : part.toUpperCase();

				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
					var elem = checkSet[i];
					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName === part ? parent : false;
					}
				}
			} else {
				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
					var elem = checkSet[i];
					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},
		"": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck;

			if ( !part.match(/\W/) ) {
				var nodeCheck = part = isXML ? part : part.toUpperCase();
				checkFn = dirNodeCheck;
			}

			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
		},
		"~": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck;

			if ( typeof part === "string" && !part.match(/\W/) ) {
				var nodeCheck = part = isXML ? part : part.toUpperCase();
				checkFn = dirNodeCheck;
			}

			checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
		}
	},
	find: {
		ID: function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? [m] : [];
			}
		},
		NAME: function(match, context, isXML){
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [], results = context.getElementsByName(match[1]);

				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}

				return ret.length === 0 ? null : ret;
			}
		},
		TAG: function(match, context){
			return context.getElementsByTagName(match[1]);
		}
	},
	preFilter: {
		CLASS: function(match, curLoop, inplace, result, not, isXML){
			match = " " + match[1].replace(/\\/g, "") + " ";

			if ( isXML ) {
				return match;
			}

			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
						if ( !inplace )
							result.push( elem );
					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}

			return false;
		},
		ID: function(match){
			return match[1].replace(/\\/g, "");
		},
		TAG: function(match, curLoop){
			for ( var i = 0; curLoop[i] === false; i++ ){}
			return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
		},
		CHILD: function(match){
			if ( match[1] == "nth" ) {
				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
				var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
					match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

				// calculate the numbers (first)n+(last) including if they are negative
				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}

			// TODO: Move to normal caching system
			match[0] = done++;

			return match;
		},
		ATTR: function(match, curLoop, inplace, result, not, isXML){
			var name = match[1].replace(/\\/g, "");
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

			if ( match[2] === "~=" ) {
				match[4] = " " + match[4] + " ";
			}

			return match;
		},
		PSEUDO: function(match, curLoop, inplace, result, not){
			if ( match[1] === "not" ) {
				// If we're dealing with a complex expression, or a simple one
				if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
					match[3] = Sizzle(match[3], null, null, curLoop);
				} else {
					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
					if ( !inplace ) {
						result.push.apply( result, ret );
					}
					return false;
				}
			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
				return true;
			}
			
			return match;
		},
		POS: function(match){
			match.unshift( true );
			return match;
		}
	},
	filters: {
		enabled: function(elem){
			return elem.disabled === false && elem.type !== "hidden";
		},
		disabled: function(elem){
			return elem.disabled === true;
		},
		checked: function(elem){
			return elem.checked === true;
		},
		selected: function(elem){
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			elem.parentNode.selectedIndex;
			return elem.selected === true;
		},
		parent: function(elem){
			return !!elem.firstChild;
		},
		empty: function(elem){
			return !elem.firstChild;
		},
		has: function(elem, i, match){
			return !!Sizzle( match[3], elem ).length;
		},
		header: function(elem){
			return /h\d/i.test( elem.nodeName );
		},
		text: function(elem){
			return "text" === elem.type;
		},
		radio: function(elem){
			return "radio" === elem.type;
		},
		checkbox: function(elem){
			return "checkbox" === elem.type;
		},
		file: function(elem){
			return "file" === elem.type;
		},
		password: function(elem){
			return "password" === elem.type;
		},
		submit: function(elem){
			return "submit" === elem.type;
		},
		image: function(elem){
			return "image" === elem.type;
		},
		reset: function(elem){
			return "reset" === elem.type;
		},
		button: function(elem){
			return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
		},
		input: function(elem){
			return /input|select|textarea|button/i.test(elem.nodeName);
		}
	},
	setFilters: {
		first: function(elem, i){
			return i === 0;
		},
		last: function(elem, i, match, array){
			return i === array.length - 1;
		},
		even: function(elem, i){
			return i % 2 === 0;
		},
		odd: function(elem, i){
			return i % 2 === 1;
		},
		lt: function(elem, i, match){
			return i < match[3] - 0;
		},
		gt: function(elem, i, match){
			return i > match[3] - 0;
		},
		nth: function(elem, i, match){
			return match[3] - 0 == i;
		},
		eq: function(elem, i, match){
			return match[3] - 0 == i;
		}
	},
	filter: {
		PSEUDO: function(elem, match, i, array){
			var name = match[1], filter = Expr.filters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
			} else if ( name === "not" ) {
				var not = match[3];

				for ( var i = 0, l = not.length; i < l; i++ ) {
					if ( not[i] === elem ) {
						return false;
					}
				}

				return true;
			}
		},
		CHILD: function(elem, match){
			var type = match[1], node = elem;
			switch (type) {
				case 'only':
				case 'first':
					while (node = node.previousSibling)  {
						if ( node.nodeType === 1 ) return false;
					}
					if ( type == 'first') return true;
					node = elem;
				case 'last':
					while (node = node.nextSibling)  {
						if ( node.nodeType === 1 ) return false;
					}
					return true;
				case 'nth':
					var first = match[2], last = match[3];

					if ( first == 1 && last == 0 ) {
						return true;
					}
					
					var doneName = match[0],
						parent = elem.parentNode;
	
					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
						var count = 0;
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 
						parent.sizcache = doneName;
					}
					
					var diff = elem.nodeIndex - last;
					if ( first == 0 ) {
						return diff == 0;
					} else {
						return ( diff % first == 0 && diff / first >= 0 );
					}
			}
		},
		ID: function(elem, match){
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},
		TAG: function(elem, match){
			return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
		},
		CLASS: function(elem, match){
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},
		ATTR: function(elem, match){
			var name = match[1],
				result = Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];

			return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value != check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},
		POS: function(elem, match, i, array){
			var name = match[2], filter = Expr.setFilters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			}
		}
	}
};

var origPOS = Expr.match.POS;

for ( var type in Expr.match ) {
	Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}

var makeArray = function(array, results) {
	array = Array.prototype.slice.call( array );

	if ( results ) {
		results.push.apply( results, array );
		return results;
	}
	
	return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
try {
	Array.prototype.slice.call( document.documentElement.childNodes );

// Provide a fallback method if it does not work
} catch(e){
	makeArray = function(array, results) {
		var ret = results || [];

		if ( toString.call(array) === "[object Array]" ) {
			Array.prototype.push.apply( ret, array );
		} else {
			if ( typeof array.length === "number" ) {
				for ( var i = 0, l = array.length; i < l; i++ ) {
					ret.push( array[i] );
				}
			} else {
				for ( var i = 0; array[i]; i++ ) {
					ret.push( array[i] );
				}
			}
		}

		return ret;
	};
}

var sortOrder;

if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( "sourceIndex" in document.documentElement ) {
	sortOrder = function( a, b ) {
		var ret = a.sourceIndex - b.sourceIndex;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( document.createRange ) {
	sortOrder = function( a, b ) {
		var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
		aRange.selectNode(a);
		aRange.collapse(true);
		bRange.selectNode(b);
		bRange.collapse(true);
		var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
}

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
	// We're going to inject a fake input element with a specified name
	var form = document.createElement("form"),
		id = "script" + (new Date).getTime();
	form.innerHTML = "<input name='" + id + "'/>";

	// Inject it into the root element, check its status, and remove it quickly
	var root = document.documentElement;
	root.insertBefore( form, root.firstChild );

	// The workaround has to do additional checks after a getElementById
	// Which slows things down for other browsers (hence the branching)
	if ( !!document.getElementById( id ) ) {
		Expr.find.ID = function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
			}
		};

		Expr.filter.ID = function(elem, match){
			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
			return elem.nodeType === 1 && node && node.nodeValue === match;
		};
	}

	root.removeChild( form );
})();

(function(){
	// Check to see if the browser returns only elements
	// when doing getElementsByTagName("*")

	// Create a fake element
	var div = document.createElement("div");
	div.appendChild( document.createComment("") );

	// Make sure no comments are found
	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function(match, context){
			var results = context.getElementsByTagName(match[1]);

			// Filter out possible comments
			if ( match[1] === "*" ) {
				var tmp = [];

				for ( var i = 0; results[i]; i++ ) {
					if ( results[i].nodeType === 1 ) {
						tmp.push( results[i] );
					}
				}

				results = tmp;
			}

			return results;
		};
	}

	// Check to see if an attribute returns normalized href attributes
	div.innerHTML = "<a href='#'></a>";
	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#" ) {
		Expr.attrHandle.href = function(elem){
			return elem.getAttribute("href", 2);
		};
	}
})();

if ( document.querySelectorAll ) (function(){
	var oldSizzle = Sizzle, div = document.createElement("div");
	div.innerHTML = "<p class='TEST'></p>";

	// Safari can't handle uppercase or unicode characters when
	// in quirks mode.
	if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
		return;
	}
	
	Sizzle = function(query, context, extra, seed){
		context = context || document;

		// Only use querySelectorAll on non-XML documents
		// (ID selectors don't work in non-HTML documents)
		if ( !seed && context.nodeType === 9 && !isXML(context) ) {
			try {
				return makeArray( context.querySelectorAll(query), extra );
			} catch(e){}
		}
		
		return oldSizzle(query, context, extra, seed);
	};

	Sizzle.find = oldSizzle.find;
	Sizzle.filter = oldSizzle.filter;
	Sizzle.selectors = oldSizzle.selectors;
	Sizzle.matches = oldSizzle.matches;
})();

if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
	var div = document.createElement("div");
	div.innerHTML = "<div class='test e'></div><div class='test'></div>";

	// Opera can't find a second classname (in 9.6)
	if ( div.getElementsByClassName("e").length === 0 )
		return;

	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";

	if ( div.getElementsByClassName("e").length === 1 )
		return;

	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function(match, context, isXML) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};
})();

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	var sibDir = dir == "previousSibling" && !isXML;
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			if ( sibDir && elem.nodeType === 1 ){
				elem.sizcache = doneName;
				elem.sizset = i;
			}
			elem = elem[dir];
			var match = false;

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 && !isXML ){
					elem.sizcache = doneName;
					elem.sizset = i;
				}

				if ( elem.nodeName === cur ) {
					match = elem;
					break;
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	var sibDir = dir == "previousSibling" && !isXML;
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			if ( sibDir && elem.nodeType === 1 ) {
				elem.sizcache = doneName;
				elem.sizset = i;
			}
			elem = elem[dir];
			var match = false;

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem.sizcache = doneName;
						elem.sizset = i;
					}
					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
						match = elem;
						break;
					}
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

var contains = document.compareDocumentPosition ?  function(a, b){
	return a.compareDocumentPosition(b) & 16;
} : function(a, b){
	return a !== b && (a.contains ? a.contains(b) : true);
};

var isXML = function(elem){
	return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
		!!elem.ownerDocument && isXML( elem.ownerDocument );
};

var posProcess = function(selector, context){
	var tmpSet = [], later = "", match,
		root = context.nodeType ? [context] : context;

	// Position selectors must be done after the filter
	// And so must :not(positional) so we move all PSEUDOs to the end
	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
		later += match[0];
		selector = selector.replace( Expr.match.PSEUDO, "" );
	}

	selector = Expr.relative[selector] ? selector + "*" : selector;

	for ( var i = 0, l = root.length; i < l; i++ ) {
		Sizzle( selector, root[i], tmpSet );
	}

	return Sizzle.filter( later, tmpSet );
};

// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;

Sizzle.selectors.filters.hidden = function(elem){
	return elem.offsetWidth === 0 || elem.offsetHeight === 0;
};

Sizzle.selectors.filters.visible = function(elem){
	return elem.offsetWidth > 0 || elem.offsetHeight > 0;
};

Sizzle.selectors.filters.animated = function(elem){
	return jQuery.grep(jQuery.timers, function(fn){
		return elem === fn.elem;
	}).length;
};

jQuery.multiFilter = function( expr, elems, not ) {
	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	return Sizzle.matches(expr, elems);
};

jQuery.dir = function( elem, dir ){
	var matched = [], cur = elem[dir];
	while ( cur && cur != document ) {
		if ( cur.nodeType == 1 )
			matched.push( cur );
		cur = cur[dir];
	}
	return matched;
};

jQuery.nth = function(cur, result, dir, elem){
	result = result || 1;
	var num = 0;

	for ( ; cur; cur = cur[dir] )
		if ( cur.nodeType == 1 && ++num == result )
			break;

	return cur;
};

jQuery.sibling = function(n, elem){
	var r = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType == 1 && n != elem )
			r.push( n );
	}

	return r;
};

return;

window.Sizzle = Sizzle;

})();
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code originated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {

	// Bind an event to an element
	// Original by Dean Edwards
	add: function(elem, types, handler, data) {
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		// For whatever reason, IE has trouble passing the window object
		// around, causing it to be cloned in the process
		if ( elem.setInterval && elem != window )
			elem = window;

		// Make sure that the function being executed has a unique ID
		if ( !handler.guid )
			handler.guid = this.guid++;

		// if data is passed, bind to handler
		if ( data !== undefined ) {
			// Create temporary function pointer to original handler
			var fn = handler;

			// Create unique handler function, wrapped around original handler
			handler = this.proxy( fn );

			// Store data in unique handler
			handler.data = data;
		}

		// Init the element's event structure
		var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
				// Handle the second event of a trigger and when
				// an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
					jQuery.event.handle.apply(arguments.callee.elem, arguments) :
					undefined;
			});
		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native
		// event in IE.
		handle.elem = elem;

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		jQuery.each(types.split(/\s+/), function(index, type) {
			// Namespaced event handlers
			var namespaces = type.split(".");
			type = namespaces.shift();
			handler.type = namespaces.slice().sort().join(".");

			// Get the current list of functions bound to this event
			var handlers = events[type];
			
			if ( jQuery.event.specialAll[type] )
				jQuery.event.specialAll[type].setup.call(elem, data, namespaces);

			// Init the event handler queue
			if (!handlers) {
				handlers = events[type] = {};

				// Check for a special event handler
				// Only use addEventListener/attachEvent if the special
				// events handler returns false
				if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
					// Bind the global event handler to the element
					if (elem.addEventListener)
						elem.addEventListener(type, handle, false);
					else if (elem.attachEvent)
						elem.attachEvent("on" + type, handle);
				}
			}

			// Add the function to the element's handler list
			handlers[handler.guid] = handler;

			// Keep track of which events have been used, for global triggering
			jQuery.event.global[type] = true;
		});

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	guid: 1,
	global: {},

	// Detach an event or set of events from an element
	remove: function(elem, types, handler) {
		// don't do events on text and comment nodes
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		var events = jQuery.data(elem, "events"), ret, index;

		if ( events ) {
			// Unbind all events for the element
			if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
				for ( var type in events )
					this.remove( elem, type + (types || "") );
			else {
				// types is actually an event object here
				if ( types.type ) {
					handler = types.handler;
					types = types.type;
				}

				// Handle multiple events seperated by a space
				// jQuery(...).unbind("mouseover mouseout", fn);
				jQuery.each(types.split(/\s+/), function(index, type){
					// Namespaced event handlers
					var namespaces = type.split(".");
					type = namespaces.shift();
					var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

					if ( events[type] ) {
						// remove the given handler for the given type
						if ( handler )
							delete events[type][handler.guid];

						// remove all handlers for the given type
						else
							for ( var handle in events[type] )
								// Handle the removal of namespaced events
								if ( namespace.test(events[type][handle].type) )
									delete events[type][handle];
									
						if ( jQuery.event.specialAll[type] )
							jQuery.event.specialAll[type].teardown.call(elem, namespaces);

						// remove generic event handler if no more handlers exist
						for ( ret in events[type] ) break;
						if ( !ret ) {
							if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
								if (elem.removeEventListener)
									elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
								else if (elem.detachEvent)
									elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
							}
							ret = null;
							delete events[type];
						}
					}
				});
			}

			// Remove the expando if it's no longer used
			for ( ret in events ) break;
			if ( !ret ) {
				var handle = jQuery.data( elem, "handle" );
				if ( handle ) handle.elem = null;
				jQuery.removeData( elem, "events" );
				jQuery.removeData( elem, "handle" );
			}
		}
	},

	// bubbling is internal
	trigger: function( event, data, elem, bubbling ) {
		// Event object or event type
		var type = event.type || event;

		if( !bubbling ){
			event = typeof event === "object" ?
				// jQuery.Event object
				event[expando] ? event :
				// Object literal
				jQuery.extend( jQuery.Event(type), event ) :
				// Just the event type (string)
				jQuery.Event(type);

			if ( type.indexOf("!") >= 0 ) {
				event.type = type = type.slice(0, -1);
				event.exclusive = true;
			}

			// Handle a global trigger
			if ( !elem ) {
				// Don't bubble custom events when global (to avoid too much overhead)
				event.stopPropagation();
				// Only trigger if we've ever bound an event for it
				if ( this.global[type] )
					jQuery.each( jQuery.cache, function(){
						if ( this.events && this.events[type] )
							jQuery.event.trigger( event, data, this.handle.elem );
					});
			}

			// Handle triggering a single element

			// don't do events on text and comment nodes
			if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
				return undefined;
			
			// Clean up in case it is reused
			event.result = undefined;
			event.target = elem;
			
			// Clone the incoming data, if any
			data = jQuery.makeArray(data);
			data.unshift( event );
		}

		event.currentTarget = elem;

		// Trigger the event, it is assumed that "handle" is a function
		var handle = jQuery.data(elem, "handle");
		if ( handle )
			handle.apply( elem, data );

		// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
		if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
			event.result = false;

		// Trigger the native events (except for clicks on links)
		if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
			this.triggered = true;
			try {
				elem[ type ]();
			// prevent IE from throwing an error for some hidden elements
			} catch (e) {}
		}

		this.triggered = false;

		if ( !event.isPropagationStopped() ) {
			var parent = elem.parentNode || elem.ownerDocument;
			if ( parent )
				jQuery.event.trigger(event, data, parent, true);
		}
	},

	handle: function(event) {
		// returned undefined or false
		var all, handlers;

		event = arguments[0] = jQuery.event.fix( event || window.event );
		event.currentTarget = this;
		
		// Namespaced event handlers
		var namespaces = event.type.split(".");
		event.type = namespaces.shift();

		// Cache this now, all = true means, any handler
		all = !namespaces.length && !event.exclusive;
		
		var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

		handlers = ( jQuery.data(this, "events") || {} )[event.type];

		for ( var j in handlers ) {
			var handler = handlers[j];

			// Filter the functions by class
			if ( all || namespace.test(handler.type) ) {
				// Pass in a reference to the handler function itself
				// So that we can later remove it
				event.handler = handler;
				event.data = handler.data;

				var ret = handler.apply(this, arguments);

				if( ret !== undefined ){
					event.result = ret;
					if ( ret === false ) {
						event.preventDefault();
						event.stopPropagation();
					}
				}

				if( event.isImmediatePropagationStopped() )
					break;

			}
		}
	},

	props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

	fix: function(event) {
		if ( event[expando] )
			return event;

		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = jQuery.Event( originalEvent );

		for ( var i = this.props.length, prop; i; ){
			prop = this.props[ --i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Fix target property, if necessary
		if ( !event.target )
			event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either

		// check if target is a textnode (safari)
		if ( event.target.nodeType == 3 )
			event.target = event.target.parentNode;

		// Add relatedTarget, if necessary
		if ( !event.relatedTarget && event.fromElement )
			event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var doc = document.documentElement, body = document.body;
			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
		}

		// Add which for key events
		if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
			event.which = event.charCode || event.keyCode;

		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey )
			event.metaKey = event.ctrlKey;

		// Add which for click: 1 == left; 2 == middle; 3 == right
		// Note: button is not normalized, so don't use it
		if ( !event.which && event.button )
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

		return event;
	},

	proxy: function( fn, proxy ){
		proxy = proxy || function(){ return fn.apply(this, arguments); };
		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
		// So proxy can be declared as an argument
		return proxy;
	},

	special: {
		ready: {
			// Make sure the ready event is setup
			setup: bindReady,
			teardown: function() {}
		}
	},
	
	specialAll: {
		live: {
			setup: function( selector, namespaces ){
				jQuery.event.add( this, namespaces[0], liveHandler );
			},
			teardown:  function( namespaces ){
				if ( namespaces.length ) {
					var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
					
					jQuery.each( (jQuery.data(this, "events").live || {}), function(){
						if ( name.test(this.type) )
							remove++;
					});
					
					if ( remove < 1 )
						jQuery.event.remove( this, namespaces[0], liveHandler );
				}
			}
		}
	}
};

jQuery.Event = function( src ){
	// Allow instantiation without the 'new' keyword
	if( !this.preventDefault )
		return new jQuery.Event(src);
	
	// Event object
	if( src && src.type ){
		this.originalEvent = src;
		this.type = src.type;
	// Event type
	}else
		this.type = src;

	// timeStamp is buggy for some events on Firefox(#3843)
	// So we won't rely on the native value
	this.timeStamp = now();
	
	// Mark it as fixed
	this[expando] = true;
};

function returnFalse(){
	return false;
}
function returnTrue(){
	return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;

		var e = this.originalEvent;
		if( !e )
			return;
		// if preventDefault exists run it on the original event
		if (e.preventDefault)
			e.preventDefault();
		// otherwise set the returnValue property of the original event to false (IE)
		e.returnValue = false;
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;

		var e = this.originalEvent;
		if( !e )
			return;
		// if stopPropagation exists run it on the original event
		if (e.stopPropagation)
			e.stopPropagation();
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation:function(){
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Traverse up the tree
	while ( parent && parent != this )
		try { parent = parent.parentNode; }
		catch(e) { parent = this; }
	
	if( parent != this ){
		// set the correct event type
		event.type = event.data;
		// handle event if we actually just moused on to a non sub-element
		jQuery.event.handle.apply( this, arguments );
	}
};
	
jQuery.each({ 
	mouseover: 'mouseenter', 
	mouseout: 'mouseleave'
}, function( orig, fix ){
	jQuery.event.special[ fix ] = {
		setup: function(){
			jQuery.event.add( this, orig, withinElement, fix );
		},
		teardown: function(){
			jQuery.event.remove( this, orig, withinElement );
		}
	};			   
});

jQuery.fn.extend({
	bind: function( type, data, fn ) {
		return type == "unload" ? this.one(type, data, fn) : this.each(function(){
			jQuery.event.add( this, type, fn || data, fn && data );
		});
	},

	one: function( type, data, fn ) {
		var one = jQuery.event.proxy( fn || data, function(event) {
			jQuery(this).unbind(event, one);
			return (fn || data).apply( this, arguments );
		});
		return this.each(function(){
			jQuery.event.add( this, type, one, fn && data);
		});
	},

	unbind: function( type, fn ) {
		return this.each(function(){
			jQuery.event.remove( this, type, fn );
		});
	},

	trigger: function( type, data ) {
		return this.each(function(){
			jQuery.event.trigger( type, data, this );
		});
	},

	triggerHandler: function( type, data ) {
		if( this[0] ){
			var event = jQuery.Event(type);
			event.preventDefault();
			event.stopPropagation();
			jQuery.event.trigger( event, data, this[0] );
			return event.result;
		}		
	},

	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments, i = 1;

		// link all the functions, so any of them can unbind this click handler
		while( i < args.length )
			jQuery.event.proxy( fn, args[i++] );

		return this.click( jQuery.event.proxy( fn, function(event) {
			// Figure out which function to execute
			this.lastToggle = ( this.lastToggle || 0 ) % i;

			// Make sure that clicks stop
			event.preventDefault();

			// and execute the function
			return args[ this.lastToggle++ ].apply( this, arguments ) || false;
		}));
	},

	hover: function(fnOver, fnOut) {
		return this.mouseenter(fnOver).mouseleave(fnOut);
	},

	ready: function(fn) {
		// Attach the listeners
		bindReady();

		// If the DOM is already ready
		if ( jQuery.isReady )
			// Execute the function immediately
			fn.call( document, jQuery );

		// Otherwise, remember the function for later
		else
			// Add the function to the wait list
			jQuery.readyList.push( fn );

		return this;
	},
	
	live: function( type, fn ){
		var proxy = jQuery.event.proxy( fn );
		proxy.guid += this.selector + type;

		jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );

		return this;
	},
	
	die: function( type, fn ){
		jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
		return this;
	}
});

function liveHandler( event ){
	var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
		stop = true,
		elems = [];

	jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
		if ( check.test(fn.type) ) {
			var elem = jQuery(event.target).closest(fn.data)[0];
			if ( elem )
				elems.push({ elem: elem, fn: fn });
		}
	});

	elems.sort(function(a,b) {
		return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
	});
	
	jQuery.each(elems, function(){
		if ( this.fn.call(this.elem, event, this.fn.data) === false )
			return (stop = false);
	});

	return stop;
}

function liveConvert(type, selector){
	return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}

jQuery.extend({
	isReady: false,
	readyList: [],
	// Handle when the DOM is ready
	ready: function() {
		// Make sure that the DOM is not already loaded
		if ( !jQuery.isReady ) {
			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If there are functions bound, to execute
			if ( jQuery.readyList ) {
				// Execute all of them
				jQuery.each( jQuery.readyList, function(){
					this.call( document, jQuery );
				});

				// Reset the list of functions
				jQuery.readyList = null;
			}

			// Trigger any bound ready events
			jQuery(document).triggerHandler("ready");
		}
	}
});

var readyBound = false;

function bindReady(){
	if ( readyBound ) return;
	readyBound = true;

	// Mozilla, Opera and webkit nightlies currently support this event
	if ( document.addEventListener ) {
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", function(){
			document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
			jQuery.ready();
		}, false );

	// If IE event model is used
	} else if ( document.attachEvent ) {
		// ensure firing before onload,
		// maybe late but safe also for iframes
		document.attachEvent("onreadystatechange", function(){
			if ( document.readyState === "complete" ) {
				document.detachEvent( "onreadystatechange", arguments.callee );
				jQuery.ready();
			}
		});

		// If IE and not an iframe
		// continually check to see if the document is ready
		if ( document.documentElement.doScroll && window == window.top ) (function(){
			if ( jQuery.isReady ) return;

			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch( error ) {
				setTimeout( arguments.callee, 0 );
				return;
			}

			// and execute any waiting functions
			jQuery.ready();
		})();
	}

	// A fallback to window.onload, that will always work
	jQuery.event.add( window, "load", jQuery.ready );
}

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
	"mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
	"change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

	// Handle event binding
	jQuery.fn[name] = function(fn){
		return fn ? this.bind(name, fn) : this.trigger(name);
	};
});

// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){ 
	for ( var id in jQuery.cache )
		// Skip the window
		if ( id != 1 && jQuery.cache[ id ].handle )
			jQuery.event.remove( jQuery.cache[ id ].handle.elem );
}); 
(function(){

	jQuery.support = {};

	var root = document.documentElement,
		script = document.createElement("script"),
		div = document.createElement("div"),
		id = "script" + (new Date).getTime();

	div.style.display = "none";
	div.innerHTML = '   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';

	var all = div.getElementsByTagName("*"),
		a = div.getElementsByTagName("a")[0];

	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return;
	}

	jQuery.support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: div.firstChild.nodeType == 3,
		
		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,
		
		// Make sure that you can get all elements in an <object> element
		// IE 7 always returns no results
		objectAll: !!div.getElementsByTagName("object")[0]
			.getElementsByTagName("*").length,
		
		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,
		
		// Get the style information from getAttribute
		// (IE uses .cssText insted)
		style: /red/.test( a.getAttribute("style") ),
		
		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: a.getAttribute("href") === "/a",
		
		// Make sure that element opacity exists
		// (IE uses filter instead)
		opacity: a.style.opacity === "0.5",
		
		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Will be defined later
		scriptEval: false,
		noCloneEvent: true,
		boxModel: null
	};
	
	script.type = "text/javascript";
	try {
		script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
	} catch(e){}

	root.insertBefore( script, root.firstChild );
	
	// Make sure that the execution of code works by injecting a script
	// tag with appendChild/createTextNode
	// (IE doesn't support this, fails, and uses .text instead)
	if ( window[ id ] ) {
		jQuery.support.scriptEval = true;
		delete window[ id ];
	}

	root.removeChild( script );

	if ( div.attachEvent && div.fireEvent ) {
		div.attachEvent("onclick", function(){
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			jQuery.support.noCloneEvent = false;
			div.detachEvent("onclick", arguments.callee);
		});
		div.cloneNode(true).fireEvent("onclick");
	}

	// Figure out if the W3C box model works as expected
	// document.body must exist before we can do this
	jQuery(function(){
		var div = document.createElement("div");
		div.style.width = div.style.paddingLeft = "1px";

		document.body.appendChild( div );
		jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
		document.body.removeChild( div ).style.display = 'none';
	});
})();

var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";

jQuery.props = {
	"for": "htmlFor",
	"class": "className",
	"float": styleFloat,
	cssFloat: styleFloat,
	styleFloat: styleFloat,
	readonly: "readOnly",
	maxlength: "maxLength",
	cellspacing: "cellSpacing",
	rowspan: "rowSpan",
	tabindex: "tabIndex"
};
jQuery.fn.extend({
	// Keep a copy of the old load
	_load: jQuery.fn.load,

	load: function( url, params, callback ) {
		if ( typeof url !== "string" )
			return this._load( url );

		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params )
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else if( typeof params === "object" ) {
				params = jQuery.param( params );
				type = "POST";
			}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" )
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );

				if( callback )
					self.each( callback, [res.responseText, status, res] );
			}
		});
		return this;
	},

	serialize: function() {
		return jQuery.param(this.serializeArray());
	},
	serializeArray: function() {
		return this.map(function(){
			return this.elements ? jQuery.makeArray(this.elements) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				(this.checked || /select|textarea/i.test(this.nodeName) ||
					/text|hidden|password|search/i.test(this.type));
		})
		.map(function(i, elem){
			var val = jQuery(this).val();
			return val == null ? null :
				jQuery.isArray(val) ?
					jQuery.map( val, function(val, i){
						return {name: elem.name, value: val};
					}) :
					{name: elem.name, value: val};
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
	jQuery.fn[o] = function(f){
		return this.bind(o, f);
	};
});

var jsc = now();

jQuery.extend({
  
	get: function( url, data, callback, type ) {
		// shift arguments if data argument was ommited
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = null;
		}

		return jQuery.ajax({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	getScript: function( url, callback ) {
		return jQuery.get(url, null, callback, "script");
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get(url, data, callback, "json");
	},

	post: function( url, data, callback, type ) {
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = {};
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	ajaxSetup: function( settings ) {
		jQuery.extend( jQuery.ajaxSettings, settings );
	},

	ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		username: null,
		password: null,
		*/
		// Create the request object; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
		// This function can be overriden by calling jQuery.ajaxSetup
		xhr:function(){
			return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
		},
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	},

	// Last-Modified header cache for next request
	lastModified: {},

	ajax: function( s ) {
		// Extend the settings, but re-extend 's' so that it can be
		// checked again later (in the test suite, specifically)
		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

		var jsonp, jsre = /=\?(&|$)/g, status, data,
			type = s.type.toUpperCase();

		// convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" )
			s.data = jQuery.param(s.data);

		// Handle JSONP Parameter Callbacks
		if ( s.dataType == "jsonp" ) {
			if ( type == "GET" ) {
				if ( !s.url.match(jsre) )
					s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
			} else if ( !s.data || !s.data.match(jsre) )
				s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
			s.dataType = "json";
		}

		// Build temporary JSONP function
		if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
			jsonp = "jsonp" + jsc++;

			// Replace the =? sequence both in the query string and the data
			if ( s.data )
				s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
			s.url = s.url.replace(jsre, "=" + jsonp + "$1");

			// We need to make sure
			// that a JSONP style response is executed properly
			s.dataType = "script";

			// Handle JSONP-style loading
			window[ jsonp ] = function(tmp){
				data = tmp;
				success();
				complete();
				// Garbage collect
				window[ jsonp ] = undefined;
				try{ delete window[ jsonp ]; } catch(e){}
				if ( head )
					head.removeChild( script );
			};
		}

		if ( s.dataType == "script" && s.cache == null )
			s.cache = false;

		if ( s.cache === false && type == "GET" ) {
			var ts = now();
			// try replacing _= if it is there
			var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
			// if nothing was replaced, add timestamp to the end
			s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
		}

		// If data is available, append data to url for get requests
		if ( s.data && type == "GET" ) {
			s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

			// IE likes to send both get and post data, prevent this
			s.data = null;
		}

		// Watch for a new set of requests
		if ( s.global && ! jQuery.active++ )
			jQuery.event.trigger( "ajaxStart" );

		// Matches an absolute URL, and saves the domain
		var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );

		// If we're requesting a remote document
		// and trying to load JSON or Script with a GET
		if ( s.dataType == "script" && type == "GET" && parts
			&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){

			var head = document.getElementsByTagName("head")[0];
			var script = document.createElement("script");
			script.src = s.url;
			if (s.scriptCharset)
				script.charset = s.scriptCharset;

			// Handle Script loading
			if ( !jsonp ) {
				var done = false;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function(){
					if ( !done && (!this.readyState ||
							this.readyState == "loaded" || this.readyState == "complete") ) {
						done = true;
						success();
						complete();

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;
						head.removeChild( script );
					}
				};
			}

			head.appendChild(script);

			// We handle everything using the script element injection
			return undefined;
		}

		var requestDone = false;

		// Create the request object
		var xhr = s.xhr();

		// Open the socket
		// Passing null username, generates a login popup on Opera (#2865)
		if( s.username )
			xhr.open(type, s.url, s.async, s.username, s.password);
		else
			xhr.open(type, s.url, s.async);

		// Need an extra try/catch for cross domain requests in Firefox 3
		try {
			// Set the correct header, if data is being sent
			if ( s.data )
				xhr.setRequestHeader("Content-Type", s.contentType);

			// Set the If-Modified-Since header, if ifModified mode.
			if ( s.ifModified )
				xhr.setRequestHeader("If-Modified-Since",
					jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );

			// Set header so the called script knows that it's an XMLHttpRequest
			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

			// Set the Accepts header for the server, depending on the dataType
			xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
				s.accepts[ s.dataType ] + ", */*" :
				s.accepts._default );
		} catch(e){}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
			// close opended socket
			xhr.abort();
			return false;
		}

		if ( s.global )
			jQuery.event.trigger("ajaxSend", [xhr, s]);

		// Wait for a response to come back
		var onreadystatechange = function(isTimeout){
			// The request was aborted, clear the interval and decrement jQuery.active
			if (xhr.readyState == 0) {
				if (ival) {
					// clear poll interval
					clearInterval(ival);
					ival = null;
					// Handle the global AJAX counter
					if ( s.global && ! --jQuery.active )
						jQuery.event.trigger( "ajaxStop" );
				}
			// The transfer is complete and the data is available, or the request timed out
			} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;

				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}

				status = isTimeout == "timeout" ? "timeout" :
					!jQuery.httpSuccess( xhr ) ? "error" :
					s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
					"success";

				if ( status == "success" ) {
					// Watch for, and catch, XML document parse errors
					try {
						// process the data (runs the xml through httpData regardless of callback)
						data = jQuery.httpData( xhr, s.dataType, s );
					} catch(e) {
						status = "parsererror";
					}
				}

				// Make sure that the request was successful or notmodified
				if ( status == "success" ) {
					// Cache Last-Modified header, if ifModified mode.
					var modRes;
					try {
						modRes = xhr.getResponseHeader("Last-Modified");
					} catch(e) {} // swallow exception thrown by FF if header is not available

					if ( s.ifModified && modRes )
						jQuery.lastModified[s.url] = modRes;

					// JSONP handles its own success callback
					if ( !jsonp )
						success();
				} else
					jQuery.handleError(s, xhr, status);

				// Fire the complete handlers
				complete();

				if ( isTimeout )
					xhr.abort();

				// Stop memory leaks
				if ( s.async )
					xhr = null;
			}
		};

		if ( s.async ) {
			// don't attach the handler to the request, just poll it instead
			var ival = setInterval(onreadystatechange, 13);

			// Timeout checker
			if ( s.timeout > 0 )
				setTimeout(function(){
					// Check to see if the request is still happening
					if ( xhr && !requestDone )
						onreadystatechange( "timeout" );
				}, s.timeout);
		}

		// Send the data
		try {
			xhr.send(s.data);
		} catch(e) {
			jQuery.handleError(s, xhr, null, e);
		}

		// firefox 1.5 doesn't fire statechange for sync requests
		if ( !s.async )
			onreadystatechange();

		function success(){
			// If a local callback was specified, fire it and pass it the data
			if ( s.success )
				s.success( data, status );

			// Fire the global callback
			if ( s.global )
				jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
		}

		function complete(){
			// Process result
			if ( s.complete )
				s.complete(xhr, status);

			// The request was completed
			if ( s.global )
				jQuery.event.trigger( "ajaxComplete", [xhr, s] );

			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
		}

		// return XMLHttpRequest to allow aborting the request etc.
		return xhr;
	},

	handleError: function( s, xhr, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error ) s.error( xhr, status, e );

		// Fire the global callback
		if ( s.global )
			jQuery.event.trigger( "ajaxError", [xhr, s, e] );
	},

	// Counter for holding the number of active queries
	active: 0,

	// Determines if an XMLHttpRequest was successful or not
	httpSuccess: function( xhr ) {
		try {
			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
			return !xhr.status && location.protocol == "file:" ||
				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
		} catch(e){}
		return false;
	},

	// Determines if an XMLHttpRequest returns NotModified
	httpNotModified: function( xhr, url ) {
		try {
			var xhrRes = xhr.getResponseHeader("Last-Modified");

			// Firefox always returns 200. check Last-Modified date
			return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
		} catch(e){}
		return false;
	},

	httpData: function( xhr, type, s ) {
		var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";
			
		// Allow a pre-filtering function to sanitize the response
		// s != null is checked to keep backwards compatibility
		if( s && s.dataFilter )
			data = s.dataFilter( data, type );

		// The filter can actually parse the response
		if( typeof data === "string" ){

			// If the type is "script", eval it in global context
			if ( type == "script" )
				jQuery.globalEval( data );

			// Get the JavaScript object, if JSON is used.
			if ( type == "json" )
				data = window["eval"]("(" + data + ")");
		}
		
		return data;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a ) {
		var s = [ ];

		function add( key, value ){
			s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
		};

		// If an array was passed in, assume that it is an array
		// of form elements
		if ( jQuery.isArray(a) || a.jquery )
			// Serialize the form elements
			jQuery.each( a, function(){
				add( this.name, this.value );
			});

		// Otherwise, assume that it's an object of key/value pairs
		else
			// Serialize the key/values
			for ( var j in a )
				// If the value is an array then the key names need to be repeated
				if ( jQuery.isArray(a[j]) )
					jQuery.each( a[j], function(){
						add( j, this );
					});
				else
					add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );

		// Return the resulting serialization
		return s.join("&").replace(/%20/g, "+");
	}

});
var elemdisplay = {},
	timerId,
	fxAttrs = [
		// height animations
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		// width animations
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		// opacity animations
		[ "opacity" ]
	];

function genFx( type, num ){
	var obj = {};
	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
		obj[ this ] = type;
	});
	return obj;
}

jQuery.fn.extend({
	show: function(speed,callback){
		if ( speed ) {
			return this.animate( genFx("show", 3), speed, callback);
		} else {
			for ( var i = 0, l = this.length; i < l; i++ ){
				var old = jQuery.data(this[i], "olddisplay");
				
				this[i].style.display = old || "";
				
				if ( jQuery.css(this[i], "display") === "none" ) {
					var tagName = this[i].tagName, display;
					
					if ( elemdisplay[ tagName ] ) {
						display = elemdisplay[ tagName ];
					} else {
						var elem = jQuery("<" + tagName + " />").appendTo("body");
						
						display = elem.css("display");
						if ( display === "none" )
							display = "block";
						
						elem.remove();
						
						elemdisplay[ tagName ] = display;
					}
					
					jQuery.data(this[i], "olddisplay", display);
				}
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( var i = 0, l = this.length; i < l; i++ ){
				this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
			}
			
			return this;
		}
	},

	hide: function(speed,callback){
		if ( speed ) {
			return this.animate( genFx("hide", 3), speed, callback);
		} else {
			for ( var i = 0, l = this.length; i < l; i++ ){
				var old = jQuery.data(this[i], "olddisplay");
				if ( !old && old !== "none" )
					jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( var i = 0, l = this.length; i < l; i++ ){
				this[i].style.display = "none";
			}

			return this;
		}
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,

	toggle: function( fn, fn2 ){
		var bool = typeof fn === "boolean";

		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle.apply( this, arguments ) :
			fn == null || bool ?
				this.each(function(){
					var state = bool ? fn : jQuery(this).is(":hidden");
					jQuery(this)[ state ? "show" : "hide" ]();
				}) :
				this.animate(genFx("toggle", 3), fn, fn2);
	},

	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	animate: function( prop, speed, easing, callback ) {
		var optall = jQuery.speed(speed, easing, callback);

		return this[ optall.queue === false ? "each" : "queue" ](function(){
		
			var opt = jQuery.extend({}, optall), p,
				hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
				self = this;
	
			for ( p in prop ) {
				if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
					return opt.complete.call(this);

				if ( ( p == "height" || p == "width" ) && this.style ) {
					// Store display property
					opt.display = jQuery.css(this, "display");

					// Make sure that nothing sneaks out
					opt.overflow = this.style.overflow;
				}
			}

			if ( opt.overflow != null )
				this.style.overflow = "hidden";

			opt.curAnim = jQuery.extend({}, prop);

			jQuery.each( prop, function(name, val){
				var e = new jQuery.fx( self, opt, name );

				if ( /toggle|show|hide/.test(val) )
					e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
				else {
					var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
						start = e.cur(true) || 0;

					if ( parts ) {
						var end = parseFloat(parts[2]),
							unit = parts[3] || "px";

						// We need to compute starting value
						if ( unit != "px" ) {
							self.style[ name ] = (end || 1) + unit;
							start = ((end || 1) / e.cur(true)) * start;
							self.style[ name ] = start + unit;
						}

						// If a +=/-= token was provided, we're doing a relative animation
						if ( parts[1] )
							end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

						e.custom( start, end, unit );
					} else
						e.custom( start, val, "" );
				}
			});

			// For JS strict compliance
			return true;
		});
	},

	stop: function(clearQueue, gotoEnd){
		var timers = jQuery.timers;

		if (clearQueue)
			this.queue([]);

		this.each(function(){
			// go in reverse order so anything added to the queue during the loop is ignored
			for ( var i = timers.length - 1; i >= 0; i-- )
				if ( timers[i].elem == this ) {
					if (gotoEnd)
						// force the next step to be the last
						timers[i](true);
					timers.splice(i, 1);
				}
		});

		// start the next in the queue if the last step wasn't forced
		if (!gotoEnd)
			this.dequeue();

		return this;
	}

});

// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx("show", 1),
	slideUp: genFx("hide", 1),
	slideToggle: genFx("toggle", 1),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" }
}, function( name, props ){
	jQuery.fn[ name ] = function( speed, callback ){
		return this.animate( props, speed, callback );
	};
});

jQuery.extend({

	speed: function(speed, easing, fn) {
		var opt = typeof speed === "object" ? speed : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
		};

		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
			jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;

		// Queueing
		opt.old = opt.complete;
		opt.complete = function(){
			if ( opt.queue !== false )
				jQuery(this).dequeue();
			if ( jQuery.isFunction( opt.old ) )
				opt.old.call( this );
		};

		return opt;
	},

	easing: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
		}
	},

	timers: [],

	fx: function( elem, options, prop ){
		this.options = options;
		this.elem = elem;
		this.prop = prop;

		if ( !options.orig )
			options.orig = {};
	}

});

jQuery.fx.prototype = {

	// Simple function for setting a style value
	update: function(){
		if ( this.options.step )
			this.options.step.call( this.elem, this.now, this );

		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );

		// Set display property to block for height/width animations
		if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
			this.elem.style.display = "block";
	},

	// Get the current size
	cur: function(force){
		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
			return this.elem[ this.prop ];

		var r = parseFloat(jQuery.css(this.elem, this.prop, force));
		return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
	},

	// Start an animation from one number to another
	custom: function(from, to, unit){
		this.startTime = now();
		this.start = from;
		this.end = to;
		this.unit = unit || this.unit || "px";
		this.now = this.start;
		this.pos = this.state = 0;

		var self = this;
		function t(gotoEnd){
			return self.step(gotoEnd);
		}

		t.elem = this.elem;

		if ( t() && jQuery.timers.push(t) && !timerId ) {
			timerId = setInterval(function(){
				var timers = jQuery.timers;

				for ( var i = 0; i < timers.length; i++ )
					if ( !timers[i]() )
						timers.splice(i--, 1);

				if ( !timers.length ) {
					clearInterval( timerId );
					timerId = undefined;
				}
			}, 13);
		}
	},

	// Simple 'show' function
	show: function(){
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.show = true;

		// Begin the animation
		// Make sure that we start at a small width/height to avoid any
		// flash of content
		this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());

		// Start by showing the element
		jQuery(this.elem).show();
	},

	// Simple 'hide' function
	hide: function(){
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.hide = true;

		// Begin the animation
		this.custom(this.cur(), 0);
	},

	// Each step of an animation
	step: function(gotoEnd){
		var t = now();

		if ( gotoEnd || t >= this.options.duration + this.startTime ) {
			this.now = this.end;
			this.pos = this.state = 1;
			this.update();

			this.options.curAnim[ this.prop ] = true;

			var done = true;
			for ( var i in this.options.curAnim )
				if ( this.options.curAnim[i] !== true )
					done = false;

			if ( done ) {
				if ( this.options.display != null ) {
					// Reset the overflow
					this.elem.style.overflow = this.options.overflow;

					// Reset the display
					this.elem.style.display = this.options.display;
					if ( jQuery.css(this.elem, "display") == "none" )
						this.elem.style.display = "block";
				}

				// Hide the element if the "hide" operation was done
				if ( this.options.hide )
					jQuery(this.elem).hide();

				// Reset the properties, if the item has been hidden or shown
				if ( this.options.hide || this.options.show )
					for ( var p in this.options.curAnim )
						jQuery.attr(this.elem.style, p, this.options.orig[p]);
					
				// Execute the complete function
				this.options.complete.call( this.elem );
			}

			return false;
		} else {
			var n = t - this.startTime;
			this.state = n / this.options.duration;

			// Perform the easing function, defaults to swing
			this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
			this.now = this.start + ((this.end - this.start) * this.pos);

			// Perform the next step of the animation
			this.update();
		}

		return true;
	}

};

jQuery.extend( jQuery.fx, {
	speeds:{
		slow: 600,
 		fast: 200,
 		// Default speed
 		_default: 400
	},
	step: {

		opacity: function(fx){
			jQuery.attr(fx.elem.style, "opacity", fx.now);
		},

		_default: function(fx){
			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
				fx.elem.style[ fx.prop ] = fx.now + fx.unit;
			else
				fx.elem[ fx.prop ] = fx.now;
		}
	}
});
if ( document.documentElement["getBoundingClientRect"] )
	jQuery.fn.offset = function() {
		if ( !this[0] ) return { top: 0, left: 0 };
		if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
		var box  = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
			clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
			top  = box.top  + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop  || body.scrollTop ) - clientTop,
			left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
		return { top: top, left: left };
	};
else 
	jQuery.fn.offset = function() {
		if ( !this[0] ) return { top: 0, left: 0 };
		if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
		jQuery.offset.initialized || jQuery.offset.initialize();

		var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
			doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
			body = doc.body, defaultView = doc.defaultView,
			prevComputedStyle = defaultView.getComputedStyle(elem, null),
			top = elem.offsetTop, left = elem.offsetLeft;

		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
			computedStyle = defaultView.getComputedStyle(elem, null);
			top -= elem.scrollTop, left -= elem.scrollLeft;
			if ( elem === offsetParent ) {
				top += elem.offsetTop, left += elem.offsetLeft;
				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
					top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
					left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
				prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
			}
			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
				top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
				left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
			prevComputedStyle = computedStyle;
		}

		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
			top  += body.offsetTop,
			left += body.offsetLeft;

		if ( prevComputedStyle.position === "fixed" )
			top  += Math.max(docElem.scrollTop, body.scrollTop),
			left += Math.max(docElem.scrollLeft, body.scrollLeft);

		return { top: top, left: left };
	};

jQuery.offset = {
	initialize: function() {
		if ( this.initialized ) return;
		var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
			html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';

		rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
		for ( prop in rules ) container.style[prop] = rules[prop];

		container.innerHTML = html;
		body.insertBefore(container, body.firstChild);
		innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;

		this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
		this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

		innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
		this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

		body.style.marginTop = '1px';
		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
		body.style.marginTop = bodyMarginTop;

		body.removeChild(container);
		this.initialized = true;
	},

	bodyOffset: function(body) {
		jQuery.offset.initialized || jQuery.offset.initialize();
		var top = body.offsetTop, left = body.offsetLeft;
		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
			top  += parseInt( jQuery.curCSS(body, 'marginTop',  true), 10 ) || 0,
			left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
		return { top: top, left: left };
	}
};


jQuery.fn.extend({
	position: function() {
		var left = 0, top = 0, results;

		if ( this[0] ) {
			// Get *real* offsetParent
			var offsetParent = this.offsetParent(),

			// Get correct offsets
			offset       = this.offset(),
			parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();

			// Subtract element margins
			// note: when an element has margin: auto the offsetLeft and marginLeft 
			// are the same in Safari causing offset.left to incorrectly be 0
			offset.top  -= num( this, 'marginTop'  );
			offset.left -= num( this, 'marginLeft' );

			// Add offsetParent borders
			parentOffset.top  += num( offsetParent, 'borderTopWidth'  );
			parentOffset.left += num( offsetParent, 'borderLeftWidth' );

			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}

		return results;
	},

	offsetParent: function() {
		var offsetParent = this[0].offsetParent || document.body;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return jQuery(offsetParent);
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
	var method = 'scroll' + name;
	
	jQuery.fn[ method ] = function(val) {
		if (!this[0]) return null;

		return val !== undefined ?

			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo(
						!i ? val : jQuery(window).scrollLeft(),
						 i ? val : jQuery(window).scrollTop()
					) :
					this[ method ] = val;
			}) :

			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
					jQuery.boxModel && document.documentElement[ method ] ||
					document.body[ method ] :
				this[0][ method ];
	};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){

	var tl = i ? "Left"  : "Top",  // top or left
		br = i ? "Right" : "Bottom", // bottom or right
		lower = name.toLowerCase();

	// innerHeight and innerWidth
	jQuery.fn["inner" + name] = function(){
		return this[0] ?
			jQuery.css( this[0], lower, false, "padding" ) :
			null;
	};

	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function(margin) {
		return this[0] ?
			jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
			null;
	};
	
	var type = name.toLowerCase();

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		return this[0] == window ?
			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
			document.body[ "client" + name ] :

			// Get document width or height
			this[0] == document ?
				// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
				Math.max(
					document.documentElement["client" + name],
					document.body["scroll" + name], document.documentElement["scroll" + name],
					document.body["offset" + name], document.documentElement["offset" + name]
				) :

				// Get or set width or height on the element
				size === undefined ?
					// Get width or height on the element
					(this.length ? jQuery.css( this[0], type ) : null) :

					// Set the width or height on the element (default to pixels if value is unitless)
					this.css( type, typeof size === "string" ? size : size + "px" );
	};

});
})();

// core
/* Copyright Eventful, Inc. All rights reserved except where otherwise noted. */
if (typeof window.Eventful === "undefined")
{
  window.Eventful = {};
}

// Console stubs for Firebug (or lack thereof)

Eventful.console_proxy = function (sFunc)
{
  return function()
  {
    if (window.console && console[sFunc])
    {
      if (console.firebug >= "1.3.0")
      {
        return console[sFunc].apply(console, arguments);
      } else
      {
        return console[sFunc](Array.prototype.slice.call(arguments));
      }
    }
  }
}

Eventful.console = {
  error: Eventful.console_proxy('error'),
  info:  Eventful.console_proxy('info'),
  debug: Eventful.console_proxy('debug'),
  warn:  Eventful.console_proxy('warn'),
  log:   Eventful.console_proxy('log')
}

// IE detection (ugh)
Eventful.isIE = false /*@cc_on @*//*@if (@_win32) || true/*@end @*/;
Eventful.isSafari = navigator && navigator.userAgent.indexOf('Safari') > 0 ;

// JS-CSS relationship ("yes CSS, we have JS enabled")
Eventful.JSCheck = function()
{
  document.body.className += " has-js";
}

Eventful.fixKeyCode = function(keyCode)
{
  var keyEnter = 13;
  if(Eventful.isSafari && keyCode == 3) return keyEnter;
  if(Eventful.isIE && keyCode == 0) return keyEnter;
  return keyCode;
}


/*
  DEVELOPMENT-ONLY CODE. DO NOT MERGE
  THE FOLLOWING INTO PRE-RELEASE.
*/

// require jquery.core

$(function ()
{
  // check for duplicate IDs (only when firebug is enabled and profiling is disabled)
  if (Eventful.Session && !Eventful.Session.Prefs.profiling && window.console && window.console.firebug && !Eventful.SkipDupeIdCheck)
  {
    $('[id]').each(function ()
    {
      if ($('[id='+this.id+']').size() > 1)
      {
        Eventful.console.error('Duplicate ID: #'+this.id);
      }
    });
  }
});

// require eventful.core

/**
  Eventful Custom JS Events
  2007-11-26 / <john@eventful.com>
**/

Eventful.UIEvent = function ()
{
  this.subscribers = [];  
}

Eventful.UIEvent.prototype.subscribe = function (fnCallback)
{
  this.subscribers.push(fnCallback);
}

Eventful.UIEvent.prototype.fire = function ()
{
  var aArgs = arguments;
  // call the subscribers with the given arguments
  for (var i = 0; i < this.subscribers.length; i++)
  {
    this.subscribers[i].apply(undefined, aArgs);
  }
}

// require eventful.core

/**
  Pageview tracking with Google Analytics
  2008-04-10 / <john@eventful.com>
**/

Eventful.TrackPageview = function (oArgs)
{
  oArgs = oArgs || {};
  
  if (typeof oArgs == 'string')
  {
    return Eventful.TrackPageview({page: oArgs});
  }
  
  oArgs.page = oArgs.page || window.location.pathname;
  oArgs.query = oArgs.query || '';
  var sQuery = Eventful.TrackPageview.query();
  
  // resolve query strings
  // note: will not remove repeated parameters
  if (oArgs.query && oArgs.page.indexOf('?') >= 0)
  {
    oArgs.query = '&' + oArgs.query.substring(1); // change "?..." to "&..."
  }
  if (sQuery && (oArgs.page.indexOf('?') >= 0 || oArgs.query))
  {
    sQuery = '&' + sQuery.substring(1); // change "?..." to "&..."
  }
  Eventful.TrackPageview.track(oArgs.page + oArgs.query + sQuery);
}

Eventful.TrackPageview.track = function (sPage)
{
  if (window.pageTracker)
  {
    pageTracker._trackPageview(sPage);
  }
}

// pls follow the pattern TrackEvent, since ga api not support event at this point
Eventful.TrackPageview.trackVirturalEvent = function ()
{ 
  Eventful.TrackPageview.track('/virtual/event/'+Array.prototype.slice.call(arguments).join('/'));
}

Eventful.TrackPageview.trackEvent = function (category, action, optional_label, optional_value)
{
  if (window.pageTracker)
  {
    pageTracker._trackEvent(category, action, optional_label, optional_value);
  }
}

Eventful.TrackPageview.query = function (sQuery)
{
  // sets and gets query string
  return Eventful.TrackPageview._sQuery =
    sQuery ||
    Eventful.TrackPageview._sQuery ||
    window.location.search.toLowerCase();
}

Eventful.TrackPageview.setParams = function (oParams)
{
  // note: will not remove repeated parameters
  var aParams = [];
  for (var sKey in oParams)
  {
    aParams.push(sKey + '=' + oParams[sKey]);
  }
  var sQuery = Eventful.TrackPageview.query();
  Eventful.TrackPageview.query((sQuery ? sQuery + '&' : '?') + aParams.join('&'));
}

// require eventful.core
// require jquery.core

Eventful.Forms = {};

Eventful.Forms.focusFirstField = function (elForm)
{
  // focus first form field
  $(":input", elForm).not('.inactive,:hidden,:file,[value]').eq(0).focus();
}

// require jquery.core

/** This code originated with the Prototype JS library.
  *  Prototype is freely distributable under the terms of an MIT-style license.
  *  For details, see the Prototype web site: http://prototype.conio.net/
  */
if (!Function.prototype.bind)
{
  Function.prototype.bind = function() {
    var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
    return function() {
      var local_args = args.concat(Array.prototype.slice.call(arguments));
      if (this !== window) local_args.push(this);
      return __method.apply(object, local_args);
    }
  }
}

Function.prototype.mixin = function (fn)
{
  this.prototype = $.extend(this.prototype, fn.prototype);
  return this;
}

Function.prototype.later = function (msec)
{
  var fn = this,
     args = Array.prototype.slice.call(arguments,1);
  return window.setTimeout(
    function(){fn.apply(this,args)},
    msec
  );
}

Function.prototype.slow = function (msec, next) {
  var fn = this, tm;
  if(next) {
    // do it right now and "sleep" for msec
    return function() {
      if (tm) return;
      tm = 1;
      fn.apply(this,Array.prototype.slice.call(arguments));
      (function(){tm = 0;}).later(msec);
    }
  } else {
    // wait for msec, do it if no more call; otherwise wait for another msec
    return function(){
      if (tm) clearTimeout(tm);
      tm = (function(args){ tm = 0; fn.apply(this,args); })
        .bind(this,Array.prototype.slice.call(arguments))
        .later(msec);
    }
  }
}

Function.prototype.invert = function ()
{
  return function ()
  {
    return !this.call();
  }.bind(this);
}

; // semicolon to terminate inline code before this block
/*
 * SimpleModal 1.1.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://plugins.jquery.com/project/SimpleModal
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2007 Eric Martin - http://ericmmartin.com
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Revision: $Id: jquery.simplemodal.js 93 2008-01-15 16:14:20Z emartin24 $
 *
 */

/**
 * SimpleModal is a lightweight jQuery plugin that provides a simple
 * interface to create a modal dialog.
 *
 * The goal of SimpleModal is to provide developers with a cross-browser 
 * overlay and container that will be populated with data provided to
 * SimpleModal.
 *
 * There are two ways to call SimpleModal:
 * 1) As a chained function on a jQuery object, like $('#myDiv').modal();.
 * This call would place the DOM object, #myDiv, inside a modal dialog.
 * Chaining requires a jQuery object. An optional options object can be
 * passed as a parameter.
 *
 * @example $('<div>my data</div>').modal({options});
 * @example $('#myDiv').modal({options});
 * @example jQueryObject.modal({options});
 *
 * 2) As a stand-alone function, like $.modal(data). The data parameter
 * is required and an optional options object can be passed as a second
 * parameter. This method provides more flexibility in the types of data 
 * that are allowed. The data could be a DOM object, a jQuery object, HTML
 * or a string.
 * 
 * @example $.modal('<div>my data</div>', {options});
 * @example $.modal('my data', {options});
 * @example $.modal($('#myDiv'), {options});
 * @example $.modal(jQueryObject, {options});
 * @example $.modal(document.getElementById('myDiv'), {options}); 
 * 
 * A SimpleModal call can contain multiple elements, but only one modal 
 * dialog can be created at a time. Which means that all of the matched
 * elements will be displayed within the modal container.
 * 
 * SimpleModal internally sets the CSS needed to display the modal dialog
 * properly in all browsers, yet provides the developer with the flexibility
 * to easily control the look and feel. The styling for SimpleModal can be 
 * done through external stylesheets, or through SimpleModal, using the
 * overlayCss and/or containerCss options.
 *
 * SimpleModal has been tested in the following browsers:
 * - IE 6, 7
 * - Firefox 2
 * - Opera 9
 * - Safari 3
 *
 * @name SimpleModal
 * @type jQuery
 * @requires jQuery v1.1.2
 * @cat Plugins/Windows and Overlays
 * @author Eric Martin (http://ericmmartin.com)
 * @version 1.1.1
 */
(function ($) {
	/*
	 * Stand-alone function to create a modal dialog.
	 * 
	 * @param {string, object} data A string, jQuery object or DOM object
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.modal = function (data, options) {
		return $.modal.impl.init(data, options);
	};

	/*
	 * Stand-alone close function to close the modal dialog
	 */
	$.modal.close = function () {
		// call close with the external parameter set to true
		$.modal.impl.close(true);
	};

	/*
	 * Chained function to create a modal dialog.
	 * 
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.fn.modal = function (options) {
		return $.modal.impl.init(this, options);
	};

	/*
	 * SimpleModal default options
	 * 
	 * overlay: (Number:50) The overlay div opacity value, from 0 - 100
	 * overlayId: (String:'modalOverlay') The DOM element id for the overlay div
	 * overlayCss: (Object:{}) The CSS styling for the overlay div
	 * containerId: (String:'modalContainer') The DOM element id for the container div
	 * containerCss: (Object:{}) The CSS styling for the container div
	 * close: (Boolean:true) Show the default window close icon? Uses CSS class modalCloseImg
	 * closeTitle: (String:'Close') The title value of the default close link. Depends on close
	 * closeClass: (String:'modalClose') The CSS class used to bind to the close event
	 * persist: (Boolean:false) Persist the data across modal calls? Only used for existing
	            DOM elements. If true, the data will be maintained across modal calls, if false,
				the data will be reverted to its original state.
	 * onOpen: (Function:null) The callback function used in place of SimpleModal's open
	 * onShow: (Function:null) The callback function used after the modal dialog has opened
	 * onClose: (Function:null) The callback function used in place of SimpleModal's close
	 */
	$.modal.defaults = {
		overlay: 50,
		overlayId: 'modalOverlay',
		overlayCss: {},
		containerId: 'modalContainer',
		containerCss: {},
		close: true,
		closeTitle: 'Close',
		closeClass: 'modalClose',
		persist: false,
		onOpen: null,
		onShow: null,
		onClose: null
	};

	/*
	 * Main modal object
	 */
	$.modal.impl = {
		/*
		 * Modal dialog options
		 */
		opts: null,
		/*
		 * Contains the modal dialog elements and is the object passed 
		 * back to the callback (onOpen, onShow, onClose) functions
		 */
		dialog: {},
		/*
		 * Initialize the modal dialog
		 */
		init: function (data, options) {
			// don't allow multiple calls
			if (this.dialog.data) {
				return false;
			}

			// merge defaults and user options
			this.opts = $.extend({}, $.modal.defaults, options);

			// determine how to handle the data based on its type
			if (typeof data == 'object') {
				// convert DOM object to a jQuery object
				data = data instanceof jQuery ? data : $(data);

				// if the object came from the DOM, keep track of its parent
				if (data.parent().parent().size() > 0) {
					this.dialog.parentNode = data.parent();

					// persist changes? if not, make a clone of the element
					if (!this.opts.persist) {
						this.dialog.original = data.clone(true);
					}
				}
			}
			else if (typeof data == 'string' || typeof data == 'number') {
				// just insert the data as innerHTML
				data = $('<div>').html(data);
			}
			else {
				// unsupported data type!
				if (console) {
					console.log('SimpleModal Error: Unsupported data type: ' + typeof data);
				}
				return false;
			}
			this.dialog.data = data.addClass('modalData');
			data = null;

			// create the modal overlay, container and, if necessary, iframe
			this.create();

			// display the modal dialog
			this.open();

			// useful for adding events/manipulating data in the modal dialog
			if ($.isFunction(this.opts.onShow)) {
				this.opts.onShow.apply(this, [this.dialog]);
			}

			// don't break the chain =)
			return this;
		},
		/*
		 * Create and add the modal overlay and container to the page
		 */
		create: function () {
			// create the overlay
			this.dialog.overlay = $('<div>')
				.attr('id', this.opts.overlayId)
				.addClass('modalOverlay')
				.css($.extend(this.opts.overlayCss, {
					opacity: this.opts.overlay / 100,
					height: '100%',
					width: '100%',
					position: 'fixed',
					left: 0,
					top: 0,
					zIndex: 3000
				}))
				.hide()
				.appendTo('body');

			// create the container
			this.dialog.container = $('<div>')
				.attr('id', this.opts.containerId)
				.addClass('modalContainer')
				.css($.extend(this.opts.containerCss, {
          // position: 'fixed',
					zIndex: 3100
				}))
				.append(this.opts.close 
					? '<a class="modalCloseImg ' 
						+ this.opts.closeClass 
						+ '" title="' 
						+ this.opts.closeTitle + '"></a>'
					: '')
				.hide()
				.appendTo('body');

			// fix issues with IE and create an iframe
			if ($.browser.msie && ($.browser.version < 7)) {
				this.fixIE();
			}

			// hide the data and add it to the container
			this.dialog.container.append(this.dialog.data.hide());
		},
		/*
		 * Bind events
		 */
		bindEvents: function () {
			var modal = this;

			// bind the close event to any element with the closeClass class
			$('.' + this.opts.closeClass).click(function (e) {
				e.preventDefault();
				modal.close();
			});
		},
		/*
		 * Unbind events
		 */
		unbindEvents: function () {
			// remove the close event
			$('.' + this.opts.closeClass).unbind('click');
		},
		/*
		 * Fix issues in IE 6
		 */
		fixIE: function () {
      if ($(document.body).height() < $(document).height())
      {
        // increase body height to fill viewport
        $(document.body).css({height: '100%'});
      }
      
			var wHeight = $(document.body).height() + 'px';
			var wWidth = $(document.body).width() + 'px';

			// position hacks
			this.dialog.overlay.css({position: 'absolute', height: wHeight, width: wWidth});
			this.dialog.container.css({position: 'absolute'});

			// add an iframe to prevent select options from bleeding through
			this.dialog.iframe = $('<iframe src="javascript:false;">')
				.css($.extend(this.opts.iframeCss, {
					opacity: 0, 
					position: 'absolute',
					height: wHeight,
					width: wWidth,
					zIndex: 1000,
					width: '100%',
					top: 0,
					left: 0
				}))
				.hide()
				.appendTo('body');
		},
		/*
		 * Open the modal dialog elements
		 * - Note: If you use the onOpen callback, you must "show" the 
		 *         overlay and container elements manually 
		 *         (the iframe will be handled by SimpleModal)
		 */
		open: function () {
			// display the iframe
			if (this.dialog.iframe) {
				this.dialog.iframe.show();
			}

			if ($.isFunction(this.opts.onOpen)) {
				// execute the onOpen callback 
				this.opts.onOpen.apply(this, [this.dialog]);
			}
			else {
				// display the remaining elements
				this.dialog.overlay.show();
				this.dialog.container.show();
				this.dialog.data.show();
			}

			// bind default events
      // this.bindEvents();
		},
		/*
		 * Close the modal dialog
		 *
		 * @param {boolean} external Indicates whether the call to this
		 *     function was internal or external. If it was external, the
		 *     onClose callback will be ignored
		 */
		close: function (external) {
			// prevent close when dialog does not exist
			if (!this.dialog.data) {
				return false;
			}

			if ($.isFunction(this.opts.onClose) && !external) {
				// execute the onClose callback
				this.opts.onClose.apply(this, [this.dialog]);
			}
			
			// if the data came from the DOM, put it back
			if (this.dialog.parentNode) {
				// save changes to the data?
				if (this.opts.persist) {
					// insert the (possibly) modified data back into the DOM
					this.dialog.data.hide().appendTo(this.dialog.parentNode);
				}
				else {
					// remove the current and insert the original, 
					// unmodified data back into the DOM
					this.dialog.data.remove();
					this.dialog.original.appendTo(this.dialog.parentNode);
				}
			}
			else {
				// otherwise, remove it
				this.dialog.data.remove();
			}

			// remove the remaining elements
			this.dialog.container.remove();
			this.dialog.overlay.remove();
			if (this.dialog.iframe) {
				this.dialog.iframe.remove();
			}

			// reset the dialog object
			this.dialog = {};
				

			// remove the default events
			this.unbindEvents();
		}
	};
})(jQuery);
// require eventful.core
// require eventful.uievent
// require eventful.track-pageview
// require eventful.forms
// require prototype.function
// require jquery.core
// require jquery.modal

/**
  Panels built on jQuery's SimpleModal plugin
  2008-05-22 / <john@eventful.com>
**/

Eventful.Panel = function (id)
{
  this.id = id;
  this.trackingString = null;
  this.eventShow = new Eventful.UIEvent();
  this.eventClose = new Eventful.UIEvent();
  this.eventReady = new Eventful.UIEvent();
  
  // toggle ads on show/close
  var fnToggleAds = function (){$('.rev-gen').toggle();};
  this.eventShow.subscribe(fnToggleAds);
  this.eventClose.subscribe(fnToggleAds);
}

Eventful.Panel.prototype.panel = function ()
{
  if (!this.jqPanel) this.jqPanel = $('#'+this.id);
  return this.jqPanel;
}

Eventful.Panel.prototype.find = function (sExpr)
{
  return this.panel().find(sExpr)
}

Eventful.Panel.prototype.options = function (oOptions)
{
  
  if (oOptions.tracking_string)
  {
    // Set up tracking var
    this.trackingString = oOptions.tracking_string;
  }
  
  if (oOptions.width)
  {
    // convert to numeric
    oOptions.width = +oOptions.width.toString().replace('px', '');
    
    // set width and center horizontally
    oOptions.containerCss = $.extend(oOptions.containerCss, {
      width: oOptions.width,
      marginLeft: -oOptions.width/2
    });
  }
  
  // merge options with defaults
  oOptions = $.extend({
    persist: true,
    overlay: 75,
    onShow: this.listenShow.bind(this),
    // onClose: this.listenClose.bind(this),
    closeClass: 'modalClose',
    closeOnKeyEsc: false
  }, oOptions);
  
  oOptions.containerCss = $.extend({
    position: 'absolute'
  }, oOptions.containerCss);
  
  this.oOptions = oOptions;
  
  return this;
}

Eventful.Panel.prototype.autoShow = function (sHash)
{
  if (window.location.hash == "#"+sHash)
  {
    $(this.show.bind(this));
  }
}

Eventful.Panel.prototype.clickShow = function (sQuery)
{
  return this.clickClose(sQuery, true);
}

Eventful.Panel.prototype.clickClose = function (sQuery, bShow)
{
  $(function ()
  {
    if (sQuery instanceof Array) sQuery = $.map(sQuery, function (id) {return '#'+id}).join();
    $(sQuery).click(function (evt)
    {
      evt.preventDefault();
      if (bShow) this.show(evt);
      else this.close(evt);
    }.bind(this));
  }.bind(this));
  return this;
}

Eventful.Panel.prototype.show = function (evt)
{
  if (!this.panel().length) return this;
  
  if (this.oOptions.containerCss.position == 'absolute')
  {
    // this.oOptions.containerCss.top = 0;
    this.oOptions.containerCss.top = (Eventful.scrollTop()+30)+'px';
  }
  
  // save parent panel
  if (this.parent(Eventful.Panel.current())) 
  {
    this.parent().close();
  }
  
  this.jqModal = this.panel().modal(this.oOptions);
  Eventful.Panel.current(this);
  
  // vertically center, leave ie6 alone
  if (this.oOptions.containerCss.position == 'fixed' && !($.browser.msie && ($.browser.version < 7)))
  { 
    var jqMC = $('#modalContainer');
    jqMC
      .css('top','50%')
      .css('marginTop','-'+Math.round(jqMC.height() * 0.67)+'px');
  }
  
  //close lightbox if hit ESC
  if (this.oOptions.closeOnKeyEsc) 
  {
    $('#modalContainer').one( 'keyup',
      function(evt){ if( evt.keyCode == 27 ) this.close(); }.bind(this)
    );
  }

  $('#modalContainer .'+this.oOptions.closeClass).one('click',this.close.bind(this));
  
  if (this.trackingString) {
    Eventful.TrackPageview.track(this.trackingString);
  }
  this.eventShow.fire(evt);
  return this;
}

Eventful.Panel.prototype.close = function (evt)
{
  if (this.jqModal) this.jqModal.close();
  this.eventClose.fire(evt);
  
  if (Eventful.Panel.current() == this)
  {
    // clear the current
    Eventful.Panel.current(null);
  }
  
  if (this.parent())
  {
    // restore and clear the parent
    this.parent().show();
    this.parent(null);
  }
  
  return this;
}

Eventful.Panel.prototype.parent = function (obj)
{
  return obj !== undefined ? this.oParent = obj : this.oParent || null;
}

Eventful.Panel.prototype.listenShow = function ()
{
  Eventful.Forms.focusFirstField(this.panel());
}

Eventful.Panel.current = function (obj)
{
  return obj !== undefined ? Eventful.Panel.oCurrent = obj : Eventful.Panel.oCurrent || null;
}

Eventful.scrollTop = function ()
{
  return document.body.scrollTop || document.documentElement.scrollTop || 0;
}

// require eventful.core
// require eventful.panel
// require prototype.function

Eventful.PanelSigninRequired = function (oArgs)
{
  // for singleton access
  Eventful.PanelSigninRequired._oInstance = this;
  
  // handle arguments: freatureIds (optional), idPanel (optional)
  oArgs = oArgs || {};
  var featureIds = oArgs.featureIds;
  var idPanel = oArgs.idPanel || "panel-signin-required";
  
  var tracking_string = "lbox_mustsignin_unknown";
  var panel_width = "540px";
  
  if (Eventful.Session.userType == 'email')
  {
    tracking_string = "lbox_mustsignin_known";
  }
  
  if ($('#uid-pwd-line').size())
  {
    // narrow variation
    panel_width = "360px";
  }

  Eventful.Panel.call(this, idPanel);
  
  this.options({
    width: panel_width, 
    tracking_string: tracking_string,
    closeOnKeyEsc: true, 
    containerCss: { position: 'fixed' }
  });
  
  if (featureIds)
  {
    this.clickShow(featureIds);
  }
}.mixin(Eventful.Panel)

// convenience methods

Eventful.PanelSigninRequired.get = function()
{
  return Eventful.PanelSigninRequired._oInstance || new Eventful.PanelSigninRequired();
}

Eventful.PanelSigninRequired.show = function()
{
  return Eventful.PanelSigninRequired.get().show();
}

// require eventful.core

Eventful.Cookies = {};

Eventful.Cookies.addCookie = function(sKey, sValue, nExpires)
{
  var sCurrentValue = Eventful.Cookies.getCookie(sKey);
  sValue = (sCurrentValue?sCurrentValue+'^':'')+sValue;
  Eventful.Cookies.setCookie(sKey, sValue, nExpires);
}

Eventful.Cookies.setCookie = function(sKey, sValue, nExpires, sPath)
{
  if(!sPath) sPath = '/';
  var sCookie = sKey+'='+sValue+';path='+sPath+';';
  if (nExpires)
  {
    var oDate = new Date(new Date().getTime()+nExpires*60000); // nExpires in minutes
    sCookie += 'expires='+oDate.toUTCString()+';';
  }
  document.cookie = sCookie;
}

Eventful.Cookies.getCookie = function(sKey)
{
  var rx = new RegExp(sKey+'=([^;]*)');
  return (document.cookie.match(rx) || [])[1];
}


Eventful.Cookies.removeCookie = function(sKey, sPath)
{
  Eventful.Cookies.setCookie (sKey, '', -1, sPath);
}

// require eventful.core
// require eventful.cookies
// require jquery.core

Eventful.Tracker = function ()
{
  $('body').click(Eventful.Tracker.listenClick);
}

Eventful.Tracker.setCookie = function (sValue)
{
  // initialize cookie with current location
  var sCookie = Eventful.Cookies.getCookie('tid2') || window.location.href;
  Eventful.Cookies.setCookie('tid2', sCookie+'^'+sValue, 30);
}

Eventful.Tracker.listenClick = function (evt)
{
  // var el = Events.getTargetElement(evt);
  var el = $(evt.target).parents('[id]:first');
  
  if (el.size())
  {
    if (el.is('select') && $.browser.msie)
    {
      setTimeout(function(){Eventful.Tracker.setCookie(el.attr('id'));}, 0);
    } else
    {
      Eventful.Tracker.setCookie(el.attr('id'));
    }
  }
}

$(Eventful.Tracker);

// require eventful.core
// require prototype.function
// require jquery.core

Eventful.HeatMap = function ()
{
  $(this.setup.bind(this));
}

Eventful.HeatMap.prototype.setup = function ()
{
  $('body').append('<button class="heat-toggle">Show heatmap</button>');
  $('button.heat-toggle').click(this.listenToggle.bind(this));
}

Eventful.HeatMap.prototype.request = function ()
{
  $('button.heat-toggle').html('Loading...');
  $.ajax({
    url: '/json/tools/tid2',
    data: {url: window.location.pathname},
    success: this.listenServerResponse.bind(this),
    dataType: 'json'
  });
}

Eventful.HeatMap.prototype.build = function ()
{
  // remove old heatmap
  $('.heat, .heat-info').remove();
  
  var nMin = 0;
  var nMax = 0;
  
  // intify everything
  for (var sId in this.oData)
    for (var sKey in this.oData[sId])
      this.oData[sId][sKey] = parseInt(this.oData[sId][sKey]);
  
  // compute the min and max of the "total" key
  for (var sId in this.oData)
  {
    if (sId != 'sum')
    {
      var nTotal = this.oData[sId].total;
      if (!nMin || nTotal < nMin) nMin = nTotal;
      if (!nMax || nTotal > nMax) nMax = nTotal;
    }
  }
  
  for (var sId in this.oData)
  {
    var el = $('#'+sId);
    var elParent = el.parent();
    
    if (el.length)
    {
      var nNorm = Math.pow((this.oData[sId].total-nMin)/(nMax-nMin), 0.5);
      var aColor = Eventful.HeatMap.BYRGradient(nNorm);
      var sColor = 'rgb('+aColor.join(',')+')';

      if (!el.width())
      {
        // compute height/width from some child
        for (el = el.children(':first'); el.length && !el.width(); el = el.next()) ;
      }
      
      if (!el.length)
      {
        continue;
      }
      
      var sHTML ="<strong>#"+sId+"</strong><ul>";
      for(var sKey in this.oData[sId])
      {
        var nValue = this.oData[sId][sKey];
        var nSum = this.oData.sum[sKey];
        sHTML += "<li>"+sKey+": "+nValue+" ("+Math.floor(100*nValue/nSum)+"%)</li>";
      }
      sHTML += "</ul>";
              
      var elInfo = $('<div class="heat-info">'+sHTML+'</div>').
        css({
          borderColor: sColor
        }).
        appendTo(elParent);
      
      $('<div class="heat"></div>').
        css({
          left: el[0].offsetLeft-10,
          top: el[0].offsetTop-10,
          width: el.width()+20,
          height: el.height()+20,
          zIndex: 1000+el.parents().length,
          backgroundColor: sColor
        }).
        click(function() { $(this).hide(); }).
        mouseover(this.listenMouseOver.bind(this, elInfo)).
        mousemove(this.listenMouseMove.bind(this, elInfo)).
        mouseout(this.listenMouseOut.bind(this, elInfo)).
        appendTo(elParent);
    }
  }
  
  $('button.heat-toggle').html('Hide heatmap');
  $('body').addClass('show-heat');
}

/* server response handler */

Eventful.HeatMap.prototype.listenServerResponse = function (oResponse)
{
  this.oData = oResponse.tid2;
  this.build();
}

/* event handlers */

Eventful.HeatMap.prototype.listenToggle = function (elToggle)
{
  if ($('body').hasClass('show-heat'))
  {
    $('body').removeClass('show-heat');
    $('button.heat-toggle').html('Show heatmap');
  } else if (this.oData)
  {
    this.build();
  } else
  {
    this.request();
  }
}

Eventful.HeatMap.prototype.listenMouseOver = function (elInfo)
{
  elInfo.addClass('show-info');
}

Eventful.HeatMap.prototype.listenMouseMove = function (elInfo, evt)
{
  elInfo.css({
    left: evt.clientX+10,
    top: evt.clientY-10
  });
}

Eventful.HeatMap.prototype.listenMouseOut = function (elInfo, evt)
{
  elInfo.removeClass('show-info');
}

/* utility methods */

Eventful.HeatMap.BYRGradient = function (n)
{
  if (n < 0.5)
  {
    // blue to yellow
    return [Math.floor((2*n)*255), Math.floor((2*n)*255), Math.floor((1-2*n)*255)];
  } else
  {
    // red to yellow
    return [255, Math.floor((1-n)*2*255), 0];
  }
}

Eventful.HeatMap.Setup = function ()
{
  if (Eventful.Session.Prefs.heat_map)
  {
    new Eventful.HeatMap();
  }
}

$(Eventful.HeatMap.Setup);

; // semicolon to terminate inline code before this block
/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
		if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
			return colors['transparent'];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}

	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break;

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};

	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0],
		transparent: [255,255,255]
	};

})(jQuery);

// require prototype.function
// require eventful.core
// require jquery.core
// require jquery.color_anim
 
Eventful.Notification = function(){
  var fnAnimation = function(){
    var oStyle = Eventful.Notification.style();
    $('.notification#notification')
    .animate({ 
      backgroundColor: "#ffffff",
      color:"#666666",
      borderBottomColor: oStyle.borderColor,
      borderLeftColor: oStyle.borderColor,
      borderRightColor: oStyle.borderColor,
      borderTopColor: oStyle.borderColor
    }, 2000)
    .find('.sign').animate({ 
      backgroundColor: "#eeeeee"
    }, 2000);

  }
  
  $(function(){fnAnimation.later(1000);});
}

Eventful.Notification.oStyle = {
  borderColor: '#eeeeee'
}

Eventful.Notification.style = function (oArgs)
{
  if (oArgs)
  {
    $.extend(Eventful.Notification.oStyle, oArgs);
  }
  
  return Eventful.Notification.oStyle;
}

// require eventful.core
// require eventful.uievent
// require prototype.function
// require jquery.core

/* 
  Eventful.FormVal
  2008-06-21 / <tao@eventful.com>
*/

Eventful.FormVal = function (formJExpr, summaryJExpr, oArgs) {
  // the form we are going to deal with
  this.jForm = $(formJExpr);

  // summary error sometime been omit when form is small
  if(summaryJExpr) this.jqFormSummary = $(summaryJExpr);

  // operating args
  if(!oArgs) oArgs = {};
  this.args = {
    summaryError: oArgs.summaryError || "Oh no! Errors! Please check the fields above.",
    summaryEmpty: oArgs.summaryEmpty || "You forgot to fill out the fields! Good thing I reminded you.",
    keepValidate: oArgs.keepValidate === undefined ? false : oArgs.keepValidate // unless set, validation will stop once success
  };

  // the form will be validate again these rule, add later
  this.rules = [];
  
  // pay attention to those events
  this.eventPassValid = new Eventful.UIEvent();
  this.eventJSONValidate = new Eventful.UIEvent();
  this.eventFailValid = new Eventful.UIEvent();
  this.eventErrorShown = new Eventful.UIEvent();

  // capture the form submit from this point
  this.initialize();
}

Eventful.FormVal.prototype.bindEvent = function(nm, fn) {
  var nmEvts = {
    'passValid':this.eventPassValid,
    'failValid':this.eventFailValid,
    'errorShown':this.eventErrorShown,
    'JSONValidate':this.eventJSONValidate
  };
  if(nmEvts[nm]) nmEvts[nm].subscribe(fn);
  return this;
}

// return RE literal, welcome contribution
Eventful.FormVal.GetPattern = function(type) {
  var allPatterns = {
    "float": /^-?(\d+\.?\d*|\d*\.\d+)$/,
    "number": /^[-+]?\d+$/,
    "email": /^[\w.%+-]+@([\w-]+\.)+[A-Za-z]{2,4}$/,
    "url": /^https?:\/\/([\w-]+\.)+[A-Za-z]{2,4}/i
  };   
  
  return allPatterns[type];
} 
Eventful.FormVal.prototype.getPattern = Eventful.FormVal.GetPattern;

// Toggle active status, with alt text attribute
Eventful.FormVal.setInactive = function(exprActiveToggle) {
  $(exprActiveToggle || 'input[type=text][alt],textarea[alt]', 
    !exprActiveToggle && this.jForm ? this.jForm : undefined)
    .bind('focus',function(){
      if($(this).hasClass('inactive')){
        $(this).removeClass('inactive').val('');
      }
    })
    .bind('blur',function(){
      var alt = $(this).attr('alt');
      if(this.value == ''){
        $(this).addClass('inactive').val(alt);
      }
    })
    .each(function(i,el){
      var alt = $(this).attr('alt');
      if(el.value == "" || el.value == alt ){
        $(el).addClass('inactive').val(alt);
      }
    });
  return this;
}
Eventful.FormVal.prototype.setInactive = Eventful.FormVal.setInactive;

// Your need to do this before submit
Eventful.FormVal.emptyInactive = function(exprActiveToggle) {
  $(exprActiveToggle || 'input.inactive[type=text][alt],textarea.inactive[alt]', 
    !exprActiveToggle && this.jForm ? this.jForm : undefined ).val('');
  return this;
}
Eventful.FormVal.prototype.emptyInactive = Eventful.FormVal.emptyInactive;

// capture the form submit and do validate
Eventful.FormVal.prototype.initialize = function (){
  this._serializedValues = this.jForm.serialize();

  this.jForm.bind('submit.formval',function(){
    this.validateForm.bind(this).later(1);
    return false;
  }.bind(this));

  return this;
}

// no validation any more
Eventful.FormVal.prototype.deinitialize = function() {
  this.jForm.unbind('submit.formval');
  return this;
}

// pay more attention for error field
Eventful.FormVal.prototype.focusFirstField = function (){
  // try to focus the first input with an error
  var jqInputs = this.jForm.find('.has-error :input').not(':hidden');
  
  if (!jqInputs.size())
  {
    // try to focus the first input
    jqInputs = this.jForm.find(':input').not(':hidden');
  }
  
  jqInputs.eq(0).trigger('focus');
  
  return this;
}

// Check if the form has been changed since initialize
Eventful.FormVal.prototype.isDirty = function(){
  return this._serializedValues !== this.jForm.serialize();
}

// do validation, fire the result
Eventful.FormVal.prototype.validateForm = function() {
  // peole like to submit without any input, stop it quick
  if( $.grep(
        this.jForm.find(":input").not(':hidden,:button,:reset,:image,:submit,.inactive').serializeArray(),
        function(pair){return !!$.trim(pair.value)}).length === 0 &&
    $.grep(this.rules, function(rule){return rule.rule.required;}).length > 0 &&
    this.jqFormSummary ) 
  {
      this.showSummaryError(this.args.summaryEmpty);
      return;
  } 

  this.hideSummaryError().hideHasError();

  // clean up validation
  $.each(this.rules, function (_, oNameRulePair) {
    oNameRulePair.rule.quality = {
      error: 0,
      message: '',
      defaultMessage: ''
    };
  });
  
  // helper
  function _markBadQuality(errInput, jInput, rule, errBit, defMsg, msg){
    errInput.push(jInput);

    rule.quality.error |= 1<<errBit;
    rule.quality.defaultMessage = defMsg || "The input has error";
    rule.quality.message = msg || rule.message;
  }

  var errInput = [], jsonQueue = [];

  // start to check each rule
  $.each(this.rules, function (_, oNameRulePair) {
    var jInput = this.jForm.find(':input[name='+oNameRulePair.name+']'),
        rule = oNameRulePair.rule;
    if(jInput.length == 0 ||
      $.grep(errInput,function(j){return jInput.attr('name')===j.attr('name')}).length ||
      !rule) return;

    /* grep all NON-empty value, possiblly array of nameval object for checkbox multi-select */
    var nameValues = $.grep(
      jInput.not('.inactive').serializeArray(),
      function(pair){return !!$.trim(pair.value)}
    );
    
    // ignore rule if ignoreCb returns true
    if (rule.ignoreCb && rule.ignoreCb(jInput.length === 1 ? jInput[0] : jInput, nameValues)) {
      return;
    }

    /* RULE required */
    if(rule.required && !nameValues.length) {
      _markBadQuality(errInput,jInput,rule,0,"Data is required");

    /* RULE pattern */
    }else if (nameValues.length && rule.pattern &&
      $.grep(nameValues, function (oPair) {return rule.pattern.test(oPair.value)===false;}).length) {
      _markBadQuality(errInput,jInput,rule,1,"The input has incorrect format");
      
    /* RULE minlen for string or multi selector */
    }else if (nameValues.length && rule.hasOwnProperty("minlen")) {
      // min string length
      if(jInput.is(':text, :password, textarea') && jInput.val().length < rule.minlen) {
        _markBadQuality(errInput,jInput,rule,2, "string length must >= " + rule.minlen);

      // min selected item  
      } else if(jInput.is(':checkbox, select') && nameValues.length < rule.minlen) {
        _markBadQuality(errInput,jInput,rule,3,"at least " + rule.minlen + " selected");
      } 

    /* RULE maxlen for string or multi selector */
    }else if(nameValues.length && rule.hasOwnProperty("maxlen")){
      // max string length
      if(jInput.is(':text, :password, textarea') && jInput.val().length > rule.maxlen) {
        _markBadQuality(errInput,jInput,rule,4,"string length must <= " + rule.maxlen);

      // max selected items
      } else if(jInput.is(':checkbox, select') && nameValues.length > rule.maxlen) {
        _markBadQuality(errInput,jInput,rule,5,"at most " + rule.maxlen + " selected");
      } 

    /* RULE min for number */
    }else if (nameValues.length && rule.hasOwnProperty("min") && jInput.is(':text')) {
      var aNum = /^[+-]?\d+$/.test(jInput.val()) ? parseInt(jInput.val()) : parseFloat(jInput.val());
      
      if(isNaN(aNum) || aNum < rule.min) {
        _markBadQuality(errInput,jInput,rule,6,"must >= " + rule.min);
      }

    /* RULE max for number */
    }else if (nameValues.length && rule.hasOwnProperty("max") && jInput.is(':text')) {
      var aNum = /^[+-]?\d+$/.test(jInput.val()) ? parseInt(jInput.val()) : parseFloat(jInput.val());

      if(isNaN(aNum) || aNum > rule.max) {
        _markBadQuality(errInput,jInput,rule,7,"must <= " + rule.max);
      }

    /* RULE helperCb */
    } else if (rule.helperCb){
      var msg = rule.helperCb(jInput.length === 1 ? jInput[0] : jInput, nameValues);
      if(msg && msg.error) _markBadQuality(errInput,jInput,rule,8,'Failed to helper check',msg.message);

    /* RULE helperCb, BECAUSE expensive, hold it until all other ready */
    } else if (rule.jsonCb){
      var oJSONsetup = rule.jsonCb(jInput.length == 1 ? jInput[0] : jInput, nameValues);
      if (oJSONsetup && (oJSONsetup.post || oJSONsetup.get))
      {
        jsonQueue.push($.extend(oJSONsetup,{
          'rule':rule,
          'jInput':jInput
        }));
      }
    }

  }.bind(this));  // end of each rule check

  // if any error input
  if(errInput.length) {
    this._afterFailure(errInput);

  // if need json validation
  } else if (jsonQueue.length){
     var _onJsonResponse = function(helperCb, jInput, rule, oResponse) {
       var msg = helperCb(oResponse, jInput.length == 1 ? jInput[0] : jInput, this.jForm[0]);

       if(msg && msg.error){
         _markBadQuality(errInput, jInput, rule, 9, 'Failed to ajax check', msg.message);
         this._afterFailure(errInput);
       } else if(jsonQueue.length){
         _shiftJsonQueue.call(this);
       } else {
         this._afterSuccess();
       }
     },
     
     _shiftJsonQueue = function(){
       var oJson = jsonQueue.shift();
       if(oJson) $.ajax({
         url: oJson.post || oJson.get,
         type: oJson.post ? "post" : "get",
         data: oJson.data,
         success: _onJsonResponse.bind(this, oJson.helperCb, oJson.jInput, oJson.rule),
         error: _onJsonResponse.bind(this, oJson.helperErrorCb || function(){return{"error":1,"message":"Sorry! There is trouble to validate your input."}}, oJson.jInput, oJson.rule),
         dataType: oJson.dataType || 'json'
       });
     };
     
     _shiftJsonQueue.call(this);
     this.eventJSONValidate.fire();

  // happy end
  } else {
     this._afterSuccess();
  }
  
  return this;
}

Eventful.FormVal.prototype._afterSuccess = function() {
  if(!this.args.keepValidate) this.deinitialize();

  if (this.eventPassValid.subscribers.length) {
    this.eventPassValid.fire(this.jForm[0]);

  // if no interests on eventPassValid, submit form directly
  } else {
    this.emptyInactive();
    this.jForm.trigger('submit');
  }
  return this;
}

Eventful.FormVal.prototype._afterFailure = function(errInput) {
  this.showSummaryError();
  this.showHasError(errInput);

  this.eventFailValid.fire(this.jForm[0], errInput);
  return this;
}

Eventful.FormVal.prototype.addRule = function (inputname, oRule, position) {
  if(typeof position == 'number') {
    this.rules.splice(position, 0, { name: inputname, rule: oRule});
  } else {
    this.rules.push({ name: inputname, rule: oRule});
  }
  return this;
}

Eventful.FormVal.prototype.removeRule = function (inputname) { 
  this.rules = $.map(this.rules,function(oRule){
    return oRule.name === inputname ? null : oRule;
  });
  return this;
}

Eventful.FormVal.prototype.showShowError = function(elInput){
  // input container <li>
  var jqElContainer = $(elInput).parents(".field-container").addClass("show-errors");
  var sInputName = $(elInput).attr('name');
  var sMessage = "There are errors in your input."; // default error message
  
  var jqFormError = jqElContainer.find(".form-error");
  
  // if form-error not presented add form-error
  if (!jqFormError.size()){
    jqFormError = $('<div class="form-error"></div>')
      .attr('id', sInputName+'-error')
      .appendTo(jqElContainer);
  }
  
  // find first violated rule for this input
  var oNameRulePair = $.grep(this.rules, function (oNameRulePair) {
    return oNameRulePair.name == sInputName && oNameRulePair.rule.quality && oNameRulePair.rule.quality.error;
  })[0];
  
  if (oNameRulePair)
  {
    var oRule = oNameRulePair.rule;
    // backup orignal text only once
    if (oRule.markupMessage == undefined)
    {
      oRule.markupMessage = jqFormError.html();
    }
    // error message precedence
    sMessage = oRule.quality.message || oRule.markupMessage || oRule.quality.defaultMessage || sMessage;
  }
  
  jqFormError.html(sMessage);
  this.eventErrorShown.fire(elInput, jqFormError.get(0));
  return this;
}

Eventful.FormVal.prototype.hideShowError = function(elInput){
  $(elInput).parents(".field-container").removeClass("show-errors");
  return this;
}

// the most refined mothed. called after failed to verify
Eventful.FormVal.prototype.showHasError = function(errInput){
  this._fnClearHasError = this._fnClearHasError ? this._fnClearHasError.splice(0) : [];  

  // do this for every error input
  $.each(errInput,function(i,el){

    var jqEl = $(el),
        jqContainer = jqEl.parents(".field-container").addClass("has-error");
    if(jqContainer.length == 0) return;
    
    // listen on focus and blur
    jqEl.bind("focus.haserror",this.showShowError.bind(this,el))
        .bind("blur.haserror",this.hideShowError.bind(this,el));

    // after user re-try on the error input
    var afterTryAgain = function(){
      jqContainer.removeClass("has-error").removeClass("show-errors");
      jqEl.unbind("focus.haserror").unbind("blur.haserror");
    }

    // listen on user's re-try. Meanwhile, _fnClearHasError is used when hideHasError called
    if (jqEl.is(':text, :password, textarea')) {
      jqEl.bind("keyup.causechange",function(sOldVal){
        if($(this).val() != sOldVal) {
          afterTryAgain();
          $(this).unbind('keyup.causechange')
        }
      }.bind(jqEl[0],jqEl.val()));
      
      this._fnClearHasError.push(function(){
        jqEl.unbind("keyup.causechange");
        afterTryAgain();
      });
    } else if (jqEl.is('select')) {
      jqEl.one("change",afterTryAgain);
      this._fnClearHasError.push(function(){
        jqEl.unbind("change",afterTryAgain);
        afterTryAgain();
      });
    } else if (jqEl.is(':checkbox, :radio')) {
      jqEl.one("click",afterTryAgain);
      this._fnClearHasError.push(function(){
        jqEl.unbind("click",afterTryAgain);
        afterTryAgain();
      });
    }
  }.bind(this));

  return this.focusFirstField(); 
}

Eventful.FormVal.prototype.hideHasError = function(){
  if(this._fnClearHasError) {
    var fn;
    while(fn = this._fnClearHasError.pop()) fn();
  }

  return this;
}

Eventful.FormVal.prototype.showSummaryError = function(sErrorMsg){
  if(this.jqFormSummary) {
    sErrorMsg = sErrorMsg || this.args.summaryError;

    this.jqFormSummary.html(sErrorMsg).addClass("show-errors");

    // if form changed, hide summary error, ignor form changed
    var fnHideSummary = function(sOldFormValue){
      if(sOldFormValue !== this.jForm.serialize()) {
        this.hideSummaryError();

        this.jForm
          .find(':text, :password, textarea')
            .unbind("keyup",fnHideSummary)
            .end()
          .find('select')
            .unbind("change",fnHideSummary)
            .end()
          .find(':checkbox, :radio')
            .unbind("click",fnHideSummary);
      }
    }.bind(this,this.jForm.serialize());

    // listen on form change
    this.jForm
      .find(':text, :password, textarea')
        .bind("keyup",fnHideSummary)
        .end()
      .find('select')
        .bind("change",fnHideSummary)
        .end()
      .find(':checkbox, :radio')
        .bind("click",fnHideSummary);
  }

  return this.focusFirstField(); 
}

Eventful.FormVal.prototype.hideSummaryError = function(evt){
  if(this.jqFormSummary) {
    this.jqFormSummary.empty().removeClass("show-errors");
  }

  return this;
}


// require eventful.core
// require jquery.core
// require eventful.panel
// require prototype.function
// require eventful.formval
// require eventful.track-pageview

/**
  Primary JS file for the Eventful Action Items
  Created : 2008/10/13
  Author : ReShun Davis (reshun@eventful.com)
**/

Eventful.ActionItems = function (oArgs) {
  $(document).ready(this.setup.bind(this));
}

Eventful.ActionItems.prototype.setup = function() {
  this.jqActionItems  = $(".action-item");
  this.jqJoinButton   = $("#btn-signin-required-join");
  this.jqJoinFrom     = $("#form-signin-required-from");
  this.bFromSet       = false;
  
  $(".action-items li, .action-items tr, .action-items dt, .action-items dd, .actionable").hover(
      function () {
        $(this).addClass("hovering");
      }, 
      function () {
        $(this).removeClass("hovering");
      }
    );
  
  // Click handlers
  this.jqActionItems.click(this.listenActOnItemClick.bind(this));
  
  // Setup signing required panel
  this.oSignInPanel = new Eventful.PanelSigninRequired({featureIds:['nop']});
}

Eventful.ActionItems.prototype.doTrack = function(sType) {
  if (!sType) return;
  
  var sTrackId = "/click_pfav_" + sType + "&type=" + Eventful.Session.userType;
  
  // Track the event
  Eventful.TrackPageview.track(sTrackId);
}

Eventful.ActionItems.prototype.listenActOnItemClick = function(evt) {
  var jqActor = $(evt.target);
  var bDoSwitch = Eventful.Session.userType == 'session' ? false : true;

  if (jqActor.attr('href') == '/my') {
    return;
  }
  else {
    evt.preventDefault();
  }
  
  if (Eventful.Session.userType == 'session' || Eventful.Session.userType == 'email') {
    // append 'from' tag to join button
    if (!this.bFromSet) {
      // add query param to the join buttons href
      var sHref = this.jqJoinButton.attr('href');
      if (sHref) {
        var aHrefSplit = sHref.split('?');
        if (aHrefSplit[0]) {
          Eventful.console.log(aHrefSplit[0] + "?from=from_pfav&" + sHref.substring(aHrefSplit[0].length+1));
          this.jqJoinButton.attr('href', aHrefSplit[0] + "?from=from_pfav&" + sHref.substring(aHrefSplit[0].length+1));
        }
      }
      
      // set the from value
      this.jqJoinFrom.attr('value', 'from_pfav');
      Eventful.console.log("From: " + this.jqJoinFrom.attr('value'));
      
      // make note that we have set the goto so we don't re-add them again
      this.bFromSet = true;
    }
    
    // show the signin panel
    this.oSignInPanel.show();
    // Need tracking for session users so we will return in the 'doAddItem' 
    // method to prevent asynch call for those users
  }
  
  // Get the parent action-item div
  if (!jqActor.hasClass('action-item')) {
    jqActor = jqActor.parents('.action-item').eq(0);
  }
  
  if (jqActor.hasClass("action-item-inactive")) {
    // only switch icon if user is going to be able to save
    if (bDoSwitch) jqActor.removeClass('action-item-inactive').addClass('action-item-active');
    
    // do the action
    this.doAddItem(jqActor.attr('alt'), 'add');
  }
  else if (jqActor.hasClass('action-item-active')) {
    jqActor.removeClass('action-item-active').addClass('action-item-inactive');
    
    // do the action
    this.doAddItem(jqActor.attr('alt'), 'remove');
  }
}

Eventful.ActionItems.prototype.listenItemUpdated = function() {
  return;
  // Eventful.console.log("The item has been updated");
}

Eventful.ActionItems.prototype.doAddItem = function(sId, sAction) {
  // sId and sAction are required
  if (!sId || !sAction) return;
  
  var aIdSplit = sId.split('-');

  switch (aIdSplit[0]) {
    case 'E0':
      var url = "/json/tools/users/favorites/events/" + sAction;
      
      // Track this click
      this.doTrack('event');
      
      // send off the request for non-session users
      if (Eventful.Session.userType != 'session') {
        $.post(url, {id: sId}, this.listenItemUpdated.bind(this), "json");
      }
      
      break;
      
    case 'V0':
      var url = "/json/tools/users/favorites/venues/" + sAction;

      // Track this click
      this.doTrack('venue');
      
      // send off the request for non-session users
      if (Eventful.Session.userType != 'session') {
        $.post(url, {id: sId}, this.listenItemUpdated.bind(this), "json");
      }
      
      break;
      
    case 'P0':
      var url = "/json/tools/users/favorites/performers/" + sAction;
      
      // Track this click
      this.doTrack('performer');
      
      // send off the request for non-session users
      if (Eventful.Session.userType != 'session') {
        $.post(url, {id: sId}, this.listenItemUpdated.bind(this), "json");
      }
      
      break;
      
    default:
      var url = "/json/tools/users/favorites/users/" + sAction;
      
      // Track this click
      this.doTrack('user');
      
      // only users can add friends to favorites
      if (Eventful.Session.userType == 'user') {
        $.post(url, {id: sId}, this.listenItemUpdated.bind(this), "json");
      }
  }
}


new Eventful.ActionItems();

// require eventful.core
// require jquery.core
// require eventful.track-pageview

/**
  JS file for GA tracking of ticket link clicks
  Created : 2008/11/13
  Author : ReShun Davis (reshun@eventful.com)
**/

Eventful.TrackTicketLinks = function () {
  $("a.ticket-link").click(function(evt) {
    // Track the event
    Eventful.TrackPageview.track("/click_ticket");
  });
}

// initialize when page is ready
$(Eventful.TrackTicketLinks);

// require eventful.core
// require prototype.function
// jquery.core

/**
  Click Offsite - logs clicks on a.click-offsite to /r
  2008-01-21 / <john@eventful.com>
**/

Eventful.ClickOffsite = function (el)
{
  $('a.click-offsite', el).click(Eventful.ClickOffsite.listenClick);
}

Eventful.ClickOffsite.listenClick = function (evt)
{
  // allow the default behavior if any modifiers were used
  if (evt.ctrlKey || evt.shiftKey || evt.metaKey || evt.altKey) return;
  // cancel the click and force the user through our redirect script (defaults to blank window)
  evt.preventDefault();
  window.open(Eventful.ClickOffsite.redirect(this.href), this.target || '_blank'); 
}

Eventful.ClickOffsite.redirect = function (sLocation)
{
  return '/r/' + sLocation;
}

// jQuery's ready event callsback with jQuery as an argument
$(function(){Eventful.ClickOffsite()});

// require eventful.core
// require eventful.panel
// require prototype.function

Eventful.PanelAlert = function (id)
{                                       
  Eventful.Panel.call(this, id || 'panel-alert');
  
  this.options();
}.mixin(Eventful.Panel);

Eventful.PanelAlert.prototype.options = function (oOptions) {
  return Eventful.Panel.prototype.options.call(this,
    $.extend({
        width: "350px",
        closeOnKeyEsc: true,
        containerCss: { position: 'fixed' }
      }, oOptions
    )
  );
}

/* VIP instance */
Eventful.PanelHelp = function (id) {
  Eventful.PanelAlert.call(this,id);
}.mixin(Eventful.PanelAlert);

Eventful.PanelHelp.prototype.options = function (oOptions) {
  return Eventful.PanelAlert.prototype.options.call(this,
    $.extend({closeClass:'modalCloseGreen'}, oOptions)
  );
}

// require eventful.core
// require eventful.uievent
// require jquery.core

Eventful.Autoclose = function ()
{
  $('body').click(Eventful.Autoclose.body_click);
}

Eventful.Autoclose.element_id = null;
Eventful.Autoclose.afterClosed = new Eventful.UIEvent();

// Called on all clicks (which are inside the body) to close autoclose element
Eventful.Autoclose.body_click = function (evt)
{
  if (evt)
  {
    var elTarget = $(evt.target);
    if (elTarget.size())
    {
      // if we're clicking on an autoclose or autoclose-click element
      if (elTarget.hasClass("autoclose") ||
          elTarget.hasClass("autoclose-click") ||
          elTarget.parents('.autoclose').size())
      {
        // bail out early before closing the block
        return true;
      }
    }
  }
  Eventful.Autoclose.close_block();
}

// Called to close the current autoclose block
Eventful.Autoclose.close_block = function()
{
  var id = Eventful.Autoclose.element_id;
  if (id && id.length)
  {
    var elAutoclose = $('#'+id);
    if (elAutoclose.size())
    {
      elAutoclose.hide();
      Eventful.Autoclose.element_id = null;
      Eventful.Autoclose.afterClosed.fire(elAutoclose.get(0));
    }
  }
}

// Called when the *click* elements are clicked to show the autoclose elements
Eventful.Autoclose.set_id = function(idEl)
{
  if (Eventful.Autoclose.element_id != idEl)
  {
    // if we're setting a new id, close an old block (if it's open)
    Eventful.Autoclose.close_block();
    Eventful.Autoclose.element_id = idEl;
  }
}

$(Eventful.Autoclose);

// require eventful.core
// require eventful.uievent
// require eventful.autoclose
// require prototype.function
// require jquery.core
// require eventful.track-pageview
 
/**
  Popover: parallel to Panel; call when DOM ready;
  2008-10-29 / <tao@eventful.com>
 
  Example:
    (new Eventful.Popover('#comment-post-popover',{
      width:"270px",
      css: {
        'backgroundColor': false,
        'zIndex':       "1000"
      },
      position:{
        relative: "sender",
        top: 20,
        left: 'auto',
        right: 0
      }
    }))
    .clickShow(this.jqOpenPopover)
    .clickClose('#btn-comment-post-cancel');
**/
Eventful.Popover = function (jqEx,oOptions)
{
  // two interactive events
  this.eventShow = new Eventful.UIEvent();
  this.eventClose = new Eventful.UIEvent();
 
  // override those property
  this._setup({
    width:            "300px",          // shorthand for css {width:"300px"}
    css: {                              // disable default css needs explicitly by boolean false
      'backgroundColor':'#fff',
      'border':       '1px solid #666',
      'zIndex':       "10"
    },
    position: {
      "top":          10,               // in number
      "left":         10,               // in number
      "right":        'auto',           // non-number truthy value
      "bottom":       'auto',           // non-number truthy value
      "relative":     'mouse'           // ["mouse"*,"click","sender","viewport",element]
    },
    no_focus:         false,             // disable field-focus on show
    tracking:         ''                 // send GA tracking when show
  },jqEx,oOptions||{});
}
 
Eventful.Popover.prototype._setup = function (default_args,jqEx,oOptions) {
  // merge all css apply to either popover or container
  var popoverCss = {}, containerCss = {};
  $.each(
    $.extend (
      default_args.css,
      {'width':default_args.width},
      oOptions.css,
      {'width': oOptions.width}
    ), 
    
    function(attr,val) {
      if(!val) return;

      // some attr reserve for container
      if(/^(width|height|zIndex)$/.test(attr)){
        containerCss[attr] = val;
      } else {
        popoverCss[attr] = val;
      }
    }
  );
 
  // create popover and apply css
  this.popover(jqEx).css(popoverCss);

  // these are for "this"
  this.args = {
    'containerCss'    : containerCss,                                         // css for container
    'position'        : $.extend(default_args.position, oOptions.position),   // how align container
    'tracking'        : oOptions.tracking || default_args.tracking,
    'no_focus'        : oOptions.no_focus || default_args.no_focus,
    'listenKeyESC'    : !!this.find(':input').not(':hidden').length // ESC may close container if form presented
  };
}
 
// singleton, goodguy rule: do not access "this"
Eventful.Popover.prototype.container = function (){
  var jContainer,   // only one container in the page,
      oEvt,         // very last event trigger show happened
      oInst,        // the instance being shown
      
      // event handler for container
      fnKeyESCHdl = function (evt){
        if( evt.keyCode == 27 && oInst) {
          oInst.close(evt);
        }
      },
      fnReposition = function (evt){
        if (oInst) oInst._position(evt);
      },
      fnMouseLeaveHdl =  function (){
        if( oInst ) oInst._slowUIAct(!oInst.args.slowActOverPopover,true);
      },
      fnMouseEnterHdl =  function (){ // reposition only onMouseEnter container
        if( oInst ) oInst._slowUIAct(!oInst.args.slowActOverPopover,false);
      },

      // replace anthingy in container with "intc", show it and bind related event
      fnShow = function(intc,evt){
        if(oInst) fnClose(); // never should happen, but for safe

        oInst = intc;
        oEvt = evt ? {'target':evt.target, 'pageX':evt.pageX, 'pageY':evt.pageY } : null; // light copy required

        jContainer
        .prepend(oInst.popover(true))
        .css($.extend(
          {height:'auto', width:'auto', zIndex:'auto'},
          oInst.args.containerCss,
          {"top": "-1000px", "left": "-1000px"}
        ))
        .show();
        oInst._position(oEvt);

        // bind event handle
        if(oInst.args.listenOverPopover) {
          jContainer
          .bind('mouseenter',fnMouseEnterHdl)
          .bind('mouseleave',fnMouseLeaveHdl);
        }
        if(oInst.args.listenKeyESC) {
          jContainer.bind('keyup',fnKeyESCHdl);
        }
        if(oInst.args.position.relative === 'mouse' && oEvt) {
          $(oEvt.target).bind('mousemove',fnReposition);
        }
      },
      // reversely, unbind event, empty container and hide it
      fnClose = function() {
        if(oInst.args.listenOverPopover) {
          jContainer
          .unbind('mouseenter',fnMouseEnterHdl)
          .unbind('mouseleave',fnMouseLeaveHdl);
        }
        if(oInst.args.listenKeyESC) {
          jContainer.unbind('keyup',fnKeyESCHdl);
        }
        if(oInst.args.position.relative === 'mouse' && oEvt) {
          $(oEvt.target).unbind('mousemove',fnReposition);
        }
        
        jContainer
        .hide()
        .children().not('iframe')
          .each(function(){
            if (this.parentNode) this.parentNode.removeChild(this);
          });

        oInst = oEvt = null;
      };

  return function(doElse){
    // create single one container
    if (!jContainer) {
      jContainer = $('<div id="eventful-tooltip" class="popover autoclose" \
                          style="position:absolute;margin:0;border:0;padding:0;background-color:transparent;"> \
                      </div>')
        .appendTo(document.body)
        .hide()
        // onResize container, reposition. work for IE only. not important
        .bind('resize',function(){
          jContainer
            .children('iframe')
            .css({
              'width': jContainer.width(),
              'height': jContainer.height()
            });
         
          fnReposition(oEvt);
        });
        
      // fix select leaking on IE by an underneath iframe. when ie6 die? 
      if ($.browser.msie && ($.browser.version < 7)) {
        jContainer.append('<iframe frameborder="0" src="javascript:\'\'" \
                             style="position:absolute;top:0;left:0;z-index:-1;filter:mask();"> \
                           </iframe>');
      }
 
      // on window resize, reposition. !IMPORTANT
      $(window).bind('resize', function(){fnReposition(oEvt);} );
    }
    
    if (doElse) {
      if(doElse.get && doElse.get === 'event') {
        return oEvt;

      } else if(doElse.get && doElse.get === 'instance') {
        return oInst;

      // show container with passed in instance and event
      } else if(doElse.set && doElse.set[0]) {
        fnShow(doElse.set[0], doElse.set[1]);

      // close container
      } else if(doElse.set && oInst){
        fnClose();
      }
    } 
    
    return jContainer;
  }
}();
 
Eventful.Popover.prototype.popover = function (jqEx){
  //  create popover
  if(!this._jPopover && jqEx){
    this._jPopover = $(jqEx).hide();

    // in DOM, later detach it
    if(this._jPopover.parents('body').length) {
      this._jPopover._delayDetach = true;
    // not in dom, wrap it with <div>  
    } else if (typeof jqEx === 'string'){
      this._jPopover = $('<div class="popbd">'+jqEx+'</div>');
    }
    
  // signaled, detach from dom just before show
  } else if(this._jPopover._delayDetach && jqEx === true) {
    this._jPopover.each(function(){
      if (this.parentNode) this.parentNode.removeChild( this );
    }).removeClass('hidden').show();
    delete this._jPopover['_delayDetach'];

  }

  return this._jPopover;
}

Eventful.Popover.prototype.find = function (sExpr)
{
  return this.popover().find(sExpr)
}
 
// jSel: the trigger to show;  bStayOpen: default the tigger toggle the popover
Eventful.Popover.prototype.clickShow = function (jSel, bStayOpen) {
  $(jSel)
  .addClass('popover-sender autoclose') // need for autoclose and position
  .click(function (evt){

    (!bStayOpen && this.isOpen()) ? this.close(evt) : this.show(evt);
    return false;

  }.bind(this));
  return this;
}
 
Eventful.Popover.prototype.clickClose = function (jSel) {
  $(jSel).click(function(evt){

    this.close(evt);
    return false;

  }.bind(this));
  return this;
}

//  options {
//   show_over: boolean, keep the popover open when over popover
//   show_slow: boolean, 500ms slow down. when opener and popover far apart, but still show_over
// }
Eventful.Popover.prototype.hoverShow = function (jSel, options) {
  var fnShow, fnClose;

  if(options && (options.show_over || options.show_slow)) {
    fnShow = this._slowUIAct.bind(this,!options.show_slow,false);
    fnClose = this._slowUIAct.bind(this,!options.show_slow,true);

  } else {
    fnShow = this.show.bind(this);
    fnClose = this.close.bind(this);
  }

  // if listen mouse enter/leave container
  this.args.listenOverPopover = !!(options && options.show_over);
  
  // if slow handle mouse enter/leave container
  this.args.slowActOverPopover = this.args.listenOverPopover && options.show_slow; 
  
  $(jSel)
  .addClass('popover-sender')
  .bind('mouseenter',fnShow)
  .bind('mouseleave',fnClose);

  return this;
}

// when listen on enter/leave popover
Eventful.Popover.prototype._slowUIAct =(function(){
  var fn = function (evt, bClosing){ 
      bClosing === true ? this.close(evt) : this.show(evt); 
    },
    fnHalfSec = fn.slow(500),
    fnMillSec = fn.slow(10);
  
  return function(bQuick,bClosing,evt){
    (bQuick ? fnMillSec : fnHalfSec)
    .call( this, 
      evt ? {'target':evt.target, 'pageX':evt.pageX, 'pageY':evt.pageY} : null, // light copy required
      bClosing
    );
  }
})();

// if this is open; when bPopover, if any popover open
Eventful.Popover.prototype.isOpen = function(bPopover) {
  var inst = this.container({'get': 'instance'});
  return bPopover ? !!inst : this === inst;
}

Eventful.Popover.prototype.show = function (evt) {
  // "this" already open
  if(this.isOpen()){
    var lastShowEvt = this.container({'get': 'event'});
    // must be called programatically, do reposition 
    if(!evt) return this._position(lastShowEvt); 
    // not twice
    if(lastShowEvt && lastShowEvt.target === evt.target) return this._position(evt);
  }
  
  // close anything opened
  if(this.isOpen(true)) {
    this.container({'get': 'instance'}).close(evt);
  } 

  // show time
  this.container({'set': [this, evt]});
    
  // focus unless you say "No"
  if (!this.args.no_focus) {
    this.container().find(":input").not('.inactive,:hidden').eq(0).trigger('focus');
  }

  // tracking
  if (this.args.tracking) {
    Eventful.TrackPageview.track(this.args.tracking);
  } 

  // work with autoclose
  Eventful.Autoclose.set_id(this.container().attr('id'));

  this.eventShow.fire(evt);
  return this;
}
 
Eventful.Popover.prototype.close = function(evt) {
  this.container({'set': [null, null]});

  // work with autoclose
  Eventful.Autoclose.element_id = null;

  this.eventClose.fire(evt);
  return this;
}

Eventful.Autoclose.afterClosed.subscribe(function(elClose){
  // if Autoclose close container, need a nicer close
  if (elClose === Eventful.Popover.prototype.container()[0]) {
    var intsToClose = Eventful.Popover.prototype.container({'get': 'instance'});
    if(intsToClose) intsToClose.close();
  }
});
 
// only ["viewport",element] without evt
Eventful.Popover.prototype._position = function (evt){
  var docScrollTop = document.body.scrollTop || document.documentElement.scrollTop || 0, //$(document).scrollTop()
     docScrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft || 0, //$(document).scrollLeft()
     h = this.container().height(),
     w = this.container().width(),
     top = 0,
     left = 0;  // make these two right
 
  // relative to a dom element or sender who triggered the show,
  if(typeof this.args.position.relative == 'object' || (this.args.position.relative == 'sender' && evt)) {
 
    var jRelative = typeof this.args.position.relative === 'object' ?
                    $(this.args.position.relative):
                    $(evt.target).parents('.popover-sender').andSelf(),
        positionOffset = jRelative.offset();

    if( typeof this.args.position.top == 'number') {
     top = positionOffset.top + this.args.position.top;
    } else if( typeof this.args.position.bottom == 'number'){
     top = positionOffset.top + jRelative.height() - h - this.args.position.bottom;
    } else {
     top = positionOffset.top + 10;
    }

    if( typeof this.args.position.left == 'number') {
     left = positionOffset.left + this.args.position.left;
    } else if( typeof this.args.position.right == 'number'){
     left = positionOffset.left + jRelative.width() - w - this.args.position.right;
    } else {  
     left = positionOffset.left + 10;
    }

   // relative to viewport
  } else if(this.args.position.relative == 'viewport'){

    if( typeof this.args.position.top == 'number') {
     top = docScrollTop + this.args.position.top;
    } else if( typeof this.args.position.bottom == 'number'){
     top = docScrollTop + $(window).height() - h - this.args.position.bottom;
    } else {
     top = docScrollTop + 10;
    }
   
    if( typeof this.args.position.left == 'number') {
     left = docScrollLeft + this.args.position.left;
    } else if( typeof this.args.position.right == 'number'){
     left = docScrollLeft + $(window).width() - w - this.args.position.right;
    } else {  
     left = docScrollLeft + 10;
    }

  // relative to mouse, only top/left effective and try stay within viewport
  } else if(/^(mouse|click)$/.test(this.args.position.relative) && evt){
    if (typeof this.args.position.top !== 'number') this.args.position.top = 10;
    if (typeof this.args.position.left !== 'number') this.args.position.left = 10;
    
    if(evt.pageY <= docScrollTop + $(window).height() * 0.5) {
      top = evt.pageY + this.args.position.top;
    } else {
      top = evt.pageY - this.args.position.top - h;   
    }
    
    if(evt.pageX <= docScrollLeft + $(window).width() * 0.5) {
      left = evt.pageX + this.args.position.left;
    } else {
      left = evt.pageX - this.args.position.left - w;   
    }
  }

  this.container().css({"top": top + "px", "left": left + "px"});
  return this;
}

Eventful.Popover.blockUI = function() {
  if(!Eventful.Popover.blockUI.blocker) Eventful.Popover.blockUI.blocker =new Eventful.Popover(
      '<div id="eventful-uiblocker" style="height:'+$(document).height()+
      'px;background:#FFFFFF url(http://static.eventful.com/store/skin/throbbers/throbber_32x32.gif) no-repeat fixed center center;"></div>',{
    css:{
      width: '100%',
      border: false,
      opacity: 0.66
    },
    position:{
      top: 0,
      left:0,
      relative: 'viewport'
    }
  });
  Eventful.Popover.blockUI.blocker.show();
}

Eventful.Popover.unblockUI = function() {
  if(Eventful.Popover.blockUI.blocker) Eventful.Popover.blockUI.blocker.close();
}

// require eventful.core
// require jquery.core
// require prototype.function
// require eventful.popover

Eventful.Tooltip = function (elTooltip, oPosition)
{
  var el = $(elTooltip);
  
  /* default args */
  
  var oArgs = {
    position: {
      relative: 'sender',
      top: 10
    },
    css: {
      zIndex: 1000,
      borderColor: '#777',
      width: 200
    }
  };
  
  /* defaults for left/right variations */
  
  if (el.find('.tab').is('.right'))
  {
    $.extend(oArgs.position, {
      right: 10,
      left: 'auto'
    });
  } else
  {
    $.extend(oArgs.position, {
      right: 'auto',
      left: 10
    });
  }
  
  /* apply overrides */
  
  $.extend(oArgs.position, oPosition);
  
  /* instantiate popover */
  
  Eventful.Popover.call(this, el, oArgs)
  this.hoverShow(el.parent(), {show_over: true});
  // close on mouseover
  el.find('.bd').mouseover(this.close.bind(this));
}.mixin(Eventful.Popover)

// require eventful.core
// require jquery.core

/**
  Inactive Text - automatically toggle .inactive and inactive text (from alt tag)
  2008-03-06 / <john@eventful.com>
**/

Eventful.InactiveText = function (el)
{
  el = $(el);
  
  el.blur();
  el.blur(Eventful.InactiveText.listenBlur);
  el.focus(Eventful.InactiveText.listenFocus);
  
  // initially inactive
  if (!el.attr('defaultValue'))
  {
    el.val(el.attr('alt'));
    el.addClass('inactive');
  } else
  {
    el.val(el.attr('defaultValue'));
  }
  
  // always remove 'inactive-text' class
  el.removeClass('inactive-text');
}

Eventful.InactiveText.attachHandlers = function (root)
{
  // attach handlers to all .inactive elements under elRoot
  $('.inactive-text', root).each(function (_, el) {
    Eventful.InactiveText(el);
  });
}

Eventful.InactiveText.listenBlur = function (evt)
{
  var el = $(evt.target);
  
  if (!el.val() && !el.parents('.field-container.has-error').size())
  {
    // add inactive state
    el.addClass('inactive');
    el.val(el.attr('alt'));
  }
}

Eventful.InactiveText.listenFocus = function (evt)
{
  var el = $(evt.target);
  
  if (el.hasClass('inactive'))
  {
    // remove inactive state
    el.removeClass('inactive');
    el.val('');
  }
}

Eventful.InactiveText.doForcedUpdate = function (el)
{
  el = $(el);
  // add inactive state
  el.addClass('inactive');
  el.val(el.attr('alt'));
}

// require eventful.core
// require eventful.uievent
// require eventful.inactive-text
// require jquery.core
// require prototype.function

Eventful.DropDown = function (oArgs)
{
  this.elInput         = oArgs.input;
  this.elPopover       = oArgs.popover;
  this.nMinInputLength = oArgs.minInputLength || 0;
  
  // If 'exact' is true, then only input that is actually in the 
  // queue will be reported by eventItemSelected. If it's false,
  // then the input will be reported instead of the current
  // queue value if the user has not engaged the queue by clicking
  // on a queue element or using up/down arrow keys.
  this.bExact          = oArgs.exact;

  this.eventItemSelected    = new Eventful.UIEvent();
  this.eventInputChanged    = new Eventful.UIEvent();
  this.eventPopoverShown    = new Eventful.UIEvent();
  this.eventItemHighlighted = new Eventful.UIEvent();
  this.eventBlur            = new Eventful.UIEvent();
  this.eventBadFocus        = new Eventful.UIEvent();
  this.eventEnterAfterSelected    = new Eventful.UIEvent();

  $(this.setup.bind(this));
}

Eventful.DropDown.prototype.popover = function ()
{
  return this.jqPopover ? this.jqPopover : this.jqPopover = $(this.elPopover);
}

Eventful.DropDown.prototype.find = function (sExpr)
{
  return this.popover().find(sExpr);
}

Eventful.DropDown.prototype.input = function ()
{
  return this.jqInput ? this.jqInput : this.jqInput = $(this.elInput);
}

Eventful.DropDown.prototype.list = function ()
{
  return this.jqList ? this.jqList : this.jqList = this.find('ul');
}

Eventful.DropDown.prototype.setup = function ()
{
  if (this.input().hasClass('inactive-text'))
  {
    Eventful.InactiveText(this.input());
  }
  
  this.input().
    focus(this.listenFocus.bind(this)).
    click(this.listenClick.bind(this)).
    blur(this.listenBlur.bind(this)).
    keyup(this.listenKeyUp.bind(this));
  
  if (jQuery.browser.safari || jQuery.browser.msie)
  {
    this.input().keydown(this.listenKeyDown.bind(this));
  } else
  {
    this.input().keypress(this.listenKeyDown.bind(this));
  }
  
  this.popover().
    mousedown(this.listenMouseDown.bind(this)).
    mouseup(this.listenMouseUp.bind(this));
  
  if (this.list().html())
  {
    // static list: attach handlers directly to li elements (supports scrollbar)
    this.list().find('li').
      mouseover(this.listenMouseOver.bind(this)).
      click(this.listenClickItem.bind(this))
  } else
  {
    // dynamic list: attach handlers to ul element (doesn't support scrollbar)
    this.list().
      mouseover(this.listenMouseOver.bind(this)).
      click(this.listenClickItem.bind(this));
  }
}

Eventful.DropDown.prototype.reset = function ()
{
  // reset state
  this.input().val('');
  this.popover().hide();
  this.list().empty();
  this.queue(null);
  
  // reset inactive text
  if (!this.bHasFocus)
  {
    Eventful.InactiveText.doForcedUpdate(this.input())
  }
}

Eventful.DropDown.prototype.currentElement = function ()
{
  // return the element corresponding to the current item in the queue
  if (this.oQueue)
  {
    return this.list().find('li').eq(this.oQueue.iter);
  }
}

Eventful.DropDown.prototype.indexFromElement = function (el)
{
  el = $(el);
  el = el.is('li') ? el : el.parents('li'); // get the li
  return this.list().find('li').index(el[0]); // index the li
}

Eventful.DropDown.prototype.queue = function (oQueue)
{
  if (oQueue !== undefined)
  {
    if (oQueue) oQueue.next(); // initialize
    this.oQueue = oQueue;
  }
  
  return this.oQueue;
}

Eventful.DropDown.prototype.usingQueue = function (bUsingQueue)
{
  // true if the user is using the queue
  // false if the user is giving manual input
  if (bUsingQueue !== undefined) this.bUsingQueue = bUsingQueue;
  return this.bUsingQueue;
}

Eventful.DropDown.prototype.showPopover = function ()
{
  var sVal = this.input().hasClass('inactive') ? '' : this.input().val();
  
  if ((this.list().html() || this.popover().hasClass('empty'))
    && sVal.length >= this.nMinInputLength)
  {
    // show results popover
    this.popover().show();
    // fix popover width and height with room to grow
    this.find('iframe.popover-layer').css({
      width: this.popover().width(),
      height: this.popover().height()+500
    });
    this.eventPopoverShown.fire();
    setTimeout(function(){this.input().select()}.bind(this), 0);
  }
}

Eventful.DropDown.prototype.highlight = function (arg)
{
  // arg is index, "next", or "prev"
  
  if (this.oQueue[arg] || arg != this.oQueue.iter)
  {
    if (this.oQueue[arg])
    {
      this.oQueue[arg](); // next() or prev()
    } else
    {
      this.oQueue.goto(arg % this.oQueue.queue.length + 1);
    }
    // this.eventItemHighlighted.fire(this.oQueue.current(), oEventArgs);
  }
  
  this.list().find('li.highlight').removeClass('highlight'); // kill current highlight
  this.currentElement().addClass('highlight'); // add new highlight
}

Eventful.DropDown.prototype.clearInput = function ()
{
  if (!this.input().hasClass('inactive'))
  {
    // clear the field unless it is handled by Eventful.InactiveText
    this.input().val('');
  
    if (this.input().attr('alt'))
    {
      // delegate to Eventful.InactiveText
      Eventful.InactiveText.listenBlur({target: this.input()});
    }
  }
}

/* event handlers */

Eventful.DropDown.prototype.listenClick = function ()
{
  if (this.popover().css('display') != 'block')
  {
    this.showPopover();
  }
}

Eventful.DropDown.prototype.listenFocus = function ()
{
  if (!this.input().is(':visible'))
  {
    // Safari and IE do not handle the case of focusing on an
    // invisible element very well. This event allows the controller
    // script to give focus to the expected field.
    this.eventBadFocus.fire();
    return;
  }
  
  if (this.bHasFocus) return;
  this.bHasFocus = true;
  this.showPopover();
}

Eventful.DropDown.prototype.listenBlur = function ()
{
  if (this.bIgnoreBlur)
  {
    this.bIgnoreBlur = false;
    return;
  }
  
  this.eventBlur.fire();
  
  // hide results popover
  this.popover().hide();
  this.bHasFocus = false;
}

Eventful.DropDown.prototype.listenKeyDown = function (evt)
{
  switch (evt.keyCode)
  {
    case 38: // up
    if (this.oQueue)
    {
      evt.preventDefault();
      this.usingQueue(true);
      this.highlight('prev');
      this.eventItemHighlighted.fire(this.oQueue.current());
    }
    break;

    case 40: // down
    if (this.oQueue)
    {
      evt.preventDefault();
      this.usingQueue(true);
      this.highlight('next');
      this.eventItemHighlighted.fire(this.oQueue.current());
    }
    break;

    case 13: // enter/return
    if (this.oQueue)
    {
      evt.preventDefault();
      if(this.popover().is(':visible'))
      {
        if (this.usingQueue() || this.bExact)
        {
          this.eventItemSelected.fire(this.oQueue.current());
        } else
        {
          this.eventItemSelected.fire(this.input().val())
        }
        this.popover().hide();
      } 
      else // likely, this means moving on
      {
        this.eventEnterAfterSelected.fire();
      }
    }
    break;
  }
  
  this.sOldInput = this.input().val();
}

Eventful.DropDown.prototype.listenKeyUp = function (evt)
{
  // check for changes
  var sInput = this.input().val();
  if (this.sOldInput != sInput)
  {
    this.usingQueue(false);
    this.eventInputChanged.fire(sInput);
  }
}

Eventful.DropDown.prototype.listenMouseOver = function (evt)
{
  this.highlight(this.indexFromElement(evt.target));
}

Eventful.DropDown.prototype.listenClickItem = function (evt)
{
  var i = this.indexFromElement(evt.target);
  this.oQueue.goto(i+1);
  this.eventItemSelected.fire(this.oQueue.current());
  this.popover().hide();
}

Eventful.DropDown.prototype.listenMouseDown = function ()
{
  // This flag causes the popover to remain visible on blur. As a side-effect,
  // it keeps the showPopover method from being called on focus.
  this.bIgnoreBlur = true;
}

Eventful.DropDown.prototype.listenMouseUp = function ()
{
  this.input().focus();
}

/* jQuery UI Date Picker v3.4.3 (previously jQuery Calendar)
   Written by Marc Grabanski (m@marcgrabanski.com) and Keith Wood (kbwood@virginbroadband.com.au).

   Copyright (c) 2007 Marc Grabanski (http://marcgrabanski.com/code/ui-datepicker)
   Dual licensed under the MIT (MIT-LICENSE.txt)
   and GPL (GPL-LICENSE.txt) licenses.
   Date: 09-03-2007  */
   
;(function($) { // hide the namespace

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

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._nextId = 0; // Next ID for a date picker instance
	this._inst = []; // List of instances indexed by ID
	this._curInst = null; // The current instance in use
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		clearText: 'Clear', // Display text for clear link
		clearStatus: 'Erase the current date', // Status text for clear link
		closeText: 'Close', // Display text for close link
		closeStatus: 'Close without change', // Status text for close link
		prevText: '&#x3c;Prev', // Display text for previous month link
		prevStatus: 'Show the previous month', // Status text for previous month link
		nextText: 'Next&#x3e;', // Display text for next month link
		nextStatus: 'Show the next month', // Status text for next month link
		currentText: '', // Display text for current month link
		currentStatus: 'Show the current month', // Status text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		monthStatus: 'Show a different month', // Status text for selecting a month
		yearStatus: 'Show a different year', // Status text for selecting a year
		weekHeader: 'Wk', // Header for the week of the year column
		weekStatus: 'Week of the year', // Status text for the week of the year column
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dayStatus: 'Set DD as first week day', // Status text for the day of the week selection
		dateStatus: 'Select DD, M d', // Status text for the date selection
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		initStatus: 'Select a date', // Initial Status text on opening
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		closeAtTop: true, // True to have the clear/close at the top,
			// false to have them at the bottom
		mandatory: false, // True to hide the Clear link, false to include it
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		changeFirstDay: false, // True to click on day name to change, false to remain as set
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		showWeeks: false, // True to show week of the year, false to omit
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century, 
			// string value starting with '+' for current year + value
		showStatus: false, // True to show status bar at bottom, false to not show it
		statusForDate: this.dateStatus, // Function to provide status text for a date -
			// takes date and instance as parameters, returns display text
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		speed: 'normal', // Speed of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not,
			// [1] = custom CSS class name(s) or '', e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		stepMonths: 1, // Number of months to step back/forward
		rangeSelect: false, // Allows for selecting a date range on one date picker
		rangeSeparator: ' - ' // Text between two dates in a range
	};
	$.extend(this._defaults, this.regional['']);
	this._datepickerDiv = $('<div id="datepicker_div">');
}

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

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},
	
	/* Register a new date picker instance - with custom settings. */
	_register: function(inst) {
		var id = this._nextId++;
		this._inst[id] = inst;
		return id;
	},

	/* Retrieve a particular date picker instance based on its ID. */
	_getInst: function(id) {
		return this._inst[id] || id;
	},

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

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

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var nodeName = target.nodeName.toLowerCase();
		var calId = target._calId;
		target._calId = null;
		var $target = $(target);
		if (nodeName == 'input') {
			$target.siblings('.datepicker_append').replaceWith('').end()
				.siblings('.datepicker_trigger').replaceWith('').end()
				.removeClass(this.markerClassName)
				.unbind('focus', this._showDatepicker)
				.unbind('keydown', this._doKeyDown)
				.unbind('keypress', this._doKeyPress);
			var wrapper = $target.parents('.datepicker_wrap');
			if (wrapper)
				wrapper.replaceWith(wrapper.html());
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
		if ($('input[_calId=' + calId + ']').length == 0)
			// clean up if last for this ID
			this._inst[calId] = null;
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		target.disabled = false;
		$(target).siblings('button.datepicker_trigger').each(function() { this.disabled = false; }).end()
			.siblings('img.datepicker_trigger').css({opacity: '1.0', cursor: ''});
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		target.disabled = true;
		$(target).siblings('button.datepicker_trigger').each(function() { this.disabled = true; }).end()
			.siblings('img.datepicker_trigger').css({opacity: '0.5', cursor: 'default'});
		this._disabledInputs = $.map($.datepicker._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[$.datepicker._disabledInputs.length] = target;
	},

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

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    string - the name of the setting to change or
	                   object - the new settings to update
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_changeDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		if (inst = this._getInst(target._calId)) {
			extendRemove(inst._settings, settings);
			this._updateDatepicker(inst);
		}
	},

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

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

	/* Handle keystrokes. */
	_doKeyDown: function(e) {
		var inst = $.datepicker._getInst(this._calId);
		if ($.datepicker._datepickerShowing)
			switch (e.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: $.datepicker._selectDay(inst, inst._selectedMonth, inst._selectedYear,
							$('td.datepicker_daysCellOver', inst._datepickerDiv)[0]);
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, inst._get('speed'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(inst,
							(e.ctrlKey ? -1 : -inst._get('stepMonths')), (e.ctrlKey ? 'Y' : 'M'));
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(inst,
							(e.ctrlKey ? +1 : +inst._get('stepMonths')), (e.ctrlKey ? 'Y' : 'M'));
						break; // next month/year on page down/+ ctrl
				case 35: if (e.ctrlKey) $.datepicker._clearDate(inst);
						break; // clear on ctrl+end
				case 36: if (e.ctrlKey) $.datepicker._gotoToday(inst);
						break; // current on ctrl+home
				case 37: if (e.ctrlKey) $.datepicker._adjustDate(inst, -1, 'D');
						break; // -1 day on ctrl+left
				case 38: if (e.ctrlKey) $.datepicker._adjustDate(inst, -7, 'D');
						break; // -1 week on ctrl+up
				case 39: if (e.ctrlKey) $.datepicker._adjustDate(inst, +1, 'D');
						break; // +1 day on ctrl+right
				case 40: if (e.ctrlKey) $.datepicker._adjustDate(inst, +7, 'D');
						break; // +1 week on ctrl+down
			}
		else if (e.keyCode == 36 && e.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
	},

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

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

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var input = $(target);
		if (input.is('.' + this.markerClassName))
			return;
		input.addClass(this.markerClassName).append(inst._datepickerDiv)
			.bind("setData.datepicker", function(event, key, value){
				inst._settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return inst._get(key);
			});
		input[0]._calId = inst._id;
		this._updateDatepicker(inst);
	},

	/* Tidy up after displaying the date picker. */
	_inlineShow: function(inst) {
		var numMonths = inst._getNumberOfMonths(); // fix width for dynamic number of date pickers
		inst._datepickerDiv.width(numMonths[1] * $('.datepicker', inst._datepickerDiv[0]).width());
	}, 

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

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

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

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input._calId);
		var beforeShow = inst._get('beforeShow');
		extendRemove(inst._settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		inst._setDateFromField(input);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		inst._datepickerDiv.css('position', ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')))
			.css({ left: $.datepicker._pos[0] + 'px', top: $.datepicker._pos[1] + 'px' });
		$.datepicker._pos = null;
		inst._rangeStart = null;
		$.datepicker._updateDatepicker(inst);
		if (!inst._inline) {
			var speed = inst._get('speed');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				$.datepicker._afterShow(inst);
			};
			var showAnim = inst._get('showAnim') || 'show';
			inst._datepickerDiv[showAnim](speed, postProcess);
			if (speed == '')
				postProcess();
			if (inst._input[0].type != 'hidden')
				inst._input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		inst._datepickerDiv.empty().append(inst._generateDatepicker());
		var numMonths = inst._getNumberOfMonths();
		if (numMonths[0] != 1 || numMonths[1] != 1)
			inst._datepickerDiv.addClass('datepicker_multi');
		else
			inst._datepickerDiv.removeClass('datepicker_multi');

		if (inst._get('isRTL'))
			inst._datepickerDiv.addClass('datepicker_rtl');
		else
			inst._datepickerDiv.removeClass('datepicker_rtl');

		if (inst._input && inst._input[0].type != 'hidden')
			inst._input[0].focus();
	},

	/* Tidy up after displaying the date picker. */
	_afterShow: function(inst) {
		var numMonths = inst._getNumberOfMonths(); // fix width for dynamic number of date pickers
		inst._datepickerDiv.width(numMonths[1] * $('.datepicker', inst._datepickerDiv[0])[0].offsetWidth);
		if ($.browser.msie && parseInt($.browser.version) < 7) { // fix IE < 7 select problems
			$('#datepicker_cover').css({width: inst._datepickerDiv.width() + 4,
				height: inst._datepickerDiv.height() + 4});
		}
		// re-position on screen if necessary
		var isFixed = inst._datepickerDiv.css('position') == 'fixed';
		var pos = inst._input ? $.datepicker._findPos(inst._input[0]) : null;
		var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
		var scrollX = (isFixed ? 0 : document.documentElement.scrollLeft || document.body.scrollLeft);
		var scrollY = (isFixed ? 0 : document.documentElement.scrollTop || document.body.scrollTop);
		// reposition date picker horizontally if outside the browser window
		if ((inst._datepickerDiv.offset().left + inst._datepickerDiv.width() -
				(isFixed && $.browser.msie ? document.documentElement.scrollLeft : 0)) >
				(browserWidth + scrollX)) {
			inst._datepickerDiv.css('left', Math.max(scrollX,
				pos[0] + (inst._input ? $(inst._input[0]).width() : null) - inst._datepickerDiv.width() -
				(isFixed && $.browser.opera ? document.documentElement.scrollLeft : 0)) + 'px');
		}
		// reposition date picker vertically if outside the browser window
		if ((inst._datepickerDiv.offset().top + inst._datepickerDiv.height() -
				(isFixed && $.browser.msie ? document.documentElement.scrollTop : 0)) >
				(browserHeight + scrollY) ) {
			inst._datepickerDiv.css('top', Math.max(scrollY,
				pos[1] - (this._inDialog ? 0 : inst._datepickerDiv.height()) -
				(isFixed && $.browser.opera ? document.documentElement.scrollTop : 0)) + 'px');
		}
	},
	
	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  speed  string - the speed at which to close the date picker */
	_hideDatepicker: function(input, speed) {
		var inst = this._curInst;
		if (!inst)
			return;
		var rangeSelect = inst._get('rangeSelect');
		if (rangeSelect && this._stayOpen) {
			this._selectDate(inst, inst._formatDate(
				inst._currentDay, inst._currentMonth, inst._currentYear));
		}
		this._stayOpen = false;
		if (this._datepickerShowing) {
			speed = (speed != null ? speed : inst._get('speed'));
			var showAnim = inst._get('showAnim');
			inst._datepickerDiv[(showAnim == 'slideDown' ? 'slideUp' :
				(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))](speed, function() {
				$.datepicker._tidyDialog(inst);
			});
			if (speed == '')
				this._tidyDialog(inst);
			var onClose = inst._get('onClose');
			if (onClose) {
				onClose.apply((inst._input ? inst._input[0] : null),
					[inst._getDate(), inst]);  // trigger custom callback
			}
			this._datepickerShowing = false;
			this._lastInput = null;
			inst._settings.prompt = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this._datepickerDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst._datepickerDiv.removeClass('datepicker_dialog').unbind('.datepicker');
		$('.datepicker_prompt', inst._datepickerDiv).remove();
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents("#datepicker_div").length == 0) &&
				($target.attr('class') != 'datepicker_trigger') &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI)) {
			$.datepicker._hideDatepicker(null, '');
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var inst = this._getInst(id);
		inst._adjustDate(offset, period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var date = new Date();
		var inst = this._getInst(id);
		inst._selectedDay = date.getDate();
		inst._drawMonth = inst._selectedMonth = date.getMonth();
		inst._drawYear = inst._selectedYear = date.getFullYear();
		this._adjustDate(inst);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var inst = this._getInst(id);
		inst._selectingMonthYear = false;
		inst[period == 'M' ? '_drawMonth' : '_drawYear'] =
			select.options[select.selectedIndex].value - 0;
		this._adjustDate(inst);
	},

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

	/* Action for changing the first week day. */
	_changeFirstDay: function(id, day) {
		var inst = this._getInst(id);
		inst._settings.firstDay = day;
		this._updateDatepicker(inst);
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		if ($(td).is('.datepicker_unselectable'))
			return;
		var inst = this._getInst(id);
		var rangeSelect = inst._get('rangeSelect');
		if (rangeSelect) {
			if (!this._stayOpen) {
				$('.datepicker td').removeClass('datepicker_currentDay');
				$(td).addClass('datepicker_currentDay');
			} 
			this._stayOpen = !this._stayOpen;
		}
		inst._selectedDay = inst._currentDay = $('a', td).html();
		inst._selectedMonth = inst._currentMonth = month;
		inst._selectedYear = inst._currentYear = year;
		this._selectDate(id, inst._formatDate(
			inst._currentDay, inst._currentMonth, inst._currentYear));
		if (this._stayOpen) {
			inst._endDay = inst._endMonth = inst._endYear = null;
			inst._rangeStart = new Date(inst._currentYear, inst._currentMonth, inst._currentDay);
			this._updateDatepicker(inst);
		}
		else if (rangeSelect) {
			inst._endDay = inst._currentDay;
			inst._endMonth = inst._currentMonth;
			inst._endYear = inst._currentYear;
			inst._selectedDay = inst._currentDay = inst._rangeStart.getDate();
			inst._selectedMonth = inst._currentMonth = inst._rangeStart.getMonth();
			inst._selectedYear = inst._currentYear = inst._rangeStart.getFullYear();
			inst._rangeStart = null;
			if (inst._inline)
				this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var inst = this._getInst(id);
		if (inst._get('mandatory'))
			return;
		this._stayOpen = false;
		inst._endDay = inst._endMonth = inst._endYear = inst._rangeStart = null;
		this._selectDate(inst, '');
	},

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

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},
	
	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), (date.getTimezoneOffset() / -60));
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				checkDate.setDate(checkDate.getDate() + 3); // Generate for next year
				return $.datepicker.iso8601Week(checkDate);
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},
	
	/* Provide status text for a particular date.
	   @param  date  the date to get the status for
	   @param  inst  the current datepicker instance
	   @return  the status display text for this date */
	dateStatus: function(date, inst) {
		return $.datepicker.formatDate(inst._get('dateStatus'), date, inst._getFormatConfig());
	},

	/* Parse a string value into a date object.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   '...' - literal text
	   '' - single quote

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

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

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

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

/* Individualised settings for date picker functionality applied to one or more related inputs.
   Instances are managed and manipulated through the Datepicker manager. */
function DatepickerInstance(settings, inline) {
	this._id = $.datepicker._register(this);
	this._selectedDay = 0; // Current date for selection
	this._selectedMonth = 0; // 0-11
	this._selectedYear = 0; // 4-digit year
	this._drawMonth = 0; // Current month at start of datepicker
	this._drawYear = 0;
	this._input = null; // The attached input field
	this._inline = inline; // True if showing inline, false if used in a popup
	this._datepickerDiv = (!inline ? $.datepicker._datepickerDiv :
		$('<div id="datepicker_div_' + this._id + '" class="datepicker_inline">'));
	// customise the date picker object - uses manager defaults if not overridden
	this._settings = extendRemove(settings || {}); // clone
	if (inline)
		this._setDate(this._getDefaultDate());
}

$.extend(DatepickerInstance.prototype, {
	/* Get a setting value, defaulting if necessary. */
	_get: function(name) {
		return this._settings[name] || $.datepicker._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(input) {
		this._input = $(input);
		var dateFormat = this._get('dateFormat');
		var dates = this._input ? this._input.val().split(this._get('rangeSeparator')) : null; 
		this._endDay = this._endMonth = this._endYear = null;
		var date = defaultDate = this._getDefaultDate();
		if (dates.length > 0) {
			var settings = this._getFormatConfig();
			if (dates.length > 1) {
				date = $.datepicker.parseDate(dateFormat, dates[1], settings) || defaultDate;
				this._endDay = date.getDate();
				this._endMonth = date.getMonth();
				this._endYear = date.getFullYear();
			}
			try {
				date = $.datepicker.parseDate(dateFormat, dates[0], settings) || defaultDate;
			} catch (e) {
				$.datepicker.log(e);
				date = defaultDate;
			}
		}
		this._selectedDay = date.getDate();
		this._drawMonth = this._selectedMonth = date.getMonth();
		this._drawYear = this._selectedYear = date.getFullYear();
		this._currentDay = (dates[0] ? date.getDate() : 0);
		this._currentMonth = (dates[0] ? date.getMonth() : 0);
		this._currentYear = (dates[0] ? date.getFullYear() : 0);
		this._adjustDate();
	},
	
	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function() {
		var date = this._determineDate('defaultDate', new Date());
		var minDate = this._getMinMaxDate('min', true);
		var maxDate = this._getMinMaxDate('max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

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

	/* Set the date(s) directly. */
	_setDate: function(date, endDate) {
		this._selectedDay = this._currentDay = date.getDate();
		this._drawMonth = this._selectedMonth = this._currentMonth = date.getMonth();
		this._drawYear = this._selectedYear = this._currentYear = date.getFullYear();
		if (this._get('rangeSelect')) {
			if (endDate) {
				this._endDay = endDate.getDate();
				this._endMonth = endDate.getMonth();
				this._endYear = endDate.getFullYear();
			} else {
				this._endDay = this._currentDay;
				this._endMonth = this._currentMonth;
				this._endYear = this._currentYear;
			}
		}
		this._adjustDate();
	},

	/* Retrieve the date(s) directly. */
	_getDate: function() {
		var startDate = (!this._currentYear || (this._input && this._input.val() == '') ? null :
			new Date(this._currentYear, this._currentMonth, this._currentDay));
		if (this._get('rangeSelect')) {
			return [startDate, (!this._endYear ? null :
				new Date(this._endYear, this._endMonth, this._endDay))];
		} else
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateDatepicker: function() {
		var today = new Date();
		today = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // clear time
		var showStatus = this._get('showStatus');
		var isRTL = this._get('isRTL');
		// build the date picker HTML
		var clear = (this._get('mandatory') ? '' :
			'<div class="datepicker_clear"><a onclick="jQuery.datepicker._clearDate(' + this._id + ');"' + 
			(showStatus ? this._addStatus(this._get('clearStatus') || '&#xa0;') : '') + '>' +
			this._get('clearText') + '</a></div>');
		var controls = '<div class="datepicker_control">' + (isRTL ? '' : clear) +
			'<div class="datepicker_close"><a onclick="jQuery.datepicker._hideDatepicker();"' +
			(showStatus ? this._addStatus(this._get('closeStatus') || '&#xa0;') : '') + '>' +
			this._get('closeText') + '</a></div>' + (isRTL ? clear : '')  + '</div>';
		var prompt = this._get('prompt');
		var closeAtTop = this._get('closeAtTop');
		var hideIfNoPrevNext = this._get('hideIfNoPrevNext');
		var numMonths = this._getNumberOfMonths();
		var stepMonths = this._get('stepMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var minDate = this._getMinMaxDate('min', true);
		var maxDate = this._getMinMaxDate('max');
		var drawMonth = this._drawMonth;
		var drawYear = this._drawYear;
		if (maxDate) {
			var maxDraw = new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate());
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (new Date(drawYear, drawMonth, 1) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		// controls and links
		var prev = '<div class="datepicker_prev">' + (this._canAdjustMonth(-1, drawYear, drawMonth) ? 
			'<a onclick="jQuery.datepicker._adjustDate(' + this._id + ', -' + stepMonths + ', \'M\');"' +
			(showStatus ? this._addStatus(this._get('prevStatus') || '&#xa0;') : '') + '>' +
			this._get('prevText') + '</a>' :
			(hideIfNoPrevNext ? '' : '<label>' + this._get('prevText') + '</label>')) + '</div>';
		var next = '<div class="datepicker_next">' + (this._canAdjustMonth(+1, drawYear, drawMonth) ?
			'<a onclick="jQuery.datepicker._adjustDate(' + this._id + ', +' + stepMonths + ', \'M\');"' +
			(showStatus ? this._addStatus(this._get('nextStatus') || '&#xa0;') : '') + '>' +
			this._get('nextText') + '</a>' :
			(hideIfNoPrevNext ? '>' : '<label>' + this._get('nextText') + '</label>')) + '</div>';
		var html = (prompt ? '<div class="datepicker_prompt">' + prompt + '</div>' : '') +
			(closeAtTop && !this._inline ? controls : '') +
			'<div class="datepicker_links">' + (isRTL ? next : prev) +
			this._generateMonthYearHeader(drawMonth, drawYear, minDate, maxDate,
			selectedDate, row > 0 || col > 0) + // draw month headers
			// (this._isInRange(today) ? '<div class="datepicker_current">' +
			//       '<a onclick="jQuery.datepicker._gotoToday(' + this._id + ');"' +
			//       (showStatus ? this._addStatus(this._get('currentStatus') || '&#xa0;') : '') + '>' +
			//       this._get('currentText') + '</a></div>' : '') + 
			(isRTL ? prev : next) + '</div>';
		var showWeeks = this._get('showWeeks');
		for (var row = 0; row < numMonths[0]; row++)
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = new Date(drawYear, drawMonth, this._selectedDay);
				html += '<div class="datepicker_oneMonth' + (col == 0 ? ' datepicker_newRow' : '') + '">' +
					// this._generateMonthYearHeader(drawMonth, drawYear, minDate, maxDate,
					//           selectedDate, row > 0 || col > 0) + // draw month headers
					'<table class="datepicker" cellpadding="0" cellspacing="0"><thead>' + 
					'<tr class="datepicker_titleRow">' +
					(showWeeks ? '<td>' + this._get('weekHeader') + '</td>' : '');
				var firstDay = this._get('firstDay');
				var changeFirstDay = this._get('changeFirstDay');
				var dayNames = this._get('dayNames');
				var dayNamesShort = this._get('dayNamesShort');
				var dayNamesMin = this._get('dayNamesMin');
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					var status = this._get('dayStatus') || '&#xa0;';
					status = (status.indexOf('DD') > -1 ? status.replace(/DD/, dayNames[day]) :
						status.replace(/D/, dayNamesShort[day]));
					html += '<td' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="datepicker_weekEndCell"' : '') + '>' +
						(!changeFirstDay ? '<span' :
						'<a onclick="jQuery.datepicker._changeFirstDay(' + this._id + ', ' + day + ');"') + 
						(showStatus ? this._addStatus(status) : '') + ' title="' + dayNames[day] + '">' +
						dayNamesMin[day] + (changeFirstDay ? '</a>' : '</span>') + '</td>';
				}
				html += '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == this._selectedYear && drawMonth == this._selectedMonth) {
					this._selectedDay = Math.min(this._selectedDay, daysInMonth);
				}
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var currentDate = (!this._currentDay ? new Date(9999, 9, 9) :
					new Date(this._currentYear, this._currentMonth, this._currentDay));
				var endDate = this._endDay ? new Date(this._endYear, this._endMonth, this._endDay) : currentDate;
				var printDate = new Date(drawYear, drawMonth, 1 - leadDays);
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var beforeShowDay = this._get('beforeShowDay');
				var showOtherMonths = this._get('showOtherMonths');
				var calculateWeek = this._get('calculateWeek') || $.datepicker.iso8601Week;
				var dateStatus = this._get('statusForDate') || $.datepicker.dateStatus;
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					html += '<tr class="datepicker_daysRow">' +
						(showWeeks ? '<td class="datepicker_weekCol">' + calculateWeek(printDate) + '</td>' : '');
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((this._input ? this._input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						html += '<td class="datepicker_daysCell' +
							((dow + firstDay + 6) % 7 >= 5 ? ' datepicker_weekEndCell' : '') + // highlight weekends
							(otherMonth ? ' datepicker_otherMonth' : '') + // highlight days from other months
							(printDate.getTime() == selectedDate.getTime() && drawMonth == this._selectedMonth ?
							' datepicker_daysCellOver' : '') + // highlight selected day
							(unselectable ? ' datepicker_unselectable' : '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ?  // in current range
							' datepicker_currentDay' : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' datepicker_today' : '')) + '"' + // highlight today (if different)
							(unselectable ? '' : ' onmouseover="jQuery(this).addClass(\'datepicker_daysCellOver\');' +
							(!showStatus || (otherMonth && !showOtherMonths) ? '' : 'jQuery(\'#datepicker_status_' +
							this._id + '\').html(\'' + (dateStatus.apply((this._input ? this._input[0] : null),
							[printDate, this]) || '&#xa0;') +'\');') + '"' +
							' onmouseout="jQuery(this).removeClass(\'datepicker_daysCellOver\');' +
							(!showStatus || (otherMonth && !showOtherMonths) ? '' : 'jQuery(\'#datepicker_status_' +
							this._id + '\').html(\'&#xa0;\');') + '" onclick="jQuery.datepicker._selectDay(' +
							this._id + ',' + drawMonth + ',' + drawYear + ', this);"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span>' + printDate.getDate() + '</span>' : '<a>' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
					}
					html += '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				html += '</tbody></table></div>';
			}
		html += (showStatus ? '<div id="datepicker_status_' + this._id + 
			'" class="datepicker_status">' + (this._get('initStatus') || '&#xa0;') + '</div>' : '') +
			(!closeAtTop && !this._inline ? controls : '') +
			'<div style="clear: both;"></div>';
		return html;
	},
	
	/* Generate the month and year header. */
	_generateMonthYearHeader: function(drawMonth, drawYear, minDate, maxDate, selectedDate, secondary) {
		minDate = (this._rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var showStatus = this._get('showStatus');
		var html = '<div class="datepicker_header">';
		// month selection
		var monthNames = this._get('monthNames');
		if (secondary || !this._get('changeMonth'))
			html += monthNames[drawMonth] + '&#xa0;';
			
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			html += '<select class="datepicker_newMonth" ' +
				'onchange="jQuery.datepicker._selectMonthYear(' + this._id + ', this, \'M\');" ' +
				'onclick="jQuery.datepicker._clickMonthYear(' + this._id + ');"' +
				(showStatus ? this._addStatus(this._get('monthStatus') || '&#xa0;') : '') + '>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth())) {
					html += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNames[month] + '</option>';
				}
			}
			html += '</select>';
		}
		// year selection
		if (secondary || !this._get('changeYear'))
			html += drawYear;
		else {
			// determine range of years to display
			var years = this._get('yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="datepicker_newYear" ' +
				'onchange="jQuery.datepicker._selectMonthYear(' + this._id + ', this, \'Y\');" ' +
				'onclick="jQuery.datepicker._clickMonthYear(' + this._id + ');"' +
				(showStatus ? this._addStatus(this._get('yearStatus') || '&#xa0;') : '') + '>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Provide code to set and clear the status panel. */
	_addStatus: function(text) {
		return ' onmouseover="jQuery(\'#datepicker_status_' + this._id + '\').html(\'' + text + '\');" ' +
			'onmouseout="jQuery(\'#datepicker_status_' + this._id + '\').html(\'&#xa0;\');"';
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(offset, period) {
		var year = this._drawYear + (period == 'Y' ? offset : 0);
		var month = this._drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(this._selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = new Date(year, month, day);
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate('min', true);
		var maxDate = this._getMinMaxDate('max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		this._selectedDay = date.getDate();
		this._drawMonth = this._selectedMonth = date.getMonth();
		this._drawYear = this._selectedYear = date.getFullYear();
	},
	
	/* Determine the number of months to show. */
	_getNumberOfMonths: function() {
		var numMonths = this._get('numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(minMax, checkRange) {
		var date = this._determineDate(minMax + 'Date', null);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return date || (checkRange ? this._rangeStart : null);
	},

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

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

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

	/* Is the given date in the accepted range? */
	_isInRange: function(date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!this._rangeStart ? null :
			new Date(this._selectedYear, this._selectedMonth, this._selectedDay));
		newMinDate = (newMinDate && this._rangeStart < newMinDate ? this._rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate('min');
		var maxDate = this._getMinMaxDate('max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},
	
	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function() {
		var shortYearCutoff = this._get('shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get('dayNamesShort'), dayNames: this._get('dayNames'),
			monthNamesShort: this._get('monthNamesShort'), monthNames: this._get('monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(day, month, year) {
		if (!day) {
			this._currentDay = this._selectedDay;
			this._currentMonth = this._selectedMonth;
			this._currentYear = this._selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day : new Date(year, month, day)) :
			new Date(this._currentYear, this._currentMonth, this._currentDay));
		return $.datepicker.formatDate(this._get('dateFormat'), date, this._getFormatConfig());
	}
});

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

/* Invoke the datepicker functionality.
   @param  options  String - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){
	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate')) {
		return $.datepicker['_' + options + 'Datepicker'].apply($.datepicker, [this[0]].concat(otherArgs));
	}
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};
	
/* Initialise the date picker. */
$(document).ready(function() {
	$(document.body).append($.datepicker._datepickerDiv)
		.mousedown($.datepicker._checkExternalClick);
});

$.datepicker = new Datepicker(); // singleton instance

})(jQuery);
/**
 * @version: 1.0 Alpha-1
 * @author: Coolite Inc. http://www.coolite.com/
 * @date: 2008-05-13
 * @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * @license: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/. 
 * @website: http://www.datejs.com/
 */
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|aft(er)?|from|hence)/i,subtract:/^(\-|bef(ore)?|ago)/i,yesterday:/^yes(terday)?/i,today:/^t(od(ay)?)?/i,tomorrow:/^tom(orrow)?/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^mn|min(ute)?s?/i,hour:/^h(our)?s?/i,week:/^w(eek)?s?/i,month:/^m(onth)?s?/i,day:/^d(ay)?s?/i,year:/^y(ear)?s?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a(?!u|p)|p)/i},timezones:[{name:"UTC",offset:"-000"},{name:"GMT",offset:"-000"},{name:"EST",offset:"-0500"},{name:"EDT",offset:"-0400"},{name:"CST",offset:"-0600"},{name:"CDT",offset:"-0500"},{name:"MST",offset:"-0700"},{name:"MDT",offset:"-0600"},{name:"PST",offset:"-0800"},{name:"PDT",offset:"-0700"}]};
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,p=function(s,l){if(!l){l=2;}
return("000"+s).slice(l*-1);};$P.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};$P.setTimeToNow=function(){var n=new Date();this.setHours(n.getHours());this.setMinutes(n.getMinutes());this.setSeconds(n.getSeconds());this.setMilliseconds(n.getMilliseconds());return this;};$D.today=function(){return new Date().clearTime();};$D.compare=function(date1,date2){if(isNaN(date1)||isNaN(date2)){throw new Error(date1+" - "+date2);}else if(date1 instanceof Date&&date2 instanceof Date){return(date1<date2)?-1:(date1>date2)?1:0;}else{throw new TypeError(date1+" - "+date2);}};$D.equals=function(date1,date2){return(date1.compareTo(date2)===0);};$D.getDayNumberFromName=function(name){var n=$C.dayNames,m=$C.abbreviatedDayNames,o=$C.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s||o[i].toLowerCase()==s){return i;}}
return-1;};$D.getMonthNumberFromName=function(name){var n=$C.monthNames,m=$C.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};$D.isLeapYear=function(year){return((year%4===0&&year%100!==0)||year%400===0);};$D.getDaysInMonth=function(year,month){return[31,($D.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};$D.getTimezoneAbbreviation=function(offset){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].offset===offset){return z[i].name;}}
return null;};$D.getTimezoneOffset=function(name){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].name===name.toUpperCase()){return z[i].offset;}}
return null;};$P.clone=function(){return new Date(this.getTime());};$P.compareTo=function(date){return Date.compare(this,date);};$P.equals=function(date){return Date.equals(this,date||new Date());};$P.between=function(start,end){return this.getTime()>=start.getTime()&&this.getTime()<=end.getTime();};$P.isAfter=function(date){return this.compareTo(date||new Date())===1;};$P.isBefore=function(date){return(this.compareTo(date||new Date())===-1);};$P.isToday=function(){return this.isSameDay(new Date());};$P.isSameDay=function(date){return this.clone().clearTime().equals(date.clone().clearTime());};$P.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};$P.addSeconds=function(value){return this.addMilliseconds(value*1000);};$P.addMinutes=function(value){return this.addMilliseconds(value*60000);};$P.addHours=function(value){return this.addMilliseconds(value*3600000);};$P.addDays=function(value){this.setDate(this.getDate()+value);return this;};$P.addWeeks=function(value){return this.addDays(value*7);};$P.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,$D.getDaysInMonth(this.getFullYear(),this.getMonth())));return this;};$P.addYears=function(value){return this.addMonths(value*12);};$P.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.milliseconds){this.addMilliseconds(x.milliseconds);}
if(x.seconds){this.addSeconds(x.seconds);}
if(x.minutes){this.addMinutes(x.minutes);}
if(x.hours){this.addHours(x.hours);}
if(x.weeks){this.addWeeks(x.weeks);}
if(x.months){this.addMonths(x.months);}
if(x.years){this.addYears(x.years);}
if(x.days){this.addDays(x.days);}
return this;};var $y,$m,$d;$P.getWeek=function(){var a,b,c,d,e,f,g,n,s,w;$y=(!$y)?this.getFullYear():$y;$m=(!$m)?this.getMonth()+1:$m;$d=(!$d)?this.getDate():$d;if($m<=2){a=$y-1;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=0;f=$d-1+(31*($m-1));}else{a=$y;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=s+1;f=$d+((153*($m-3)+2)/5)+58+s;}
g=(a+b)%7;d=(f+g-e)%7;n=(f+3-d)|0;if(n<0){w=53-((g-s)/5|0);}else if(n>364+s){w=1;}else{w=(n/7|0)+1;}
$y=$m=$d=null;return w;};$P.getISOWeek=function(){$y=this.getUTCFullYear();$m=this.getUTCMonth()+1;$d=this.getUTCDate();return p(this.getWeek());};$P.setWeek=function(n){return this.moveToDayOfWeek(1).addWeeks(n-this.getWeek());};$D._validate=function(n,min,max,name){if(typeof n=="undefined"){return false;}else if(typeof n!="number"){throw new TypeError(n+" is not a Number.");}else if(n<min||n>max){throw new RangeError(n+" is not a valid value for "+name+".");}
return true;};$D.validateMillisecond=function(value){return $D._validate(value,0,999,"millisecond");};$D.validateSecond=function(value){return $D._validate(value,0,59,"second");};$D.validateMinute=function(value){return $D._validate(value,0,59,"minute");};$D.validateHour=function(value){return $D._validate(value,0,23,"hour");};$D.validateDay=function(value,year,month){return $D._validate(value,1,$D.getDaysInMonth(year,month),"day");};$D.validateMonth=function(value){return $D._validate(value,0,11,"month");};$D.validateYear=function(value){return $D._validate(value,0,9999,"year");};$P.set=function(config){if($D.validateMillisecond(config.millisecond)){this.addMilliseconds(config.millisecond-this.getMilliseconds());}
if($D.validateSecond(config.second)){this.addSeconds(config.second-this.getSeconds());}
if($D.validateMinute(config.minute)){this.addMinutes(config.minute-this.getMinutes());}
if($D.validateHour(config.hour)){this.addHours(config.hour-this.getHours());}
if($D.validateMonth(config.month)){this.addMonths(config.month-this.getMonth());}
if($D.validateYear(config.year)){this.addYears(config.year-this.getFullYear());}
if($D.validateDay(config.day,this.getFullYear(),this.getMonth())){this.addDays(config.day-this.getDate());}
if(config.timezone){this.setTimezone(config.timezone);}
if(config.timezoneOffset){this.setTimezoneOffset(config.timezoneOffset);}
if(config.week&&$D._validate(config.week,0,53,"week")){this.setWeek(config.week);}
return this;};$P.moveToFirstDayOfMonth=function(){return this.set({day:1});};$P.moveToLastDayOfMonth=function(){return this.set({day:$D.getDaysInMonth(this.getFullYear(),this.getMonth())});};$P.moveToNthOccurrence=function(dayOfWeek,occurrence){var shift=0;if(occurrence>0){shift=occurrence-1;}
else if(occurrence===-1){this.moveToLastDayOfMonth();if(this.getDay()!==dayOfWeek){this.moveToDayOfWeek(dayOfWeek,-1);}
return this;}
return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek,+1).addWeeks(shift);};$P.moveToDayOfWeek=function(dayOfWeek,orient){var diff=(dayOfWeek-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};$P.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};$P.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/86400000)+1;};$P.getTimezone=function(){return $D.getTimezoneAbbreviation(this.getUTCOffset());};$P.setTimezoneOffset=function(offset){var here=this.getTimezoneOffset(),there=Number(offset)*-6/10;return this.addMinutes(there-here);};$P.setTimezone=function(offset){return this.setTimezoneOffset($D.getTimezoneOffset(offset));};$P.hasDaylightSavingTime=function(){return(Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.isDaylightSavingTime=function(){return(this.hasDaylightSavingTime()&&new Date().getTimezoneOffset()===Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r.charAt(0)+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};$P.getElapsed=function(date){return(date||new Date())-this;};if(!$P.toISOString){$P.toISOString=function(){function f(n){return n<10?'0'+n:n;}
return'"'+this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z"';};}
$P._toString=$P.toString;$P.toString=function(format){var x=this;if(format&&format.length==1){var c=$C.formatPatterns;x.t=x.toString;switch(format){case"d":return x.t(c.shortDate);case"D":return x.t(c.longDate);case"F":return x.t(c.fullDateTime);case"m":return x.t(c.monthDay);case"r":return x.t(c.rfc1123);case"s":return x.t(c.sortableDateTime);case"t":return x.t(c.shortTime);case"T":return x.t(c.longTime);case"u":return x.t(c.universalSortableDateTime);case"y":return x.t(c.yearMonth);}}
var ord=function(n){switch(n*1){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};return format?format.replace(/(\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S)/g,function(m){if(m.charAt(0)==="\\"){return m.replace("\\","");}
x.h=x.getHours;switch(m){case"hh":return p(x.h()<13?(x.h()===0?12:x.h()):(x.h()-12));case"h":return x.h()<13?(x.h()===0?12:x.h()):(x.h()-12);case"HH":return p(x.h());case"H":return x.h();case"mm":return p(x.getMinutes());case"m":return x.getMinutes();case"ss":return p(x.getSeconds());case"s":return x.getSeconds();case"yyyy":return p(x.getFullYear(),4);case"yy":return p(x.getFullYear());case"dddd":return $C.dayNames[x.getDay()];case"ddd":return $C.abbreviatedDayNames[x.getDay()];case"dd":return p(x.getDate());case"d":return x.getDate();case"MMMM":return $C.monthNames[x.getMonth()];case"MMM":return $C.abbreviatedMonthNames[x.getMonth()];case"MM":return p((x.getMonth()+1));case"M":return x.getMonth()+1;case"t":return x.h()<12?$C.amDesignator.substring(0,1):$C.pmDesignator.substring(0,1);case"tt":return x.h()<12?$C.amDesignator:$C.pmDesignator;case"S":return ord(x.getDate());default:return m;}}):this._toString();};}());
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,$N=Number.prototype;$P._orient=+1;$P._nth=null;$P._is=false;$P._same=false;$P._isSecond=false;$N._dateElement="day";$P.next=function(){this._orient=+1;return this;};$D.next=function(){return $D.today().next();};$P.last=$P.prev=$P.previous=function(){this._orient=-1;return this;};$D.last=$D.prev=$D.previous=function(){return $D.today().last();};$P.is=function(){this._is=true;return this;};$P.same=function(){this._same=true;this._isSecond=false;return this;};$P.today=function(){return this.same().day();};$P.weekday=function(){if(this._is){this._is=false;return(!this.is().sat()&&!this.is().sun());}
return false;};$P.at=function(time){return(typeof time==="string")?$D.parse(this.toString("d")+" "+time):this.set(time);};$N.fromNow=$N.after=function(date){var c={};c[this._dateElement]=this;return((!date)?new Date():date.clone()).add(c);};$N.ago=$N.before=function(date){var c={};c[this._dateElement]=this*-1;return((!date)?new Date():date.clone()).add(c);};var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),pxf=("Milliseconds Seconds Minutes Hours Date Week Month FullYear").split(/\s/),nth=("final first second third fourth fifth").split(/\s/),de;$P.toObject=function(){var o={};for(var i=0;i<px.length;i++){o[px[i].toLowerCase()]=this["get"+pxf[i]]();}
return o;};$D.fromObject=function(config){config.week=null;return Date.today().set(config);};var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
if(this._nth!==null){if(this._isSecond){this.addSeconds(this._orient*-1);}
this._isSecond=false;var ntemp=this._nth;this._nth=null;var temp=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(n,ntemp);if(this>temp){throw new RangeError($D.getDayName(n)+" does not occur "+ntemp+" times in the month of "+$D.getMonthName(temp.getMonth())+" "+temp.getFullYear()+".");}
return this;}
return this.moveToDayOfWeek(n,this._orient);};};var sdf=function(n){return function(){var t=$D.today(),shift=n-t.getDay();if(n===0&&$C.firstDayOfWeek===1&&t.getDay()!==0){shift=shift+7;}
return t.addDays(shift);};};for(var i=0;i<dx.length;i++){$D[dx[i].toUpperCase()]=$D[dx[i].toUpperCase().substring(0,3)]=i;$D[dx[i]]=$D[dx[i].substring(0,3)]=sdf(i);$P[dx[i]]=$P[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};var smf=function(n){return function(){return $D.today().set({month:n,day:1});};};for(var j=0;j<mx.length;j++){$D[mx[j].toUpperCase()]=$D[mx[j].toUpperCase().substring(0,3)]=j;$D[mx[j]]=$D[mx[j].substring(0,3)]=smf(j);$P[mx[j]]=$P[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(this._isSecond){this._isSecond=false;return this;}
if(this._same){this._same=this._is=false;var o1=this.toObject(),o2=(arguments[0]||new Date()).toObject(),v="",k=j.toLowerCase();for(var m=(px.length-1);m>-1;m--){v=px[m].toLowerCase();if(o1[v]!=o2[v]){return false;}
if(k==v){break;}}
return true;}
if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$P[de]=$P[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}
$P._ss=ef("Second");var nthfn=function(n){return function(dayOfWeek){if(this._same){return this._ss(arguments[0]);}
if(dayOfWeek||dayOfWeek===0){return this.moveToNthOccurrence(dayOfWeek,n);}
this._nth=n;if(n===2&&(dayOfWeek===undefined||dayOfWeek===null)){this._isSecond=true;return this.addSeconds(this._orient);}
return this;};};for(var l=0;l<nth.length;l++){$P[nth[l]]=(l===0)?nthfn(-1):nthfn(l);}}());
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo;var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};$D.Grammar={};$D.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=(s.length==3)?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4:Number(s)-1;};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<$C.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
var now=new Date();if((this.hour||this.minute)&&(!this.month&&!this.year&&!this.day)){this.day=now.getDate();}
if(!this.year){this.year=now.getFullYear();}
if(!this.month&&this.month!==0){this.month=now.getMonth();}
if(!this.day){this.day=1;}
if(!this.hour){this.hour=0;}
if(!this.minute){this.minute=0;}
if(!this.second){this.second=0;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.day>$D.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
var today=$D.today();if(this.now&&!this.unit&&!this.operator){return new Date();}else if(this.now){today=new Date();}
var expression=!!(this.days&&this.days!==null||this.orient||this.operator);var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(!this.now&&"hour minute second".indexOf(this.unit)!=-1){today.setTimeToNow();}
if(this.month||this.month===0){if("year day hour minute second".indexOf(this.unit)!=-1){this.value=this.month+1;this.month=null;expression=true;}}
if(!expression&&this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(!this.month){this.month=temp.getMonth();}
this.year=temp.getFullYear();}
if(expression&&this.weekday&&this.unit!="month"){this.unit="day";gap=($D.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month&&this.unit=="day"&&this.operator){this.value=(this.month+1);this.month=null;}
if(this.value!=null&&this.month!=null&&this.year!=null){this.day=this.value*1;}
if(this.month&&!this.day&&this.value){today.set({day:this.value*1});if(!expression){this.day=this.value*1;}}
if(!this.month&&this.value&&this.unit=="month"&&!this.now){this.month=this.value;expression=true;}
if(expression&&(this.month||this.month===0)&&this.unit!="year"){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(!this.value&&this.operator&&this.operator!==null&&this[this.unit+"s"]&&this[this.unit+"s"]!==null){this[this.unit+"s"]=this[this.unit+"s"]+((this.operator=="add")?1:-1)+(this.value||0)*orient;}else if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
this[this.unit+"s"]=this.value*orient;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(temp.getMonth()!==today.getMonth()){this.month=temp.getMonth();}}
if((this.month||this.month===0)&&!this.day){this.day=1;}
if(!this.orient&&!this.operator&&this.unit=="week"&&this.value&&!this.day&&!this.month){return Date.today().setWeek(this.value);}
if(expression&&this.timezone&&this.day&&this.days){this.day=this.days;}
return(expression)?today.add(this):today.set(this);}};var _=$D.Parsing.Operators,g=$D.Grammar,t=$D.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|@|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=$C.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken($C.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.m,g.s],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("second minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[$C.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw $D.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["\"yyyy-MM-ddTHH:mm:ssZ\"","yyyy-MM-ddTHH:mm:ssZ","yyyy-MM-ddTHH:mm:ssz","yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mmZ","yyyy-MM-ddTHH:mmz","yyyy-MM-ddTHH:mm","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","MMddyyyy","ddMMyyyy","Mddyyyy","ddMyyyy","Mdyyyy","dMyyyy","yyyy","Mdyy","dMyy","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};$D._parse=$D.parse;$D.parse=function(s){var r=null;if(!s){return null;}
if(s instanceof Date){return s;}
try{r=$D.Grammar.start.call({},s.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"));}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};$D.getParseFunction=function(fx){var fn=$D.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};$D.parseExact=function(s,fx){return $D.getParseFunction(fx)(s);};}());

// require eventful.core
// require eventful.drop-down
// require eventful.uievent
// require prototype.function
// require jquery.core
// require jquery.datepicker
// require coolite.date

Eventful.DatePicker = function (oArgs)
{
  this.id = oArgs.id;
  this.bRequired = oArgs.required;
  this.sMinDate = (typeof oArgs.minDate !== 'undefined' ? oArgs.minDate : '0');
  
  this.oDropDown = new Eventful.DropDown({
    input: '#inp-'+this.id,
    popover: '#date-picker-'+this.id+' .popover'
  });
  
  this.oDropDown.eventPopoverShown.subscribe(this.listenPopoverShown.bind(this));
  this.oDropDown.eventInputChanged.subscribe(this.listenInputChanged.bind(this));
  this.oDropDown.eventBlur.subscribe(this.listenBlur.bind(this));
  
  this.eventDatePicked = new Eventful.UIEvent();
  
  $(this.setup.bind(this));
}

Eventful.DatePicker.prototype.calendar = function ()
{
  return this.jqCalendar ? this.jqCalendar : this.jqCalendar = this.oDropDown.find('.calendar');
}

Eventful.DatePicker.prototype.setup = function ()
{
  this.calendar().datepicker({
    prevText: '<span class="prev">&laquo;</span>',
    nextText: '<span class="next">&raquo;</span>',
    dayNamesMin: ['S','M','T','W','T','F','S'],
    onSelect: this.listenDateSelected.bind(this),
    minDate: this.sMinDate,
    defaultDate: Eventful.DatePicker.parseDate(this.oDropDown.input().val())
  });
  
  // needs DOM to read current date from form
  this.oDropDown.queue(new Eventful.DateQueue(this));
}

Eventful.DatePicker.prototype.date = function (oDate)
{
  // given a date, set the current value to that date
  if (oDate)
  {
    // convert date string to date object
    oDate = Eventful.DatePicker.parseDate(oDate);
    
    // update the calendar's current date
    this.calendar().datepicker('setDate', oDate);
    
    // replace the current value
    var sDate = Eventful.DatePicker.formatDate(oDate);
    this.oDropDown.input().val(sDate);

    // activate input
    this.oDropDown.input().removeClass('inactive');
  }
  
  if (!this.oDropDown.input().hasClass('inactive'))
  {
    // return the current value as a date object
    return Eventful.DatePicker.parseDate(this.oDropDown.input().val());
  }
}

Eventful.DatePicker.prototype.fixPopoverPosition = function ()
{
  if (this.bFixedPosition) return;
  this.bFixedPosition = true;
  
  this.oDropDown.popover().css({
    top: $('#date-picker-'+this.id).height()
  });
}

Eventful.DatePicker.prototype.after = function (oMinDate)
{
  // convert date string to date object
  oMinDate = Eventful.DatePicker.parseDate(oMinDate);
  
  // change current date to be after the given date
  oMinDate.addDays(1);
  
  // update the calendar's minimum date
  this.oMinDate = oMinDate;
  this.calendar().datepicker('change', {minDate: oMinDate});
  
  var oDate = this.date();
  if (oDate)
  {
    // set the date if the current date is before the start date
    if (oMinDate.compareTo(oDate) > 0)
    {
      this.date(oMinDate);
    }
  } else
  {
    // just set the calendar's date if we don't have a current date
    this.calendar().datepicker('setDate', oMinDate);
  }
}

/* event handlers */

Eventful.DatePicker.prototype.listenBlur = function ()
{
  if (!this.date())
  {
    // time failed to parse
    if (this.bRequired)
    {
      // use currently highlighted value in list
      var oDate = this.calendar().datepicker('getDate');
      var sDate = Eventful.DatePicker.formatDate(oDate);
      this.oDropDown.input().val(sDate).removeClass('inactive');
    } else
    {
      this.oDropDown.clearInput();
    }
  }
  
  if (this.date())
  {
    this.oDropDown.input().val(Eventful.DatePicker.formatDate(this.date()));
  }
  
  this.eventDatePicked.fire(this.date());
}

Eventful.DatePicker.prototype.listenPopoverShown = function ()
{
  this.fixPopoverPosition();
}

Eventful.DatePicker.prototype.listenInputChanged = function (sDate)
{
  var oDate = Eventful.DatePicker.parseDate(sDate) || new Date();
  // date is required to be same as or after minimum date
  if (!this.oMinDate || oDate.compareTo(this.oMinDate) >= 0)
  {
    this.calendar().datepicker('setDate', oDate);
  }
}

Eventful.DatePicker.prototype.listenDateSelected = function (sDate)
{
  var oDate = Eventful.DatePicker.parseDate(sDate);
  if (oDate)
  {
    this.oDropDown.input().val(Eventful.DatePicker.formatDate(oDate)).select();
    
    setTimeout(function() {
      // simulate blur (delayed because IE sucks)
      this.oDropDown.popover().hide();
      this.oDropDown.bHasFocus = false;
    }.bind(this), 0);
  }
}

/* utility methods */

Eventful.DatePicker.parseDate = function (oDate)
{
  if (typeof oDate === 'string')
  {
    return Date.parseExact(oDate, Eventful.DatePicker.format()) ||
           Date.parse(oDate);
  }
  return oDate;
}

Eventful.DatePicker.formatDate = function (oDate)
{
  return oDate.toString(Eventful.DatePicker.format());
}

Eventful.DatePicker.format = function ()
{
  if (!Eventful.DatePicker.sFormat)
  {
    Eventful.DatePicker.sFormat = 'M/d/yy';
  
    if (Eventful.Session && Eventful.Session.Prefs.sf)
    {
      var sFormat = Eventful.Session.Prefs.sf.
        replace('%m', 'MM').
        replace('%Y', 'yyyy').
        replace('%y', 'yy').
        replace('%e', 'd').
        replace('%f', 'M');
    
      if (sFormat.indexOf('%') == -1)
      {
        Eventful.DatePicker.sFormat = sFormat;
      }
    }
  }
  
  return Eventful.DatePicker.sFormat;
}

/* DateQueue is used to cycle through dates like a circular queue, but not exactly */

Eventful.DateQueue = function (oDatePicker)
{
  this.oDatePicker = oDatePicker;
  this.bIgnoreNext = true; // need to do this because queues are initialized with a call to next()
}

Eventful.DateQueue.prototype.next = function ()
{
  if (this.bIgnoreNext)
  {
    this.bIgnoreNext = false;
    return;
  }
  
  var oDate = this.oDatePicker.date() || this.oDatePicker.calendar().datepicker('getDate');
  if (oDate)
  {
    oDate.addDays(1);
    this.oDatePicker.date(oDate);
  }
}

Eventful.DateQueue.prototype.prev = function ()
{
  var oDate = this.oDatePicker.date() || this.oDatePicker.calendar().datepicker('getDate');
  var oMinDate = this.oDatePicker.oMinDate || Date.today();
  if (oDate && oDate.compareTo(oMinDate) > 0)
  {
    oDate.addDays(-1);
    this.oDatePicker.date(oDate);
  }
}

Eventful.DateQueue.prototype.current = function ()
{
  return this.oDatePicker.date();
}

// require eventful.core
// require jquery.core
// require prototype.function

Eventful.QuickSearch = function (oArgs)
{
  this.oStartDatePicker = new Eventful.DatePicker({id: 'from', minDate: null});
  this.oStartDatePicker.eventDatePicked.subscribe(this.listenDatePicked.bind(this));
  
  this.oStopDatePicker  = new Eventful.DatePicker({id: 'to', minDate: null});
  this.oStopDatePicker.eventDatePicked.subscribe(this.listenDatePicked.bind(this));

  $(this.setup.bind(this));
}

Eventful.QuickSearch.prototype.setup = function ()
{
  
  this.jqQuickSearch = $('.quick-search');
  this.jqFrom    = this.jqQuickSearch.find('[name=from]');
  this.jqTo      = this.jqQuickSearch.find('[name=to]');
  
  // Tooltip
  new Eventful.Tooltip('#tooltip-quick-search', {right: -10, top: 25});
  
  // prevent category links from actually link (Purpose: SEO)
  $("#quick-search .categories a").click(this.listenCategoryClick.bind(this));

  Eventful.InactiveText.attachHandlers(this.jqQuickSearch);
  
  this.jqQuickSearch.submit(this.listenSubmit.bind(this));
}

Eventful.QuickSearch.prototype.isCustom = function ()
{
  
  if (!this.jqFrom.hasClass('inactive') || !this.jqTo.hasClass('inactive')) { 
    return true;
  }
  return false;
}

/* event handlers */

Eventful.QuickSearch.prototype.listenDatePicked = function ()
{
  if (this.oStartDatePicker.date())
  {
    this.oStopDatePicker.after(this.oStartDatePicker.date());
  }
}

Eventful.QuickSearch.prototype.listenSubmit = function (evt)
{
  // Prevent the normal form action
  evt.preventDefault();
  
  this.submit();
}

Eventful.QuickSearch.prototype.submit = function ()
{
  var sAction = this.jqQuickSearch.attr('action');
  var sVars = this.jqQuickSearch.find('[type=hidden], [name=c]').serialize()
  
  if (!this.isCustom()){
    // regular search: so boring *yawn*
    // do the search with computed future time and given vars
    window.location = sAction+'?t=Future&'+sVars; // Do the search!
  } else {
    var t = this._buildT();
    
    if(t) {
      // do the search with computed time and given vars
      window.location = sAction+'?t='+t+'&'+sVars; // make rocket go now!
      return;
    }

    // regular search if dates are missing
    // reset the date fields
    Eventful.InactiveText.doForcedUpdate(this.jqFrom);
    Eventful.InactiveText.doForcedUpdate(this.jqTo);
  
    // do the search with computed future time and given vars
    window.location = sAction+'?t=Future&'+sVars; // Do the search!
  }
}

Eventful.QuickSearch.prototype._buildT = function() {
  // custom search: gogogogo!
  var oStartDate = this.oStartDatePicker.date();
  var oStopDate = this.oStopDatePicker.date();
  var sTime = '';
  if (oStartDate && oStopDate)
  {
    // both start and stop date
    sTime = oStartDate.toString('yyyyMMdd00')+'-'+oStopDate.toString('yyyyMMdd23');
  } 
  else if (oStartDate)
  {
    // only start date
    sTime = oStartDate.toString('yyyyMMdd00')+'-'+oStartDate.toString('yyyyMMdd23');
  } 
  else if (oStopDate)
  {
    // only stop date
    sTime = new Date().toString('yyyyMMdd00')+'-'+oStopDate.toString('yyyyMMdd23');
  }
  return sTime;
}

Eventful.QuickSearch.prototype.listenCategoryClick = function (evt) {
  //prevent the click
  evt.preventDefault();

  // Deslect any selected categories
  $("#quick-search input[@name='c']").attr("checked", "");

  // select the clicked item
  $(evt.target).parents('span.field').find('input').attr("checked", "checked");
  
  this.submit();
}

// require eventful.core
// require prototype.function
// require jquery.core

Eventful.QuickSearchDate = function(){
  Eventful.QuickSearch.call(this);
}.mixin(Eventful.QuickSearch);

Eventful.QuickSearchDate.prototype.setup = function ()
{
  Eventful.QuickSearch.prototype.setup.call(this);
  
  $('#quick-search button[name=pick-go]').bind('click',this.onGoClicked.bind(this));
  
  // Tooltip
  new Eventful.Tooltip('#tooltip-quick-search', {left: -10, top: 25});

  var fromTo = this._parseT();
  
  if(fromTo) {
    if(fromTo[0]) this.oStartDatePicker.date(fromTo[0]);
    if(fromTo[1]) this.oStopDatePicker.date(fromTo[1]);
  } else if($.browser.safari){
    (function(){
      $('#box-browse-events .white-out').css({
        'height': $('#box-browse-events .entries').height() + 15
      });
      $('#quick-search :input[name=from]').trigger('focus');
    }).later(5000);
  } else {
    $('#quick-search :input[name=from]').trigger('focus');
  }

}

// HACK! why i can NOT specify $('#date-picker-'+this.id).height()
Eventful.DatePicker.prototype.fixPopoverPosition = function ()
{
  if (this.bFixedPosition) return;
  this.bFixedPosition = true;
  
  this.oDropDown.popover().css({
    top: $('#date-picker-'+this.id).height() + 5
  });
}

Eventful.QuickSearchDate.prototype.onGoClicked = function() {
  var t= this._buildT();
  if(t) {
    location.assign(location.pathname + '?t=' + t);
  }
}

Eventful.QuickSearchDate.prototype._parseT = function() {
  var dates = location.search.match(/t=(\d{10})-(\d{10})/);
  
  if(dates) {
    var sFrom = dates[1];
    var sTo = dates[2];

    var parseForm = new Date(this.makeNum(sFrom.substr(0,4)), this.makeNum(sFrom.substr(4,2))-1, this.makeNum(sFrom.substr(6,2)));
    var parseTo =   new Date(this.makeNum(sTo.substr(0,4)),   this.makeNum(sTo.substr(4,2))-1,   this.makeNum(sTo.substr(6,2)));

    if(sFrom.substring(0,8) == sTo.substring(0,8)) {
      return [parseForm, null];
    } 
    else if (new Date().toString('yyyyMMdd') == sFrom.substring(0,8)) {
      return [null,parseTo];
    } else {
      return [parseForm,parseTo];
    }
    
  }
  return null;
}

Eventful.QuickSearchDate.prototype.makeNum = function(sNum) {
  return parseInt(sNum.replace(/^0+|[^\d]/g,''));
} 

// require eventful.core
// require prototype.function
// jquery.core

/**
  Click PLU - logs clicks on a.click-plu to plu tracking handler
  2008-01-21 / <reshun@eventful.com>
**/

Eventful.ClickPLU = function (el) {
  $('.click-plu a', el).click(Eventful.ClickPLU.listenClick);
}

Eventful.ClickPLU.listenClick = function (evt) {
  // cancel the click and force the user through our redirect script
  evt.preventDefault();
  
  // get the id
  var sId = $(evt.target).parents('.click-plu').eq(0).attr('id');
  if (sId) {
    sId = sId.substr(4);

    // do the redirect
    Eventful.ClickPLU.redirect(this.href, sId);

  } else if (this.href){
    window.location = this.href;
  }
}

Eventful.ClickPLU.redirect = function (sLocation, sId) {
  var sUrl = '/tools/plu/click/report?custom_id='+sId+'&goto='+sLocation;
  window.location = sUrl;
}

// jQuery's ready event callsback with jQuery as an argument
$(function(){Eventful.ClickPLU()});

// require eventful.popover

$(function(){
  var jSigninPane = $('#user-panel-popover');
  if(jSigninPane.length != 1) return;

  (new Eventful.Popover(jSigninPane,{
    css:{
      width: '',
      border: '',
      backgroundColor: ''
    },
    position:{
      relative: $('#user-panel-signin'),
      top: 20,
      left: 'auto',
      right: 0
    },
    tracking: 'lbox_signin'
  }))
  .clickShow('#user-panel-signin,#user-panel-signin-block',true)
  .clickClose('#btn-user-panel-cancel');
  
  // cache bk image
  (new Image()).src = "http://static.eventful.com/store/skin/chrome/chamfer_corner_strip.png";
});


// require eventful.core
// require jquery.core
// require prototype.function
// require eventful.panel
// require eventful.track-pageview
// require eventful.cookies

Eventful.PanelExitSurvey = function ()
{
  Eventful.Panel.call(this, 'panel-exit-survey');
  this.options({width: 500, closeClass: 'surveyClose'});
  this.clickClose('#panel-exit-survey .reject');
  
  // log the panel when it shows
  this.eventShow.subscribe(this.listenShow.bind(this));
  
  this.show(); // does nothing if the panel doesn't exist
  
  this.find('.reject, .surveyClose').click(this.listenReject.bind(this));
  this.find('.accept').click(this.listenAccept.bind(this));
  this.find('form').submit(this.listenSubmit.bind(this));
}.mixin(Eventful.Panel);

Eventful.PanelExitSurvey.prototype.listenShow = function ()
{
  Eventful.TrackPageview.track('/lbox_exitsurvey_invite');
  this.log("impression");
  Eventful.Cookies.setCookie('exitsurvey1', 1, 129600); // 90 days
}

Eventful.PanelExitSurvey.prototype.listenReject = function ()
{
  Eventful.TrackPageview.track('/lbox_exitsurvey_reject');
}

Eventful.PanelExitSurvey.prototype.listenAccept = function ()
{
  $('#panel-exit-survey .bd').removeClass('init').addClass('purpose');

  $('#panel-exit-survey #inp-purpose_code')
    .click(function(){
      var jqSelect = $('#panel-exit-survey input:checked[type=radio][name=purpose_code]');

      if(jqSelect.val() == "9") {
        $(this).parents('ul').children('.field-container.purpose')
            .removeClass('hidden')
            .find('textarea')
              .focus();
      } else {
        $(this).parents('ul').children('.field-container.purpose')
            .addClass('hidden');
      }
    })
  
  Eventful.TrackPageview.track('/lbox_exitsurvey_page1');
  this.log("accepted");
}

Eventful.PanelExitSurvey.prototype.listenSubmit = function (evt)
{
  evt.preventDefault();
  
  var jqSelect = $('#panel-exit-survey input:checked[type=radio][name=purpose_code]');
  
  if( jqSelect.val() != "9") {
    $('#panel-exit-survey textarea[name=purpose]')
      .val(jqSelect.next().text());
  }

  window.open(
    "/exit-survey?"+$('#panel-exit-survey form').serialize(), "_blank",
    "resizable=no,scrollbars=no,location=no,status=no,width=600,height=525"
  );
  
  this.close(evt);

  (function(win) {
    win.focus();
  }).later(100,window);
}

Eventful.PanelExitSurvey.prototype.log = function (sType)
{
  $.post(
    '/json/tools/utils/report',
    {
      name: 'exit_survey_analytics',
      type: sType
    }
  );
}

Eventful.PanelExitSurvey.setup = function()
{
  if (Eventful.Session.Tests.exit_survey == '1')
  {
    $.get(
      '/sections/panel_exit_survey',
      null,
      function (sPanel)
      {
        $(document.body).append(sPanel);
        new Eventful.PanelExitSurvey();
      },
      'html'
    );
  }
}

$(Eventful.PanelExitSurvey.setup);

// require eventful.core
// require eventful.inactive-text
// require eventful.panel-exit-survey
// require eventful.popover
// require jquery.core

/**
  Site search
  2007-11-07 / <reshun@eventful.com>
**/

Eventful.Search = function()
{
  $(this.setup.bind(this));
  
  this.oAltText = {
    events: "e.g. festivals; art show",
    venues: "e.g. bar; Madison Square",
    performers: "e.g. Rolling Stones; Jay-Z",
    demands: "e.g. Rolling Stones; Jay-Z",
    groups: "e.g. Web 2.0; music",
    users: "e.g. tallwilly; disco"
  };
}

Eventful.Search.prototype.find = function (el)
{
  return this.oPopover.find(el);
}

Eventful.Search.prototype.setup = function ()
{
  this.elSearchBox = $("#q");
  
  this.oPopover = new Eventful.Popover('#search-popover', {
    width: 206,
    css: {
      zIndex: 100,
      borderColor: "#999"
    },
    position: {
      top: 24,
      left: 0,
      relative: 'sender'
    },
    no_focus: 1
  });
  
  this.oPopover.eventShow.subscribe(this.listenShowPopover.bind(this));
  
  this.elSearchBox.focus(this.oPopover.show.bind(this.oPopover));
  $("#search-form-action").submit(this.listenSubmit.bind(this));
  this.find(':radio').click(this.listenClick.bind(this));
  
  this.render();
  
  Eventful.InactiveText(this.elSearchBox);
}

Eventful.Search.prototype.area = function (sArea)
{
  var elArea = $("#search-form-action [name=area]");
  
  if (sArea)
  {
    elArea.val(sArea);
  } else if (!elArea.val())
  {
    // compute area from the body class
    var elBody = $('body');
    elArea.val(
      elBody.hasClass('nav-events') ?
        "events":
      elBody.hasClass('nav-demands') ?
        "demands":
      elBody.hasClass('nav-performers') ?
        "performers":
      elBody.hasClass('nav-venues') ?
        "venues":
      elBody.hasClass('nav-groups') || elBody.hasClass('nav-community') ?
        "groups":
      elBody.hasClass('nav-users') ? "users":
        "events"
    );
  }
  
  return elArea.val();
}

Eventful.Search.prototype.render = function ()
{
  var sArea = this.area();
  
  // Set class on list to enable bold highlight of current option
  this.find('#search-areas-list').removeClass().addClass('search-'+sArea);
  
  // Set up the alt text for the inactive-text widget
  this.elSearchBox.attr({alt: this.oAltText[sArea]});
  
  // updated the hint text if the input is inactive
  if (this.elSearchBox.hasClass('inactive')) {
    Eventful.InactiveText.doForcedUpdate(this.elSearchBox);
  }
}

/* event handlers */

Eventful.Search.prototype.listenShowPopover = function()
{
  // check the current area
  this.find('[value='+this.area()+']').attr({checked: true});
}

Eventful.Search.prototype.listenClick = function (evt, el)
{
  // update search area
  this.area($(el).val());
  
  // highlight the radio button and update the alt text
  this.render();
}

Eventful.Search.prototype.listenSubmit = function (evt)
{
  if (this.elSearchBox.hasClass('inactive'))
  {
    this.elSearchBox.val('');
  }
}

Eventful.Location = function ()
{
  this.eventLocationChanged = new Eventful.UIEvent();
  this.eventSetup = new Eventful.UIEvent();
  this.oOptions = {};
  $(this.setup.bind(this));
}

Eventful.Location.prototype.setup = function (evt)
{
  this.oChangeLocation = new Eventful.PopoverChangeLocation({
    token: 'change_location',
    css: {
      zIndex: 100
    },
    position: {
      top: 16,
      left: 1,
      relative: 'sender'
    }
  });
  this.oChangeLocation.clickShow('#header-location-change', true);
  this.oChangeLocation.eventLocationChanged.subscribe(this.listenLocationChanged.bind(this));
  
  this.eventSetup.fire();
  this.bSetup = true;
}

Eventful.Location.prototype.options = function (oArgs)
{
  return $.extend(this.oOptions, oArgs);
}

Eventful.Location.prototype.subscribeSetup = function (fnSubscriber)
{
  if (this.bSetup)
  {
    fnSubscriber();
  } else
  {
    this.eventSetup.subscribe(fnSubscriber);
  }
}

Eventful.Location.prototype.listenLocationChanged = function (oArgs)
{
  this.eventLocationChanged.fire();
  
  if (this.oOptions.no_reload)
  {
    return;
  }
  
  if (oArgs.response.base_path)
  {
    // redirect to the base path, let backend take care of location-specific redirect
    window.location = window.location.protocol+'//'+window.location.host+oArgs.response.base_path;
  } else 
  {
    window.location.reload();
  }
}

Eventful.NetflixOpener = function() {
  if (!Eventful.Cookies) return;
  if (Eventful.Cookies.getCookie('netflix_promo') === "f") return;
  
  // set the cookie
  Eventful.Cookies.setCookie('netflix_promo', 'f', 1440); // 24 hours

  // open the window
  var sUrl = "http://"+ document.location.hostname + "/netflix";
  var oW = window;
  var sOptions = "menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=720,height=300";
  var oNewWindow = window.open(sUrl, 'Netflix', sOptions);

  if (oNewWindow) {
    oNewWindow.blur();
    oW.focus();
  }
}

// require eventful.core

Eventful.CircularQ = function()
{
  this.iter = null;
  if (arguments.length == 1)
  {
    this.queue = arguments[0];
  }
  else
  {
    this.queue = [];
  }
}

Eventful.CircularQ.prototype = {
  next: function()
  {
    if (this.queue.length > 0)
    {
      var next;
      if (this.iter === null) next = 0;
      else next = this.iter + 1;
      if (next >= this.queue.length)
      {
        next = 0;
      }
      this.iter = next;
      return this.queue[next];
    }
    else
    {
      return null;
    }
  },
  prev: function()
  {
    if (this.queue.length > 0)
    {
      var prev;
      if (this.iter === null) prev = this.queue.length - 1;
      else prev = this.iter - 1;
      if (prev < 0)
      {
        prev = this.queue.length - 1;
      }
      this.iter = prev;
      return this.queue[prev];
    }
    else
    {
      return null;
    }
  },
  goto: function(goTo)
  {
    if ((this.queue.length > 0) && (goTo <= this.queue.length))
    {
      var idToGoTo = goTo - 1;
      this.iter = idToGoTo;
      return this.queue[idToGoTo];
    }
    else
    {
      return null;
    }
  },
  current: function()
  {
    if (this.queue.length > 0)
    {
      var current = this.iter;
      return this.queue[current];
    }
    else
    {
      return null;
    }
  },
  add: function(item)
  {
    this.queue.push(item);
  },
  extend: function (items)
  {
    this.queue = this.queue.concat(items);
  },
  rem: function(idx)
  {
    this.queue.splice(idx, 1);
  }
}

// require eventful.core
// require eventful.circularq
// require eventful.uievent
// require eventful.inactive-text
// require eventful.drop-down
// require jquery.core
// require prototype.function

Eventful.TypeAhead = function (oArgs)
{
  this.id               = oArgs.id;
  this.bSingular        = !oArgs.multiple;
  this.sExcludeQuery    = null;
  this.oItemsToExclude  = {};
  this.bOptions         = oArgs.options;
  this.bRequired        = oArgs.required;

  this.eventItemSelected = new Eventful.UIEvent();
  this.eventOptionSelected = new Eventful.UIEvent();
  this.eventItemRemoved = new Eventful.UIEvent();
  this.eventEnterConfirm = new Eventful.UIEvent();
  
  this.oDropDown = new Eventful.DropDown({
    exact: 1,
    input: '#inp-'+this.id,
    popover: '#popover-'+this.id,
    minInputLength: oArgs.minInputLength !== undefined ?
      oArgs.minInputLength : 2
  });
  
  this.oDropDown.eventItemSelected.subscribe(this.listenItemSelected.bind(this));
  this.oDropDown.eventItemHighlighted.subscribe(this.listenItemHighlighted.bind(this));
  this.oDropDown.eventInputChanged.subscribe(this.listenInputChanged.bind(this));
  this.oDropDown.eventEnterAfterSelected.subscribe(this.listenEnterAfterSelected.bind(this));
  
  if (this.bRequired)
  {
    // behave more like a field
    this.oDropDown.eventBlur.subscribe(this.listenBlur.bind(this));
  }
  
  $(this.setup.bind(this));
}

Eventful.TypeAhead.prototype.typeahead = function ()
{
  return this.jqTypeahead ? this.jqTypeahead : this.jqTypeahead = $('#type-ahead-'+this.id);
}

Eventful.TypeAhead.prototype.selected = function ()
{
  return this.jqSelected ? this.jqSelected : this.jqSelected = $('ul', this.typeahead());
}

Eventful.TypeAhead.prototype.description = function ()
{
  return this.jqDescription ? this.jqDescription : this.jqDescription = $('#description-'+this.id);
}

Eventful.TypeAhead.prototype.setup = function ()
{
  Eventful.InactiveText(this.oDropDown.input());
  
  if (this.bSingular)
  {
    this.oDropDown.input().css({width: '98%'});
    this.selected().hide();
  }
  
  if (this.bOptions)
  {
    // render options
    this.renderResults();
  }
  
  // resize the input field
  this.updateInputLength();
}

Eventful.TypeAhead.prototype.updateInputLength = function ()
{
  if (this.bSingular) return;
  
  var nWidth = this.typeahead().width()-this.selected().width()-10;
  this.oDropDown.input().css({width: nWidth+'px'});
  this.oDropDown.popover().css({left: this.selected().width()+'px'});
}

// This method was made to be overloaded by the parent class (i.e. performer, venue, etc..)
Eventful.TypeAhead.prototype.removeExcluded = function (aResults) {
  return aResults;
}

Eventful.TypeAhead.prototype.setValue = function (sValue)
{
  if (sValue)
  {
    this.oDropDown.input().val(sValue).removeClass('inactive');
  } else
  {
    this.item(null); // alias
  }
}

Eventful.TypeAhead.prototype.reset = function ()
{
  this.item(null); // alias
}

Eventful.TypeAhead.prototype.renderResults = function (sQuery, aResults)
{
  // remove loading state
  this.typeahead().removeClass('loading');
  
  if (this.bOptions)
  {
    // add options
    var aOptions = this.options();
    if (aOptions && aOptions.length)
    {
      aResults = (aResults || []).concat(aOptions);
    }
  }
  
  if (!aResults) return;
  
  // remove ones we don't want in the list before trying to render
  aResults = this.removeExcluded(aResults);

  if (sQuery)
  {
    // regex for matching query in results
    var aSplit = $.grep(sQuery.split(/[\s,']+/), function (s) { return s;});
    var rxBold = new RegExp('('+aSplit.join('|')+')', 'ig');
  }
  
  if (aResults.length)
  {
    // remove empty state and add content
    this.oDropDown.popover().removeClass('empty');
    this.oDropDown.queue(new Eventful.CircularQ(aResults));
    this.oDropDown.list().empty();
    $.each(aResults, function (i, oItem)
    {
      var sTitle = this.itemTitle(oItem);
      if (rxBold && !oItem.option)
      {
        sTitle = sTitle.replace(rxBold, '<b>$1</b>');
      }
      var sDescription = this.itemDescription(oItem);
      var elItem = $('<li>').
        addClass('click-result').
        html(sTitle+(sDescription?'<p class="diminished">'+sDescription+'</p>':'')).
        appendTo(this.oDropDown.list());
      if (!i) elItem.addClass(i?'':'highlight'); // highlight first
      // add ID if we have one
      if (this.itemId)
      {
        var sItemID = this.itemId(oItem);
        if (sItemID) elItem.attr('id', 'type-ahead-'+this.id+'-'+sItemID);
      }
      // indicate options
      if (oItem.option) elItem.addClass('option');
      // indicate first item
      if (i == 0) elItem.addClass('first');
    }.bind(this));
  } else
  {
    // add empty state and clear content
    this.oDropDown.popover().addClass('empty');
    this.oDropDown.queue(null);
    this.oDropDown.list().empty();
  }

  if (this.oDropDown.bHasFocus)
  {
    // show results popover
    this.oDropDown.popover().show();
  }
}

Eventful.TypeAhead.prototype.item = function (oItem)
{
  if (oItem === null)
  {
    // reset state
    this.description().hide();
    this.oDropDown.reset();
    // clear results, preserving options
    this.renderResults();
  } else if (oItem)
  {
    // set description and value
    var sTitle = this.itemTitle(oItem);
    var sDescription = this.itemDescription(oItem);
  
    if (this.bSingular) // singular-mode
    {
      this.setValue(sTitle);
      if (sDescription)
      {
        this.description().html(sDescription).show().removeClass('hidden');
      } else
      {
        this.description().hide();
      }
    } else // multiple-mode
    {
      this.oDropDown.input().css({width: 0}).val(''); // clear and hide momentarily
      this.oDropDown.list().empty();
    
      var elItem = $('<li>'+sTitle+' <span class="faded delete_box click-remove">X</span></li>').
        appendTo(this.selected());
      
      elItem.find('.click-remove').click(this.listenClickRemove.bind(this, elItem, oItem));
      this.updateInputLength();
    }
  }
  
  // keep & return item
  if (typeof oItem !== 'undefined') this.oItem = oItem;
  return this.oItem;
}

/* event handlers */

Eventful.TypeAhead.prototype.listenBlur = function ()
{
  // ignore blur if field is not required or not visible
  if (!this.bRequired || !this.oDropDown.input().is(':visible')) return;
  
  var oItem = this.item();
  var oQueue = this.oDropDown.oQueue;
  
  if (oQueue && oQueue.queue[0] && !oQueue.queue[0].option
      && (oQueue.iter == 0 || !oItem))
  {
    // The user had a search with results and either
    // simply blurred away without mousing over any items
    // or did not have a venue yet, so take the top item.
    this.item(oQueue.queue[0]);
    this.eventItemSelected.fire(oQueue.queue[0]);
  } else if (oItem)
  {
    // Revert back to the old venue.
    this.item(oItem);
  }
}

Eventful.TypeAhead.prototype.listenItemSelected = function (oItem)
{
  if (oItem.option)
  {
    // option case
    this.eventOptionSelected.fire(oItem);
  } else
  {
    // item case
    this.item(oItem);
    this.eventItemSelected.fire(oItem);
    // clean up inactive text and select field
    Eventful.InactiveText.listenFocus({target: this.oDropDown.input()});
    this.oDropDown.input().select();
  }
}

Eventful.TypeAhead.prototype.listenEnterAfterSelected = function ()
{
  if (this.item())
  {
    this.eventEnterConfirm.fire(this.item());
  }
}
Eventful.TypeAhead.prototype.listenItemHighlighted = function (oItem)
{
  if (!oItem.option)
  {
    this.item(oItem);
  }
}

Eventful.TypeAhead.prototype.listenInputChanged = function (sInput)
{
  this.description().hide();
    
  if (!this.oDropDown.input().hasClass('inactive') && sInput.length > 1)
  {
    this.typeahead().addClass('loading');
    this.search(sInput);
  } else
  {
    // hide results popover
    this.oDropDown.popover().hide();
  }
}

Eventful.TypeAhead.prototype.listenClickRemove = function (elItem, oItem, evt)
{
  $(elItem).remove();
  this.updateInputLength();
  this.eventItemRemoved.fire(oItem);
}

Eventful.TypeAhead.prototype.listenServerResponse = function (sQuery, oResponse)
{
  var aResults = (oResponse||{}).results||[];
  this.renderResults(sQuery, aResults);
}

/* Eventful JS String helper functions */
String.prototype.truncate = function(n, suffix)
{
  if (!this.length || !n) return this;
  suffix = suffix || '...';

  if (this.length > n)
  {
    return this.substring(0, n) + suffix;
  }
  else {
    return this.substring(0);
  }
}

String.prototype.append = function(sAdd, sSep)
{
  return this + ((this.length)?sSep:'') + sAdd;
}

String.prototype.trim = function()
{
  return this.replace(/(^\s+|\s+$)/g, '');
}

String.prototype.lpad = function(n, sPad)
{
  if (n && this.length < n)
  {
    return (sPad + this).lpad(n, sPad);
  } else
  {
    return this; 
  }
}

String.prototype.commify = function()
{
  return this.replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,");
}

String.prototype.uppercaseFirst = function()
{
  return this.replace(/\b(\w)/g, function(_, m)
  {
    return m.toUpperCase();
  });
}

// replace "{something}" with O.something
String.prototype.surplant = function(O)
{
  return this.replace(/\{(\w+)\}/g,function(a,b){
    var r = O[b];
    return typeof r === "string" ? r : a;
  });
}

// require eventful.core
// require eventful.type-ahead
// require eventful.uievent
// require eventful.string
// require prototype.function
// require jquery.core

/**
  Location Type Ahead
  2008-04-07 / <john@eventful.com>
**/

Eventful.LocationTypeAhead = function (oArgs)
{
  this.nTruncate = oArgs.truncate || oArgs.length || 64;
  this.sExclude = oArgs.exclude || '';
  this.bBubbleUp = oArgs.bubble_up || '';
  Eventful.TypeAhead.call(this, oArgs);
  
  this.eventLocationPosted = new Eventful.UIEvent();
  
  if (oArgs.post)
  {
    this.eventItemSelected.subscribe(this.listenLocationSelected.bind(this));
  }
  
}.mixin(Eventful.TypeAhead);

Eventful.LocationTypeAhead.prototype.itemTitle = function (oLocation)
{
  var aSplit = this.splitLines(oLocation);
  if (aSplit)
  {
    // the part before the parentheses
    return aSplit[1].trim().truncate(this.nTruncate);
  }
  
  return oLocation.pretty_name.truncate(this.nTruncate);
}

Eventful.LocationTypeAhead.prototype.itemDescription = function (oLocation)
{
  var aSplit = this.splitLines(oLocation);
  if (aSplit)
  {
    // the part in the parentheses
    return aSplit[2].trim().truncate(this.nTruncate);
  }
}

Eventful.LocationTypeAhead.prototype.splitLines = function (oLocation)
{
  return oLocation.pretty_name.match(/^(.*)\((.*)\)$/);
}

Eventful.LocationTypeAhead.prototype.itemId = function (oLocation)
{
  return oLocation.location_type+'-'+oLocation.location_id;
}

Eventful.LocationTypeAhead.prototype.search = function (sQuery)
{
  $.get(
    '/json/tools/location/typedown',
    {
      location: sQuery,
      destination_key: 'results',
      recent: 1,
      bubble_up: this.bBubbleUp,
      exclude: this.sExclude
    },
    this.listenServerResponse.bind(this, sQuery),
    'json'
  );
}.slow(500);

Eventful.LocationTypeAhead.prototype.listenLocationSelected = function (oLocation)
{
  $.post(
    '/json/tools/location',
    {
      location_type: oLocation.location_type,
      location_id: oLocation.location_id,
      input_token: 'save'
    },
    this.listenLocationPosted.bind(this, oLocation),
    'json'
  );
}

Eventful.LocationTypeAhead.prototype.listenLocationPosted = function (oLocation, oResponse)
{
  this.eventLocationPosted.fire(oLocation, oResponse);
}

Eventful.LocationTypeAhead.prototype.options = function ()
{
  return Eventful.LocationTypeAhead.options;
}

Eventful.LocationTypeAhead.options = [{
  pretty_name: 'Worldwide',
  option: 1,
  worldwide: 1,
  svid: 'V0-001-000000001-8'
}];

// require eventful.core
// require eventful.uievent
// require eventful.popover
// require eventful.formval
// require eventful.type-ahead.location
// require prototype.function
// require jquery.core

/**
 * Change Location Popover Widget
 * 
 * Locations are automatically loaded by asynchronous request to /json/tools/location.
 *  
 * The 'locationChanged' event (eventLocationChanged) is fired after the server
 * responds to a change-location request. This occurs when a user selects a location
 * from the location list or submits a valid location.
 *  
 *  2007-11-07 / <john@eventful.com>
 **/

Eventful.PopoverChangeLocation = function (oArgs)
{
  Eventful.Popover.call(this, '#popover-change-location',
    $.extend({width: 250}, oArgs));
    
  this.bPost = typeof oArgs.post == 'undefined' ? true : oArgs.post;
  this.sInputToken = oArgs.token;
  
  // locationChanged event is called after the server changes your location
  this.eventLocationChanged = new Eventful.UIEvent();
  
  this.oValidator = new Eventful.FormVal(this.find('#location-form'));
  this.oValidator.addRule('location-search',
  {
    required: 1,
    message: 'Please enter a location.'
  });
  this.oValidator.eventPassValid.subscribe(this.listenLocationValidated.bind(this));
  this.oValidator.eventFailValid.subscribe(this.listenLocationInvalid.bind(this));
    
  // switch into 'guessed' layout
  if (this.popover().hasClass('guessed'))
  {
    this.swapTopAndBottom();
  }
  
  this.eventShow.subscribe(this.listenShow.bind(this));
  
  /* type-ahead */
  
  this.oLocationTypeAhead = new Eventful.LocationTypeAhead({
    id: 'location-search',
    required: 1,
    exclude: ['place_id'],
    length: 28
  });
  
  this.oLocationTypeAhead.eventItemSelected.subscribe(this.changeLocation.bind(this));  
  
  /* geo-location */
  
  if (window.navigator && navigator.geolocation)
  {
    this.find('.geolocate')
      .show()
      .click(this.listenClickGeoLocate.bind(this));
  }
}.mixin(Eventful.Popover);

Eventful.PopoverChangeLocation.prototype.updateLocations = function (aLocales, oCurrentLocale)
{
  // hide the loading state on the form
  this.find('#location-form').removeClass('loading'); 
  // clear the search box
  this.find('#location-search').val('');
  // hide error state
  this.find('#location-form').removeClass('has-error');
  this.find('#location-form').removeClass('show-errors');
  // update the list
  if (aLocales && oCurrentLocale)
  {
    this.aLocales = aLocales; // copy the given locations
    var bFoundCurrent = false;
    // add worldwide if we aren't in the demand flow and aren't currently worldwide
    if (this.sInputToken != 'demand_flow' && oCurrentLocale.pretty_name != 'Worldwide')
    {
      aLocales.push({
        pretty_name:   'Worldwide',
        location_type: 'worldwide',
        location_id:   'worldwide'
      });
    }
    // empty the current list
    this.find('#locations-list').empty();
    // add the locations to the list
    $.each(aLocales, function (_, oLocale)
    {
      // mark the current location with current=true
      if (oLocale.location_type == oCurrentLocale.location_type &&
          oLocale.location_id   == oCurrentLocale.location_id)
      {
        oLocale.current = true;
        bFoundCurrent = true;
      } else
      {
        oLocale.current = false;
      }
      this.addLocationItem(oLocale);
    }.bind(this));
    // add the current location if wasn't in the location response
    if (!bFoundCurrent)
    {
      oCurrentLocale.current = true;
      this.addLocationItem(oCurrentLocale);
      // copy current to the  unless its worldwide
      if (oCurrentLocale.pretty_name != 'Worldwide')
      {
        this.aLocales.push(oCurrentLocale);
      }
    }
  }
  // switch out of 'guessed' layout
  if (this.popover().hasClass('guessed') && !oCurrentLocale.geo_ip_guess)
  {
    this.popover().removeClass('guessed');
    this.swapTopAndBottom();
  }
}

Eventful.PopoverChangeLocation.prototype.swapTopAndBottom = function ()
{
  var elBody = this.find('.popbd:first')
  elBody.children(':first').remove().appendTo(elBody);
}

Eventful.PopoverChangeLocation.prototype.addLocationItem = function (oLocale)
{
  var elItem = $('\
    <li>\
      <span class="link-arrow">\
        <span class="title">\
          '+oLocale.pretty_name+'\
          <span class="progress"></span>\
        </span>\
      </span>\
    </li>\
  ').appendTo(this.find('#locations-list'));
  
  if (oLocale.current)
  {
    elItem.addClass('current');
  } else
  {
    elItem.find('.title')
      .addClass('fakelink')
      .click(this.listenLocationClick.bind(this, elItem, oLocale));
  }
  
  if (oLocale.pretty_name == 'Worldwide')
  {
    elItem.find('.title').attr({id: 'location-worldwide'});
  }
}

Eventful.PopoverChangeLocation.prototype.changeLocation = function (oLocale, bFire)
{
  if (this.bPost)
  {
    // change the location
    this.bLoading = true;
    $.post(
      '/json/tools/location',
      {
        location_type: oLocale.location_type,
        location_id: oLocale.location_id,
        input_token: this.sInputToken,
        path: window.location.pathname + window.location.search
      },
      this.listenChangeLocationServerResponse.bind(this, oLocale, bFire),
      'json'
    );
  } else
  {
    // simulate a post using the previous response
    this.updateLocations(this.aLocales, oLocale);
    this.eventLocationChanged.fire({locale: oLocale});
  }
}

/* event listeners */

Eventful.PopoverChangeLocation.prototype.listenShow = function ()
{
  // reposition popover
  this.show();
  
  // focus on type-ahead
  this.oLocationTypeAhead.oDropDown.input().focus();
  
  if (!this.bLoaded && !this.bLoading)
  {
    // request locations
    $.get(
      '/json/tools/location',
      '?'+new Date().getTime(), // no cache, kthx
      this.listenGetLocationsServerResponse.bind(this),
      'json'
    );
  }
}

Eventful.PopoverChangeLocation.prototype.listenClickGeoLocate = function ()
{
  navigator.geolocation.getCurrentPosition(this.listenGeoLocate.bind(this));
}

Eventful.PopoverChangeLocation.prototype.listenGeoLocate = function (oPosition)
{
  if (oPosition && oPosition.coords) {
    $.getJSON(
      '/json/tools/location/latlong',
      {
        latitude: oPosition.coords.latitude,
        longitude: oPosition.coords.longitude
      },
      function (oResponse)
      {
        if (oResponse.location)
        {
          this.changeLocation(oResponse.location);
        }
      }.bind(this)
    )
  }
}

Eventful.PopoverChangeLocation.prototype.listenChangeLocationServerResponse = function (oLocale, bFire, oResponse)
{
  this.bLoaded = true;
  this.bLoading = false;
  var aLocales = oResponse.saved_locations || oResponse.recent_locations;
  
  // update the list
  this.updateLocations(aLocales, oLocale);
  
  // close the popover
  this.close();
  
  if (bFire || typeof bFire == 'undefined')
  {
    // fire the 'locationChanged' event with the original location
    this.eventLocationChanged.fire({locale: oLocale, response: oResponse});
  }
}

/* listenGetLocationsServerResponse()
 * Called when the server responds to a change location request (i.e., a call to location.post)
 * oLocale is the location we sent to the server and R is the server's response. The change
 * location widget will consider oLocale the 'current' location even if the server responded
 * with a different current location (for instance, in the demand flow, where clicking a location
 * doesn't change your current location, but it does change your demand location).
 */

Eventful.PopoverChangeLocation.prototype.listenGetLocationsServerResponse = function (oResponse)
{
  this.bLoaded = true;
  var aLocales = oResponse.saved_locations || oResponse.recent_locations;
  var oCurrentLocale = oResponse.current;
  
  // update the list
  this.updateLocations(aLocales, oCurrentLocale);
  
  // reposition popover
  this.show();
}

Eventful.PopoverChangeLocation.prototype.listenLocationClick = function (elItem, oLocale)
{
  if (!this.bLoading)
  {
    // show the loading state on the item (hidden via updateLocations)
    elItem.addClass('loading');
    this.changeLocation(oLocale);
  }
}

Eventful.PopoverChangeLocation.prototype.listenLocationValidated = function ()
{
  this.oValidator.initialize();
  
  // submit location
  var oLocale = this.oLocationTypeAhead.item();
  if (oLocale)
  {
    this.changeLocation(oLocale);
  }
}

Eventful.PopoverChangeLocation.prototype.listenLocationInvalid = function ()
{
  // hide the loading state on the form
  this.find('#location-form').removeClass('loading'); 
}

// require eventful.signin
// require eventful.header
// require eventful.popover-change-location

// require eventful.core
// require jquery.core
// require eventful.string

Eventful.EventBrowse=function() {   
  $(this.setup.bind(this));
}

Eventful.EventBrowse.prototype.setup = function() {
  // rely on jquery to handle opacity
  $('#box-browse-events .white-out').css({
    'opacity': 0.7,
    'height': $('#box-browse-events .entries').height() + 15
  });

  // add calendar panel
  this.panelAddCal = new Eventful.PanelAlert('panel-add-calendar');
  this.panelAddCal.options({width: '270px'});
  
  var oriHtml = decodeURI(this.panelAddCal.panel().find('.bd').html());
  
  $('a.calendar').bind('click', this.updatePanel.bind(this,oriHtml));
}

/*
{
  'calendar_<seid>': {
    yahoo: ...,,
    google:
    outlook:
    ical:
  }
}
*/
Eventful.EventBrowse.calendarEvents = {};

// update content according to clicked.id
Eventful.EventBrowse.prototype.updatePanel = function(oriHtml,evt,clicked){
  this.panelAddCal.show();

  var newHtml = oriHtml.surplant(Eventful.EventBrowse.calendarEvents[clicked.id]);
  this.panelAddCal.panel().find('.bd').html(newHtml);
}

new Eventful.EventBrowse();
