﻿/*!
 * 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" );
	};

});
})();


var $j = jQuery.noConflict();
if (typeof(sap) == 'undefined') {
	var sap = {};
}


sap._namespaces = {};
sap.global = window;

sap.provide = function(ns) {
	if ( sap._namespaces[ns] != undefined ) {
		return 0;
	}
	return (sap._namespaces[ns] = sap.getObject(ns, true));
};

sap._getProp = function(/*Array*/parts, /*Boolean*/create, /*Object*/context){
	var obj=context || sap.global;
	for(var i=0, p; obj && (p=parts[i]); i++){
		obj = (p in obj ? obj[p] : (create ? obj[p]={} : undefined));
	}
	return obj; // mixed
}

sap.getObject = function(/*String*/name, /*Boolean*/create, /*Object*/context){
	return sap._getProp(name.split("."), create, context); // Object
}

sap.exists = function(/*String*/name, /*Object?*/obj){
	return !!d.getObject(name, false, obj); // Boolean
}


sap.isFunction = function( fn ) {
	return !!fn && typeof fn != "string" && !fn.nodeName && 
		fn.constructor != Array && /function/i.test( fn + "" );
}

sap.__extend = function(/*Object*/ obj1, /*Object*/ obj2) {
	var tobj = {};
	for(var x in obj2){
		// the "tobj" condition avoid copying properties in "props"
		// inherited from Object.prototype.  For example, if obj has a custom
		// toString() method, don't overwrite it with the toString() method
		// that props inherited from Object.prototype
		if(tobj[x] === undefined || tobj[x] != obj2[x]){
			obj1[x] = obj2[x];
		}
	}
	// IE doesn't recognize custom toStrings in for..in
	if(sap.isIE && obj2){
		var p = obj2.toString;
		if(typeof p == "function" && p != obj.toString && p != tobj.toString &&
			p != "\nfunction toString() {\n    [native code]\n}\n"){
				obj1.toString = obj2.toString;
		}
	}
	return obj1; // Object
}

sap.extend = function(/*Object*/ obj1, /*Object...*/ objs) {
	for (var i = 1; i < arguments.length; ++i) {
		sap.__extend(obj1, arguments[i]);
	}
	return obj1;
}

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


sap.globalEval = function( data ) {
		data = sap.trim( data );

		if ( 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 ( sap.browser && sap.browser.msie )
				script.text = data;
			else
				script.appendChild( document.createTextNode( data ) );

			head.appendChild( script );
			head.removeChild( script );
		}
	}
	
   sap.hasClass = function(ele,cls) {
	            return (ele && ele.className && ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')));
            }
             
   sap.addClass = function(ele,cls) {
	            if (!sap.hasClass(ele,cls)) ele.className += " "+cls;
            }
             
   sap.removeClass = function(ele,cls) {
	            if (sap.hasClass(ele,cls)) {
    	            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		            ele.className=ele.className.replace(reg,' ');
	            }
            }
            
	sap.requireCss = function(uri, options) {
		var head = document.getElementsByTagName("head")[0] || document.documentElement,
		link = document.createElement("link");
		link.type = "text/css";
		link.rel = "stylesheet";
		link.href = uri;
		sap.extend(link, options);
		
		head.appendChild(link);
	}            	
   
   sap.requireScript = function(uri, options) {
		var head = document.getElementsByTagName("head")[0] || document.documentElement,
		script = document.createElement("script");
		script.type = "text/javascript";
		script.src = uri;
		sap.extend(script, options);
		
		head.appendChild(script);
	}         

Date.isLeapYear=function(y){return(((y%4===0)&&(y%100!==0))||(y%400===0));};
Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));};
Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};            
Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,Date.getDaysInMonth(this.getFullYear(),this.getMonth())));return this;};            

sap.provide("sap.ajax");

(function(){
	sap.ajax = {
		get: function( url, data, success_callback, error_callback, type ) {
			// shift arguments if data argument was ommited
			if ( sap.isFunction( data ) ) {
				callback = data;
				data = null;
			}
		
			return sap.ajax.ajax({
				type: "GET",
				url: url,
				data: data,
				success: success_callback,
				error: error_callback,
				dataType: type
			});
		},		
		
		getScript: function( url, callback ) {
			return sap.ajax.get(url, null, callback, "script");
		},

		getJSONP: function( url, data, success, error ) {
			return sap.ajax.get(url, data, success, error, "jsonp");
		},
		
		getJSON: function( url, data, callback ) {
			return sap.ajax.get(url, data, callback, "json");
		},

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

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

		ajaxSettings: {
			global: true,
			type: "GET",
			timeout: 0,
			contentType: "application/x-www-form-urlencoded",
			processData: true,
			async: true,
			data: null,
			username: null,
			password: null,
			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: {},
		jsc: 1,

		ajax: function( s ) {
			var jsonp, jsre = /=\?(&|$)/g, status, data;

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

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

			// Handle JSONP Parameter Callbacks
			if ( s.dataType == "jsonp" ) {
				if ( s.type.toLowerCase() == "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" + sap.ajax.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 && s.type.toLowerCase() == "get" ) {
				var ts = (new Date()).getTime();
				// 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 && s.type.toLowerCase() == "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 && ! sap.ajax.active++ )
				;
				//jQuery.event.trigger( "ajaxStart" );

			// If we're requesting a remote document
			// and trying to load JSON or Script with a GET
			if ( (!s.url.indexOf("http") || !s.url.indexOf("//")) && s.dataType == "script" && s.type.toLowerCase() == "get" ) {
				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();
							head.removeChild( script );
						}
					};
				}

				head.appendChild(script);

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

			var requestDone = false;

			// Create the request object; Microsoft failed to properly
			// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
			var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

			// Open the socket
			xml.open(s.type, s.url, s.async, s.username, s.password);

			// 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 )
					xml.setRequestHeader("Content-Type", s.contentType);

				// Set the If-Modified-Since header, if ifModified mode.
				if ( s.ifModified ) {
					xml.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
				xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");

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

			// Allow custom headers/mimetypes
			if ( s.beforeSend ) {
				s.beforeSend(xml);
			}
				
			if ( s.global );
				//jQuery.event.trigger("ajaxSend", [xml, s]);

			// Wait for a response to come back
			var onreadystatechange = function(isTimeout){
				// The transfer is complete and the data is available, or the request timed out
				if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
					requestDone = true;
					
					// clear poll interval
					if (ival) {
						clearInterval(ival);
						ival = null;
					}
					
					status = isTimeout == "timeout" && "timeout" ||
						!sap.ajax.httpSuccess( xml ) && "error" ||
						s.ifModified && jQuery.httpNotModified( xml, 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 = sap.ajax.httpData( xml, s.dataType );
						} 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 = xml.getResponseHeader("Last-Modified");
						} catch(e) {} // swallow exception thrown by FF if header is not available
		
						if ( s.ifModified && modRes )
							sap.ajax.lastModified[s.url] = modRes;

						// JSONP handles its own success callback
						if ( !jsonp ) {
							success();	
						}
					} else {
						sap.ajax.handleError(s, xml, status);
					}
					// Fire the complete handlers
					complete();
					

					// Stop memory leaks
					if ( s.async ) {
						xml = 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 ( xml ) {
							// Cancel the request
							xml.abort();
		
							if( !requestDone ) {
								onreadystatechange( "timeout" );
							}
						}
					}, s.timeout);
				}
			}
				
			// Send the data
			try {
				xml.send(s.data);
			} catch(e) {
				sap.ajax.handleError(s, xml, 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", [xml, s] );
			}

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

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

				// Handle the global AJAX counter
				if ( s.global && ! --sap.ajax.active );
					//jQuery.event.trigger( "ajaxStop" );
			}
			
			// return XMLHttpRequest to allow aborting the request etc.
			return xml;
		},

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

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

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

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

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

				// Firefox always returns 200. check Last-Modified date
				return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
					jQuery.browser.safari && xml.status == undefined;
			} catch(e){}
			return false;
		},

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

			if ( xml && data.documentElement.tagName == "parsererror" ) {
				throw "parsererror";
			}

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

			// Get the JavaScript object, if JSON is used.
			if ( type == "json" ) {
				data = 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 = [];

			// If an array was passed in, assume that it is an array
			// of form elements
			if ( a.constructor == Array || a.jquery ) {
				// Serialize the form elements
				jQuery.each( a, function(){
					s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( 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 ( a[j] && a[j].constructor == Array ) {
						for(var i = 0; i < a[j].length; ++i) {
							s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j][i] ) );
						}
					}
					else {
						s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
					}
				}
			}

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

