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

});
})();
﻿/*
* jQuery blockUI plugin
* Version 2.14 (18-JAN-2009)
* @requires jQuery v1.2.3 or later
*
* Examples at: http://malsup.com/jquery/block/
* Copyright (c) 2007-2008 M. Alsup
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* 
* Thanks to Amir-Hossein Sobhi for some excellent contributions!
*/

; (function($) {

    if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
        alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
        return;
    }

    // global $ methods for blocking/unblocking the entire page
    $.blockUI = function(opts) { install(window, opts); };
    $.unblockUI = function(opts) { remove(window, opts); };

    // convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
    $.growlUI = function(title, message, timeout) {
        var $m = $('<div class="growlUI"></div>');
        if (title) $m.append('<h1>' + title + '</h1>');
        if (message) $m.append('<h2>' + message + '</h2>');
        if (timeout == undefined) timeout = 3000;
        $.blockUI({
            message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
            timeout: timeout, showOverlay: false,
            css: $.blockUI.defaults.growlCSS
        });
    };

    // plugin method for blocking element content
    $.fn.block = function(opts) {
        return this.each(function() {
            if ($.css(this, 'position') == 'static')
                this.style.position = 'relative';
            if ($.browser.msie)
                this.style.zoom = 1; // force 'hasLayout'
            install(this, opts);
        });
    };

    // plugin method for unblocking element content
    $.fn.unblock = function(opts) {
        return this.each(function() {
            remove(this, opts);
        });
    };

    $.blockUI.version = 2.14; // 2nd generation blocking at no extra cost!

    // override these in your code to change the default behavior and style
    $.blockUI.defaults = {
        // message displayed when blocking (use null for no message)
        message: '<h1>Please wait...</h1>',

        // styles for the message when blocking; if you wish to disable
        // these and use an external stylesheet then do this in your code:
        // $.blockUI.defaults.css = {};
        css: {
            padding: 0,
            margin: 0,
            width: '30%',
            top: '40%',
            left: '35%',
            textAlign: 'center',
            color: '#000',
            border: '3px solid #aaa',
            backgroundColor: '#fff',
            cursor: 'wait'
        },

        // styles for the overlay
        overlayCSS: {
            backgroundColor: '#000',
            opacity: '0.6'
        },

        // styles applied when using $.growlUI
        growlCSS: {
            width: '350px',
            top: '10px',
            left: '',
            right: '10px',
            border: 'none',
            padding: '5px',
            opacity: '0.6',
            cursor: null,
            color: '#fff',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px'
        },

        // z-index for the blocking overlay
        baseZ: 1000,

        // set these to true to have the message automatically centered
        centerX: true, // <-- only effects element blocking (page block controlled via css above)
        centerY: true,

        // allow body element to be stetched in ie6; this makes blocking look better
        // on "short" pages.  disable if you wish to prevent changes to the body height
        allowBodyStretch: true,

        // be default blockUI will supress tab navigation from leaving blocking content;
        constrainTabKey: true,

        // fadeIn time in millis; set to 0 to disable fadeIn on block
        fadeIn: 200,

        // fadeOut time in millis; set to 0 to disable fadeOut on unblock
        fadeOut: 400,

        // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
        timeout: 0,

        // disable if you don't want to show the overlay
        showOverlay: true,

        // if true, focus will be placed in the first available input field when
        // page blocking
        focusInput: true,

        // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
        applyPlatformOpacityRules: true,

        // callback method invoked when unblocking has completed; the callback is
        // passed the element that has been unblocked (which is the window object for page
        // blocks) and the options that were passed to the unblock call:
        //     onUnblock(element, options)
        onUnblock: null,

        // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
        quirksmodeOffsetHack: 4
    };

    // private data and functions follow...

    var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
    var pageBlock = null;
    var pageBlockEls = [];

    function install(el, opts) {
        var full = (el == window);
        var msg = opts && opts.message !== undefined ? opts.message : undefined;
        opts = $.extend({}, $.blockUI.defaults, opts || {});
        opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
        var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
        msg = msg === undefined ? opts.message : msg;

        // remove the current block (if there is one)
        if (full && pageBlock)
            remove(window, { fadeOut: 0 });

        // if an existing element is being used as the blocking content then we capture
        // its current place in the DOM (and current display style) so we can restore
        // it when we unblock
        if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
            var node = msg.jquery ? msg[0] : msg;
            var data = {};
            $(el).data('blockUI.history', data);
            data.el = node;
            data.parent = node.parentNode;
            data.display = node.style.display;
            data.position = node.style.position;
            if (data.parent)
                data.parent.removeChild(node);
        }

        var z = opts.baseZ;

        // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
        // layer1 is the iframe layer which is used to supress bleed through of underlying content
        // layer2 is the overlay layer which has opacity and a wait cursor
        // layer3 is the message content that is displayed while blocking

        var lyr1 = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:' + z++ + ';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>')
                                : $('<div class="blockUI" style="display:none"></div>');
        var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:' + z++ + ';display:none;cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
        var lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:' + z + ';display:none;position:fixed"></div>')
                    : $('<div class="blockUI blockMsg blockElement" style="z-index:' + z + ';display:none;position:absolute"></div>');

        // if we have a message, style it
        if (msg)
            lyr3.css(css);

        // style the overlay
        if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform)))
            lyr2.css(opts.overlayCSS);
        lyr2.css('position', full ? 'fixed' : 'absolute');

        // make iframe layer transparent in IE
        if ($.browser.msie)
            lyr1.css('opacity', '0.0');

        $([lyr1[0], lyr2[0], lyr3[0]]).appendTo(full ? 'body' : el);

        // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
        var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
        if (ie6 || expr) {
            // give body 100% height
            if (full && opts.allowBodyStretch && $.boxModel)
                $('html,body').css('height', '100%');

            // fix ie6 issue when blocked element has a border width
            if ((ie6 || !$.boxModel) && !full) {
                var t = sz(el, 'borderTopWidth'), l = sz(el, 'borderLeftWidth');
                var fixT = t ? '(0 - ' + t + ')' : 0;
                var fixL = l ? '(0 - ' + l + ')' : 0;
            }

            // simulate fixed position
            $.each([lyr1, lyr2, lyr3], function(i, o) {
                var s = o[0].style;
                s.position = 'absolute';
                if (i < 2) {
                    full ? s.setExpression('height', 'Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:' + opts.quirksmodeOffsetHack + ') + "px"')
                     : s.setExpression('height', 'this.parentNode.offsetHeight + "px"');
                    full ? s.setExpression('width', 'jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                     : s.setExpression('width', 'this.parentNode.offsetWidth + "px"');
                    if (fixL) s.setExpression('left', fixL);
                    if (fixT) s.setExpression('top', fixT);
                }
                else if (opts.centerY) {
                    if (full) s.setExpression('top', '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                    s.marginTop = 0;
                }
                else if (!opts.centerY && full) {
                    var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0;
                    var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + ' + top + ') + "px"';
                    s.setExpression('top', expression);
                }
            });
        }

        // show the message
        lyr3.append(msg); //.show();
        if (msg && (msg.jquery || msg.nodeType))
            $(msg).show();

        if (opts.fadeIn) {
            if ($.browser.msie && opts.showOverlay)
                lyr1.fadeIn(opts.fadeIn);
            if (opts.showOverlay)
                lyr2.fadeIn(opts.fadeIn);
            lyr3.fadeIn(opts.fadeIn);
        }
        else {
            if ($.browser.msie && opts.showOverlay)
                lyr1.show();
            if (opts.showOverlay)
                lyr2.show();
            lyr3.show();
        }

        // bind key and mouse events
        bind(1, el, opts);

        if (full) {
            pageBlock = lyr3[0];
            pageBlockEls = $(':input:enabled:visible', pageBlock);
            if (opts.focusInput)
                setTimeout(focus, 20);
        }
        else
            center(lyr3[0], opts.centerX, opts.centerY);

        if (opts.timeout) {
            // auto-unblock
            setTimeout(function() {
                full ? $.unblockUI(opts) : $(el).unblock(opts);
            }, opts.timeout);
        }
    };

    // remove the block
    function remove(el, opts) {
        var full = el == window;
        var data = $(el).data('blockUI.history');
        opts = $.extend({}, $.blockUI.defaults, opts || {});
        bind(0, el, opts); // unbind events
        var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);

        if (full)
            pageBlock = pageBlockEls = null;

        if (opts.fadeOut) {
            els.fadeOut(opts.fadeOut);
            setTimeout(function() { reset(els, data, opts, el); }, opts.fadeOut);
        }
        else
            reset(els, data, opts, el);
    };

    // move blocking element back into the DOM where it started
    function reset(els, data, opts, el) {
        els.each(function(i, o) {
            // remove via DOM calls so we don't lose event handlers
            if (this.parentNode)
                this.parentNode.removeChild(this);
        });

        if (data && data.el) {
            data.el.style.display = data.display;
            data.el.style.position = data.position;
            if (data.parent)
                data.parent.appendChild(data.el);
            $(data.el).removeData('blockUI.history');
        }

        if (typeof opts.onUnblock == 'function')
            opts.onUnblock(el, opts);
    };

    // bind/unbind the handler
    function bind(b, el, opts) {
        var full = el == window, $el = $(el);

        // don't bother unbinding if there is nothing to unbind
        if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
            return;
        if (!full)
            $el.data('blockUI.isBlocked', b);

        if (b && !opts.showOverlay) // don't prevent events when overlay not in use
            return;

        // bind anchors and inputs for mouse and key events
        var events = 'mousedown mouseup keydown keypress';
        b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

        // former impl...
        //    var $e = $('a,:input');
        //    b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
    };

    // event handler to suppress keyboard/mouse events when blocking
    function handler(e) {
        // allow tab navigation (conditionally)
        if (e.keyCode && e.keyCode == 9) {
            if (pageBlock && e.data.constrainTabKey) {
                var els = pageBlockEls;
                var fwd = !e.shiftKey && e.target == els[els.length - 1];
                var back = e.shiftKey && e.target == els[0];
                if (fwd || back) {
                    setTimeout(function() { focus(back) }, 10);
                    return false;
                }
            }
        }
        // allow events within the message content
        if ($(e.target).parents('div.blockMsg').length > 0)
            return true;

        // allow events for content that is not being blocked
        return $(e.target).parents().children().filter('div.blockUI').length == 0;
    };

    function focus(back) {
        if (!pageBlockEls)
            return;
        var e = pageBlockEls[back === true ? pageBlockEls.length - 1 : 0];
        if (e)
            e.focus();
    };

    function center(el, x, y) {
        var p = el.parentNode, s = el.style;
        var l = ((p.offsetWidth - el.offsetWidth) / 2) - sz(p, 'borderLeftWidth');
        var t = ((p.offsetHeight - el.offsetHeight) / 2) - sz(p, 'borderTopWidth');
        if (x) s.left = l > 0 ? (l + 'px') : '0';
        if (y) s.top = t > 0 ? (t + 'px') : '0';
    };

    function sz(el, p) {
        return parseInt($.css(el, p)) || 0;
    };

})(jQuery);/*
* Facebox (for jQuery)
* version: 1.2 (05/05/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://famspam.com/facebox/
*
* Licensed under the MIT:
*   http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
*
* Usage:
*  
*  jQuery(document).ready(function() {
*    jQuery('a[rel*=facebox]').facebox() 
*  })
*
*  <a href="#terms" rel="facebox">Terms</a>
*    Loads the #terms div in the box
*
*  <a href="terms.html" rel="facebox">Terms</a>
*    Loads the terms.html page in the box
*
*  <a href="terms.png" rel="facebox">Terms</a>
*    Loads the terms.png image in the box
*
*
*  You can also use it programmatically:
* 
*    jQuery.facebox('some html')
*
*  The above will open a facebox with "some html" as the content.
*    
*    jQuery.facebox(function($) { 
*      $.get('blah.html', function(data) { $.facebox(data) })
*    })
*
*  The above will show a loading screen before the passed function is called,
*  allowing for a better ajaxy experience.
*
*  The facebox function can also display an ajax page or image:
*  
*    jQuery.facebox({ ajax: 'remote.html' })
*    jQuery.facebox({ image: 'dude.jpg' })
*
*  Want to close the facebox?  Trigger the 'close.facebox' document event:
*
*    jQuery(document).trigger('close.facebox')
*
*  Facebox also has a bunch of other hooks:
*
*    loading.facebox
*    beforeReveal.facebox
*    reveal.facebox (aliased as 'afterReveal.facebox')
*    init.facebox
*
*  Simply bind a function to any of these hooks:
*
*   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
*
*/
(function($) {
	$.facebox = function(data, klass) {
		$.facebox.loading()
		if (data.ajax) fillFaceboxFromAjax(data.ajax)
		else if (data.image) fillFaceboxFromImage(data.image)
		else if (data.div) fillFaceboxFromHref(data.div)
		else if ($.isFunction(data)) data.call($)
		else $.facebox.reveal(data, klass)
	}

	/*
	* Public, $.facebox methods
	*/

	$.extend($.facebox, {
		settings: {
			opacity: 0,
			overlay: true,
			loading_image: imgPrefix + '/scripts/facebox/loading.gif',
			imageTypes: ['png', 'jpg', 'jpeg', 'gif'],
			faceboxHtml: '\
    <div id="facebox" style="display:none; z-index: 300;"> \
    <div class="popup"> \
      <table> \
        <tbody> \
          <tr> \
            <td class="pop_topleft"/><td class="pop_border pop_top"/><td class="pop_topright"/> \
          </tr> \
          <tr> \
            <td class="pop_border pop_side"/> \
            <td class="pop_content"> \
              <div class="content"> \
              </div> \
            </td> \
            <td class="pop_border pop_side"/> \
          </tr> \
          <tr> \
            <td class="pop_bottomleft"/><td class="pop_border pop_bottom"/><td class="pop_bottomright"/> \
          </tr> \
        </tbody> \
      </table> \
    </div> \
  </div>'
		},

		loading: function() {
			init()
			if ($('#facebox .loading').length == 1) return true
			showOverlay()

			$('#facebox .content').empty()
			$('#facebox .body').children().hide().end()
				.append('<div class="loading"><img src="' + $.facebox.settings.loadingImage + '"/></div>')

			//debugger;
			var pageScroll = getPageScroll();
			$('#facebox').css({
				top: pageScroll[1] + (getPageHeight() / 10),
				left: pageScroll[0]
			}).show()

			$(document).bind('keydown.facebox', function(e) {
				if (e.keyCode == 27) $.facebox.close()
				return true
			})
			$(document).trigger('loading.facebox')
		},

		reveal: function(data, klass) {
			$(document).trigger('beforeReveal.facebox')
			if (klass) $('#facebox .content').addClass(klass)
			$('#facebox .content').append(data)
			$('#facebox .loading').remove()
			$('#facebox .body').children().fadeIn('normal')
			//debugger;
			//$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
			$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
		},

		close: function() {
			$(document).trigger('close.facebox')
			return false
		}
	})

	/*
	* Public, $.fn methods
	*/

	$.fn.facebox = function(settings) {
		init(settings)

		function clickHandler() {
			$.facebox.loading(true)

			// support for rel="facebox.inline_popup" syntax, to add a class
			// also supports deprecated "facebox[.inline_popup]" syntax
			var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
			if (klass) klass = klass[1]

			fillFaceboxFromHref(this.href, klass)
			return false
		}

		return this.click(clickHandler)
	}

	/*
	* Private methods
	*/

	// called one time to setup facebox on this page
	function init(settings) {
		if ($.facebox.settings.inited) return true
		else $.facebox.settings.inited = true

		$(document).trigger('init.facebox')
		makeCompatible()

		var imageTypes = $.facebox.settings.imageTypes.join('|')
		$.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

		if (settings) $.extend($.facebox.settings, settings)
		$('body').append($.facebox.settings.faceboxHtml)

		var preload = [new Image(), new Image()]
		//preload[0].src = $.facebox.settings.closeImage
		preload[0].src = $.facebox.settings.loadingImage

		$('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
			preload.push(new Image())
			preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
		})

		$('#facebox .close').click($.facebox.close)
		//$('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
	}

	// getPageScroll() by quirksmode.com
	function getPageScroll() {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}
		return new Array(xScroll, yScroll)
	}

	// Adapted from getPageSize() by quirksmode.com
	function getPageHeight() {
		var windowHeight
		if (self.innerHeight) {	// all except Explorer
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowHeight = document.body.clientHeight;
		}
		return windowHeight
	}

	// Backwards compatibility
	function makeCompatible() {
		var $s = $.facebox.settings

		$s.loadingImage = $s.loading_image || $s.loadingImage
		$s.closeImage = $s.close_image || $s.closeImage
		$s.imageTypes = $s.image_types || $s.imageTypes
		$s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
	}

	// Figures out what you want to display and displays it
	// formats are:
	//     div: #id
	//   image: blah.extension
	//    ajax: anything else
	function fillFaceboxFromHref(href, klass) {
		// div
		if (href.match(/#/)) {
			var url = window.location.href.split('#')[0]
			var target = href.replace(url, '')
			$.facebox.reveal($(target).clone().show(), klass)

			// image
		} else if (href.match($.facebox.settings.imageTypesRegexp)) {
			fillFaceboxFromImage(href, klass)
			// ajax
		} else {
			fillFaceboxFromAjax(href, klass)
		}
	}

	function fillFaceboxFromImage(href, klass) {
		var image = new Image()
		image.onload = function() {
			$.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
		}
		image.src = href
	}

	function fillFaceboxFromAjax(href, klass) {
		$.get(href, function(data) { $.facebox.reveal(data, klass) })
	}

	function skipOverlay() {
		return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
	}

	function showOverlay() {
		if (skipOverlay()) return

		if ($('facebox_overlay').length == 0)
			$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

		$('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
		return false
	}

	function hideOverlay() {
		if (skipOverlay()) return

		$('#facebox_overlay').fadeOut(200, function() {
			$("#facebox_overlay").removeClass("facebox_overlayBG")
			$("#facebox_overlay").addClass("facebox_hide")
			$("#facebox_overlay").remove()
		})

		return false
	}

	/*
	* Bindings
	*/

	$(document).bind('close.facebox', function() {
		$(document).unbind('keydown.facebox')
		$('#facebox').fadeOut(function() {
			$('#facebox .content').removeClass().addClass('content')
			hideOverlay()
			$('#facebox .loading').remove()
		})
	})

})(jQuery);
﻿var Forums = {}
Forums.DoForumReply = function(source, e) {

	// get all inputs of document.
	var items = document.getElementsByTagName("input");
	var tbx;
	var btn;
	var item;
	for (var i = 0; i < items.length; i++) {
		item = items[i];
		if (item.id.indexOf("_ReplyPostIdTextBox") > -1) tbx = item;
		if (item.id.indexOf("_ReplyPostIdButton") > -1) btn = item;
	}
	var tItems = document.getElementsByTagName("span");
	// Disable validators.
	for (var i = 0; i < tItems.length; i++) {
		item = tItems[i];
		if (item.id.indexOf("_BodyTextBoxValidator") > -1) {
			//ValidatorEnable(item, false);
			Array.remove(Page_Validators, item);
		}
	}
	if (tbx != null && btn != null) {
		tbx.value = e;
		setTimeout(function() { btn.click(); }, 500);
	} else {
		//alert("not found");
	}
	return false;
}