sap.data.form = function(topNode) {

	this.topNode = topNode;
	
	this.bind = function(data, query) {
		var object = jsonPath(data, query);
		this.topNode.parentNode.replaceChild(this.__bind(this.topNode, this.getData(this.topNode), object), this.topNode);
	};
	
	this.class_data_regexp = /({.*})/;
	this.getData = function(node) {
  
      if ( !node || !node.tagName ) return;
		
		var data = $j.data(node, '_sap_data');
		if (data) {
			return data;
		}
		
      data = "{}";

      var m = this.class_data_regexp.exec( node.className );
      if ( m )
          data = m[1];

		 if ( !/^{/.test( data ) ) {
	          data = "{" + data + "}";
      }

      eval("data = " + data);
   
		$j.data(node, '_sap_data', data);
      return data;
    }
    
    this.setNodeValue = function(node, value) {
		 if ( node.nodeType == 1 && node.tagName ) {
			  switch ( node.tagName.toLowerCase() ) {
					case 'input':
					case 'textarea':
						 node.value = value;
						 break;
					default:
						 node.innerHTML = value;
	            
	        
			  }
	    
		 }
	}
    
	this.__bind = function(node, data, jpathObject) {
		data = (data || {});
         
       var returnNode = null;
       var op = (data['sap-type']||'').toLowerCase();
       
       if ( sap.hasClass(node, 'sap-delete') ) {
			return null;
       }

       var temp_dom_node;
       
       switch (op) {
           case 'value-of': 
               var new_node = node.cloneNode(false);
               //console.log(data['sap-select'], jpathObject, jsonPath((jpathObject.length)?jpathObject[0]:jpathObject, data['sap-select']));
               this.setNodeValue(new_node, jsonPath((jpathObject.length)?jpathObject[0]:jpathObject, data['sap-select']));
               returnNode = new_node;
               break;
           case 'apply-template':
               
               var objects = jsonPath((jpathObject.length)?jpathObject[0]:jpathObject, data['sap-select'])[0];
               var rootNode = document.createDocumentFragment();
               
               for ( var k = 0, ol = objects.length; k < ol; ++k ) {
                   var domNode = node.cloneNode(false);
                   objects[k]['pos'] = k + 1;
                   if ( node.childNodes && node.childNodes.length > 0 ) {
                       for ( var i = 0, nl = node.childNodes.length; i < nl; ++i ) {
                           temp_dom_node = this.__bind(node.childNodes[i], this.getData(node.childNodes[i]), objects[k]);
                           if ( temp_dom_node ) {
										domNode.appendChild(temp_dom_node);
									}
                       }
                   
                   }
                   sap.removeClass(domNode, 'even');
                   sap.removeClass(domNode, 'odd');
                   sap.addClass(domNode, (k%2)?'even':'odd');
                   if (k > 0) { sap.addClass(domNode, 'sap-delete'); }
                   rootNode.appendChild(domNode);
               }
               
               returnNode = rootNode;
               break;
           case 'if':
               var rootNode;
               var test = (data['sap-test']);
               var results = jsonPath((jpathObject.length)?jpathObject[0]:jpathObject, test);
               
               var isTrue = (results && results.length);
               var rootNode = node.cloneNode(!isTrue);
               window[(isTrue)?'removeClass':'addClass'](rootNode,'else');
               
               if ( isTrue ) {
                   if ( node.childNodes && node.childNodes.length > 0 ) {
                       for ( var i = 0, nl = node.childNodes.length; i < nl; ++i ) {
									temp_dom_node = this.__bind(node.childNodes[i], this.getData(node.childNodes[i]), jpathObject);
                           if (temp_dom_node) {
										rootNode.appendChild(temp_dom_node);
                           }
                       }
                   }   
               }
                                       
               returnNode = rootNode;
               break;
           default:
               node = (node) ? node : document.createTextNode('');
               returnNode = node.cloneNode(false);
               if ( node.childNodes && node.childNodes.length > 0 ) {
                   for ( var i = 0, nl = node.childNodes.length; i < nl; ++i ) {
								temp_dom_node = this.__bind(node.childNodes[i], this.getData(node.childNodes[i]), jpathObject);
								if ( temp_dom_node ) {
									returnNode.appendChild(temp_dom_node);
                        }
                   }
               }
               break;
       }
       
       if ( data['sap-attr'] ) {
           var attrs = data['sap-attr'];
           var val, a;
           
           
           
           tempObj = {};
           for ( var i = 0, al = attrs.length; i < al; ++i ) {
               a = attrs[i];
               
               if ( a.jpath ) {
                   val = jsonPath(jpathObject, a.jpath);
               } else {
                   val = a.text;
               }
               
               tempObj[a.attr] = (tempObj[a.attr]||'') + (val+'').toString();
           }
           
           for ( var obj in tempObj ) {
               if ( obj == "toJSONString" ) continue;
               if ( obj == "class" ) {
						returnNode['className'] = tempObj[obj];
					} else {
						returnNode.setAttribute(obj, tempObj[obj]);
					}
           }
       
       }
       
       if ( returnNode && returnNode.tagName ) {
			 $j.data(returnNode, '_sap_data', sap.extend({},data));
			 if (typeof console != 'undefined' && console.log ) {
				console.log(returnNode, data);
			}
			 
		 } else {
       }
       
       return returnNode;	

	}
}
/* JSONPath 0.8.b - XPath for JSON
 *
 * Copyright (c) 2007 Stefan Goessner (goessner.net)
 * Licensed under the MIT (MIT-LICENSE.txt) licence.
 Upgrades by Kris Zyp, SitePen:
 Fixed bugs with special characters in the object keys, and operator keys
 Fixed bug with nested [([()])]
 Add result based evaluation argument
 evalType=="RESULT" will use result based evaluation instead of ITEM based (the default)
 I switched the code from recursive to iterative in order implement the changes
 */
function jsonPath(obj, expr, arg) {
   var strs = [];
   function _str(i) { return strs[i];}
   var acc;
   if (arg && arg.resultType == "PATH" && arg.evalType == "RESULT") throw Error("RESULT based evaluation not supported with PATH based results");
   var P = {
      resultType: arg && arg.resultType || "VALUE",
      normalize: function(expr) {
         var subx = [];
         expr = expr.replace(/'([^']|'')*'/g, function(t){return "_str("+(strs.push(eval(t))-1)+")";});
         var ll = -1;
         while(ll!=subx.length){
         	ll=subx.length;//TODO: Do expression syntax checking
         	expr = expr.replace(/(\??\([^\(\)]*\))/g, function($0){return "#"+(subx.push($0)-1);});
         }
         expr = expr.replace(/[\['](#[0-9]+)[\]']/g,'[$1]')
                    .replace(/'?\.'?|\['?/g, ";")
                    .replace(/;;;|;;/g, ";..;")
                    .replace(/;$|'?\]|'$/g, "");
         var ll = -1;
         while(ll!=expr){
         	ll=expr;
                expr = expr.replace(/#([0-9]+)/g, function($0,$1){return subx[$1];});
         }
         return expr.split(";");
      },
      asPaths: function(paths) {
      	for (var j=0;j<paths.length;j++) {
         var p = "$";
         var x= paths[j];
         for (var i=1,n=x.length; i<n; i++)
            p += /^[0-9*]+$/.test(x[i]) ? ("["+x[i]+"]") : ("['"+x[i]+"']");
         paths[j]=p;
        }
         return paths;
      },
      exec: function(locs, val, rb) {
         var path = ['$'];
         var result=rb?val:[val];
         var paths=[path];
         function add(v, p,def) {
	        if (v && v.hasOwnProperty(p) && P.resultType == "PATH") paths.push(path.concat([p]));
         	if (def) 
         	  result = v[p];
	        else if (v && v.hasOwnProperty(p))  
	         	result.push(v[p]);
         }
         function desc(v) {
         	result.push(v);
         	paths.push(path);
         	P.walk(v,function(i){
         		if (typeof v[i] ==='object')  {
         			var oldPath = path;
         			path = path.concat(i);
         			desc(v[i]);
         			path = oldPath;
         		}
         	});
         }
         function slice(loc, val) {
           if (val instanceof Array) {
              var len=val.length, start=0, end=len, step=1;
              loc.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g, function($0,$1,$2,$3){start=parseInt($1||start);end=parseInt($2||end);step=parseInt($3||step);});
              start = (start < 0) ? Math.max(0,start+len) : Math.min(len,start);
              end   = (end < 0)   ? Math.max(0,end+len)   : Math.min(len,end);
              for (var i=start; i<end; i+=step)
                 add(val,i);
           }
         }
         function repStr(str){
         	var i=loc.match(/^_str\(([0-9]+)\)$/);
         	return i?strs[i[1]]:str;
         }
	 function oper(val) {
	     if (/^\(.*?\)$/.test(loc)) // [(expr)]
		add(val, P.eval(loc, val),rb);
	     else if (loc === "*") {
		P.walk(val, rb && val instanceof Array ? // if it is result based, there is no point to just return the same array
			function(i) {P.walk(val[i],function(j){ add(val[i],j); })} :
			function(i) { add(val,i); });
	     }
	     else if (loc === "..") 
		desc(val);
	     else if (/,/.test(loc)) { // [name1,name2,...]
		for (var s=loc.split(/'?,'?/),i=0,n=s.length; i<n; i++)
		   add(val,repStr(s[i])); 
	     }
	     else if (/^\?\(.*?\)$/.test(loc)) // [?(expr)]
		P.walk(val, function(i) { if (P.eval(loc.replace(/^\?\((.*?)\)$/,"$1"),val[i])) add(val,i); });
	     else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) // [start:end:step]  python slice syntax
		slice(loc, val);
	     else {
		loc=repStr(loc);
		if (rb && val instanceof Array && !/^[0-9*]+$/.test(loc)) 
		  P.walk(val, function(i) { add(val[i], loc) });
		else 
		  add(val,loc,rb);		
	     }

	 }
         while (locs.length) {
            var loc = locs.shift();
            if ((val = result) === null || val===undefined) return val;
            result = [];
            var valPaths = paths;
            paths = [];
            if (rb) 
              oper(val)
            else
              P.walk(val,function(i){path=valPaths[i]||path;oper(val[i])});
         }
         return P.resultType == "PATH" ? P.asPaths(paths):result;
      },
      walk: function(val, f) {
         if (val instanceof Array) {
            for (var i=0,n=val.length; i<n; i++)
               if (i in val)
                  f(i);
         }
         else if (typeof val === "object") {
            for (var m in val)
               if (val.hasOwnProperty(m))
                  f(m);
         }
      },
      eval: function(x, _v) {
         try { return $ && _v && eval(x.replace(/@/g,'_v')); }
         catch(e) { throw new SyntaxError("jsonPath: " + e.message + ": " + x.replace(/@/g, "_v").replace(/\^/g, "_a")); }
      }
   };

   var $ = obj;
   if (expr && obj && (P.resultType == "VALUE" || P.resultType == "PATH")) {
      return P.exec(P.normalize(expr).slice(1), obj, arg && arg.evalType == "RESULT");
   }
} 
sap.provide("sap.encoding");
sap.provide("sap.encoding.utf8");

(function(){
	var encoding = sap.encoding;
	encoding.utf8 = function(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = [];

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext.push(String.fromCharCode(c));
            }
            else if((c > 127) && (c < 2048)) {
                utftext.push(String.fromCharCode((c >> 6) | 192));
                utftext.push(String.fromCharCode((c & 63) | 128));
            }
            else {
                utftext.push(String.fromCharCode((c >> 12) | 224));
                utftext.push(String.fromCharCode(((c >> 6) & 63) | 128));
                utftext.push(String.fromCharCode((c & 63) | 128));
            }

        }

        return utftext.join('');
    };

})();

sap.provide("sap.encoding.hex");

(function(){
	var hexEncode = function(data){
	var b16_digits = '0123456789abcdef';
	var b16_map = new Array();
	for (var i=0; i<256; i++) {
		b16_map[i] = b16_digits.charAt(i >> 4) + b16_digits.charAt(i & 15);
	}
	
	var result = new Array();
	for (var i=0; i<data.length; i++) {
		result[i] = b16_map[data.charCodeAt(i)];
	}
	
	return result.join('');
};
	
	sap.encoding.hex = function(string, decode) {
		return hexEncode(string);
	}
	

})();

sap.provide("sap.encryption.symmetric.RC4");
	
	/* RC4 symmetric cipher encryption/decryption
 * Copyright (c) 2006 by Ali Farhadi.
 * released under the terms of the Gnu Public License.
 * see the GPL for details.
 *
 * Email: ali[at]farhadi[dot]ir
 * Website: http://farhadi.ir/
 */

/**
 * Encrypt given plain text using the key with RC4 algorithm.
 * All parameters and return value are in binary format.
 *
 * @param string key - secret key for encryption
 * @param string pt - plain text to be encrypted
 * @return string
 */
sap.encryption.symmetric.RC4 = { 
	encrypt: function (key, pt) {
	s = new Array();
	for (var i=0; i<256; i++) {
		s[i] = i;
	}
	var j = 0;
	var x;
	for (i=0; i<256; i++) {
		j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
		x = s[i];
		s[i] = s[j];
		s[j] = x;
	}
	i = 0;
	j = 0;
	var ct = '';
	for (var y=0; y<pt.length; y++) {
		i = (i + 1) % 256;
		j = (j + s[i]) % 256;
		x = s[i];
		s[i] = s[j];
		s[j] = x;
		ct += String.fromCharCode(pt.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
	}
	return ct;
},

/**
 * Decrypt given cipher text using the key with RC4 algorithm.
 * All parameters and return value are in binary format.
 *
 * @param string key - secret key for decryption
 * @param string ct - cipher text to be decrypted
 * @return string
*/
decrypt: function(key, ct) {
	return sap.encryption.symmetric.RC4.encrypt(key, ct);
}
};




//sap.require("sap.encoding.utf8");
sap.provide("sap.encryption.digests.MD5");

(function () {

	var digests = sap.encryption.digests;
	
    function RotateLeft(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }

    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
     }

     function F(x,y,z) { return (x & y) | ((~x) & z); }
     function G(x,y,z) { return (x & z) | (y & (~z)); }
     function H(x,y,z) { return (x ^ y ^ z); }
    function I(x,y,z) { return (y ^ (x | (~z))); }

    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };

	digests.MD5 = function(string) {

    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;

    string = sap.encoding.utf8(string);

    x = ConvertToWordArray(string);

    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

    for (k=0;k<x.length;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }

    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

    return temp.toLowerCase();
}})();
sap.provide("sap.rpc.SDSService");

sap.rpc.SDSService = function(uri, api_key) {
	//this.counter = 0;
	this.uri = uri;
	this.api_key;
	
	this.call = function(/*String*/method, /*Object*/ params_in, /*Function?*/ callback) {
		
		var params = sap.extend({}, params_in);
		
		var signature = this.getMethodSignature(params);
		
		params['sig'] = signature;
		params['method'] = method;
		params['api_key'] = api_key;
		params['ref'] = sap.encoding.hex(sap.encryption.symmetric.RC4.encrypt( signature, ((document.referrer) ? document.referrer.href : null) || ((document.location) ? document.location.href : null)));
		//params['call_id'] = ++call_id;
		
		sap.ajax.getJSONP(this.uri, params, callback, this.error_callback);
	
	}

	this.callback = function(json) {
		
	}
	
	this.error_callback = function(x, s, j) {
		alert('error => ' + s);
	
	}

	this.getMethodSignature = function(/*Object*/ a) {
		
			var s = [];

				// Serialize the key/values
				for ( var j in a ) {
					// If the value is an array then the key names need to be repeated
					if ( a[j] && a[j].constructor == Array ) {
						for(var i = 0; i < a[j].length; ++i) {
							s.push( j + "=" + a[j][i] );
						}
					}
					else
						s.push( j + "=" +  a[j] );
				}
		
		
		s.sort();

		return sap.encryption.digests.MD5(s.join());
		
	}

};
// Singleton class to perform basic formatting operations
Formatter = {
	formatFloat:    
	    function(s) {
            var i = parseFloat(s);
	    	return (isNaN(i)) ? 0 : i;
	    },
	    
	formatInt:
	    function(s) {
			var i = parseInt(s, 10);
			return (isNaN(i)) ? 0 : i;
		},
		
    trim:
        function(t) {
            if ( typeof t == 'number' ) { return t; }
            if ( !t ) { return ''; }
            return (t+''||'').replace(/^\s+|\s+$/g, "");
        }
};

  
if ( typeof(sap) == 'undefined' ) {
	sap = {};
}

if ( typeof(sap.generic) == 'undefined' ) {
	sap.generic = {};
}

if ( typeof(sap.dom) == 'undefined' ) {
	sap.dom = {};
}


// Enumeration for describing sort orders
sap.SortOrder = { Ascending: 0, Descending: 1 };