Forums.ShowHidePreviousId = null;
Forums.ShowHide = function(source, e) {
//	debugger;
	var curr = document.getElementById(e.PanelId);
	// If this is same button then...
	if (Forums.ShowHidePreviousId != e.PanelId) {
		// Get previous container if set.
		var prev = (Forums.ShowHidePreviousId)
			? document.getElementById(Forums.ShowHidePreviousId)
			: null
		// Hide previous message if visible.
		if (prev && prev.style.display != "none") prev.style.display = "none";
		Forums.ShowHidePreviousId = e.PanelId;
	}
	curr.style.display = (curr.style.display == "none") ? "" : "none";
	return false;
}



Forums.ShowMessage = function(source, e) {
	Forums.ShowHide(source, e);
	RecountMail(e.ItemId);
	return false;
}

function RecountMail(postId) {
	Bookarmy.Api.RecountMail(postId, function() {
		RecountMailDone(postId);});
	return false;
}

function RecountMailDone(postId) {
	//$get('Tick' + tickid).style.display = 'none';
}

Forums.Controls = {};

Forums.DisableMe = function(sender, e) {
	// If page have validator and it prevents from submiting then.
	if (typeof (Page_ClientValidate) == "function" && !Page_ClientValidate(e.Validator)) {
		// Do nothing
		return true;
	}
	if (sender.innerHTML != e.Text) {
		sender.innerHTML = e.Text;
		//setTimeout(function() { sender.innerHTML = "Post"; }, 2000);
		return true;
	}
	return false;
}
﻿function RegisterMacStyleMenuScrollBars(elementId, index) {
	var container = document.getElementById(elementId);
	if (container != null) {
		if (typeof CSBfleXcroll == 'function') CSBfleXcroll(container);
		var step = new String((parseInt(index) * 2)) + 's';
		if (container.contentScroll) {
			container.contentScroll(false, step, true);
		}
	}
}﻿var message_delete_group =           'Are you sure you want to delete this group?<br/>This action is permanent.';
var message_delete_event =           'Are you sure you want to delete this event?<br/>This action is permanent.';
var message_remove_user_from_group = 'Are you sure you want to remove <b>{0}</b> from the group?<br/>This action is permanent.';
var message_leave_groupmembership =  'Are you sure you want to leave this group?<br/>This action is permanent.';
var message_remove_friendship =      'Are you sure you want to remove <b>{0}</b> from your friend list?';
var message_delete_friendship =      'Are you sure you want to delete <b>{0}</b> from your friend list?'; // delete record
var Message_Delete_ForumThread =	 'Are you sure you want to delete this forum?<br/>This action is permanent.';
var Message_Delete_VideoThread =	 'Are you sure you want to delete this video?<br/>This action is permanent.';
var message_remove_book =            'Are you sure you want to remove this book from your books list?'
var message_delete_all_ticks = 'Are you sure you want to delete all your Alerts?'
var message_delete_all_messages = 'Are you sure you want to delete all your Messages?'


var is_chrome = (Sys.Browser.agent == Sys.Browser.Chrome);
var is_ie = (Sys.Browser.agent == Sys.Browser.InternetExplorer);
var is_ie6 = (is_ie && Sys.Browser.version == 6);
var is_ie6up = (is_ie && Sys.Browser.version >= 6);
var is_ie6down = (is_ie && Sys.Browser.version <= 6);
var is_ie7 = (is_ie && Sys.Browser.version == 7);
var is_ie7up = (is_ie && Sys.Browser.version >= 7);