// Class to perform sorting operations on arrays of objects
// @Requires('Formatter.js')
sap.generic.Sorter = function() {
	var debugMode = false;
	var parsers = [];
	
	// Public routine for adding new value parsers.  All parsers must have @format and @is functions, along with 
	// @id and @type properties.  @type is either 'text' or 'numeric'.
	this.addParser = function(parser) {
	    var l = parsers.length, alreadyExists = false;
		for ( var i=0; i < l; ++i ) {
		    if ( parsers[i].id.toLowerCase() == parser.id.toLowerCase() ) {
			    alreadyExists = true;
			    break;
			}
		}
		
		if ( !alreadyExists ) { 
		    parsers.push(parser);
		}
	};
	
	this.cacheData = function() { };
	
	// Private routine to detect an appropriate parser from the list of available parsers
	// based on a representative value.
	var detectParserFromPropertyValue = function(value) {
	    value = Formatter.trim(value);
	    // This is a bit hacked but we will always offer a default text sorter at position 0
	    var parser = parsers[0];
	
	    // Loop through available parsers and test to see if value conforms by running the parser's @is function.
		for ( var i = 1, pl = parsers.length; i < pl; i++ ) {
			if ( parsers[i].is(value) ) {
				parser = parsers[i];
				break;
			}
		}
			
		return parser;
	};
	
	// Private routine to return a typical property value
	// Essentially no more than looping through the available data until you find a value that is not equal to
	// empty string or null.
	var getExampleValue = function(data, property) {
	    var value = ' ';
	    for ( var i = 0, dl = data.length; i < dl && (value !== '' && value !== null); ++i ) { 
	         value = data[i][property];
	    }
	    
	    return value;
	};
	
	// Private routine to return an appropriate value parser for a property.  
	var getParser = function(data, property) {
	    
	    var sorter;
	    
	    // If we have already parser information stored for this property, use it.
	    // Otherwise, grab a representative value and pass that along to detect the proper parser to use.
	    // If not cached already, the parser for the @property will be cached.  If no suitable parser is found
	    // the default parser (text) will be used.
	    if ( data.__parserCache && data.__parserCache[property] ) {
	        sorter = data.__parserCache[property];
	    } else { // otherwise detect the parser from the first 
	        sorter = detectParserFromPropertyValue(getExampleValue(data, property));
	        if (!data.__parserCache) {
	            data.__parserCache = {};
	        }
	        data.__parserCache[property] = sorter;
	    }
        
        return sorter;
	
	};
	
	// Routine to build a normalized data set suitable for sorting. The last item in each sub-array is the index of the row in
	// the original @data array.
	this.buildCache = function(data, columnList) {
        var dl = data.length || 0;
        var cache = { normalized: [], original: [] };
        var cols;
        var row;
        var sorter;
        var property;
        
        if ( !columnList ) {
				columnList = [];
				
				if ( data[0].length ) {
					for ( var i = 0; i < data[0].length; ++i ) {
						columnList.push([i]);
					}
				} else {
					for ( var i in data[0] ) {
						columnList.push([i]);
					}
				}
        }
        
        for ( var i = 0; i < dl; ++i ) {
            cols = [];        
            row = data[i];
            
            // Be sure the row exists
            if ( !row ) { continue; }
            
            cache.original.push(row);
            
            for ( var j = 0, sl = columnList.length; j < sl; ++j ) {
                sorter = columnList[j];
                property = sorter[0];
            
                cols.push(getParser(data, property).format(Formatter.trim(row[property])));
            }
            
            cols.push(i);
            
            cache.normalized.push(cols);
            cols = null;
        }	
        
        return cache;
	};
	
	// Public routine to perform the actual sort.  @data can be an array of objects or an array of arrays.  @sortList
	// is an array of arrays.  Each item of the sortList array has a property and an order.  
	// e.g. [ [ 'property', Sorting.Ascending ] ]
	//
	// This function returns a new array containing the referenced sort columns from the original array in a normalized state
	// along with the index number of the row in the original array (@data).
	this.sort = function(data, sortList, cache)	{ 
	
		if ( !(sortList && sortList.length) ) {
			throw Error('sap.generic.Sorter.sort: sortList is null.  expected array of arrays.');
		}
		
	    var sorter, order, property, parser, sortType, sortFunction;
	    
	    // Store the eval script as an array for now - string concatenations are costly and we can't know how
	    // nested a multi-sort may be.
	    var evalSortScript = [];
	    
	    evalSortScript.push('var custom_sort_function = function(a,b) {');
	    
	    // Loop through the sort list and generate a custom sort function
	    // The general idea is: if the current sort level is equal (0) then drop into the next
	    // sort evaluator and so on until we return either -1,0,1.
	    for ( var i = 0, sl = sortList.length; i < sl; ++i ) {
            sorter = sortList[i];
            
            //todo: add object for sort information
            property = sorter[0];
            
            if ( property === null || property === undefined ) {
					throw Error('sap.generic.Sorter.sort: sortList is malformed.  expected array of arrays.2');
            }
            
            order = sorter[1];
            parser = getParser(data, property);
            
	        sortType = parser.type;
            e = 'temp' + i;
            sortFunction = (sortType == 'text') ? 
                ((order == sap.SortOrder.Ascending) ? 'sortText' : 'sortTextDesc') :
                ((order == sap.SortOrder.Ascending) ? 'sortNumeric' : 'sortNumericDesc');
            
            if ( isNaN(property) ) {
					property = '"' + property + '"';
				}
            
            evalSortScript.push('var ' + e + ' = ' + sortFunction + '(a[' + property + '],b[' + property + ']);');
            evalSortScript.push('if (' + e + ') { return ' + e + '; }');
            evalSortScript.push('else { ');
            
        }
        
        // Close our open if braces
        for (var j=0; j < sl; ++j) {
            evalSortScript.push('};');
        }
        
        // If we've reached this point in our dynamic sort the values are equal (0)
        evalSortScript.push('return 0;');
        evalSortScript.push('};');   
        
        // Evaluate the dynamic sort function so we may use it    	        
        eval(evalSortScript.join(''));
        
        // Build a value cache array of applicable property values to speed our sort along.
        // This only caches the referenced properties.
        
        if ( !cache) { alert('no cache'); }
        cache = (cache) ? cache : buildCache(data, sortList);
        
        // Sort the normalized cache data.  Note: This function does not modify the original array.  This returns
        // a new array with the referenced search properties and a final array item with the original array index.
        // Use this index to retrieve the full original data.		

	    cache.normalized.sort(custom_sort_function);

	    // Attempt to release our function to the void
	    custom_sort_function = null;
	    delete custom_sort_function;
				
		return cache;
		
	};
	
	// Basic text sort function			
	function sortText(a,b) {
		return ((a < b) ? -1 : ((a > b) ? 1 : 0));
	}
	
	// Basic text sort function, inverted to sort descendingly
	function sortTextDesc(a,b) {
		return ((b < a) ? -1 : ((b > a) ? 1 : 0));
	}	
	
	// Basic numeric sort function
	function sortNumeric(a,b) {
		return a-b;
	}
	
	// Basic numeric sort function, inverted to sort descendingly
	function sortNumericDesc(a,b) {
		return b-a;
	}
			
	this.addParser({
		id: "text",
		is: function(s) {
			return true;
		},
		format: function(s) {
			return Formatter.trim(s).toLowerCase();
		},
		type: "text"
	});
	
	this.addParser({
		id: "integer",
		is: function(s) {
			return s.match(new RegExp(/^(\+|-)?\d+$/));
		},
		format: function(s) {
			return Formatter.formatInt(s);
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "currency",
		is: function(s) {
			return /^(\()?[å£$‰?Â?.]/.test(s);
		},
		format: function(s) {
			return Formatter.formatFloat(s.replace(new RegExp(/^[\(]/g),'-').replace(new RegExp(/[^0-9\-.]/g),""));
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "integer",
		is: function(s) {
			return /^\d+$/.test(s);
		},
		format: function(s) {
			return Formatter.formatFloat(s);
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "floating",
		is: function(s) {
			return s.match(new RegExp(/^(\+|-)?[0-9]+\.[0-9]+((E|e)(\+|-)?[0-9]+)?$/));
		},
		format: function(s) {
			return Formatter.formatFloat(s.replace(new RegExp(/,/),""));
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "ipAddress",
		is: function(s) {
			return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
		},
		format: function(s) {
			var a = s.split(".");
			var r = "";
			for (var i = 0, item; (item = a[i]); i++) {
			   if(item.length == 2) {
					r += "0" + item;
			   } else {
					r += item;
			   }
			}
			return Formatter.formatFloat(s);
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "url",
		is: function(s) {
			return /^(https?|ftp|file):\/\/$/.test(s);
		},
		format: function(s) {
			return Formatter.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));
		},
		type: "text"
	});
	
	this.addParser({
		id: "isoDate",
		is: function(s) {
			return /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(s);
		},
		format: function(s) {
			return Formatter.formatFloat((s != "") ? new Date(s.replace(new RegExp(/-/g),"/")).getTime() : "0");
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "percent",
		is: function(s) {
			return /(^[\+|\-]?\d{1,4}\.?\d{0,8}%$)|--/.test(s);
		},
		format: function(s) {
			return Formatter.formatFloat(s.replace(new RegExp(/%\+/g),""));
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "usLongDate",
		is: function(s) {
			return /^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|\'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/.test(s);
		},
		format: function(s) {
			return Formatter.formatFloat(new Date(s).getTime());
		},
		type: "numeric"
	});
	
	this.addParser({
		id: "shortDate",
		is: function(s) {
			return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
		},
		format: function(s,table) {
			var c = sap.extend({dateFormat:"us"},(table&&table.config)?table.config:{});
			s = s.replace(new RegExp(/-/g),"/");
			if(c.dateFormat == "us") {
				/** reformat the string in ISO format */
				s = s.replace(new RegExp(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/), "$3/$1/$2");
			} else if(c.dateFormat == "uk") {
				/** reformat the string in ISO format */
				s = s.replace(new RegExp(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/), "$3/$2/$1");
			} else if(c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
				s = s.replace(new RegExp(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/), "$1/$2/$3");	
			}
			return Formatter.formatFloat(new Date(s).getTime());
		},
		type: "numeric"
	});
	
	this.addParser({
	    id: "time",
	    is: function(s) {
	        return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
	    },
	    format: function(s) {
	        return Formatter.formatFloat(new Date("2000/01/01 " + s).getTime());
	    },
	  type: "numeric"
	});
			
			
	
};


        
        sap.dom.SorterHeaderClick = function(event) {
				var element = event.target;

            if ( !element || !element.genericSorterData || !element.genericSorterData.length ) {
					throw Error('sap.genericSorterHeaderClick: event target/sorter data is null');
            }
            
            var sorterHeader = element.genericSorterData[0].sorter;
            var columnIndex = element.genericSorterData[0].index;
            
            var existingSortIndex = sorterHeader.getSortByColumnIndex(columnIndex[0]);
            
				var sortOrder = ( existingSortIndex > -1 ) ?
						 (!(sorterHeader.getSort(existingSortIndex)[1]) ? 1 : 0) : 0;

            if ( sorterHeader.options.multiSort && event[sorterHeader.options.multiSortKey] ) {
            } else {
					sorterHeader.clearSort();
            }
            
            sorterHeader.addSort(columnIndex, sortOrder);
            sorterHeader.sort();
            
            if ( sorterHeader.options.callback ) {
					sorterHeader.options.callback(sorterHeader);
            }
            
        };
        
        sap.dom.SorterHeader = function(sorter, options) {
            var default_options = {
                data: null,
                multiSort: true,
                multiSortKey: 'ctrlKey'
            };
            
            this.options = sap.extend(default_options, options);
            
            var headers = [];
            var sortList = [];
            
            this.addSort = function(columnIndex, sortOrder) {
					
					columnIndex = ( columnIndex.length ) ? columnIndex : [ columnIndex ];
					sortOrder = ( sortOrder.length ) ? sortOrder : [ sortOrder ];
					
					var index;

					for ( var j = 0, cl = columnIndex.length; j < cl; ++j ) {
						index = sortList.length;
						for ( var i = 0, sl = sortList.length; i < sl; ++i ) {
							if ( sortList[i][0] == columnIndex[j] ) {
								index = i;
								break;
							}
						}
						
						sortList[index] = [columnIndex[j], (sortOrder[j] || sortOrder[sortOrder.length-1])];
					}
					
            };
            
            this.sort = function() {
					sorter.sort(this.getSort());
					this.writeClasses();
            };
            
            this.writeClasses = function() {
					var h, s;
					
					for ( var i = 0, hl = headers.length; i < hl; ++i ) {
						h = headers[i];
						$j(h.element).removeClass('sort-asc').removeClass('sort-desc');
						for ( var j = 0, sl = sortList.length; j < sl; ++j ) {
							s = sortList[j];
							if ( h.index == s[0] ) {
								$j(h.element).addClass((s[1])?'sort-desc':'sort-asc');
							}
						}
					}
            };
            
            this.clearSort = function() { 
					sortList = [];
				};
				
				this.getSort = function(index) {
					return ( index !== null && index !== undefined ) ? sortList[index] : sortList;
				};
            
            this.getSortByColumnIndex = function(columnIndex) {
					var index = -1;
					for ( var i = 0, sl = sortList.length; i < sl; ++i ) {
						if ( sortList[i][0] == columnIndex ) {
							index = i;
							break;
						}
					}
					return index;
            };
            
            this.getSortListCSS = function () {
            
            };
            
            this.addHeader = function(elem, columnIndex) {
					if (!(elem = $j(elem).get(0))) {
						throw Error('sap.dom.SorterHeader.addHeader: element is null or undefined');
					}
					
                for ( var i, hl = headers.length; i < hl; ++i ) {
                    if ( headers[hl].element == elem ) {
                        throw Error('sap.dom.SorterHeader: cannot add duplicate element \'' + elem + '\'');
                    }
                }
            
                if ( !elem.genericSorterData ) {
                    elem.genericSorterData = [];
                }
                
                columnIndex = (columnIndex.length) ? columnIndex : [ columnIndex ];
                
                elem.genericSorterData.push( { sorter: this, index: columnIndex } );
                
                headers.push({ element: elem, index: columnIndex });
                $j(elem).click(function(o){ sap.dom.SorterHeaderClick(o); });
                
            };
            
            this.addHeaders = function(element_list) {
					for ( var i = 0, el = element_list.length; i < el; ++i ) {
						this.addHeader(element_list[i], i);
					}
            };
        };
    
			// Generic routine to build a cache object from the DOM
			sap.dom.buildValueSet = function (parent, row_selector, column_selectors) {
				var rows = $j(row_selector, parent);
				
				var vals = [];
				var selector;
				
				rows.each(function(i,o) {
					var item = [];
					$j(column_selectors).each(function(j,n) {
						selector = ( isNaN((n[0]||n)) ) ? (n[0]||n) : ':nth-child(' + (n[0]||n) + ')';
						item.push($j(o).children(selector).text());
					});
				
					item.push(o);
					vals.push(item);	
				
				});
				
				return vals;
			};
    
			sap.dom.Sorter = function (id, row_selector, column_selectors) {
				var element = $j(id);
				var vals = sap.dom.buildValueSet(element, row_selector, column_selectors);
				
				var sorter = new sap.generic.Sorter(vals);
				var cache = sorter.buildCache(vals);
            
            this.sort = function(sortList) {
					var list = sorter.sort(vals, sortList, cache);

					$j(list.normalized).each(function(i,o) {
						 var r = list.original[list.normalized[i][list.normalized[i].length-1]][list.original[i].length-1];
						 r.parentNode.appendChild(r);
						 sap.removeClass(r, 'odd');
						 sap.removeClass(r, 'even');
						 sap.addClass(r,['odd','even'][i%2]);
					});	 			 
				 }
			}; 
 
 // requires sap.dom.Sorter, sap.generic.Sorter
 sap.dom.TableSorter = function(element, callback) {
            element = $j(element);
        
            if ( ! element ) {
                throw new Exception('sap.tableSorterHeader: element is null');
            }
            
            if ( element.tagName && element.tagName !== 'table' ) {
                throw new Exception('sap.tableSorterHeader: element is not <TABLE>');
            }
            
            var trs = $j('thead tr', element);           
            var headerList = [];
            var headers = getHeaders(trs, 0);
            var colList = [];
            var colSpan, header;
            var referencedColumns = {};
            var rowIndex, columnIndex;
            var rowColIndex = {};
            var header, th;
            
            for ( var i = 0, hl = headers.length; i < hl; ++i ) {
					header = headers[i];
					th = $j(header[0]);
					
					rowIndex = header[2];
					
					colList = [];
					
					columnIndex = ( rowColIndex[rowIndex] ) ? rowColIndex[rowIndex] : 0;
					
					if ( th.hasClass('no-sort') ) {
						continue;
					}
					
					colSpan = header[0].colSpan ? header[0].colSpan : 1;
					
					for ( var k = columnIndex, kl = (columnIndex + colSpan); k < kl; ++k ) {
						referencedColumns[i+1] = i+1; // easy way to enforce a unique list
						colList.push(columnIndex++);
					}

					for ( var k = rowIndex, kl = (rowIndex + header[0].rowSpan); k < kl; ++k ) {
						rowColIndex[k] = columnIndex;
					}
					
					
					headerList.push({ el: header[0], cols: colList });
					
            }
            
            colList = [];
				for ( var column in referencedColumns ) {
					colList.push(column);
				}
				
            var sorter = new sap.dom.Sorter(element, (element.get(0).tBodies)?(element.get(0).tBodies[0].rows):'tbody tr', colList);
            var headers = new sap.dom.SorterHeader(sorter, { callback: callback });
            
            $j(headerList).each(function(i,o) {
					headers.addHeader(o.el, o.cols);
            });
            
            
           function getHeaders(rows, row_index) {
					var r = rows[row_index];
					var cells = r.cells;
					var c;
					var arr = [];
					
					for ( var i = 0, cl = cells.length; i < cl; ++i ) {
						c = cells[i];
						
						if ( c && c.colSpan > 1 ) {
							arr = arr.concat(getHeaders(rows, row_index + 1));
							arr.push([ c, $j(c).text(), row_index ]);
						}
							if ( (c.rowSpan > 1 || !rows[row_index+1]) ) {
								arr.push([ c, $j(c).text(), row_index ]);
							}
						
					
					}
						
					return arr;
            }
            
        };
sap.provide("com.mlsstratus.Search");
		
		com.mlsstratus.uid = 0;
		com.mlsstratus.Search = function(node, api_key, options) {
			var that = this;

			this.search = function(criteria, save_criteria) {
				if (save_criteria) {
					this.criteria = criteria;
				}

				document.getElementById('idx-search-display').style.display = '';
				this.rpc_service.call('listings:search', criteria, this.results_callback, function() { alert('error!'); });
			};

			this.getObject = function(criteria, callback, error_callback) {
				this.rpc_service.call('listings:get', criteria, this.object_callback, function() { alert('error!'); });
			};

			this.createLegend = function() {
				this.legendNode = document.createElement('DIV');
				this.legendNode.setAttribute('id', 'idx-legend-container');

				this.legendNode.innerHTML = '<a id="idx-legend-toggle" href="#" onclick="var d=document.getElementById(\'idx-legend\');var b=(d.style.display==\'none\');d.style.display=(b)?\'\':\'none\';this.innerHTML=(b)?\'Hide Legend\':\'Show Legend\';">Show Legend</a><ul id="idx-legend" style="display:none;"><li class="idx-legend-cl"><img /><label>Sold</label></li><li class="idx-legend-location"><img /><label>Your Location</label></li></ul>';
				this.toolbarNode.appendChild(this.legendNode);
			};

			this.createResults = function() {
				this.resultsNode.innerHTML = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" id=\"idx-results-list\"><thead><tr><th>#</th><th>Address</th><th>Town</th><th>Style</th><th>Beds</th><th>Baths</th><th>Status</th><th>Price</th><th>Sold Date</th></tr></thead><tbody><tr class=\"{ 'sap-type':'apply-template', 'sap-select': '$.data' } idx-hidden\"><td class=\"idx-list-pos  ' + { 'sap-type':'value-of', 'sap-select': '.pos', 'sap-attr':[{attr:'class',text:'idx-list-pos idx-result-'},{attr:'class',jpath:'.lsc'}] }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.addr' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.town' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.style' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.br' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.bth' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.status' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.price' }\"></td><td class=\"{ 'sap-type':'value-of', 'sap-select': '.td' }\"></td></tr></tbody></table>";

				if (this.options['results.paginate']) {
					//this.resultsNode.appendChild(this.paginateNode);
				}

				if (this.options['results.disclaimer']) {
					var textNode = document.createElement('DIV');
					textNode.setAttribute('id', 'idx-results-disclaimer');
					textNode.innerHTML = this.options['results.disclaimer'];
					this.resultsNode.appendChild(textNode);
				}

			};

			this.contains_search = function(criteria) {

				if (criteria) {
					this.criteria = criteria;
				} else {
					criteria = this.criteria;
				}

				if (criteria == null) { criteria = {}; }

				var style = this.map.GetMapStyle();

				if (style == VEMapStyle.Birdseye) {
					this.showNotice('Search is disabled in Birdseye view.');
					this.hideSearchBox();
					return;
				}

				if (this.map.GetZoomLevel() < 11) { // if zoom level > this.options.max_zoom_level
					this.showNotice('Please zoom in to search.');
					this.hideSearchBox();
					return;
				}

				var bounds = this.map.GetMapView();
				criteria.longitude = ['[>=]' + (bounds.TopLeftLatLong.Longitude + 0.001), '[<=]' + (bounds.BottomRightLatLong.Longitude - 0.001)];
				criteria.latitude = ['[>=]' + (bounds.BottomRightLatLong.Latitude + 0.001), '[<=]' + (bounds.TopLeftLatLong.Latitude - 0.001)];

				this.search(criteria, false);
			};

			this.find = function(place, callback) {
				var idx = this;
				//VEMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
				this.map.Find(null, place, null, null, 0, 1, true, true, true, true,
					function(layer, results, places) {
						if (places) {
							idx.find_marker = places[0];
						}
						callback(results, place);
					});

			};

			this.results_callback = function(result) {
				idx.currentResults = result;
				if (!result) return;

				if (result.status == 'error') {
					idx.hideSearchBox();
					alert(result.error_msg);
					return;
				}

				if (result.data.length && !result.overflow) {
					var f = new sap.data.form(document.getElementById('idx-results'));
					f.bind(result, '$');
					new sap.dom.TableSorter('#idx-results-list', function() { window['idx1'].showPage(1); });
					document.getElementById('idx-results-list').style.display = '';
					if (document.getElementById('idx-page-list'))
						document.getElementById('idx-page-list').style.display = '';
				} else {
					document.getElementById('idx-results-list').style.display = 'none';
					if (document.getElementById('idx-page-list'))
						document.getElementById('idx-page-list').style.display = 'none';
				}

				var data = result.data;
				var resultsList = document.getElementById('idx-results-list');
				var rows = resultsList.tBodies[0].rows;
				var l;

				if (idx._resultsLayer != null) {
					idx.map.DeleteShapeLayer(idx._resultsLayer);
				}

				idx._resultsLayer = new VEShapeLayer();
				idx.map.AddShapeLayer(idx._resultsLayer);

				if (!result.overflow) {
					if (idx.find_marker) {

						var m = new VEShape(VEShapeType.Pushpin, idx.find_marker.LatLong);
						idx._resultsLayer.AddShape(m);

						m.SetCustomIcon('<div class="idx-pushpin idx-find-location"></div>');
						m.SetTitle(idx.find_marker.Name);
					}

					for (var i = 0; i < data.length; ++i) {
						l = data[i];

						if (!l.longitude || !l.latitude) {
							continue;
						}

						var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(l.latitude, l.longitude));
						idx._resultsLayer.AddShape(shape);

						shape.SetCustomIcon('<div class="idx-pushpin idx-pushpin-' + (l.lsc || 'default').toLowerCase() + '"><div class="text">' + (i + 1) + '</div></div>');
						shape.SetTitle(l.addr + ' ' + ((l.apt_num) ? l.apt_num : ''));
						shape.SetDescription('<div class="idx-popup-report">' + idx.options.getDescription(l, idx) + '</div>');
						shape.row = rows[i];

						rows[i].shapeId = shape.GetID();
						rows[i].onmouseover = function() { window['idx1'].hoverIcon(this.shapeId, false); };
						rows[i].onclick = function() { window['idx1'].map.HideInfoBox(); window['idx1'].map.ShowInfoBox(window['idx1'].map.GetShapeByID(this.shapeId)); };
					}

					idx.showPage(1);

					idx.showNotice((result.data.length) + ' properties found');
					idx.findPOI(idx._poi_descriptor);

				} else {
					//idx.showPage(1);
					idx.showNotice('Too many properties to display. Narrow your criteria or zoom in.');
				}

				idx.hideSearchBox();
			};

			this.object_callback = function(result) {
				var test = window.open('http://3pv.stratusmls.com/test/idx/sold_res_details.asp?ml_num=' + result.ml_num);

			};


			this.hideSearchBox = function() {
				document.getElementById('idx-search-display').style.display = 'none';
			};



			this.paginateResults = function(/*Boolean*/paginate, /*Int*/resultsPerPage, /*Int*/currentPage) {

				var result_count = this.currentResults.data.length;
				var pages = Math.ceil(result_count / resultsPerPage);

				var page_html = [];
				var i;

				if (currentPage > pages) { currentPage = 1; }
				if (currentPage < 1) { currentPage = 1; }
				currentPage = currentPage - 1;

				page_html.push('<ul class="idx-page-list">');
				page_html.push('<li><span id="idx-page-list-label">Page:</span></li>');

				if (currentPage > 0) {
					page_html.push('<li id="idx-page-first"><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(1);">&lt;&lt;</a></li>');
					page_html.push('<li id="idx-page-prev"><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(' + (currentPage) + ');">&lt;</a></li>');
				} else {
					page_html.push('<li id="idx-page-first">&lt;&lt;</li><li id="idx-page-prev">&lt;</li>');
				}

				start = 0;
				end = pages;

				if (pages > 10) {
					start = (currentPage - 2);
					end = currentPage + 2;
					if (end > pages) {
						end = pages;
						start -= 2;
					}
					if (start < 1) {
						start = 0;

					}
					end = start + 5;
					if (end > pages) {
						end = pages;
					}
				}

				if (start != 0) {
					page_html.push('<li><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(' + (0 + 1) + ');">' + (0 + 1) + '</a></li>');

					if (start > 1) {
						page_html.push('<li>...</li>');
					}
				}

				for (i = start; i < end; ++i) {
					if (i != currentPage) {
						page_html.push('<li><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(' + (i + 1) + ');">' + (i + 1) + '</a>');
					} else {
						page_html.push('<li class="idx-page-current"><span class="idx-page-current-label">' + (i + 1) + '</span>');
					}
					page_html.push('</li>');

				}

				if (end != pages) {
					page_html.push('<li>...</li><li><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(' + (pages) + ');">' + (pages) + '</a></li>');
				}

				if (currentPage < (pages - 1)) {
					page_html.push('<li id="idx-page-next"><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(' + (currentPage + 2) + ');">&gt;</a></li>');
					page_html.push('<li id="idx-page-last"><a href="#" onclick="window[\'' + this.globalId + '\'].showPage(' + (pages) + ');">&gt;&gt;</a></li>');
				} else {
					page_html.push('<li id="idx-page-next">&gt;</li><li id="idx-page-last">&gt;&gt;</li>');
				}

				page_html.push('</ul>');

				page_html.push('<div class="idx-page-results-container"><span>Results / Page:</span><select id="idx-page-results-select" onchange="window[\'' + this.globalId + '\'].setResultsPerPage(this.value);">');
				for (i = 5; i <= 25; i += 5) {
					page_html.push('<option value="' + (i) + '"' + ((i == this.options['results.resultsPerPage']) ? ' selected' : '') + '>' + i + '</option>');
				}
				page_html.push('</select></div>');

				document.getElementById(this.paginateNode.getAttribute('id')).innerHTML = page_html.join('');
			};

			this.showPage = function(page) {
				if (!this.currentResults) { return; }

				this.paginateResults(this.options['results.paginate'], this.options['results.resultsPerPage'], page);

				var data = this.currentResults.data;

				var recs = this.options['results.resultsPerPage'];
				var max_index = (recs * page);
				var start_index = (page == 1) ? 0 : recs * (page - 1);
				var resultsList = document.getElementById('idx-results-list');
				var rows = resultsList.tBodies[0].rows;
				var i;
				for (i = 0; i < rows.length; ++i) {
					sap.addClass(rows[i], 'idx-hidden');
				}

				for (i = start_index; i < max_index && i < data.length; ++i) {

					sap.removeClass(rows[i], 'idx-hidden');
				}

			};

			this.setResultsPerPage = function(resultsPerPage) {
				resultsPerPage = (resultsPerPage) ? resultsPerPage : 10;
				this.options['results.resultsPerPage'] = resultsPerPage;
				this.showPage(1);
			};

			this.showNotice = function(html) {

				if (html) {
					this.noticeNode.innerHTML = html;
				}

				this.noticeNode.style.display = '';
			};

			this._setZIndex = function(shape, index) {
				if (shape && shape.GetPrimitive) {
					var el = document.getElementById(shape.GetPrimitive(0).iid);
					if (el && el.style) {
						el.style.zIndex = index;
					}
				}
			};

			this.hoverIcon = function(shapeId, addClass) {
				var s = this.map.GetShapeByID(shapeId);
				if (!s) { return false; }
				this._setZIndex(s, ++window['IDX_ZINDEX']); //, window['IDX_ZINDEX']);
				var e = s.GetIconElement();

				if (sap.hasClass(s, 'idx-poi')) { return; }
				if (e) {
					sap.addClass(e, 'idx-hover');
					//var div = e.firstChild;
					//while (div.
					e.parentNode.appendChild(this.shadowNode);
					this.shadowNode.style.top = e.style.top;
					this.shadowNode.style.left = e.style.left;
					this.shadowNode.style.zIndex = 900;
				}

				if (addClass !== false && s.row) {
					sap.addClass(s.row, 'idx-hover');
				}

				this.shadowNode.style.visibility = 'visible';

			};

			this.unhoverIcon = function(shapeId) {
				var s = this.map.GetShapeByID(shapeId);
				if (!s) { return false; }
				var e = s.GetIconElement();
				if (sap.hasClass(s, 'idx-poi')) { return; }
				if (e) {
					sap.removeClass(e, 'idx-hover');
				}

				if (s.row) {
					sap.removeClass(s.row, 'idx-hover');
				}

				this.shadowNode.style.visibility = 'hidden';

			};

			this.hideNotice = function() {
				this.noticeNode.style.display = 'none';
			};

			this.switchFocus = function(focus) {
				if (focus == 'search') {
					document.getElementById('idx-search-form').style.display = '';
					this.node.style.display = 'none';
				}
			};

			this.clearPOI = function() {
				this._poi_descriptor = null;
				if (this._poiLayer) {
					if (this._poiLayer != null) {
						this.map.DeleteShapeLayer(this._poiLayer);
					}
				}

				this._poiLayer = new VEShapeLayer();
				this.map.AddShapeLayer(this._poiLayer);

			};

			this.findPOI = function(poi_descriptor) {
				this.clearPOI();
				if (!poi_descriptor) return;

				try {
					this.map.Find(poi_descriptor, null, VEFindType.Business, this._poiLayer, 0, 20, false, false, false, false, this._locatePOICallback);
				} catch (e) {
				}

				this._poi_descriptor = poi_descriptor;

			};

			this._locatePOICallback = function(layer, resultsArray, places, hasMore, veErrorMessage) {
				if (resultsArray != null) {
					for (var x = 0; x < resultsArray.length; ++x) {
						var shape = new VEShape(VEShapeType.Pushpin, resultsArray[x].LatLong);
						shape.SetTitle(resultsArray[x].Name);
						shape.SetDescription(resultsArray[x].Description + "<br />" + resultsArray[x].Phone);

						sap.addClass(shape, "idx-poi");

						var imageUrl = "http://www.mlsstratus.com/Maps/Images/pointBubble.gif";
						var iconHtml = "<img src=\"" + imageUrl + "\" border=\"0\" style=\"position:relative; top:-6px; left:-9px;\" />";
						shape.SetCustomIcon(iconHtml);

						that._poiLayer.AddShape(shape);
					}
				}
			};


			this.refreshPOI = function(what) {
				this.findPOI(what);
			};

			this._getHR = function() {
				var d = document.createElement('HR');
				d.className = 'idx-clear';
				return d;
			};

			this.loadMap = function() {
				this.map = new VEMap(this.mapNode.getAttribute('id'));
				var lon = -73.028208007;
				var lat = 40.873413085;
				var zoom = 9;

				this.map.LoadMap(new VELatLong(lat, lon), zoom, 'r', false, null, false);

				//this.map.AttachEvent("onendzoom", this.contains_search);
				this.map.AttachEvent("onendzoom", function(o) { if (idx.criteria) { idx.contains_search(); } });
				this.map.AttachEvent("onendpan", function(o) { if (idx.criteria) { idx.contains_search(); } });
				this.map.AttachEvent("onmouseover", function(e) { if (!e.elementID) { return; } return idx.hoverIcon(e.elementID); return false; });
				this.map.AttachEvent("onmouseout", function(e) { if (!e.elementID) { return; } return idx.unhoverIcon(e.elementID); return false; });

				document.getElementById('MSVE_navAction_container').appendChild(this.noticeNode);
			}

			node.style.position = 'relative';

			sap.requireCss('http://idx.mlsstratus.com/idx/sold/css.asp?' + api_key);

			this.rpc_service = new sap.rpc.SDSService('http://idx.mlsstratus.com/api/service/api.ashx', api_key);
			//this.rpc_service = new sap.rpc.SDSService('/lib/external/sapience/examples/service/api.ashx', api_key);
			this.node = node;
			this.api_key = api_key;
			this.options = sap.extend({
				'results.paginate': true,
				'results.resultsPerPage': 10,
				'results.hoverIcon': '/img/glow1.png',
				//'results.disclaimer': 'A sold price may not reflect the current market value of homes.  Be sure to contact a REALTOR&reg; for an estimate of your home\'s market value.',
				'results.disclaimer': '* A sold price may not reflect the current market value of homes.',
				showMap: true,
				getDescription: function(object, map) {
					var ml = object.ml_num;
					var rStr = '<div><img class="idx-popup-image" onerror="this.src=\'http://idx.mlsstratus.com/images/PhotoNotAvailable.gif\'; this.onerror=null;" src="http://www.mlsstratus.com/mlsmultiphotos/full/1/' + ml.substr(ml.length - 3) + '/' + ml + '.jpg" />' +
						'<div>' + object.town + ', ' + object.ste + ' ' + object.zip + '</div>' +
						((object.status == 'Sold') ? '<div>Sold Price: ' + object.price + '</div>' +
						'<div>Sold Date: ' + object.td + '</div>' : '<div>Price: ' + object.price + '</div>') +
						'<div>' + object.style + ((object.br) ? ', ' + object.br + ' Beds' : '') + ((object.bth) ? ', ' + object.bth + ' Baths' : '') + '</div>' +

						'<div><a href="http://idx.mlsstratus.com/idx/sold/details.asp?ml_num=' + object.ml_num + '&key=' + api_key + '" target="_blank">More Property Detail</a></div>';
					//'<div><a href="#" onclick="window.idx1.getObject({\'id\':\'' + object.ml_num + '\'});">More Property Detail</a></div>';

					if (object.latitude && object.longitude) {
						rStr += '<div><a href="#" onclick="window[\'' + map.globalId + '\'].map.SetBirdseyeScene(new VELatLong(' + object.latitude + ', ' + object.longitude + '));">Birds eye</a></div>';
					}

					if (object.coh_st_dt) {
						rStr += '<div><b>Open House</b>: ';

						if (object.coh_st_dt == object.coh_end_dt) {
							rStr += object.coh_st_dt;
						} else {
							rStr += object.coh_st_dt + ' - ' + object.coh_end_dt;
						}

						rStr += ' <span class="idx-oh-time">' + object.coh_time + '</span><div class="idx-oh-note">' + ((object.coh_note) ? object.coh_note : '') + '</div></div>';
					}

					rStr += '</div>';

					return rStr;

				}
			}, options);

			sap.addClass(node, 'idx-container');
			this.mapNode = document.createElement('DIV');
			this.mapNode.setAttribute('id', 'idx-map');
			this.resultsNode = document.createElement('DIV');
			this.resultsNode.setAttribute('id', 'idx-results');
			this.poiNode = document.createElement('DIV');
			this.poiNode.setAttribute('id', 'idx-poi');
			this.poiNode.innerHTML = '<span class="idx-label">Find Points of Interest:</span><img src="http://www.mlsstratus.com/Maps/Images/pointBubble.gif" /> <input style="width:120px;" name="_FindPOI" id="_FindPOI" type="text" /><input type="button" onclick="window[\'idx1\'].findPOI(document.getElementById(\'_FindPOI\').value);" value="Find" /><input type="button" onclick="window[\'idx1\'].clearPOI();" value="Clear" /><small><i>Example: School or Supermarket or Pizza</i></small>';
			this.noticeNode = document.createElement('DIV');
			this.noticeNode.setAttribute('id', 'idx-notice');
			this.reportNode = document.createElement('DIV');
			this.reportNode.setAttribute('id', 'idx-report');
			this.paginateNode = document.createElement('DIV');
			this.paginateNode.setAttribute('id', 'idx-pagination');
			this.toolbarNode = document.createElement('DIV');
			this.toolbarNode.setAttribute('id', 'idx-toolbar');
			this.shadowNode = document.createElement('DIV');
			this.shadowNode.setAttribute('id', 'idx-shadow');
			this.navNode = document.createElement('DIV');
			this.navNode.setAttribute('id', 'idx-nav');
			this.navNode.innerHTML = "<a id=\"idx-back-to-search\" href=\"#\" onclick=\"window['idx1'].switchFocus('search');\">&lt; Revise Search</a>";
			node.appendChild(this.navNode);
			node.appendChild(this.poiNode);

			this.globalId = 'idx' + (++com.mlsstratus.uid);
			window['IDX_ZINDEX'] = 1001;
			window[this.globalId] = this;
			var idx = this;

			sap.addClass(this.mapNode, 'idx-map');
			sap.addClass(this.resultsNode, 'idx-results');
			sap.addClass(this.reportNode, 'idx-report');
			sap.addClass(this.paginateNode, 'idx-pagination');
			sap.addClass(this.toolbarNode, 'idx-toolbar');

			node.appendChild(this.mapNode);
			node.appendChild(this.toolbarNode);
			//if map && legend
			node.appendChild(this.resultsNode);
			this.toolbarNode.appendChild(this.paginateNode);
			/* this.createCustomToolbars(); */
			this.createLegend();
			//this.toolbarNode.appendChild(this._getHR());		
			node.appendChild(this.reportNode);
			this.createResults();

			if (typeof VEMap != 'undefined') { this.loadMap(); }



			//sap.ajax.getScript('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1', function() { idx.loadMap(); });

			//this.map.AddControl(this.noticeNode);

			document.getElementById('idx-search-display').style.display = 'none';

			this.hideNotice();

		};
			
sap.requireCss('http://idx.mlsstratus.com/api/form.css');
sap.requireCss('http://idx.mlsstratus.com/api/theme-test.css');
			
sap.provide("com.mlsstratus.SoldSearch");


function validateIDXForm() {
				var criteria = {};
				
				var addr = $j('#idx-street-address').val();var town = $j('#idx-town').val();
				var zip = $j('#idx-zip').val();
				
				if ( town == '' && zip == '' ) {
					alert('You must select a town or enter a zip code before performing a search.');
					$j('#idx-town').focus();
					return;
				}
				
				var prop_types = [];
				$j('input[name=idx-property-type]').each(function(i,o) {
					if ( o.checked ) {prop_types.push(o.value);}
				});
				
				criteria['prop.types'] = prop_types;
				
				var td = $j('input[name=date-range]').val();
				var br = $j('#idx-bedrooms').val();
				var bth = $j('#idx-bathrooms').val();
				var waterfront = $j('#idx-waterfront').get(0).checked;
				var waterview = $j('#idx-waterview').get(0).checked;
				var sp_dol_fr = $j('#idx-sold-price-from').val();
				var sp_dol_to = $j('#idx-sold-price-to').val();

				if ( br ) { criteria['br'] = '[>=]' + br;}
				if ( bth) { criteria['bth'] = '[>=]' + bth;}
				if ( waterfront ) { criteria['waterfront'] = '[=]Y';}
				if ( waterview ) { criteria['wtrfrtdesc'] = '[@]'; }
				
				criteria.sp_dol = [];
				if ( sp_dol_fr  == '50000' ) {} else {criteria.sp_dol.push('[>=]' + sp_dol_fr);}
				if ( sp_dol_to == '10000000' ) {} else {criteria.sp_dol.push('[<=]' + sp_dol_to);}
				
				var date = new Date().addMonths((td*-1));
				criteria['td'] = '[>=]' + (date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear();
				$j('#idx-div').show();
				$j('#idx-search-form').hide();
				var n = document.getElementById('idx-div');
				n.style.visibility = "visible";
				if (town) {addr += ', ' + town;}
				
				
				if ( !zip ) {
					if ( !town ) {
						addr += ', Long Island, NY';
					} else {
						addr += ', NY';
					}
				} else {
					addr += ', ' + zip;
				}
				
				sold_search_internal.find(addr, function() { sold_search_internal.contains_search(criteria); });
				
			}

var sold_search_internal;
com.mlsstratus.SoldSearch = function(node, api_key, options) {			
			
			node.innerHTML = '<div id="idx-search-form"><div class="idx-header">	<h1>Search Recent Home Sales</h1><h2>See what homes sold for in your area.</h2><a href="#" class="idx-step-notice" style="display:none;"><em>Step 1</em></a></div><ol class="idx-fieldset"><li class="idx-default-item idx-important"><label>Show Properties Sold in the Last:</label><div class="date-range-container"><label for="date-range-start"><input type="radio" name="date-range" value="6" checked="checked" />6 Months</label><label for="date-range-end"><input type="radio" name="date-range" value="12" />1 Year</label></div></li><li class="idx-default-item idx-optional-item"><label for="idx-street-address">Street Address <span class="idx-sub-label">(Optional)</span></label><input type="text" id="idx-street-address" /><span id="idx-street-address-help" class="idx-help">e.g. 100 Main St</span></li><li class="idx-default-item idx-li-town"><label for="idx-town">Town</label><select id="idx-town"><option value=""></option><option>Addesleigh Park</option><option>Albertson</option><option>Amaganset</option> <option>Amity Harbor</option> <option>Amityville</option> <option>Aquebogue</option> <option>Arverne</option> <option>Asharoken</option> <option>Astoria</option> <option>Atlantic Beach</option> <option>Atlantique</option> <option>Babylon</option> <option>Baisley Park</option> <option>Baiting Hollow</option> <option>Baldwin Harbor</option> <option>Baldwin</option> <option>Bar Harbor</option> <option>Barnum Isle</option> <option>Baxter Estates</option> <option>Bay Park</option> <option>Bay Shore</option> <option>Bayport</option> <option>Bayside</option> <option>Bayswater</option> <option>Bayview</option> <option>Bayville</option> <option>Beechhurst</option> <option>Bell Harbor</option> <option>Bellaire</option> <option>Belle Terre</option> <option>Bellerose Terr</option> <option>Bellerose Vill</option> <option>Bellerose</option> <option>Bellmore</option> <option>Bellport</option> <option>Bethpage</option> <option>Biltmore Shore</option> <option>Biltmore Shores</option> <option>Blue Point</option> <option>Bohemia</option> <option>Breezy Point</option> <option>Brentwood</option> <option>Briarwood</option> <option>Bridgehampton</option> <option>Brightwaters</option> <option>Broad Channel</option> <option>Brookhaven</option> <option>Brooklyn</option> <option>Brookville</option> <option>Calverton</option> <option>Cambria Heights</option> <option>Carle Place</option> <option>Cedarhurst</option> <option>Center Moriches</option> <option>Centereach</option> <option>Centerport</option> <option>Centerville</option> <option>Central Islip</option> <option>Centre Island</option> <option>Cherry Grove</option> <option>City Line</option> <option>Cold Spring Hill</option> <option>Cold Spring Hrbr</option> <option>College Point</option> <option>Commack</option> <option>Copiague</option> <option>Coram</option> <option>Corona</option> <option>Cove Neck</option> <option>Cutchogue</option> <option>Cypress Hills</option> <option>Davis Park</option> <option>Deer Park</option> <option>Deerfield</option> <option>Dix Hills</option> <option>Douglaston</option> <option>E Atlantic Beach</option> <option>E. Elmhurst</option> <option>E. Farmingdale</option> <option>E. Massapequa</option> <option>E. New York</option> <option>E. Northport</option> <option>E. Patchogue</option> <option>E. Quogue</option> <option>E. Rockaway</option> <option>E. Setauket</option> <option>E. Williston</option> <option>East Hampton</option> <option>East Hills</option> <option>East Islip</option> <option>East Marion</option> <option>East Meadow</option> <option>East Moriches</option> <option>East Norwich</option> <option>Eastport</option> <option>Eatons Neck</option> <option>Edgemere</option> <option>Edgewood</option> <option>Elmhurst</option> <option>Elmont</option> <option>Elwood</option> <option>Fair Harbor</option> <option>Far Rockaway</option> <option>Farmingdale</option> <option>Farmingville</option> <option>Fire Island Pine</option> <option>Fishers Island</option> <option>Flanders</option> <option>Floral Park Ctr</option> <option>Floral Park</option> <option>Flower Hill</option> <option>Flushing</option> <option>Forest Hills</option> <option>Fort Salonga</option> <option>Fort Tilden</option> <option>Franklin Square</option> <option>Freeport</option> <option>Fresh Meadows</option> <option>Garden City Park</option> <option>Garden City S.</option> <option>Garden City Vill</option> <option>Garden City</option> <option>Gibson</option> <option>Gilgo Beach</option> <option>Glen Cove</option> <option>Glen Head</option> <option>Glen Oaks</option> <option>Glendale</option> <option>Glenwood Landing</option> <option>Gordon Heights</option> <option>Great Neck Est</option> <option>Great Neck Plaza</option> <option>Great Neck</option> <option>Great River</option> <option>Greenlawn</option> <option>Greenport</option> <option>Greenvale</option> <option>Halesite</option> <option>Half Hollow Hill</option> <option>Hamilton Beach</option> <option>Hampton Bays</option> <option>Harbor Green Est</option> <option>Harbor Green</option> <option>Harbor Isle</option> <option>Hauppauge</option> <option>Head Of Harbor</option> <option>Hempstead</option> <option>Herricks</option> <option>Hewlett Bay Park</option> <option>Hewlett Harbor</option> <option>Hewlett Neck</option> <option>Hewlett</option> <option>Hicksville</option> <option>Highland Park</option> <option>Hillcrest</option> <option>Holbrook</option> <option>Hollis Hills</option> <option>Hollis</option> <option>Holliswood</option> <option>Holtsville</option> <option>Howard Beach</option> <option>Huntington Bay</option> <option>Huntington Manor</option> <option>Huntington Sta</option> <option>Huntington</option> <option>Inwood</option> <option>Island Park</option> <option>Islandia</option> <option>Islip Terrace</option> <option>Islip</option> <option>Jackson Heights</option> <option>Jamaica Estates</option> <option>Jamaica Hills</option> <option>Jamaica N.</option> <option>Jamaica S.</option> <option>Jamaica</option> <option>Jamesport</option> <option>Jericho</option> <option>Kensington</option> <option>Kew Garden Hills</option> <option>Kew Gardens</option> <option>Kings Park</option> <option>Kings Point</option> <option>Kismet</option> <option>Lake Grove</option> <option>Lake Panamoka</option> <option>Lake Ronkonkoma</option> <option>Lake Success</option> <option>Lakeview</option> <option>Lattingtown</option> <option>Laurel Hill</option> <option>Laurel Hollow</option> <option>Laurel</option> <option>Laurelton</option> <option>Lawrence</option> <option>Levittown</option> <option>Lido Beach</option> <option>Lindenhurst</option> <option>Lindenwood</option> <option>Little Neck</option> <option>Lloyd Harbor</option> <option>Lloyd Neck</option> <option>Locust Grove</option> <option>Locust Valley</option> <option>Long Beach</option> <option>Long Island City</option> <option>Lynbrook</option> <option>Malba</option> <option>Malverne</option> <option>Manhasset Hills</option> <option>Manhasset</option> <option>Manorhaven</option> <option>Manorville</option> <option>Maspeth</option> <option>Massapequa Park</option> <option>Massapequa Shores</option> <option>Massapequa</option> <option>Mastic Beach</option> <option>Mastic</option> <option>Matinecock</option> <option>Mattituck</option> <option>Medford</option> <option>Melville</option> <option>Merrick</option> <option>Middle Island</option> <option>Middle Village</option> <option>Middleville</option> <option>Mill Neck</option> <option>Miller Place</option> <option>Mineola</option> <option>Montauk</option> <option>Moriches</option> <option>Mt. Sinai</option> <option>Munsey Park</option> <option>Muttontown</option> <option>N. Amityville</option> <option>N. Babylon</option> <option>N. Baldwin</option> <option>N. Bellmore</option> <option>N. Great River</option> <option>N. Lindenhurst</option> <option>N. Lynbrook</option> <option>N. Massapequa</option> <option>N. Merrick</option> <option>N. New Hyde Park</option> <option>N. Patchogue</option> <option>N. Valley Stream</option> <option>N. Wantagh</option> <option>N. Woodmere</option> <option>Nassau Point</option> <option>Nassau Shores</option> <option>Neponsit</option> <option>Nesconset</option> <option>New Cassel</option> <option>New Hyde Park</option> <option>New Suffolk</option> <option>Nissequogue</option> <option>North Haven</option> <option>North Hills</option> <option>Northport</option> <option>Northville</option> <option>Noyack</option> <option>Oak Beach</option> <option>Oak Island</option> <option>Oakdale</option> <option>Oakland Gardens</option> <option>Ocean Bay Park</option> <option>Ocean Beach</option> <option>Oceanside</option> <option>Old Bethpage</option> <option>Old Brookville</option> <option>Old Field</option> <option>Old Harbor Green</option> <option>Old Westbury</option> <option>Orient Point</option> <option>Orient</option> <option>Out Of Area Town</option> <option>Oyster Bay Cove</option> <option>Oyster Bay</option> <option>Ozone Park</option> <option>Park Slope</option> <option>Patchogue</option> <option>Peconic</option> <option>Pinelawn</option> <option>Plainedge</option> <option>Plainview</option> <option>Plandome Heights</option> <option>Plandome Manor</option> <option>Plandome</option> <option>Point Lookout</option> <option>Point O\' Woods</option> <option>Poquott</option> <option>Port Jefferson</option> <option>Port Washington</option> <option>Pt.Jefferson Sta</option> <option>Pt.Jefferson Vil</option> <option>Pt.Washington N</option> <option>Queens Village N</option> <option>Queens Village S</option> <option>Queens Village</option> <option>Quogue</option> <option>Rego Park</option> <option>Remsenburg</option> <option>Richmond Hill N.</option> <option>Richmond Hill S.</option> <option>Richmond Hill</option> <option>Ridge</option> <option>Ridgewood</option> <option>Riverhead</option> <option>Roanoke</option> <option>Rochdale Village</option> <option>Rochdale</option> <option>Rockaway Beach</option> <option>Rockaway Park</option> <option>Rockaway Point</option> <option>Rockville Centre</option> <option>Rocky Point</option> <option>Ronkonkoma</option> <option>Roosevelt</option> <option>Rose Grove</option> <option>Rosedale</option> <option>Roslyn Estates</option> <option>Roslyn Harbor</option> <option>Roslyn Heights</option> <option>Roslyn</option> <option>Russell Gardens</option> <option>S. Bellmore</option> <option>S. Farmingdale</option> <option>S. Floral Park</option> <option>S. Great River</option> <option>S. Hauppauge</option> <option>S. Hempstead</option> <option>S. Huntington</option> <option>S. Jamesport</option> <option>S. Merrick</option> <option>S. Ozone Park</option> <option>S. Setauket</option> <option>Saddle Rock</option> <option>Sag Harbor</option> <option>Sagaponack</option> <option>Saltaire</option> <option>San Remo</option> <option>Sands Point</option> <option>Sayville</option> <option>Sea Cliff</option> <option>Seaford</option> <option>Searingtown</option> <option>Seaside</option> <option>Seaview</option> <option>Selden</option> <option>Setauket</option> <option>Shelter Island H</option> <option>Shelter Island</option> <option>Shinnecock</option> <option>Shirley</option> <option>Shoreham</option> <option>Smithtown</option> <option>Sound Beach</option> <option>South Haven</option> <option>Southampton</option> <option>Southold</option> <option>Southport</option> <option>Speonk</option> <option>Springfield Gdns</option> <option>Springs</option> <option>St. Albans</option> <option>St. James</option> <option>Stewart Manor</option> <option>Stony Brook</option> <option>Strathmore</option> <option>Sunnyside</option> <option>Syosset</option> <option>Tanglewood Hills</option> <option>Terryville</option> <option>Thomaston</option> <option>Tudor Village</option> <option>Uniondale</option> <option>University Gdns</option> <option>Upper Brookville</option> <option>Valley Stream</option> <option>Vill Of Branch</option> <option>W. Amityville</option> <option>W. Babylon</option> <option>W. Bay Shore</option> <option>W. Gilgo Beach</option> <option>W. Hempstead</option> <option>W. Sayville</option> <option>W. Yaphank</option> <option>Wading River</option> <option>Wainscott</option> <option>Wakefield</option> <option>Wantagh</option> <option>Water Island</option> <option>Water Mill</option> <option>West Hills</option> <option>West Islip</option> <option>Westbury</option> <option>Westhampton Bch</option> <option>Westhampton</option> <option>Wheatley Heights</option> <option>Whitestone</option> <option>Williston Park</option> <option>Woodbury</option> <option>Woodhaven</option> <option>Woodmere</option> <option>Woodsburgh</option> <option>Woodside</option> <option>Wyandanch</option> <option>Yaphank</option></select></li><li class="idx-li-or">OR</li><li class="idx-default-item idx-li-zip"><label for="idx-zip">Zip Code</label><input type="text" id="idx-zip"></li><li class="idx-default-item idx-li-prop-type"><label for="idx-property-types">Property Types</label><ul id="idx-property-types" class="idx-checkbox-list idx-horizontal-list"><li><input type="checkbox" checked="checked" name="idx-property-type" value="SF" id="idx-property-single" /><label for="idx-property-single">Single Family</label></li><li><input type="checkbox" checked="checked" name="idx-property-type" value="MF" id="idx-property-multi" /><label for="idx-property-multi">Multi Family</label></li><li><input type="checkbox" checked="checked" name="idx-property-type" value="Con" id="idx-property-condo" /><label for="idx-property-condo">Condo</label></li><li><input type="checkbox" checked="checked" name="idx-property-type" value="Coop" id="idx-property-coop" /><label for="idx-property-coop">Co-Op</label></li></ul></li><li class="idx-additional-item"><ol class="idx-additional-items" style="display:none;"><li><label for="idx-sold-price-from">Sold Price From</label><select id="idx-sold-price-from"> <option value="50000" selected="selected">$50,000 or less</option> <option value="75000">$75,000</option> <option value="100000">$100,000</option> <option value="125000">$125,000</option> <option value="150000">$150,000</option> <option value="175000">$175,000</option> <option value="200000">$200,000</option> <option value="225000">$225,000</option> <option value="250000">$250,000</option> <option value="275000">$275,000</option> <option value="300000">$300,000</option> <option value="350000">$350,000</option> <option value="400000">$400,000</option> <option value="450000">$450,000</option> <option value="500000">$500,000</option> <option value="550000">$550,000</option> <option value="600000">$600,000</option> <option value="650000">$650,000</option> <option value="700000">$700,000</option> <option value="750000">$750,000</option> <option value="800000">$800,000</option> <option value="850000">$850,000</option> <option value="900000">$900,000</option> <option value="950000">$950,000</option> <option value="1000000">$1,000,000</option> <option value="1500000">$1,500,000</option> <option value="2000000">$2,000,000</option> <option value="2500000">$2,500,000</option> <option value="3000000">$3,000,000</option> <option value="3500000">$3,500,000</option> <option value="4000000">$4,000,000</option> <option value="4500000">$4,500,000</option> <option value="5000000">$5,000,000</option> <option value="6000000">$6,000,000</option> <option value="7000000">$7,000,000</option> <option value="8000000">$8,000,000</option> <option value="9000000">$9,000,000</option> <option value="10000000">$10,000,000 or more</option> </select> 						<label for="idx-sold-price-to">Sold Price To</label><select id="idx-sold-price-to"> <option value="50000">$50,000 or less</option> <option value="75000">$75,000</option> <option value="100000">$100,000</option> <option value="125000">$125,000</option> <option value="150000">$150,000</option> <option value="175000">$175,000</option> <option value="200000">$200,000</option> <option value="225000">$225,000</option> <option value="250000">$250,000</option> <option value="275000">$275,000</option> <option value="300000">$300,000</option> <option value="350000">$350,000</option> <option value="400000">$400,000</option> <option value="450000">$450,000</option> <option value="500000">$500,000</option> <option value="550000">$550,000</option> <option value="600000">$600,000</option> <option value="650000">$650,000</option> <option value="700000">$700,000</option> <option value="750000">$750,000</option> <option value="800000">$800,000</option> <option value="850000">$850,000</option> <option value="900000">$900,000</option> <option value="950000">$950,000</option> <option value="1000000">$1,000,000</option> <option value="1500000">$1,500,000</option> <option value="2000000">$2,000,000</option> <option value="2500000">$2,500,000</option> <option value="3000000">$3,000,000</option> <option value="3500000">$3,500,000</option> <option value="4000000">$4,000,000</option> <option value="4500000">$4,500,000</option> <option value="5000000">$5,000,000</option> <option value="6000000">$6,000,000</option> <option value="7000000">$7,000,000</option> <option value="8000000">$8,000,000</option> <option value="9000000">$9,000,000</option> <option value="10000000" selected="selected">$10,000,000 or more</option> </select></li><li><label for="idx-bedrooms">Bedrooms</label><select id="idx-bedrooms"><option selected="selected" value="">Any Number (default)</option><option value="1">1 or more</option> <option value="2">2 or more</option> <option value="3">3 or more</option> <option value="4">4 or more</option> <option value="5">5 or more</option> <option value="6">6 or more</option> <option value="7">7 or more</option> <option value="8">8 or more</option> <option value="9">9 or more</option> <option value="10">10 or more</option></select></li><li><label for="idx-bathrooms">Bathrooms</label><select id="idx-bathrooms"><option selected="selected" value="">Any Number (default)</option> <option value="1">1 or more</option> <option value="1.5">1.5 or more</option> <option value="2">2 or more</option> <option value="2.5">2.5 or more</option> <option value="3">3 or more</option> <option value="4">4 or more</option> <option value="5">5 or more</option></select></li><li><label>Additional</label><ul id="idx-extras" class="idx-checkbox-list idx-horizontal-list"><li><label for="idx-waterfront"><input type="checkbox" id="idx-waterfront" />Waterfront</label></li><li><label for="idx-waterview"><input type="checkbox" id="idx-waterview" />Waterview</label></li></ul></li></ol><label class="idx-additional-items-show"><a href="#">More Options >></a></label><label class="idx-additional-items-hide" style="display:none;"><a href="#"><< Fewer Options</a></label></li></ol><ul class="idx-form-actions"><li><button class="idx-default-action idx-search-action" onclick="validateIDXForm();">Search</button></li></ul></div><div id="idx-search-display-container"><div id="idx-search-display" style="display:none;">Searching ...</div></div><div id="idx-div"></div>'
			

				$j('label.idx-additional-items-show a').click(function(e){
					var o = $j(e.target);
					o.parent().siblings('ol.idx-additional-items').show();
					o.parent().siblings('.idx-additional-items-hide').show();
					o.parent().hide();
				});
				
				$j('label.idx-additional-items-hide a').click(function(e){
					var o = $j(e.target);
					
					o.parent().siblings('ol.idx-additional-items').hide();
					o.parent().siblings('.idx-additional-items-show').show();
					o.parent().hide();
				});
			
			sold_search_internal = new com.mlsstratus.Search(document.getElementById('idx-div'), api_key);
				
	
}