String.prototype.format = function(){
    var str = this;
    for(var i=0;i<arguments.length;i++){
        var re = new RegExp('\\{' + (i) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

/* --- FaceBox Setup ------ */
$.facebox.opacity = 1;
$.facebox.overlay = true;


var LightBox = {};
LightBox.TrackPage = function(url) {
	var siteRootDir = "bookarmy.com"; //(same as directory name from step 1)
	var relativeUrl = url.substr(url.indexOf(siteRootDir) + siteRootDir.length);
	if (typeof (pageTracker) == 'object') pageTracker._trackPageview(relativeUrl);
}

/* --- Show a facebox window with an external page loaded inside -------- */

LightBox.ShowLoginBox = function() {
	var evt = window.event || LightBox.ShowLoginBox.arguments.callee.caller.arguments[0];
	return LightBox.ShowBoxAutoSize('/Boxes/loginremainder.aspx?InBox=true&RequestedLogin=true&ParentReturnUrl=' 
		+ URLEncode(document.location.href)	, false, evt);
}

LightBox.ShowBoxAutoSize = function(url, reposition, parentEvt) {
	//debugger;
	if (parentEvt!= null || LightBox.ShowBoxAutoSize.arguments.callee.caller != null) {
		var evt = parentEvt || (window.event || LightBox.ShowBoxAutoSize.arguments.callee.caller.arguments[0]);
		var related = evt.target || evt.srcElement;
		var relatedid;
		var click;
		if (related != undefined) {
			if (related.tagName == 'IMG')
				while (related.tagName != 'A' && related != undefined)
				related = related.parentNode;
			if (related == undefined) {
				//alert('this action cannot be managed');
				return false;
			}
			relatedid = related.id;
			click = related.pathname || related;
		}
		else {
			relatedid = '';
		}

		if (relatedid != '' &&
            (click.toString().startsWith("__doPostBack") ||
            click.toString().startsWith("javascript:__doPostBack") ||
            click.toString().startsWith("javascript:WebForm_DoPostBackWithOptions"))) {
			$.facebox.faceboxpostback = related.id;
		}
		else
			$.facebox.faceboxpostback = null;
	}
	this.ShowBoxFixSize(200, 200, url);
	this.RepositionBox(evt);
	return false;
}

LightBox.ShowBoxFixSize = function(width, height, url) {
	//debugger;
	var html = '<div style="width:' + width + 'px; height: ' + height + 'px;" id="insideDiv">' +
        '<iframe name="iframe_facebox" id="iframe_facebox" src="' + url + '" style="width: 100%; height: 100%;" frameborder="0"></iframe>' +
        '</div>';
	$.facebox(html);
}

LightBox.RepositionToOrigin = function() {
	if (this.InFrame()) {
		//alert('parent.LightBox.RepositionToOrigin');
		parent.LightBox.RepositionToOrigin();
		return;
	}
}

LightBox.GetPageScroll = function() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}
	return new Array(xScroll, yScroll);
}

LightBox.GetMousePosition = function(evt) {
	var xScroll, yScroll;
	if (evt.pageX)
		xScroll = evt.pageX;
	else
		if (evt.clientX)
		xScroll = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	else
		xScroll = null;

	if (evt.pageY)
		yScroll = evt.pageY;
	else
		if (evt.clientY)
		yScroll = evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	else
		yScroll = null;
	return new Array(xScroll, yScroll);
}

// Adapted from getPageSize() by quirksmode.com
LightBox.GetPageHeight = function() {
	var windowHeight;
	if (is_ie) {
		windowHeight = document.body.scrollHeight;
	} else {
		windowHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
	}
	return windowHeight;
}

LightBox.RepositionBox = function(evt) {
	var posy = 0;
	var posx = 0;

	var mousePos = this.GetMousePosition(evt);
	posx = mousePos[0]; // + scrollx
	posy = mousePos[1]; // +scrolly

	var fb = document.getElementById('facebox');
	if (posy - 220 < 220) {
		fb.style.top = (posy) + 'px';
	}
	else {
		fb.style.top = (posy - 220) + 'px';
	}
	return false;
}

LightBox.ConfirmPostBack = function(text, extrapars) {
	//alert('LightBox.ConfirmPostBack');
	$.facebox.faceboxpostback = null;

	if (text == undefined)
		text = ''
	else {
		text = text.format(extrapars);
	}

	var evt = window.event || LightBox.ConfirmPostBack.arguments.callee.caller.arguments[0];
	var related = evt.target || evt.srcElement;

	if (related.tagName == 'IMG')
		while (related.tagName != 'A' && related != undefined)
		related = related.parentNode;

	if (related == undefined) {
		//alert('this action cannot be managed');
		return false;
	}
	var click = related.pathname || related;
	var html = '<div id="insideDiv">' + text + '<br/><br /><a onclick="LightBox.CloseBox(); ' + click + '; return false;" class="BA_action_link" href="#"> Confirm</a>&nbsp;<a onclick="LightBox.CloseBox(); return false;" href="#" class="action_link_close">Cancel</a></div>';
	jQuery.facebox(html);
	this.RepositionBox(window.event || LightBox.ConfirmPostBack.arguments.callee.caller.arguments[0]);
	this.ResizeBox(400, 100, false);
	return false;
}

LightBox.InFrame = function() {
	var inFr = false;
	try {
		inFr = window.name === "iframe_facebox";
	} catch (ex) {
		// If accessing the frameElement fails, a frame is probably in a different
		// domain than its parent - and we still want to do the calculation below
		inFr = false;
	}
	return inFr;
}

LightBox.Widow_Resize;
LightBox.Widow_ResizeId;

//LightBox.UpdateIframe = function() {
//    //here we should resize the lightbox
//}

LightBox.ResizeBox = function(width, height, reload) {
	if (this.InFrame()) {
		var me = this;
		if (LightBox.Widow_ResizeId > 0) {
			window.clearInterval(LightBox.Widow_ResizeId);
		}
		//debugger;
		//if (height == 0) height = LightBox.GetPageHeight();
		LightBox.ResizeBoxDelayed(width, me.GetPageHeight(), reload);
		LightBox.Widow_Resize = function() { me.ResizeBoxDelayed(width, me.GetPageHeight(), reload); }
		// Check content so height of box will be expanded automatically if needed. 
		LightBox.Widow_ResizeId = window.setInterval(LightBox.Widow_Resize, 1000);
		var newHeight = LightBox.GetPageHeight() + "px";
		if (document.body.style.height != newHeight) {
			document.body.style.height = LightBox.GetPageHeight() + "px";
		}
		return;
	}
	var insideDiv = document.getElementById('insideDiv');
	if (insideDiv == undefined)
		return;
	if (insideDiv.style.width != width + "px") insideDiv.style.width = width + "px";
	if (insideDiv.style.height != height + "px") insideDiv.style.height = height + "px";
	// Attach resize handler.
}

LightBox.ResizeBoxDelayed = function(width, height, reload) {
	window.setTimeout(function() {
		parent.LightBox.ResizeBox(width, height, reload);
	}, 100);
}

LightBox.SimulateClick = function(id) {
	id = id.replace(/_/g, '$');
	__doPostBack(id, '__reload_data');
}

LightBox.CloseBox = function(doPostBack) {
	if (this.InFrame()) {
		parent.LightBox.CloseBox(doPostBack);
		return;
	}
	if (doPostBack) {
		$.facebox.dopostback = true;
	}
	else {
		$.facebox.dopostback = false;
	}

	if ($.facebox.dopostback && document.refreshLoginSearchSection) {
		document.refreshLoginSearchSection();
	}
	jQuery(document).trigger('close.facebox');
	return false;
}

LightBox.CloseThisBoxCancelEvent = function() {
	if (this.InFrame()) {
		return parent.LightBox.CloseThisBoxCancelEvent();
	}
	$.facebox.faceboxpostback = null;
	this.CloseBox();
	return false;
}

LightBox.CloseThisBoxAndRefreshParent = function() {
	if (this.InFrame()) {
		parent.LightBox.CloseThisBoxAndRefreshParent();
		return;
	}
    this.CloseBox();
    location.href = location.href;
    return false;
}

//extend facebox
$.facebox.faceboxpostback = null;

$(document).bind('close.facebox', function() {
	if ($.facebox.faceboxpostback != null) {
		var clientId = $get($.facebox.faceboxpostback).id;
		$.facebox.faceboxpostback = null;
		LightBox.SimulateClick(clientId);
	}
});

function executeTickAction(tickid, action) {
    CloseMessageVertically(tickid);
    Bookarmy.Api.TickAcceptIgnore(tickid, action, function() {
    	CloseHeaderVertically(tickid);
    }
    );
	return false;
}

function CloseMessageVertically(tickid) {
	$get('TickBody' + tickid).style.display = 'none';
}

function CloseHeaderVertically(tickid) {
	$get('Tick' + tickid).style.display = 'none';
}

function getURLParam(strParamName) {
	var strReturn = "";
	var strHref = window.location.href;
	var bFound = false;
	var cmpstring = strParamName + "=";
	var cmplen = cmpstring.length;
	if (strHref.indexOf("?") > -1) {
		var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
		var aQueryString = strQueryString.split("&");
		for (var iParam = 0; iParam < aQueryString.length; iParam++) {
			if (aQueryString[iParam].substr(0, cmplen) == cmpstring) {
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				bFound = true;
				break;
			}
		}
	}
	if (bFound == false) return null;
	return strReturn;
}



function URLEncode(plaintext) {
	//debugger;
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" + 				// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					"abcdefghijklmnopqrstuvwxyz";  //+
					//"-_.!~*'()"; 				// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+"; 			// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
			encoded += ch;
		} else {
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				//alert("Unicode Character '"+ ch+ "' cannot be encoded using standard URL encoding.\n" +"(URL encoding only supports 8-bit characters.)\n" +"A space (+) will be substituted.");
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
};




function searchTextRedirect(pattern) {
    debugger;
    location.href = new String(pattern).replace('{0}', $('.topSearchDDL').val()).replace('{1}', URLEncode($('.topSearch').val()));
    return false;
}﻿
﻿function GoogleAnalytics_endRequestHandler(sender, args) {
	if (top === self) {
		if (typeof InitMacStyleMenuScrollBars == 'function') { InitMacStyleMenuScrollBars(); }
		var dataItems = args.get_dataItems();
		var newpage = dataItems['newurlControl'];
		document.body.style.cursor = '';
		if (newpage != null) {
			LightBox.TrackPage(newpage);
		}
		else {
			LightBox.TrackPage(window.location.href);
		}
	}
	else {
		LightBox.TrackPage(window.location.href);
	}
}

function AdsProxy_beginRequestHandler(sender, args) {
    document.body.style.cursor = 'wait';
    //$.blockUI();
}
function AdsProxy_endRequestHandler(sender, args) {
    //$.unblockUI();
    document.body.style.cursor = '';
}


Sys.WebForms.PageRequestManager.getInstance().add_endRequest(GoogleAnalytics_endRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(AdsProxy_beginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(AdsProxy_endRequestHandler);
﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference path="../Common/Common.js" />
/// Use http://www.west-wind.com/files/tools/jsminifier.application to minify

Type.registerNamespace("Xenial.BookArmy.Website.Controls");

Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList = function(element) {
	Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList.initializeBase(this, [element]);

	this._queryInterval = null;
	this._emptyMessage = null;
	this._listWidth = null;
	this._listHeight = null;
	this._scrollBars = null;

	this._servicePath = null;
	this._serviceMethod = null;

	// Maximum number of items allowed to be selected.
	this._maximumItems = null;
	// Automattically remove first item if maximum items is reached.
	this._autoRemoveFirst = null;

	this._itemSelectedDelegate = null;
	this._itemRemovedDelegate = null;

	this._queryId = null;
	this._request = null;

	this._resultLinkItems = null;

	this._isOverDataResultList = false;

	this._popupContainerId = null;
	this._popupContainer = null;
	this._topPagContainer = null;
	this._botPagContainer = null;

	this._selectedPage = 0;

	this._dataResultList = null;

	this._mouseX = 0;
	this._mouseY = 0;

	this.Controls = null;

	this.CurrentLinkItems = [];
	this.CurrentHtmlNodes = [];

	// Index position must be synched inside these lists.
	// this.CurrentLinkItems - LinkItem objects as they came from XML.
	// this.CurrentHtmlNodes - LinkItem html nodes dispayed on page. 
	// this.Controls.DataTextBox
}

Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList.prototype = {
	initialize: function() {
		Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList.callBaseMethod(this, 'initialize');

		// Add custom initialization here

		var element = this.get_element();
		this._popupContainerId = this._getChildElement('DataResultListContainer').id + '_PopupBox';

		this.Controls = {};
		this.Controls['DataTextBox'] = this._getChildElement('DataTextBox');
		this.Controls['DataPattern'] = this._getChildElement('DataPattern');
		this.Controls['DataPatternPanel'] = this._getChildElement('DataPatternPanel');

		var readonly = jQuery(this.Controls.DataPattern).attr("readonly");

		if (readonly != undefined && !readonly) {
			this._showEmptyMessage();

			// Register Events handlers

			Sys.UI.DomEvent.addHandlers(this.Controls.DataPattern,
			{
				'focus': this.DataPattern_OnFocus,
				'blur': this.DataPattern_OnBlur,
				'kyepress': this.DataPattern_OnKeyPress,
				'keyup': this.DataPattern_OnKeyUp,
				'keydown': this.DataPattern_OnKeyDown

			}, this);

			if (this._itemSelectedDelegate === null) {
				this._itemSelectedDelegate = Function.createDelegate(this, this._itemSelectedHandler);
			}
			Sys.UI.DomEvent.addHandler(element, 'itemSelected', this._itemSelectedDelegate);

			if (this._itemRemovedDelegate === null) {
				this._itemRemovedDelegate = Function.createDelegate(this, this._itemRemovedHandler);
			}
			Sys.UI.DomEvent.addHandler(element, 'itemRemoved', this._itemRemovedDelegate);

			// Begin Track mouse coordinates        
			jQuery().mousemove(Function.createDelegate(this, function(e) { this._mouseX = e.pageX; this._mouseY = e.pageY; }));
			// Load HTML items.
			this._loadFromTextBoxes();
		}
	},
	dispose: function() {
		//Add custom dispose actions here
		Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList.callBaseMethod(this, 'dispose');
	},

	/* --- Events & Handlers ------------------------------------------------------------------------------------- */

	DataPattern_OnFocus: function(e) {

		/* --- Show Popup ---------------- */
		//debugger;
		this._createPopup();
		this._showPopup();
	},
	DataPattern_OnBlur: function(e) {
		/* --- Hide Popup ---------------- */
		// Hide popup when dataPattern blur and the mouse is not over the popup list
		if (!this._popupContainer) {
			// We can end here if user blured outside webpage with mouse.
			//alert("this " + this._popupContainer);
			return false;
		}
		//alert(this._popupContainer.css('left'));
		var pos = {
			x: parseInt(this._popupContainer.css('left')),
			y: parseInt(this._popupContainer.css('top')),
			width: this._popupContainer.width(),
			height: this._popupContainer.height()
		}
		var isOver = false;
		isOver = (this._mouseX >= pos.x && this._mouseX <= pos.x + pos.width) &&
                 (this._mouseY >= pos.y && this._mouseY <= pos.y + pos.height);

		if (!isOver) this._hidePopup();
	},
	DataPattern_OnKeyPress: function(e) {

		if (e.keyCode == 8) {
			e.stopPropagation();

			if (e && e.preventDefault) e.preventDefault();
			else if (window.ActiveXObject) window.event.returnValue = false;
		}
	},
	DataPattern_OnKeyUp: function(e) {
		if (e.keyCode == 8 || e.keyCode == 127) {
			if (e.target.value == '') {
				//if cancel or delete, clean all fields
				$get(e.target.id.replace('DataPattern', 'ItemId')).value = '00000000-0000-0000-0000-000000000000';
				$get(e.target.id.replace('DataPattern', 'ItemName')).value = '';
				$get(e.target.id.replace('DataPattern', 'ItemType')).value = '';
			}
			e.stopPropagation();
			if (e && e.preventDefault) e.preventDefault();
			else if (window.ActiveXObject) window.event.returnValue = false;

			this._selectedPage = 0;
			this._queryForDynamicData();
			//this._cancelDynamicDataQuery();
		}
		else {
			this._selectedPage = 0;
			// Call for Querying dynamic data        
			this._queryForDynamicData();
		}
	},
	DataPattern_OnKeyDown: function(e) {

		var value = this.Controls.DataPattern.value;

		if (e.keyCode == 8) {

			if (!value || value.length == 0) {

				jQuery(this.Controls.DataPattern).blur();
				jQuery(this._getChildElement('DataItemList')).find('li:last').focus();

				e.stopPropagation();

				if (e && e.preventDefault) e.preventDefault();
				else if (window.ActiveXObject) window.event.returnValue = false;
			}
		}
	},
	Close_Click: function(sender) {


	}
	,
	DynamicData_OnResults: function(caller, results) {
		var elements = null;
		// Success                                                                                
		if ('object' == typeof (results) && results.length > 0) {
			elements = new Array();
			// Remove previous items
			caller._clearResultList();
			caller._resultLinkItems = {};
			// Populate with new items
			for (var i = 0; i < results.length; i++) {
				var resultId = caller.get_element().id + '_item' + i;
				//debugger;
				var name = results[i].Description;
				//alert(name);
				if (name == undefined || name == '') name = results[i].Name;
				var item = jQuery(
                    '<li id="' + resultId + '" class="BA_general_listitem no_top">' +
                    '   <div class="thumb thumb_medium">' +
						'   <img src="' + results[i].AbsoluteImagePath + '"/>' +
                    '   </div>' +
                    '   <div class="BA_ACList_Item">' +
                        '   <a title="' + name + '">' +
                                caller._formatText(name) +
                        '   </a>' +
                    '   </div>' +
                    '</li><br>');
				var jItem = jQuery(item);

				/* --- Using double event binding because using .hover() is causing some issues --- */
				jItem.find('div').bind('mouseover', function() {
					//jQuery(this).addClass('BA_ACList_Selected');
					//jQuery(this).css('background', '#49a0d0 url(/app_themes/default/images/Bullets/big_arrow_selected.gif) no-repeat 0px 10px');
					//jQuery(this).find('a').addClass('BA_ACList_Selected');
				});
				jItem.find('div').bind('mouseleave', function() {
					//jQuery(this).removeClass('BA_ACList_Selected');
					//jQuery(this).css('background', '#ffffff url(/app_themes/default/images/Bullets/big_dot.gif) no-repeat 0px 10px');
					//jQuery(this).find('a').removeClass('BA_ACList_Selected');
				});

				elements.push(item);
				//jQuery(caller._getChildElement('DataResultList')).append(item);
				caller._resultLinkItems[resultId] = results[i];
				// function which will be executed by clicking on results item.
				jItem.click(function() {
					// Get LinkItem by html node id.
					var li = caller._resultLinkItems[this.id];
					// If we will have too many records already then fix it by removing oldest one.
					if (caller.CurrentLinkItems.length + 1 > caller._maximumItems) {
						// Remove olders item.
						caller._removeItemByIndex(0);
					}
					// If autoremove is not enabled and we will reach maximum records then...
					if (!caller._autoRemoveFirst && caller.CurrentLinkItems.length + 1 >= caller._maximumItems) {
						// Don't allow any new items to be added.
						caller.Controls.DataPattern.style.display = "none";
						caller.Controls.DataPatternPanel.style.display = "";
					}
					/* --- Create children elements ----- */
					var elm_li = jQuery('<li></li>');
					var elm_input0 = jQuery('<input type="hidden" value="' + li.Id + '" />');
					var elm_input1 = jQuery('<input type="hidden" value="' + resultId + '" />');
					var elm_table = jQuery('<table class="BA_ACList_Panel" border="0" cellspacing="0" cellpadding="0"></table>');
					var elm_row = jQuery('<tr></tr>');
					var elm_cell0 = jQuery('<td valign="middle" class="BA_ACList_CellL"></td>');
					var elm_cell1 = jQuery('<td valign="middle" class="BA_ACList_CellC"></td>');
					var elm_cell2 = jQuery('<td valign="middle" class="BA_ACList_CellR"></td>');
					//var elm_div = jQuery('<div class="BA_ACList_Panel"></div>');
					var elm_link = jQuery('<a class="BA_ACList_PanelLink"></a>');
					elm_link.attr("href", li.AbsolutePagePath);
					var elm_image = jQuery('<img class="BA_ACList_PanelImage" alt="PanelImage" />');
					elm_image.attr("src", li.AbsoluteImagePath);
					var elm_text = jQuery('<span class="BA_ACList_PanelText"></span>');
					elm_text.attr("innerHTML", caller._cropText(unescape(li.Name)));
					elm_text.attr("title", unescape(li.Name));
					var elm_button = jQuery('<a href="#" class="BA_ACList_PanelButton"></a>');
					/* --- Set item remove behavior ---- */
					jQuery(elm_button).click(function() {
						/* --- Remove item from the container --- */
						//alert(jQuery(this).parent().parent().id);
						var itemNode = jQuery(this).parent().parent();
						caller._removeItemByHtmlNode(elm_li);
						return false;
					});

					/* --- Set elm_li events ------ */

					jQuery(elm_li).click(function() { jQuery(this).focus(); return false; });

					jQuery(elm_li).bind('mouseenter mouseover', function() { jQuery(this).toggleClass('BA_ACList_Selected'); return false; });
					jQuery(elm_li).bind('mouseleave', function() { jQuery(this).removeClass('BA_ACList_Selected'); return false; });

					jQuery(elm_li).focus(function() { jQuery(this).addClass('BA_ACList_Selected'); return false; });
					jQuery(elm_li).blur(function() { jQuery(this).removeClass('BA_ACList_Selected'); return false; });

					jQuery(elm_li).bind('keyup keydown keypress', function(e) {

						if (e.which == 8) {

							jQuery(this).blur();
							jQuery(this).find('a').click();

							jQuery(caller.Controls.DataPattern).focus();

							e.stopPropagation();

							if (e && e.preventDefault) e.preventDefault();
							else if (window.ActiveXObject) window.event.returnValue = false;
						}
					});

					elm_li.append(elm_table);
					elm_table.append(elm_row);
					elm_row.append(elm_cell0);
					elm_row.append(elm_cell1);
					elm_row.append(elm_cell2);
					elm_li.append(elm_input0);
					elm_li.append(elm_input1);
					elm_link.append(elm_image);
					elm_cell0.append(elm_link);
					elm_cell1.append(elm_text);
					elm_cell2.append(elm_button);

					/* --- Add item to the container ---- */
					jQuery(caller._getChildElement('DataItemsList')).append(elm_li);
					/* --- Clean input textbox and set focus --- */
					caller.Controls.DataPattern.value = '';
					//jQuery(caller.Controls.DataPattern).focus();

					/* -- Add item to the selected items collection --- */
					caller.CurrentLinkItems.push(li);
					caller.CurrentHtmlNodes.push(elm_li);
					/* --- Add item to hidden select boxes --- */
					caller._saveToTextBoxes();
					/* --- Clear after a selection ---- */
					caller._clearResultList();
					caller._showEmptyMessage();
					/* --- Raise event --------- */
					caller._itemSelectedDelegate('', li);
					caller._hidePopup();
					return false;
				});
			}
			caller._clearMessage();
			for (var i = 0; i < elements.length; i++) {
				jQuery(caller._getChildElement('DataResultList')).append(elements[i]);
			}
		}
		else {
			caller._clearMessage();
			caller._showErrorMessage('No results. Please try again (and check your spelling).');
		}
		/* --- Show Wait Message --- */
		return elements;
	},

	/* --- Public Methods ------------------------------------------------------------- */
	AddItems: function(items) {
		for (var i = 0; i < items.length; i++) {
			this._addItem(items[i]);
		}
		/* --- Raise event --------- */
		if (items != null && items.length > 0)
			this._itemSelectedDelegate('', items);
	},

	/* --- Private Methods ------------------------------------------------------------------------------------------ */
	// Handlers
	_itemSelectedHandler: function(event, eventArgs) {
		var h = this.get_events().getHandler('itemSelected');
		if (h) h(this, eventArgs);
	},

	_itemRemovedHandler: function(event, eventArgs) {
		var h = this.get_events().getHandler('itemRemoved');
		if (h) h(this, eventArgs);
	},

	// Bind and Unbind Events

	add_itemSelected: function(handler) {
		this.get_events().addHandler('itemSelected', handler);
	},
	remove_itemSelected: function(handler) {
		this.get_events().removeHandler('itemSelected', handler);
	},
	add_itemRemoved: function(handler) {
		this.get_events().addHandler('itemRemoved', handler);
	},
	remove_itemRemoved: function(handler) {
		this.get_events().removeHandler('itemRemoved', handler);
	},

	// Private methods

	_getChildElement: function(childId) {
		var element = this.get_element();
		return $get(element.id + '_' + childId);
	},
	_getAjaxNetChildElement: function(childId) {
		var element = this.get_element();
		return $find(element.id + '_' + childId);
	},
	_getPopupElement: function() {
		return $get(this._popupContainerId);
	},

	_showPopup: function() {
		jQuery(this._getChildElement('DataResultListContainer')).css('display', 'block');
		jQuery(this._popupContainer).css('display', 'block');
	},
	_hidePopup: function() {
		jQuery(this._getChildElement('DataResultListContainer')).css('display', 'none');
		jQuery(this._popupContainer).css('display', 'none');
	},

	_queryForDynamicData: function() {
		// Cancel or stop current dynamic data request
		if (this._queryId) this._cancelDynamicDataQuery(this._queryId);
		var source = this;
		this._queryId = window.setInterval(
			function() {
				source._getDynamicData([source]);
			}, this._queryInterval);
	},
	_cancelDynamicDataQuery: function() {

		// Stop querying interval
		if (this._queryId) window.clearInterval(this._queryId);
		// Cancel request
		//if (this._request) {
		//var executor =  this._request.get_executor();
		//if (executor.get_started()) executor.abort();           
		//}

		// Cancel last item selection
		this._getChildElement('ItemId').value = '00000000-0000-0000-0000-000000000000';
	},
	_clearResultList: function() {
		/* --- Clear results list ------- */
		var container = jQuery(this._getChildElement('DataResultListContainer'));
		if (container) {
			// Clear Result List
			jQuery(this._getChildElement('DataResultList')).empty();
		}
	},
	_showEmptyMessage: function() {
		/* --- Show a Empty Message ----- */
		var container = jQuery(this._getChildElement('DataResultListContainer'));
		if (container) {
			var id = this._getChildElement('DataResultListContainer').id + "_EmptyBox";
			// Remove any previous element
			this._clearMessage();
			var elm_div = jQuery('<div id="' + id + '"class="BA_ACList_Waitbox"><div class="BA_ACList_Waitbox_Loader"></div><div class="BA_ACList_Waitbox_Message">' + this._emptyMessage + '</div></div>');
			jQuery(container).append(elm_div);
		}
	},
	_showWaitMessage: function() {
		/* --- Show a Wait Message ----- */
		var container = jQuery(this._getChildElement('DataResultListContainer'));
		if (container) {
			var id = this._getChildElement('DataResultListContainer').id + "_WaitBox";
			// Remove any previous element
			this._clearMessage();
			var elm_div = jQuery('<div id="' + id + '"class="BA_ACList_Waitbox"><div class="BA_ACList_Waitbox_Loader"></div><div class="BA_ACList_Waitbox_Message">Please Wait...</div></div>');
			jQuery(container).append(elm_div);
		}
	},
	_showErrorMessage: function(text) {
		/* --- Show an Error Message ----- */
		var container = jQuery(this._getChildElement('DataResultListContainer'));
		if (container) {
			var id = this._getChildElement('DataResultListContainer').id + "_ErrorBox";
			// Remove any previous element
			this._clearMessage();
			var elm_div = jQuery('<div id="' + id + '"class="BA_ACList_Error">' + text + '</div>');
			jQuery(container).append(elm_div);
		}
	},
	_clearMessage: function() {
		// Hide all messages
		this._clearResultList();
		this._hideEmptyMessage();
		this._hideWaitMessage();
		this._hideErrorMessage();
	},
	_hideEmptyMessage: function() {
		var id = this._getChildElement('DataResultListContainer').id + "_EmptyBox";
		jQuery('#' + id).remove();
	},
	_hideWaitMessage: function() {
		var id = this._getChildElement('DataResultListContainer').id + "_WaitBox";
		jQuery('#' + id).remove();
	},
	_hideErrorMessage: function() {
		var id = this._getChildElement('DataResultListContainer').id + "_ErrorBox";
		jQuery('#' + id).remove();
	},
	_addItem: function(item) {
		var results = new Array();
		results.push(item)
		var elements = this.DynamicData_OnResults(this, results);
		elements[0].click();
	},
	_removeItemByHtmlNode: function(htmlNode) {
		var length = this.CurrentLinkItems.length;
		for (var i = 0; i < length; i++) {
			if (this.CurrentHtmlNodes[i] == htmlNode) {
				this._removeItemByIndex(i);
				// Break because page have only one unique HTML node.
				break;
			}
		}
	},
	_loadFromTextBoxes: function() {
		// Use Json later.
		// Create link items from text boxes.
		var items = new Array();
		var lines = this.Controls.DataTextBox.value.replace("\r", "").split("\n");
		for (var i = 0; i < lines.length; i++) {
			var values = lines[i].split(",");
			if (values.length != 6) continue;
			var li = {};
			// NOTE: make sure that order match in other code parts.
			li["Id"] = values[0];
			li["Type"] = values[1];
			li["Key"] = values[2];
			li["Name"] = values[3];
			li["AbsolutePagePath"] = values[4];
			li["AbsoluteImagePath"] = values[5];
			items.push(li);
		}
		this.AddItems(items);
	}
	,
	_saveToTextBoxes: function() {
		// Use Json later.
		var data = new String();
		var length = this.CurrentLinkItems.length;
		for (var i = 0; i < length; i++) {
			var li = this.CurrentLinkItems[i];
			if (i > 0) data += "\r\n";
			// NOTE: make sure that order match in other code parts.
			data += li.Id + ",";
			data += li.Type + ",";
			data += this._escapeText(li.Key) + ",";
			data += this._escapeText(li.Name) + ",";
			data += this._escapeText(li.AbsolutePagePath) + ",";
			data += this._escapeText(li.AbsoluteImagePath);
		}
		this.Controls.DataTextBox.value = data;
	}
	,
	_removeItemById: function(id) {
		// Note: multiple item with same Linkitem.Id can be removed.
		for (var i = 0; i < this.CurrentLinkItems.length; i++) {
			// Reverse routing so multiple items can be removed..
			var r = this.CurrentLinkItems.length - i - 1;
			if (this.CurrentLinkItems[r].Id == id) {
				this._removeItemByIndex(r);
			}
		}
	},
	_removeItemByIndex: function(index) {
		var resultId = this.CurrentHtmlNodes[index].find('input')[1].value;
		// Remove HTML node from page.
		this.CurrentHtmlNodes[index].remove();
		Array.removeAt(this.CurrentLinkItems, index);
		Array.removeAt(this.CurrentHtmlNodes, index);
		if (this.CurrentLinkItems.length < this._maximumItems) {
			this.Controls.DataPatternPanel.style.display = "none";
			this.Controls.DataPattern.style.display = "";
		}
		var li = this._resultLinkItems[resultId];
		this._itemRemovedDelegate('', li);
		this._hidePopup();
		this._saveToTextBoxes();
	},
	_getDynamicData: function(args) {
		// Caller stands for the calling autocomplete list item that ask & receive for dynamic data
		var caller = args[0];

		caller._cancelDynamicDataQuery();

		var dataPattern = caller.Controls.DataPattern.value;
		if (dataPattern && dataPattern.length >= 2) {

			/* --- Show Wait Message --- */
			caller._showWaitMessage();
			// Do a web service method call (to get dynamic data)
			caller._request = Sys.Net.WebServiceProxy.invoke(
                caller._servicePath,
                caller._serviceMethod,
                false,
                { "dataPattern": dataPattern, "pageIndex": caller._selectedPage },
                function(results) {
                	//debugger;
                	jQuery(caller._topPagContainer).empty();
                	jQuery(caller._botPagContainer).empty();
                	jQuery(caller._topPagContainer).css('display', 'none');
                	jQuery(caller._botPagContainer).css('display', 'none');
                	if (results.TotPages > 0) {
                		//debugger
                		jQuery(caller._topPagContainer).css('display', 'block');
                		jQuery(caller._botPagContainer).css('display', 'block');
                		for (var p = 0; p < results.TotPages && p < 15; p++) {
                			var paget = jQuery('<a id="paget' + p + '" alt="' + p + '" href="#">&nbsp;' + (p + 1) + '&nbsp;</a>');
                			jQuery(paget).click(Function.createDelegate(paget, function() {
                				caller._showWaitMessage();
                				caller._selectedPage = $(this).attr("alt");
                				caller._queryForDynamicData();
                				return false;
                				//debugger;
                			}));
                			var pageb = jQuery('<a id="pageb' + p + '" alt="' + p + '" href="#">&nbsp;' + (p + 1) + '&nbsp;</a>');
                			jQuery(pageb).click(Function.createDelegate(pageb, function() {
                				caller._showWaitMessage();
                				caller._selectedPage = $(this).attr("alt");
                				caller._queryForDynamicData();
                				return false;
                			}));


                			if (caller._selectedPage == p) {
                				jQuery(paget).css('font-weight', 'bold');
                				jQuery(paget).css('color', 'red');
                				jQuery(pageb).css('font-weight', 'bold');
                				jQuery(pageb).css('color', 'red');
                			}
                			jQuery(caller._topPagContainer).append(paget);
                			jQuery(caller._botPagContainer).append(pageb);
                		}
                	}
                	// Success
                	caller.DynamicData_OnResults(caller, results.List);
                	caller._showPopup();
                },

                function(results) {
                	// Failure
                	caller._clearResultList();
                	caller._showErrorMessage('No results. Please try again (and check your spelling).');
                }
            );
		}
		else {

			// Remove previous items
			caller._clearResultList();
		}
	},
	_cropText: function(text, maxLength) {
		if (maxLength == null) maxLength = ((this._listWidth.Value - 32 - 12 - 12) / 6.9);
		if (text.length > maxLength) text = text.substring(0, maxLength - 3) + "...";
		return text;
	}
    ,
	_formatText: function(text) {
		if (text && text.length > 0) {

			// Unescape and trim
			text = this._cropText(unescape(text));
			// Pattern finding
			var dataPattern = this.Controls.DataPattern.value;
			var index = text.toLowerCase().indexOf(dataPattern.toLowerCase());
			if (index != -1) {

				dataPattern = text.substr(index, dataPattern.length);
				text = text.replace(new RegExp(dataPattern, 'g'), String.format('<b>{0}</b>', dataPattern));
			}

			return text;
		}
	},
	_escapeText: function(s) {
		if (!s) return "";
		var results = new String();
		for (var i = 0; i < s.length; i++) {
			var code = s.charCodeAt(i);
			//"," and "\r\n" "\" must be escaped
			if (s != "," && s != "\r\n" && s != "\\") {
				// Add char to string.
				results += s.charAt(i);
			} else {
				// Unescape char.
				var hex = code.toString(16);
				results += "\\u" + "0000".substr(0, 4 - hex.length) + hex + "";
			}
		}
		return results;
	}
	,
	_createPopup: function() {

		if (this._popupContainer == null) {

			var input = jQuery(this.Controls.DataPattern);
			var pos = $common.getBounds(this.Controls.DataPattern);

			var listContainer = jQuery(this._getChildElement('DataResultListContainer'));
			jQuery(listContainer).remove();

			if (jQuery('#' + this._popupContainerId.length > 0))
				jQuery('#' + this._popupContainerId).remove();

			var container = jQuery('<div id="' + this._popupContainerId + '" class="BA_ACList"></div>');
			jQuery(container).css('position', 'absolute');
			jQuery(container).css('left', pos.x);
			jQuery(container).css('top', pos.y + pos.height);
			jQuery(container).css('border', 'solid 1px #d0d0d0');
			jQuery(container).css('background-color', 'White');
			jQuery(container).css('display', 'block');

			if (this._listWidth && this._listWidth.Value > 0)
				jQuery(container).css('width', this._listWidth.Value + 'px');

			// Auto height on IE 6
			// 
			//            div name {
			//            min-height:500px;
			//            height:auto !important;
			//            height:500px;
			//            }

			if (this._listHeight && this._listHeight.Value > 0)
				jQuery(container).css('max-height', this._listHeight.Value + 'px');

			if (this._scrollBars)
				jQuery(container).css('overflow', 'auto');

			if (jQuery('#toppag').length > 0)
				jQuery('#toppag').remove();
			this._topPagContainer = jQuery('<div id="toppag" class="BA_ACList_Pag"></div>');
			jQuery(this._topPagContainer).css('width', (this._listWidth.Value - 18) + 'px');

			if (jQuery('#botpag').length > 0)
				jQuery('#botpag').remove();
			this._botPagContainer = jQuery('<div id="botpag" class="BA_ACList_Pag"></div>');
			jQuery(this._botPagContainer).css('width', (this._listWidth.Value - 18) + 'px');
			jQuery(this._topPagContainer).css('display', 'none');
			jQuery(this._botPagContainer).css('display', 'none');
			jQuery(container).append(this._topPagContainer);
			jQuery(container).append(listContainer);
			jQuery(container).append(this._botPagContainer);
			jQuery(document.body).append(container);

			jQuery(listContainer).bind('click', Function.createDelegate(this, function() { this._hidePopup(); }));

			this._popupContainer = container;
		}
		else {
			var pos = $common.getBounds(this.Controls.DataPattern);

			jQuery(this._popupContainer).css('left', pos.x);
			jQuery(this._popupContainer).css('top', pos.y + pos.height);
		}
	},

	/* --- Properties ------------------------------------------------------ */

	get_queryInterval: function() {
		return this._queryInterval;
	},
	set_queryInterval: function(value) {
		if (this._queryInterval !== value) {
			this._queryInterval = value;
			this.raisePropertyChanged('queryInterval');
		}
	},
	get_emptyMessage: function() {
		return this._emptyMessage;
	},
	set_emptyMessage: function(value) {
		if (this._emptyMessage !== value) {
			this._emptyMessage = value;
			this.raisePropertyChanged('emptyMessage');
		}
	},
	get_listWidth: function() {
		return this._listWidth;
	},
	set_listWidth: function(value) {
		if (this._listWidth !== value) {
			this._listWidth = value;
			this.raisePropertyChanged('listWidth');
		}
	},
	get_listHeight: function() {
		return this._listHeight;
	},
	set_listHeight: function(value) {
		if (this._listHeight !== value) {
			this._listHeight = value;
			this.raisePropertyChanged('listHeight');
		}
	},
	get_scrollBars: function() {
		return this._scrollBars;
	},
	set_scrollBars: function(value) {
		if (this._scrollBars !== value) {
			this._scrollBars = value;
			this.raisePropertyChanged('scrollBars');
		}
	},

	get_servicePath: function() {
		return this._servicePath;
	},
	set_servicePath: function(value) {
		if (this._servicePath !== value) {
			this._servicePath = value;
			this.raisePropertyChanged('servicePath');
		}
	},
	get_serviceMethod: function() {
		return this._serviceMethod;
	},
	set_serviceMethod: function(value) {
		if (this._serviceMethod !== value) {
			this._serviceMethod = value;
			this.raisePropertyChanged('serviceMethod');
		}
	},
	get_maximumItems: function() {
		return this._maximumItems;
	},
	set_maximumItems: function(value) {
		if (this._maximumItems !== value) {
			this._maximumItems = value;
			this.raisePropertyChanged('maximumItems');
		}
	},
	get_autoRemoveFirst: function() {
		return this._autoRemoveFirst;
	},
	set_autoRemoveFirst: function(value) {
		if (this._autoRemoveFirst !== value) {
			this._autoRemoveFirst = value;
			this.raisePropertyChanged('autoRemoveFirst');
		}
	},
	get_selectedText: function() {
		// Return selected item text
		return null;
	},
	get_isValidated: function() {
		// Return true if a valid item is selected
		//var selectedValueId = this._getChildElement('ItemId').value
		return this.CurrentLinkItems.length > 0;
	}
}
Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList.registerClass('Xenial.BookArmy.Website.Controls.LinkItemAutocompleteList', Sys.UI.Control);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
﻿/*
This license text has to stay intact at all times:
fleXcroll Public License Version
Cross Browser Custom Scroll Bar Script by Hesido.
Public version - Free for non-commercial uses.

This script cannot be used in any commercially built
web sites, or in sites that relates to commercial
activities. This script is not for re-distribution.
For licensing options:
Contact Emrah BASKAYA @ www.hesido.com

Derivative works are only allowed for personal uses,
and they cannot be redistributed.

FleXcroll Public Key Code: 20050907122003339
MD5 hash for this license: 9ada3be4d7496200ab2665160807745d

End of license text---
*/
//fleXcroll v1.9.5f
var fleXenv = {

	fleXcrollInit: function() { this.addTrggr(window, 'load', this.globalInit); },

	fleXcrollMain: function(dDv) {
		//Main code beg
		var dC = document, wD = window, nV = navigator;
		if (!dC.getElementById || !dC.createElement) return;
		if (typeof (dDv) == 'string') dDv = document.getElementById(dDv);
		if (dDv == null || nV.userAgent.indexOf('OmniWeb') != -1 || ((nV.userAgent.indexOf('AppleWebKit') != -1 || nV.userAgent.indexOf('Safari') != -1) && !(typeof (HTMLElement) != "undefined" && HTMLElement.prototype)) || nV.vendor == 'KDE' || (nV.platform.indexOf('Mac') != -1 && nV.userAgent.indexOf('MSIE') != -1)) return;
		if (dDv.scrollUpdate) { dDv.scrollUpdate(); return; };
		if (!dDv.id || dDv.id == '') { var sTid = "flex__", c = 1; while (document.getElementById(sTid + c) != null) { c++ }; dDv.id = sTid + c; }
		var targetId = dDv.id;
		dDv.fleXdata = new Object(); var sC = dDv.fleXdata;
		sC.keyAct = { _37: ['-1s', 0], _38: [0, '-1s'], _39: ['1s', 0], _40: [0, '1s'], _33: [0, '-1p'], _34: [0, '1p'], _36: [0, '-100p'], _35: [0, '+100p'] };
		sC.wheelAct = ["-2s", "2s"];
		sC.baseAct = ["-2s", "2s"];
		var cDv = createDiv('contentwrapper', true), mDv = createDiv('mcontentwrapper', true), tDv = createDiv('scrollwrapper', true), pDv = createDiv('copyholder', true);
		var iDv = createDiv('domfixdiv', true), fDv = createDiv('zoomdetectdiv', true), stdMode = false;
		pDv.sY.border = '1px solid blue'; pDv.fHide();
		dDv.style.overflow = 'hidden';
		fDv.sY.fontSize = "12px"; fDv.sY.height = "1em";
		fDv.sY.width = "1em"; 
		fDv.sY.position = "absolute"; 
		fDv.sY.zIndex = "-999"; fDv.fHide();
		var brdHeight = dDv.offsetHeight, brdWidth = dDv.offsetWidth;
		copyStyles(dDv, pDv, '0px', ['border-left-width', 'border-right-width', 'border-top-width', 'border-bottom-width']);
		var intlHeight = dDv.offsetHeight, intlWidth = dDv.offsetWidth, brdWidthLoss = brdWidth - intlWidth, brdHeightLoss = brdHeight - intlHeight;
		var oScrollY = (dDv.scrollTop) ? dDv.scrollTop : 0, oScrollX = (dDv.scrollLeft) ? dDv.scrollLeft : 0;
		var urlBase = document.location.href, uReg = /#([^#.]*)$/;
		var focusProtectList = ['textarea', 'input', 'select'];
		sC.scroller = []; sC.forcedBar = []; sC.containerSize = sC.cntRSize = []; sC.contentSize = sC.cntSize = []; sC.edge = [false, false];
		sC.reqS = []; sC.barSpace = [0, 0]; sC.forcedHide = []; sC.forcedPos = []; sC.paddings = [];
		while (dDv.firstChild) { cDv.appendChild(dDv.firstChild) };
		cDv.appendChild(iDv); dDv.appendChild(mDv); dDv.appendChild(pDv);
		if (getStyle(dDv, 'position') != 'absolute') 
		    dDv.style.position = "relative";

		var dAlign = getStyle(dDv, 'text-align'); dDv.style.textAlign = 'left';
		mDv.sY.width = "100px"; mDv.sY.height = "100px"; mDv.sY.top = "0px"; mDv.sY.left = "0px";
		copyStyles(dDv, pDv, "0px", ['padding-left', 'padding-top', 'padding-right', 'padding-bottom']);
		var postWidth = dDv.offsetWidth, postHeight = dDv.offsetHeight, mHeight;
		mHeight = mDv.offsetHeight; mDv.sY.borderBottom = "2px solid black";
		if (mDv.offsetHeight > mHeight) stdMode = true; mDv.sY.borderBottomWidth = "0px";
		copyStyles(pDv, dDv, false, ['padding-left', 'padding-top', 'padding-right', 'padding-bottom']);
		findPos(mDv); findPos(dDv);
		sC.paddings[0] = mDv.yPos - dDv.yPos; sC.paddings[2] = mDv.xPos - dDv.xPos;
		dDv.style.paddingTop = getStyle(dDv, "padding-bottom"); dDv.style.paddingLeft = getStyle(dDv, "padding-right");
		findPos(mDv); findPos(dDv);
		sC.paddings[1] = mDv.yPos - dDv.yPos; sC.paddings[3] = mDv.xPos - dDv.xPos;
		dDv.style.paddingTop = getStyle(pDv, "padding-top"); dDv.style.paddingLeft = getStyle(pDv, "padding-left");
		var padWidthComp = sC.paddings[2] + sC.paddings[3], padHeightComp = sC.paddings[0] + sC.paddings[1];

		mDv.style.textAlign = dAlign;
		copyStyles(dDv, mDv, false, ['padding-left', 'padding-right', 'padding-top', 'padding-bottom']);
		tDv.sY.width = dDv.offsetWidth + 'px'; tDv.sY.height = dDv.offsetHeight + 'px';
		mDv.sY.width = postWidth + 'px'; mDv.sY.height = postHeight + 'px';
		tDv.sY.position = 'absolute';
		tDv.sY.top = '0px'; 
		tDv.sY.left = '0px';
		//tDv.fHide();

		mDv.appendChild(cDv); dDv.appendChild(tDv); tDv.appendChild(fDv);

		cDv.sY.position = 'relative'; 
		mDv.sY.position = 'relative';
		cDv.sY.top = "0"; cDv.sY.width = "100%"; //fix IE7
		mDv.sY.overflow = 'hidden';
		mDv.sY.left = "-" + sC.paddings[2] + "px";
		mDv.sY.top = "-" + sC.paddings[0] + "px";
		sC.zTHeight = fDv.offsetHeight;

		sC.getContentWidth = function() {
			var cChilds = cDv.childNodes, maxCWidth = compPad = 0;
			for (var i = 0; i < cChilds.length; i++) { if (cChilds[i].offsetWidth) { maxCWidth = Math.max(cChilds[i].offsetWidth, maxCWidth) } };
			sC.cntRSize[0] = ((sC.reqS[1] && !sC.forcedHide[1]) || sC.forcedBar[1]) ? dDv.offsetWidth - sC.barSpace[0] : dDv.offsetWidth;
			sC.cntSize[0] = maxCWidth + padWidthComp;
			return sC.cntSize[0];
		};
		sC.getContentHeight = function() {
			sC.cntRSize[1] = ((sC.reqS[0] && !sC.forcedHide[0]) || sC.forcedBar[0]) ? dDv.offsetHeight - sC.barSpace[1] : dDv.offsetHeight;
			sC.cntSize[1] = cDv.offsetHeight + padHeightComp - 2;
			return sC.cntSize[1];
		};

		sC.fixIEDispBug = function() { cDv.sY.display = 'none'; cDv.sY.display = 'block'; };
		sC.setWidth = function() { mDv.sY.width = (stdMode) ? (sC.cntRSize[0] - padWidthComp - brdWidthLoss) + 'px' : sC.cntRSize[0] + 'px'; };
		sC.setHeight = function() { mDv.sY.height = (stdMode) ? (sC.cntRSize[1] - padHeightComp - brdHeightLoss) + 'px' : sC.cntRSize[1] + 'px'; };

		sC.createScrollBars = function() {
			sC.getContentWidth(); sC.getContentHeight();
			//vert
			tDv.vrt = new Array(); var vrT = tDv.vrt;
			createScrollBars(vrT, 'vscroller');
			vrT.barPadding = [parseInt(getStyle(vrT.sBr, 'padding-top')), parseInt(getStyle(vrT.sBr, 'padding-bottom'))];
			vrT.sBr.sY.padding = '0px'; vrT.sBr.curPos = 0; vrT.sBr.vertical = true;
			vrT.sBr.indx = 1; cDv.vBar = vrT.sBr;
			prepareScroll(vrT, 0); sC.barSpace[0] = vrT.sDv.offsetWidth; sC.setWidth();
			//horiz
			tDv.hrz = new Array(); var hrZ = tDv.hrz;
			createScrollBars(hrZ, 'hscroller');
			hrZ.barPadding = [parseInt(getStyle(hrZ.sBr, 'padding-left')), parseInt(getStyle(hrZ.sBr, 'padding-right'))];
			hrZ.sBr.sY.padding = '0px'; hrZ.sBr.curPos = 0; hrZ.sBr.vertical = false;
			hrZ.sBr.indx = 0; cDv.hBar = hrZ.sBr;
			if (wD.opera) 
			    hrZ.sBr.sY.position = 'relative';
			prepareScroll(hrZ, 0);
			sC.barSpace[1] = hrZ.sDv.offsetHeight; sC.setHeight();
			tDv.sY.height = dDv.offsetHeight + 'px';
			// jog
			hrZ.jBox = createDiv('scrollerjogbox');
			tDv.appendChild(hrZ.jBox); hrZ.jBox.onmousedown = function() {
				hrZ.sBr.scrollBoth = true; sC.goScroll = hrZ.sBr; hrZ.sBr.clicked = true;
				hrZ.sBr.moved = false; tDv.vrt.sBr.moved = false;
				fleXenv.addTrggr(dC, 'selectstart', retFalse); fleXenv.addTrggr(dC, 'mousemove', mMoveBar); fleXenv.addTrggr(dC, 'mouseup', mMouseUp);
				return false;
			};
		};

		sC.goScroll = null;
		sC.createScrollBars();
		cDv.removeChild(iDv);

		if (!this.addChckTrggr(dDv, 'mousewheel', mWheelProc) || !this.addChckTrggr(dDv, 'DOMMouseScroll', mWheelProc)) { dDv.onmousewheel = mWheelProc; };
		this.addChckTrggr(dDv, 'mousewheel', mWheelProc);
		this.addChckTrggr(dDv, 'DOMMouseScroll', mWheelProc);
		dDv.setAttribute('tabIndex', '0');

		this.addTrggr(dDv, 'keydown', function(e) {
			if (dDv.focusProtect) return;
			if (!e) { var e = wD.event; }; var pK = e.keyCode; sC.pkeY = pK;
			sC.mDPosFix();
			if (sC.keyAct['_' + pK] && !window.opera) { dDv.contentScroll(sC.keyAct['_' + pK][0], sC.keyAct['_' + pK][1], true); if (e.preventDefault) e.preventDefault(); return false; };
		});
		this.addTrggr(dDv, 'keypress', function(e) {//make Opera Happy
			if (dDv.focusProtect) return;
			if (!e) { var e = wD.event; }; var pK = e.keyCode;
			if (sC.keyAct['_' + pK]) { dDv.contentScroll(sC.keyAct['_' + pK][0], sC.keyAct['_' + pK][1], true); if (e.preventDefault) e.preventDefault(); return false; };
		});

		this.addTrggr(dDv, 'keyup', function() { sC.pkeY = false });

		this.addTrggr(dC, 'mouseup', intClear);
		this.addTrggr(dDv, 'mousedown', function(e) {
			if (!e) e = wD.event;
			var cTrgt = (e.target) ? e.target : (e.srcElement) ? e.srcElement : false;
			if (!cTrgt || (cTrgt.className && cTrgt.className.match(RegExp("\\bscrollgeneric\\b")))) return;
			sC.inMposX = e.clientX; sC.inMposY = e.clientY;
			pageScrolled(); findPos(dDv); intClear();
			fleXenv.addTrggr(dC, 'mousemove', tSelectMouse);
			sC.mTBox = [dDv.xPos + 10, dDv.xPos + sC.cntRSize[0] - 10, dDv.yPos + 10, dDv.yPos + sC.cntRSize[1] - 10];
		});

		function tSelectMouse(e) {
			if (!e) e = wD.event;
			var mX = e.clientX, mY = e.clientY, mdX = mX + sC.xScrld, mdY = mY + sC.yScrld;
			sC.mOnXEdge = (mdX < sC.mTBox[0] || mdX > sC.mTBox[1]) ? 1 : 0;
			sC.mOnYEdge = (mdY < sC.mTBox[2] || mdY > sC.mTBox[3]) ? 1 : 0;
			sC.xAw = mX - sC.inMposX; sC.yAw = mY - sC.inMposY;
			sC.sXdir = (sC.xAw > 40) ? 1 : (sC.xAw < -40) ? -1 : 0; sC.sYdir = (sC.yAw > 40) ? 1 : (sC.yAw < -40) ? -1 : 0;
			if ((sC.sXdir != 0 || sC.sYdir != 0) && !sC.tSelectFunc) sC.tSelectFunc = wD.setInterval(function() {
				if (sC.sXdir == 0 && sC.sYdir == 0) { wD.clearInterval(sC.tSelectFunc); sC.tSelectFunc = false; return; }; pageScrolled();
				if (sC.mOnXEdge == 1 || sC.mOnYEdge == 1) dDv.contentScroll((sC.sXdir * sC.mOnXEdge) + "s", (sC.sYdir * sC.mOnYEdge) + "s", true);
			}, 45)
		};
		function intClear() {
			fleXenv.remTrggr(dC, 'mousemove', tSelectMouse); if (sC.tSelectFunc) wD.clearInterval(sC.tSelectFunc); sC.tSelectFunc = false;
			if (sC.barClickRetard) wD.clearTimeout(sC.barClickRetard); if (sC.barClickScroll) wD.clearInterval(sC.barClickScroll);
		};
		function pageScrolled() {
			sC.xScrld = (wD.pageXOffset) ? wD.pageXOffset : (dC.documentElement && dC.documentElement.scrollLeft) ? dC.documentElement.scrollLeft : 0;
			sC.yScrld = (wD.pageYOffset) ? wD.pageYOffset : (dC.documentElement && dC.documentElement.scrollTop) ? dC.documentElement.scrollTop : 0;
		};

		dDv.scrollUpdate = function(recurse) {
			tDv.fShow();
			if (tDv.getSize[1]() === 0 || tDv.getSize[0]() === 0) return;
			cDv.sY.padding = '1px'; var reqH = sC.reqS[0], reqV = sC.reqS[1], vBr = tDv.vrt, hBr = tDv.hrz, vUpReq, hUpReq, cPSize = [];
			tDv.sY.width = dDv.offsetWidth - brdWidthLoss + 'px'; tDv.sY.height = dDv.offsetHeight - brdHeightLoss + 'px';
			cPSize[0] = sC.cntRSize[0]; cPSize[1] = sC.cntRSize[1];
			sC.reqS[0] = sC.getContentWidth() > sC.cntRSize[0];
			sC.reqS[1] = sC.getContentHeight() > sC.cntRSize[1];
			var stateChange = (reqH != sC.reqS[0] || reqV != sC.reqS[1] || cPSize[0] != sC.cntRSize[0] || cPSize[1] != sC.cntRSize[1]) ? true : false;
			vBr.sDv.setVisibility(sC.reqS[1]); hBr.sDv.setVisibility(sC.reqS[0]);
			vUpReq = (sC.reqS[1] || sC.forcedBar[1]); hUpReq = (sC.reqS[0] || sC.forcedBar[0]);
			sC.getContentWidth(); sC.getContentHeight(); sC.setHeight(); sC.setWidth();
			if (!sC.reqS[0] || !sC.reqS[1] || sC.forcedHide[0] || sC.forcedHide[1]) hBr.jBox.fHide();
			else hBr.jBox.fShow();
			if (vUpReq) updateScroll(vBr, (hUpReq && !sC.forcedHide[0]) ? sC.barSpace[1] : 0); else cDv.sY.top = "0";
			if (hUpReq) updateScroll(hBr, (vUpReq && !sC.forcedHide[1]) ? sC.barSpace[0] : 0); else cDv.sY.left = "0";
			if (stateChange && !recurse) dDv.scrollUpdate(true);
			cDv.sY.padding = '0px';
			sC.edge[0] = sC.edge[1] = false;
		};

		dDv.commitScroll = dDv.contentScroll = function(xPos, yPos, relative) {
			var reT = [[false, false], [false, false]], Bar;
			if ((xPos || xPos === 0) && sC.scroller[0]) { xPos = calcCScrollVal(xPos, 0); Bar = tDv.hrz.sBr; Bar.trgtScrll = (relative) ? Math.min(Math.max(Bar.mxScroll, Bar.trgtScrll - xPos), 0) : -xPos; Bar.contentScrollPos(); reT[0] = [-Bar.trgtScrll - Bar.targetSkew, -Bar.mxScroll] }
			if ((yPos || yPos === 0) && sC.scroller[1]) { yPos = calcCScrollVal(yPos, 1); Bar = tDv.vrt.sBr; Bar.trgtScrll = (relative) ? Math.min(Math.max(Bar.mxScroll, Bar.trgtScrll - yPos), 0) : -yPos; Bar.contentScrollPos(); reT[1] = [-Bar.trgtScrll - Bar.targetSkew, -Bar.mxScroll] }
			if (!relative) sC.edge[0] = sC.edge[1] = false;
			return reT;
		};

		dDv.scrollToElement = function(tEM) {
			if (tEM == null || !isddvChild(tEM)) return;
			var sPos = findRCpos(tEM);
			dDv.contentScroll(sPos[0] + sC.paddings[2], sPos[1] + sC.paddings[0], false);
			dDv.contentScroll(0, 0, true);
		};

		copyStyles(pDv, dDv, '0px', ['border-left-width', 'border-right-width', 'border-top-width', 'border-bottom-width']);

		dDv.removeChild(pDv);
		dDv.scrollTop = 0; dDv.scrollLeft = 0;
		dDv.fleXcroll = true;
		classChange(dDv, 'flexcrollactive', false);
		dDv.scrollUpdate();
		dDv.contentScroll(oScrollX, oScrollY, true);
		if (urlBase.match(uReg)) { dDv.scrollToElement(dC.getElementById(urlBase.match(uReg)[1])); };
		//tDv.fShow();

		sC.sizeChangeDetect = wD.setInterval(function() {
			var n = fDv.offsetHeight; if (n != sC.zTHeight) { dDv.scrollUpdate(); sC.zTHeight = n };
		}, 2500);

		function calcCScrollVal(v, i) {
			var stR = v.toString(); v = parseFloat(stR);
			return parseInt((stR.match(/p$/)) ? v * sC.cntRSize[i] * 0.9 : (stR.match(/s$/)) ? v * sC.cntRSize[i] * 0.1 : v);
		}
		function camelConv(spL) {
			var spL = spL.split('-'), reT = spL[0], i;
			for (i = 1; parT = spL[i]; i++) { reT += parT.charAt(0).toUpperCase() + parT.substr(1); }
			return reT;
		}
		function getStyle(elem, style) {
			if (wD.getComputedStyle) return wD.getComputedStyle(elem, null).getPropertyValue(style);
			if (elem.currentStyle) return elem.currentStyle[camelConv(style)];
			return false;
		};

		function copyStyles(src, dest, replaceStr, sList) {
			var camelList = new Array();
			for (var i = 0; i < sList.length; i++) {
				camelList[i] = camelConv(sList[i]);
				dest.style[camelList[i]] = getStyle(src, sList[i], camelList[i]);
				if (replaceStr) src.style[camelList[i]] = replaceStr;
			}
		};
		function createDiv(typeName, noGenericClass) {
			var nDiv = dC.createElement('div'); //,pTx=dC.createTextNode('\u00a0');
			nDiv.id = targetId + '_' + typeName;
			nDiv.className = (noGenericClass) ? typeName : typeName + ' scrollgeneric';
			nDiv.getSize = [function() { return nDiv.offsetWidth; }, function() { return nDiv.offsetHeight; } ];
			nDiv.setSize = [function(sVal) { nDiv.sY.width = sVal; }, function(sVal) { nDiv.sY.height = sVal; } ];
			nDiv.getPos = [function() { return getStyle(nDiv, "left"); }, function() { return getStyle(nDiv, "top"); } ];
			nDiv.setPos = [function(sVal) { nDiv.sY.left = sVal; }, function(sVal) { nDiv.sY.top = sVal; } ];
			nDiv.fHide = function() { nDiv.sY.visibility = "hidden" };
			nDiv.fShow = function(coPy) { nDiv.sY.visibility = (coPy) ? getStyle(coPy, 'visibility') : "visible" };
			nDiv.sY = nDiv.style;
			//	if(!noGenericClass) nDiv.appendChild(pTx);
			return nDiv;

		};
		function createScrollBars(ary, bse) {
			ary.sDv = createDiv(bse + 'base'); ary.sFDv = createDiv(bse + 'basebeg');
			ary.sSDv = createDiv(bse + 'baseend'); ary.sBr = createDiv(bse + 'bar');
			ary.sFBr = createDiv(bse + 'barbeg'); ary.sSBr = createDiv(bse + 'barend');
			tDv.appendChild(ary.sDv); ary.sDv.appendChild(ary.sBr);
			ary.sDv.appendChild(ary.sFDv); ary.sDv.appendChild(ary.sSDv);
			ary.sBr.appendChild(ary.sFBr); ary.sBr.appendChild(ary.sSBr);
		};
		function prepareScroll(bAr, reqSpace) {
			var sDv = bAr.sDv, sBr = bAr.sBr, i = sBr.indx;
			sBr.minPos = bAr.barPadding[0];
			sBr.ofstParent = sDv;
			sBr.mDv = mDv;
			sBr.scrlTrgt = cDv;
			sBr.targetSkew = 0;
			updateScroll(bAr, reqSpace, true);

			sBr.doScrollPos = function() {
				sBr.curPos = (Math.min(Math.max(sBr.curPos, 0), sBr.maxPos));
				sBr.trgtScrll = parseInt((sBr.curPos / sBr.sRange) * sBr.mxScroll);
				sBr.targetSkew = (sBr.curPos == 0) ? 0 : (sBr.curPos == sBr.maxPos) ? 0 : sBr.targetSkew;
				sBr.setPos[i](sBr.curPos + sBr.minPos + "px");
				cDv.setPos[i](sBr.trgtScrll + sBr.targetSkew + "px");
			};

			sBr.contentScrollPos = function() {
				sBr.curPos = parseInt((sBr.trgtScrll * sBr.sRange) / sBr.mxScroll);
				sBr.targetSkew = sBr.trgtScrll - parseInt((sBr.curPos / sBr.sRange) * sBr.mxScroll);
				sBr.curPos = (Math.min(Math.max(sBr.curPos, 0), sBr.maxPos));
				sBr.setPos[i](sBr.curPos + sBr.minPos + "px");
				sBr.setPos[i](sBr.curPos + sBr.minPos + "px");
				cDv.setPos[i](sBr.trgtScrll + "px");
			};

			sC.barZ = getStyle(sBr, 'z-index');
			sBr.sY.zIndex = (sC.barZ == "auto" || sC.barZ == "0" || sC.barZ == 'normal') ? 2 : sC.barZ;
			mDv.sY.zIndex = getStyle(sBr, 'z-index');

			sBr.onmousedown = function() {
				sBr.clicked = true; sC.goScroll = sBr; sBr.scrollBoth = false; sBr.moved = false;
				fleXenv.addTrggr(dC, 'selectstart', retFalse);
				fleXenv.addTrggr(dC, 'mousemove', mMoveBar);
				fleXenv.addTrggr(dC, 'mouseup', mMouseUp);
				return false;
			};

			sBr.onmouseover = intClear;

			sDv.onmousedown = sDv.ondblclick = function(e) {
				if (!e) { var e = wD.event; }
				if (e.target && (e.target == bAr.sFBr || e.target == bAr.sSBr || e.target == bAr.sBr)) return;
				if (e.srcElement && (e.srcElement == bAr.sFBr || e.srcElement == bAr.sSBr || e.srcElement == bAr.sBr)) return;
				var relPos, mV = []; pageScrolled();
				sC.mDPosFix();
				findPos(sBr);
				relPos = (sBr.vertical) ? e.clientY + sC.yScrld - sBr.yPos : e.clientX + sC.xScrld - sBr.xPos;
				mV[sBr.indx] = (relPos < 0) ? sC.baseAct[0] : sC.baseAct[1]; mV[1 - sBr.indx] = 0;
				dDv.contentScroll(mV[0], mV[1], true);
				if (e.type != "dblclick") {
					intClear();
					sC.barClickRetard = wD.setTimeout(function() {
						sC.barClickScroll = wD.setInterval(function() {
							dDv.contentScroll(mV[0], mV[1], true);
						}, 80)
					}, 425);
				}
				return false;
			};
			sDv.setVisibility = function(r) {
				if (r) {
					sDv.fShow(dDv);
					sC.forcedHide[i] = (getStyle(sDv, "visibility") == "hidden") ? true : false;
					if (!sC.forcedHide[i]) sBr.fShow(dDv); else sBr.fHide();
					sC.scroller[i] = true; classChange(sDv, "", "flexinactive");
				}
				else {
					sDv.fHide(); sBr.fHide();
					sC.forcedBar[i] = (getStyle(sDv, "visibility") != "hidden") ? true : false;
					sC.scroller[i] = false; sBr.curPos = 0; cDv.setPos[i]('0px');
					classChange(sDv, "flexinactive", "");
				}
				mDv.setPos[1 - i]((sC.forcedPos[i] && (r || sC.forcedBar[i]) && !sC.forcedHide[i]) ? sC.barSpace[1 - i] - sC.paddings[i * 2] + "px" : "-" + sC.paddings[i * 2] + "px");
			};
			sDv.onmouseclick = retFalse;
		};

		function updateScroll(bAr, reqSpace, firstRun) {
			var sDv = bAr.sDv, sBr = bAr.sBr, sFDv = bAr.sFDv, sFBr = bAr.sFBr, sSDv = bAr.sSDv, sSBr = bAr.sSBr, i = sBr.indx;
			sDv.setSize[i](tDv.getSize[i]() - reqSpace + 'px'); sDv.setPos[1 - i](tDv.getSize[1 - i]() - sDv.getSize[1 - i]() + 'px');
			sC.forcedPos[i] = (parseInt(sDv.getPos[1 - i]()) === 0) ? true : false;
			bAr.padLoss = bAr.barPadding[0] + bAr.barPadding[1]; bAr.baseProp = parseInt((sDv.getSize[i]() - bAr.padLoss) * 0.75);
			sBr.aSize = Math.min(Math.max(Math.min(parseInt(sC.cntRSize[i] / sC.cntSize[i] * sDv.getSize[i]()), bAr.baseProp), 45), bAr.baseProp);
			sBr.setSize[i](sBr.aSize + 'px'); sBr.maxPos = sDv.getSize[i]() - sBr.getSize[i]() - bAr.padLoss;
			sBr.curPos = Math.min(Math.max(0, sBr.curPos), sBr.maxPos);
			sBr.setPos[i](sBr.curPos + sBr.minPos + 'px'); sBr.mxScroll = mDv.getSize[i]() - sC.cntSize[i];
			sBr.sRange = sBr.maxPos;
			sFDv.setSize[i](sDv.getSize[i]() - sSDv.getSize[i]() + 'px');
			sFBr.setSize[i](sBr.getSize[i]() - sSBr.getSize[i]() + 'px');
			sSBr.setPos[i](sBr.getSize[i]() - sSBr.getSize[i]() + 'px');
			sSDv.setPos[i](sDv.getSize[i]() - sSDv.getSize[i]() + 'px');
			if (!firstRun) sBr.doScrollPos();
			sC.fixIEDispBug();
		};

		sC.mDPosFix = function() { mDv.scrollTop = 0; mDv.scrollLeft = 0; dDv.scrollTop = 0; dDv.scrollLeft = 0; };

		this.addTrggr(wD, 'load', function() { if (dDv.fleXcroll) dDv.scrollUpdate(); });
		this.addTrggr(wD, 'resize', function() {
			if (dDv.refreshTimeout) wD.clearTimeout(dDv.refreshTimeout);
			dDv.refreshTimeout = wD.setTimeout(function() { if (dDv.fleXcroll) dDv.scrollUpdate(); }, 80);
		});

		for (var j = 0, inputName; inputName = focusProtectList[j]; j++) {
			var inputList = dDv.getElementsByTagName(inputName);
			for (var i = 0, formItem; formItem = inputList[i]; i++) {
				fleXenv.addTrggr(formItem, 'focus', function() { dDv.focusProtect = true; });
				fleXenv.addTrggr(formItem, 'blur', onblur = function() { dDv.focusProtect = false; });
			} 
		};

		function retFalse() { return false; };
		function mMoveBar(e) {
			if (!e) { var e = wD.event; };
			var FCBar = sC.goScroll, movBr, maxx, xScroll, yScroll;
			if (FCBar == null) return;
			if (!fleXenv.w3events && !e.button) mMouseUp();
			maxx = (FCBar.scrollBoth) ? 2 : 1;
			for (var i = 0; i < maxx; i++) {
				movBr = (i == 1) ? FCBar.scrlTrgt.vBar : FCBar;
				if (FCBar.clicked) {
					if (!movBr.moved) {
						sC.mDPosFix();
						findPos(movBr); findPos(movBr.ofstParent); movBr.pointerOffsetY = e.clientY - movBr.yPos;
						movBr.pointerOffsetX = e.clientX - movBr.xPos; movBr.inCurPos = movBr.curPos; movBr.moved = true;
					};
					movBr.curPos = (movBr.vertical) ? e.clientY - movBr.pointerOffsetY - movBr.ofstParent.yPos - movBr.minPos : e.clientX - movBr.pointerOffsetX - movBr.ofstParent.xPos - movBr.minPos;
					if (FCBar.scrollBoth) movBr.curPos = movBr.curPos + (movBr.curPos - movBr.inCurPos);
					movBr.doScrollPos();
				} else movBr.moved = false;
			};
		};

		function mMouseUp() {
			if (sC.goScroll != null) { sC.goScroll.clicked = false; }
			sC.goScroll = null;
			fleXenv.remTrggr(dC, 'selectstart', retFalse);
			fleXenv.remTrggr(dC, 'mousemove', mMoveBar);
			fleXenv.remTrggr(dC, 'mouseup', mMouseUp);
		};

		function mWheelProc(e) {
			if (!e) e = wD.event;
			if (!this.fleXcroll) return;
			var scrDv = this, vEdge, hEdge, hoverH = false, delta = 0, iNDx;
			sC.mDPosFix();
			hElem = (e.target) ? e.target : (e.srcElement) ? e.srcElement : this;
			if (hElem.id && hElem.id.match(/_hscroller/)) hoverH = true;
			if (e.wheelDelta) delta = -e.wheelDelta; if (e.detail) delta = e.detail;
			delta = (delta < 0) ? -1 : +1; iNDx = (delta < 0) ? 0 : 1; sC.edge[1 - iNDx] = false;
			if ((sC.edge[iNDx] && !hoverH) || (!sC.scroller[0] && !sC.scroller[1])) return;
			if (sC.scroller[1] && !hoverH) scrollState = dDv.contentScroll(false, sC.wheelAct[iNDx], true);
			vEdge = !sC.scroller[1] || hoverH || (sC.scroller[1] && ((scrollState[1][0] == scrollState[1][1] && delta > 0) || (scrollState[1][0] == 0 && delta < 0)));
			if (sC.scroller[0] && (!sC.scroller[1] || hoverH)) scrollState = dDv.contentScroll(sC.wheelAct[iNDx], false, true);
			hEdge = !sC.scroller[0] || (sC.scroller[0] && sC.scroller[1] && vEdge && !hoverH) || (sC.scroller[0] && ((scrollState[0][0] == scrollState[0][1] && delta > 0) || (scrollState[0][0] == 0 && delta < 0)));
			if (vEdge && hEdge && !hoverH) sC.edge[iNDx] = true; else sC.edge[iNDx] = false;
			if (e.preventDefault) e.preventDefault();
			return false;
		};

		function isddvChild(elem) { while (elem.parentNode) { elem = elem.parentNode; if (elem == dDv) return true; } return false; };

		function findPos(elem) {
			//modified from firetree.net
			var obj = elem, curleft = curtop = 0;
			var monc = "";
			if (obj.offsetParent) { while (obj) { curleft += obj.offsetLeft; curtop += obj.offsetTop; obj = obj.offsetParent; monc += curtop + " "; } }
			else if (obj.x) { curleft += obj.x; curtop += obj.y; }
			elem.xPos = curleft; elem.yPos = curtop;
		};

		function findRCpos(elem) {
			var obj = elem; curleft = curtop = 0;
			while (!obj.offsetHeight && obj.parentNode && obj != cDv && getStyle(obj, 'display') == "inline") { obj = obj.parentNode; }
			if (obj.offsetParent) { while (obj != cDv) { curleft += obj.offsetLeft; curtop += obj.offsetTop; obj = obj.offsetParent; } }
			return [curleft, curtop];
		};

		function classChange(elem, addClass, remClass) {
			if (!elem.className) elem.className = '';
			var clsnm = elem.className;
			if (addClass && !clsnm.match(RegExp("(^|\\s)" + addClass + "($|\\s)"))) clsnm = clsnm.replace(/(\S$)/, '$1 ') + addClass;
			if (remClass) clsnm = clsnm.replace(RegExp("((^|\\s)+" + remClass + ")+($|\\s)", "g"), '$2').replace(/\s$/, '');
			elem.className = clsnm;
		};
	},
	//main code end
	globalInit: function() {
		if (fleXenv.catchFastInit) window.clearInterval(fleXenv.catchFastInit);
		var regg = /#([^#.]*)$/, urlExt = /(.*)#.*$/, matcH, i, anchoR, anchorList = document.getElementsByTagName("a"), urlBase = document.location.href;
		if (urlBase.match(urlExt)) urlBase = urlBase.match(urlExt)[1];
		for (i = 0; anchoR = anchorList[i]; i++) {
			if (anchoR.href && anchoR.href.match(regg) && anchoR.href.match(urlExt) && urlBase === anchoR.href.match(urlExt)[1]) {
				anchoR.fleXanchor = true;
				fleXenv.addTrggr(anchoR, 'click', function(e) {
					if (!e) e = window.event;
					var clickeD = (e.srcElement) ? e.srcElement : this;
					while (!clickeD.fleXanchor && clickeD.parentNode) { clickeD = clickeD.parentNode };
					if (!clickeD.fleXanchor) return;
					var tEL = document.getElementById(clickeD.href.match(regg)[1]), eScroll = false;
					if (tEL == null) tEL = (tEL = document.getElementsByName(clickeD.href.match(regg)[1])[0]) ? tEL : null;
					if (tEL != null) {
						var elem = tEL;
						while (elem.parentNode) {
							elem = elem.parentNode; if (elem.scrollToElement) {
								elem.scrollToElement(tEL); eScroll = elem;
							};
						};
						if (eScroll) { if (e.preventDefault) e.preventDefault(); document.location.href = "#" + clickeD.href.match(regg)[1]; eScroll.fleXdata.mDPosFix(); return false; }
					};
				});
			};
		};
		fleXenv.initByClass();
		if (window.onfleXcrollRun) window.onfleXcrollRun();
	},

	initByClass: function() {
		if (fleXenv.initialized) return;
		fleXenv.initialized = true;
		var fleXlist = fleXenv.getByClassName(document.getElementsByTagName("body")[0], "div", 'flexcroll');
		for (var i = 0, tgDiv; tgDiv = fleXlist[i]; i++) fleXenv.fleXcrollMain(tgDiv);
	},

	getByClassName: function(elem, elType, classString) {
		//v1.1fleX
		if (typeof (elem) == 'string') elem = document.getElementById(elem);
		if (elem == null) return false;
		var regExer = new RegExp("(^|\\s)" + classString + "($|\\s)"), clsnm, retArray = [], key = 0;
		var elems = elem.getElementsByTagName(elType);
		for (var i = 0, pusher; pusher = elems[i]; i++) {
			if (pusher.className && pusher.className.match(regExer)) {
				retArray[key] = pusher; key++;
			}
		};
		return retArray;
	},

	catchFastInit: window.setInterval(function() {
		var dElem = document.getElementById('flexcroll-init');
		if (dElem != null) { fleXenv.initByClass(); window.clearInterval(fleXenv.catchFastInit); }
	}, 100),

	addTrggr: function(elm, eventname, func) { if (!fleXenv.addChckTrggr(elm, eventname, func) && elm.attachEvent) { elm.attachEvent('on' + eventname, func); } },

	addChckTrggr: function(elm, eventname, func) { if (elm.addEventListener) { elm.addEventListener(eventname, func, false); fleXenv.w3events = true; window.addEventListener("unload", function() { fleXenv.remTrggr(elm, eventname, func) }, false); return true; } else return false; },

	remTrggr: function(elm, eventname, func) { if (!fleXenv.remChckTrggr(elm, eventname, func) && elm.detachEvent) elm.detachEvent('on' + eventname, func); },

	remChckTrggr: function(elm, eventname, func) { if (elm.removeEventListener) { elm.removeEventListener(eventname, func, false); return true; } else return false; }

};

function CSBfleXcroll(targetId) { fleXenv.fleXcrollMain(targetId) };
fleXenv.fleXcrollInit();
//** Chrome Drop Down Menu- Author: Dynamic Drive (http://www.dynamicdrive.com)

//** Updated: July 14th 06' to v2.0
	//1) Ability to "left", "center", or "right" align the menu items easily, just by modifying the CSS property "text-align".
	//2) Added an optional "swipe down" transitional effect for revealing the drop down menus.
	//3) Support for multiple Chrome menus on the same page.

//** Updated: Nov 14th 06' to v2.01- added iframe shim technique

//** Updated: July 23rd, 08 to v2.4
	//1) Main menu items now remain "selected" (CSS class "selected" applied) when user moves mouse into corresponding drop down menu. 
	//2) Adds ability to specify arbitrary HTML that gets added to the end of each menu item that carries a drop down menu (ie: a down arrow image).
	//3) All event handlers added to the menu are now unobstrusive, allowing you to define your own "onmouseover" or "onclick" events on the menu items.
	//4) Fixed elusive JS error in FF that sometimes occurs when mouse quickly moves between main menu items and drop down menus

//** Updated: Oct 29th, 08 to v2.5 (only .js file modified from v2.4)
	//1) Added ability to customize reveal animation speed (# of steps)
	//2) Menu now works in IE8 beta2 (a valid doctype at the top of the page is required)

var cssdropdown = {
    disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout
    dropdownindicator: '<img src="down.gif" border="0" />', //specify full HTML to add to end of each menu item with a drop down menu
    enablereveal: [true, 8], //enable swipe effect? [true/false, steps (Number of animation steps. Integer between 1-20. Smaller=faster)]
    enableiframeshim: 1, //enable "iframe shim" in IE5.5 to IE7? (1=yes, 0=no)

    //No need to edit beyond here////////////////////////

    dropmenuobj: null, asscmenuitem: null, domsupport: document.all || document.getElementById, standardbody: null, iframeshimadded: false, revealtimers: {},

    getposOffset: function(what, offsettype) {
        var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
        var parentEl = what.offsetParent;
        while (parentEl != null) {
            totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
            parentEl = parentEl.offsetParent;
        }
        return totaloffset;
    },

    css: function(el, targetclass, action) {
        var needle = new RegExp("(^|\\s+)" + targetclass + "($|\\s+)", "ig")
        if (action == "check")
            return needle.test(el.className)
        else if (action == "remove")
            el.className = el.className.replace(needle, "")
        else if (action == "add" && !needle.test(el.className))
            el.className += " " + targetclass
    },

    showmenu: function(dropmenu, e) {
        if (this.enablereveal[0]) {
            if (!dropmenu._trueheight || dropmenu._trueheight < 10)
                dropmenu._trueheight = dropmenu.offsetHeight
            clearTimeout(this.revealtimers[dropmenu.id])
            dropmenu.style.height = dropmenu._curheight = 0
            dropmenu.style.overflow = "hidden"
            dropmenu.style.visibility = "visible"
            this.revealtimers[dropmenu.id] = setInterval(function() { cssdropdown.revealmenu(dropmenu) }, 10)
        }
        else {
            dropmenu.style.visibility = "visible"
        }
        this.css(this.asscmenuitem, "selected", "add")
    },

    revealmenu: function(dropmenu, dir) {
        var curH = dropmenu._curheight, maxH = dropmenu._trueheight, steps = this.enablereveal[1]
        if (curH < maxH) {
            var newH = Math.min(curH, maxH)
            dropmenu.style.height = newH + "px"
            dropmenu._curheight = newH + Math.round((maxH - newH) / steps) + 1
        }
        else { //if done revealing menu
            dropmenu.style.height = "auto"
            dropmenu.style.overflow = "hidden"
            clearInterval(this.revealtimers[dropmenu.id])
        }
    },

    clearbrowseredge: function(obj, whichedge) {
        var edgeoffset = 0
        if (whichedge == "rightedge") {
            var windowedge = document.all && !window.opera ? this.standardbody.scrollLeft + this.standardbody.clientWidth - 15 : window.pageXOffset + window.innerWidth - 15
            var dropmenuW = this.dropmenuobj.offsetWidth
            if (windowedge - this.dropmenuobj.x < dropmenuW)  //move menu to the left?
                edgeoffset = dropmenuW - obj.offsetWidth
        }
        else {
            var topedge = document.all && !window.opera ? this.standardbody.scrollTop : window.pageYOffset
            var windowedge = document.all && !window.opera ? this.standardbody.scrollTop + this.standardbody.clientHeight - 15 : window.pageYOffset + window.innerHeight - 18
            var dropmenuH = this.dropmenuobj._trueheight
            if (windowedge - this.dropmenuobj.y < dropmenuH) { //move up?
                edgeoffset = dropmenuH + obj.offsetHeight
                if ((this.dropmenuobj.y - topedge) < dropmenuH) //up no good either?
                    edgeoffset = this.dropmenuobj.y + obj.offsetHeight - topedge
            }
        }
        return edgeoffset
    },

    dropit: function(obj, e, dropmenuID) {
        if (this.dropmenuobj != null) //hide previous menu
            this.hidemenu() //hide menu
        this.clearhidemenu()
        this.dropmenuobj = document.getElementById(dropmenuID) //reference drop down menu
        this.asscmenuitem = obj //reference associated menu item
        this.showmenu(this.dropmenuobj, e)
        this.dropmenuobj.x = this.getposOffset(obj, "left")
        this.dropmenuobj.y = this.getposOffset(obj, "top")
        this.dropmenuobj.style.left = this.dropmenuobj.x - this.clearbrowseredge(obj, "rightedge") + "px"
        this.dropmenuobj.style.top = this.dropmenuobj.y - this.clearbrowseredge(obj, "bottomedge") + obj.offsetHeight + 1 + "px"
        this.positionshim() //call iframe shim function
    },

    positionshim: function() { //display iframe shim function
        if (this.iframeshimadded) {
            if (this.dropmenuobj.style.visibility == "visible") {
                this.shimobject.style.width = this.dropmenuobj.offsetWidth + "px"
                this.shimobject.style.height = this.dropmenuobj._trueheight + "px"
                this.shimobject.style.left = parseInt(this.dropmenuobj.style.left) + "px"
                this.shimobject.style.top = parseInt(this.dropmenuobj.style.top) + "px"
                this.shimobject.style.display = "block"
            }
        }
    },

    hideshim: function() {
        if (this.iframeshimadded)
            this.shimobject.style.display = 'none'
    },

    isContained: function(m, e) {
        var e = window.event || e
        var c = e.relatedTarget || ((e.type == "mouseover") ? e.fromElement : e.toElement)
        while (c && c != m) try { c = c.parentNode } catch (e) { c = m }
        if (c == m)
            return true
        else
            return false
    },

    dynamichide: function(m, e) {
        if (!this.isContained(m, e)) {
            this.delayhidemenu()
        }
    },

    delayhidemenu: function() {
        this.delayhide = setTimeout("cssdropdown.hidemenu()", this.disappeardelay) //hide menu
    },

    hidemenu: function() {
        this.css(this.asscmenuitem, "selected", "remove")
        this.dropmenuobj.style.visibility = 'hidden'
        this.dropmenuobj.style.left = this.dropmenuobj.style.top = "-1000px"
        this.hideshim()
    },

    clearhidemenu: function() {
        if (this.delayhide != "undefined")
            clearTimeout(this.delayhide)
    },

    addEvent: function(target, functionref, tasktype) {
        if (target.addEventListener)
            target.addEventListener(tasktype, functionref, false);
        else if (target.attachEvent)
            target.attachEvent('on' + tasktype, function() { return functionref.call(target, window.event) });
    },

    startchrome: function() {
        if (!this.domsupport)
            return
        this.standardbody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body
        for (var ids = 0; ids < arguments.length; ids++) {
            var menuitems = document.getElementById(arguments[ids]).getElementsByTagName("a")
            for (var i = 0; i < menuitems.length; i++) {
                if (menuitems[i].getAttribute("rel")) {
                    var menuItem = menuitems[i];
                    //debugger;
                    //menuItem.addClass('dropdown');
                    var relvalue = menuitems[i].getAttribute("rel");
                    var asscdropdownmenu = document.getElementById(relvalue);
                    if (asscdropdownmenu != undefined) {
                        this.addEvent(asscdropdownmenu, function() { cssdropdown.clearhidemenu() }, "mouseover")
                        this.addEvent(asscdropdownmenu, function(e) { cssdropdown.dynamichide(this, e) }, "mouseout")
                        this.addEvent(asscdropdownmenu, function() { cssdropdown.delayhidemenu() }, "click")
                        //				try{
                        //					menuitems[i].innerHTML=menuitems[i].innerHTML+" "+this.dropdownindicator
                        //				}catch(e){}
                        this.addEvent(menuitems[i], function(e) { //show drop down menu when main menu items are mouse over-ed
                            if (!cssdropdown.isContained(this, e)) {
                                var evtobj = window.event || e
                                cssdropdown.dropit(this, evtobj, this.getAttribute("rel"))
                            }
                        }, "mouseover")
                        this.addEvent(menuitems[i], function(e) { cssdropdown.dynamichide(this, e) }, "mouseout") //hide drop down menu when main menu items are mouse out
                        this.addEvent(menuitems[i], function() { cssdropdown.delayhidemenu() }, "click") //hide drop down menu when main menu items are clicked on
                    }
                }
            } //end inner for
        } //end outer for
        if (this.enableiframeshim && document.all && !window.XDomainRequest && !this.iframeshimadded) { //enable iframe shim in IE5.5 thru IE7?
            document.write('<IFRAME id="iframeshim" src="about:blank" frameBorder="0" scrolling="no" style="left:0; top:0; position:absolute; display:none;z-index:90; background: transparent;"></IFRAME>')
            this.shimobject = document.getElementById("iframeshim") //reference iframe object
            this.shimobject.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
            this.iframeshimadded = true
        }
    } //end startchrome

}/*********************
//* jQuery Multi Level CSS Menu #2- By Dynamic Drive: http://www.dynamicdrive.com/
//* Last update: Nov 7th, 08': Limit # of queued animations to minmize animation stuttering
//* Menu avaiable at DD CSS Library: http://www.dynamicdrive.com/style/
*********************/

//Specify full URL to down and right arrow images (23 is padding-right to add to top level LIs with drop downs):
var arrowimages = { down: ['downarrowclass', '/Scripts/jqueryslidemenu/down.gif', 23], right: ['/Scripts/jqueryslidemenu/rightarrowclass', 'right.gif'] }

var jqueryslidemenu = {
    animateduration: { over: 150, out: 50 }, //duration of slide in/ out animation, in milliseconds
    buildmenu: function(menuid, arrowsvar) {
        jQuery(document).ready(function($) {
            var $mainmenu = $("#" + menuid + ">ul")
            var $headers = $mainmenu.find("ul").parent()
            $headers.each(function(i) {
                var $curobj = $(this)
                var $subul = $(this).find('ul:eq(0)')
                this._dimensions = { w: this.offsetWidth, h: this.offsetHeight, subulw: $subul.outerWidth(), subulh: $subul.outerHeight() }
                this.istopheader = $curobj.parents("ul").length == 1 ? true : false
                $subul.css({ top: this.istopheader ? this._dimensions.h + "px" : 0 })
                $curobj.children("a:eq(0)").css(this.istopheader ? { paddingRight: arrowsvar.down[2]} : {}).append(
				'<img src="' + (this.istopheader ? arrowsvar.down[1] : arrowsvar.right[1])
				+ '" class="' + (this.istopheader ? arrowsvar.down[0] : arrowsvar.right[0])
				+ '" style="border:0;" />'
			)
                $curobj.hover(
				function(e) {
				    var $targetul = $(this).children("ul:eq(0)")
				    this._offsets = { left: $(this).offset().left, top: $(this).offset().top }
				    var menuleft = this.istopheader ? 0 : this._dimensions.w
				    menuleft = (this._offsets.left + menuleft + this._dimensions.subulw > $(window).width()) ? (this.istopheader ? -this._dimensions.subulw + this._dimensions.w : -this._dimensions.w) : menuleft
				    if ($targetul.queue().length <= 1) //if 1 or less queued animations
				        $targetul.css({ left: menuleft + "px", width: this._dimensions.subulw + 'px' }).slideDown(jqueryslidemenu.animateduration.over)
				},
				function(e) {
				    //debugger;

				    var $targetul = $(this).children("ul:eq(0)")
				    //$targetul.hide();
				    //debugger;
				    $targetul.slideUp(jqueryslidemenu.animateduration.out)
				}
			) //end hover
            }) //end $headers.each()
            $mainmenu.find("ul").css({ display: 'none', visibility: 'visible' })
        }) //end document.ready
    }
}

//build menu with ID="myslidemenu" on page:
﻿/*
* jQuery Timer Plugin
* http://www.evanbot.com/article/jquery-timer-plugin/23
*
* @version      1.0
* @copyright    2009 Evan Byrne (http://www.evanbot.com)
*/ 
jQuery.timer = function(time, func, callback) {
	var a = { timer: setTimeout(func, time), callback: null }
	if (typeof (callback) == 'function') { a.callback = callback; }
	return a;
};

jQuery.clearTimer = function(a) {
	clearTimeout(a.timer);
	if (typeof (a.callback) == 'function') { a.callback(); };
	return this;
};

/*
* StarRating and  BookRating
*/
var Rates = {};
Rates.IsDebug = false;
Rates.IsAuthenticated = false;
Rates.DebugDiv = null;

/*
* Activate BookRating and StarRating
*/
Rates.Rates_endRequestHandler = function(sender, args) {
$('a.RA_BookRating_Control').BookRating();
$('a.RA_StarRating_Stars').StarRating();
}

Rates.Clear = function(divObject, init) {
    for (vari = 0; vari < 6; vari = vari + 1) { divObject.removeClass(init + vari); }
}

/*
* jQuery Rate Plugin
*
* @version      1.0
* @copyright    2009 Simone Basso (http://smnbss.spaces.live.com)
* Simple Star Rating used in ReviewBook.aspx
*/
Rates.StarsSize = 70 / 5;
$.fn.StarRating = function(options) {
	if (this.length == 0)
		return this; // quick fail
	//debugger;
	if (Rates.IsDebug) {
		if (Rates.DebugDiv == null) {
			Rates.DebugDiv = jQuery(
				'<div class="RA_BookRating_Debug">' +
				'</div>');
			$('#ctl00_Box').append(Rates.DebugDiv);
		}
		$(Rates.DebugDiv).html('');
	}
	//debugger;
	this.each(function() {
		//debugger;
		var control = $(this);
		control.mousemove(function(e) {
			//debugger;
			var rating = $(this);
			var container = $(this);
			var sel = Math.floor((e.clientX - (container.position().left + 5)) / Rates.StarsSize) + 1;
			if (Rates.IsDebug) {
				$(Rates.DebugDiv).html('');
				$(Rates.DebugDiv).append(jQuery('<div>client:' + e.clientX + ' cont:' + (container.position().left + 5) + ' rate:' + sel + '</div>'));
			}
			if (sel > 0 && sel < 6) {
				Rates.Clear(rating, 'RA_StarRating_Over');
				rating.addClass('RA_StarRating_Over' + sel);
			}
			$(this).attr("Rating", sel);
		}).click(function(e) {
			//debugger;
			var rating = $(this);
			var textbox = $("#" + rating.attr("id") + "_H");
			if (Rates.IsDebug) {
				$(Rates.DebugDiv).html('');
				$(Rates.DebugDiv).append(jQuery('<div>client:' + textbox.attr("id") + '</div>'));
			}
			textbox.attr("value", $(this).attr("Rating"));
			Rates.Clear(rating, 'RA_StarRatingReadOnly_Rated');
			Rates.Clear(rating, 'RA_StarRating_Over');
			rating.addClass('RA_StarRatingReadOnly_Rated' + $(this).attr("Rating"));
		}).mouseleave(function(e) {
			//debugger;
			var rating = $(this);
			var textbox = $("#" + rating.attr("id") + "_H");
			//debugger;
			Rates.Clear(rating, 'RA_StarRatingReadOnly_Rated');
			Rates.Clear(rating, 'RA_StarRating_Over');
			rating.addClass('RA_StarRatingReadOnly_Rated' + textbox.attr("value"));
		});
	});
}
/*
* jQuery BookRating
*
* @version      1.0
* @copyright    2009 Simone Basso (http://smnbss.spaces.live.com)
*/

Rates.BookRatingSize = 55 / 5;
//Count active web service calls
Rates.ToUpdate = 0;
//Is BookRating active?
Rates.Attached = false;
//Popup div
Rates.PopupDiv = null;
$.fn.BookRating = function(options) {
    if (this.length == 0)
        return this; // quick fail

    if (Rates.IsDebug) {
        if (Rates.DebugDiv == null) {
            Rates.DebugDiv = jQuery(
			'<div class="RA_BookRating_Debug">' +
			'</div>');
            $("body").append(Rates.DebugDiv);
        }
        $(Rates.DebugDiv).html('');
    }
    //attach common components
    if (!Rates.Attached) {
        //Create the popup div
        var popupDivHTML =
            '<div class="RA_BookRating_Popup" id="RA_BookRating_Popup">\
			    <div class="RA_BookRating_Popup_Stars">\
			        <div class="RA_BookRating_Popup_Label">Rate it:</div>\
			        <a href="0" id="pr0" class="RA_BookRating_Popup_Rating RA_BookRating_Over3">&nbsp;</a>\
			    </div>\
			    <div class="RA_BookRating_Popup_Links">\
			        <a href="1" id="pl1" class="RA_BookRating_Popup_Link RA_BookRating_Popup_CurrentlyReading" status="CurrentlyReading">Currently reading</a><br />\
			        <a href="2" id="pl2" class="RA_BookRating_Popup_Link RA_BookRating_Popup_ToRead" status="ToRead">I\'d like to read this</a><br />\
			        <a href="3" id="pl3" class="RA_BookRating_Popup_Link RA_BookRating_Popup_BlackList" status="BlackList">Not interested</a>\
			        <a href="4" id="pl4" class="RA_BookRating_Popup_Link RA_BookRating_Popup_NotAssociated" status="NotAssociated">Remove from list </a>\
			    </div>\
			 </div>';
        //<a href="1" id="A1"  class="RA_BookRating_Popup_Link RA_BookRating_Popup_WriteReview" status="WriteReview">Write Review</a><br />\
        $("body").append(popupDivHTML);
        //hide the popup div when it goes out of focus
        Rates.PopupDiv = $($(".RA_BookRating_Popup")[0]);
        Rates.PopupDiv.mouseleave(function(e) {
            $(this).hide();
            return false;
        });
        //debugger;
        // BEGIN this manage stars on popup
        var poprate = $($(".RA_BookRating_Popup_Rating:first", Rates.PopupDiv)[0]);
        poprate.mousemove(function(e) {
            var control = $('#' + Rates.PopupDiv.attr("controlid"));
            var container = $(this).parent().parent();
            var rating = $(this);
            var sel = Math.floor((e.clientX - (container.position().left + 70)) / Rates.BookRatingSize) + 1;
            if (sel > 0 && sel < 6) {
                Rates.Clear(rating, 'RA_BookRating_Over');
                rating.addClass('RA_BookRating_Over' + sel);
            }
        }).mouseleave(function(e) {
            //debugger;
            var rating = $(this);
            var control = $('#' + Rates.PopupDiv.attr("controlid"));
            var rat = control.attr("rating")
            if (rat == 0) rat = 3;
            Rates.Clear(rating, 'RA_BookRating_Over');
            rating.addClass('RA_BookRating_Over' + rat);
        }).click(function(e) {
            //alert(e);
            var id = Rates.PopupDiv.attr("controlid");
            var control = $('#' + id);
            var container = $(this).parent().parent();
            var sel = Math.floor((e.clientX - (container.position().left + 70)) / Rates.BookRatingSize) + 1;
            if (sel > 0 && sel < 6) {
                control.attr("Rating", sel)
                control.attr("Status", 'Read')
                //debugger;
                var rat = {
                    ItemType: control.attr("itemtype"),
                    ObjectId: control.attr("id"),
                    ItemId: control.attr("itemid"),
                    Rating: control.attr("Rating"),
                    Relation: Rates.RelationToInt(control.attr("Status"))
                };
                Rates.ToUpdate = Rates.ToUpdate + 1;
                document.body.style.cursor = 'wait';
                //debugger;
                if (control.attr("Status") == 'Read' && control.attr("ReviewBook") != 'False') {
                    Rates.RateComplete.call(this, rat);
                } else {
                    Bookarmy.Api.SetRating(rat, Rates.RateComplete);
                }
            }
            Rates.PopupDiv.hide();
            return false;
        })
        // END this manage stars on popup

        // BEGIN this manage links on popup
        $('.RA_BookRating_Popup_Link', Rates.PopupDiv).each(function(e) {
            $(this).click(function(e1) {
                var control = $('#' + Rates.PopupDiv.attr("controlid"));
                if ($(this).attr("Status") == "WriteReview") {
                    var rat = control.attr("Rating");
                    if (rat == 0) rat = 3;
                    LightBox.ShowBoxFixSize('520px', '460px', '/Books/Boxes/ReviewBook.aspx?BookId=' + control.attr("itemid") + "&Rating=" + rat);
                    return false;
                }
                control.attr("Rating", 0)
                control.attr("Status", $(e1.target).attr("status"))
                var rat = {
                    ItemType: control.attr("itemtype"),
                    ObjectId: control.attr("id"),
                    ItemId: control.attr("itemid"),
                    Rating: 0,
                    Relation: Rates.RelationToInt(control.attr("Status"))
                };
                //debugger;
                Rates.ToUpdate = Rates.ToUpdate + 1;
                document.body.style.cursor = 'wait';
                //debugger;
                if (control.attr("Status") == 'Read' && control.attr("ReviewBook") != 'False') {
                    Rates.RateComplete.call(this, rat);
                } else {
                    Bookarmy.Api.SetRating(rat, Rates.RateComplete);
                }
                Rates.PopupDiv.hide();
                return false;
            })
        })
    }
    //attach all the buttons
    var rates = new Array();
    var count = 0;
    //debugger;
    this.each(function() {
        //debugger;
        var control = $(this);
        if (control.attr("Attached") != 'true') {
            //debugger;
            var rating = $($(this).children(".RA_BookRating_Stars")[0]);
            control.attr("id", (control.attr("id") == '') ? 'rating' + count : control.attr("id"));
            if (Rates.IsDebug) {
                $(Rates.DebugDiv).append(jQuery('<div>' + control.attr("id") + '</div>'));
            }
            rates[count] = {
                Itemtype: control.attr("itemtype"),
                Objectid: control.attr("id"),
                Itemid: control.attr("itemid")
            };
            count = count + 1;
            var myTimer = {};
            control.click(function(e) {
                //debugger;
                if (!Rates.IsAuthenticated) {
                    return LightBox.ShowLoginBox();
                }
                else {
                    //var popup = Rates.PopupDiv;
                    Rates.PopupDiv.css('top', control.position().top - 5);
                    Rates.PopupDiv.css('left', control.position().left - 70);
                    Rates.PopupDiv.attr("controlid", control.attr("id"));
                    var writeReview = $($('.RA_BookRating_Popup_WriteReview:first', Rates.PopupDiv)[0]);
                    var currentlyReading = $($('.RA_BookRating_Popup_CurrentlyReading:first', Rates.PopupDiv)[0]);
                    var toRead = $($('.RA_BookRating_Popup_ToRead:first', Rates.PopupDiv)[0]);
                    var blacklist = $($('.RA_BookRating_Popup_BlackList:first', Rates.PopupDiv)[0]);
                    var notassociated = $($('.RA_BookRating_Popup_NotAssociated:first', Rates.PopupDiv)[0]);
                    if (control.attr("Status") == 'NotAssociated') {
                        notassociated.hide();
                        blacklist.show();
                    }
                    else {
                        notassociated.show();
                        blacklist.hide();
                    }
                    Rates.PopupDiv.show();
                    var rat = control.attr("rating")
                    if (rat == 0) rat = 3;
                    var rating = $($('.RA_BookRating_Popup_Rating:first', Rates.PopupDiv)[0]);
                    Rates.Clear(rating, 'RA_BookRating_Over');
                    rating.addClass('RA_BookRating_Over' + rat);
                }
                return false;
            });
            control.attr("Attached", 'true');
        }
        else {
        }
    });
    // END this manage links on popup
    Rates.Attached = true;
    //debugger;
    Bookarmy.Api.GetRatings(rates, Rates.OnLookupComplete);
}

Rates.RateComplete = function(result) {
	Rates.ToUpdate = Rates.ToUpdate - 1;
	if (Rates.ToUpdate == 0) {
		document.body.style.cursor = '';
	}
	//debugger;
	var control = $('#' + result.ObjectId);
	var rating = $(control.children(".RA_BookRating_Stars")[0]);
	for (vari = 0; vari < 5; vari = vari + 1) {
		control.removeClass("RA_BookRating_" + Rates.RelationToString(vari * 10));
	}
	control.addClass("RA_BookRating_" + Rates.RelationToString(result.Relation));
	Rates.Clear(rating, 'RA_BookRating_Rated');
	rating.addClass('RA_BookRating_Rated' + result.Rating);
	rating.css('display', 'block');

	//debugger;
	if (control.attr("Status") == 'Read' && control.attr("ReviewBook") != 'False')
		LightBox.ShowBoxFixSize('520px', '460px', '/Books/Boxes/ReviewBook.aspx?BookId=' + control.attr("itemid") + '&Rating=' + result.Rating);

	var callback = control.attr("callback");
	if (callback != '') {
		eval(callback);
	}
}

Rates.RelationToString = function(result) {
	switch (result) {
		case 0: return 'NotAssociated'; break;
		case 10: return 'Read'; break;
		case 20: return 'ToRead'; break;
		case 30: return 'CurrentlyReading'; break;
		case 40: return 'BlackList'; break;
	}
}

Rates.RelationToInt = function(result) {
	switch (result) {
		case 'NotAssociated': return 0; break;
		case 'Read': return 10; break;
		case 'ToRead': return 20; break;
		case 'CurrentlyReading': return 30; break;
		case 'BlackList': return 40; break;
	}
}

Rates.OnLookupComplete = function(result) {
	if (Rates.IsDebug) {
		$(Rates.DebugDiv).append(jQuery('Rates.OnLookupComplete'));
	}
	//debugger;
	$(result).each(function() {
		//debugger;
		var control = $('#' + this.ObjectId);
		if (Rates.IsDebug) {
			$(Rates.DebugDiv).append(jQuery('<div>set rate ' + control.attr("id") + '</div>'));
		}

		var rating = $(control.children(".RA_BookRating_Stars")[0]);
		control.addClass('RA_BookRating_' + Rates.RelationToString(this.Relation));
		control.attr("Rating", this.Rating);
		control.attr("Status", Rates.RelationToString(this.Relation));
		if (this.Relation == 10 && this.Rating > 0) {
			rating.addClass("RA_BookRating_Rated" + this.Rating);
			rating.show();
		}
	});
}

