/*!
 * 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
	window = this,
	undefined,
	_jQuery = window.jQuery,
	_$ = window.$,

	jQuery = window.jQuery = window.$ = function( selector, context ) {
		return new jQuery.fn.init( selector, context );
	},

	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
	isSimple = /^.[^:#\[\.,]*$/;

jQuery.fn = jQuery.prototype = {
	init: function( selector, context ) {
		selector = selector || document;

		if ( selector.nodeType ) {
			this[0] = selector;
			this.length = 1;
			this.context = selector;
			return this;
		}
		if ( typeof selector === "string" ) {
			var match = quickExpr.exec( selector );

			if ( match && (match[1] || !context) ) {

				if ( match[1] )
					selector = jQuery.clean( [ match[1] ], context );

				else {
					var elem = document.getElementById( match[3] );

					if ( elem && elem.id != match[3] )
						return jQuery().find( selector );

					var ret = jQuery( elem || [] );
					ret.context = document;
					ret.selector = selector;
					return ret;
				}

			} else
				return jQuery( context ).find( selector );

		} else if ( jQuery.isFunction( selector ) )
			return jQuery( document ).ready( selector );

		if ( selector.selector && selector.context ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

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

	selector: "",

	jquery: "1.3.2",

	size: function() {
		return this.length;
	},

	get: function( num ) {
		return num === undefined ?

			Array.prototype.slice.call( this ) :

			this[ num ];
	},

	pushStack: function( elems, name, selector ) {
		var ret = jQuery( elems );

		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 ret;
	},

	setArray: function( elems ) {
		this.length = 0;
		Array.prototype.push.apply( this, elems );

		return this;
	},

	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	index: function( elem ) {
		return jQuery.inArray(
			elem && elem.jquery ? elem[0] : elem
		, this );
	},

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

		if ( typeof name === "string" )
			if ( value === undefined )
				return this[0] && jQuery[ type || "attr" ]( this[0], name );

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

		return this.each(function(i){
			for ( name in options )
				jQuery.attr(
					type ?
						this.style :
						this,
					name, jQuery.prop( this, options[ name ], type, i, name )
				);
		});
	},

	css: function( key, value ) {
		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] ) {
			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( [] );
	},

	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 ) {
		var ret = this.map(function(){
			if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
				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);
		});

		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 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" )
			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;

				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type == "select-one";

					if ( index < 0 )
						return null;

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

						if ( option.selected ) {
							value = jQuery(option).val();

							if ( one )
								return value;

							values.push( value );
						}
					}

					return values;
				}

				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;
		}
	}
};

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() {
	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		i = 2;
	}

	if ( typeof target !== "object" && !jQuery.isFunction(target) )
		target = {};

	if ( length == i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ )
		if ( (options = arguments[ i ]) != null )
			for ( var name in options ) {
				var src = target[ name ], copy = options[ name ];

				if ( target === copy )
					continue;

				if ( deep && copy && typeof copy === "object" && !copy.nodeType )
					target[ name ] = jQuery.extend( deep,
						src || ( copy.length != null ? [ ] : { } )
					, copy );

				else if ( copy !== undefined )
					target[ name ] = copy;

			}

	return target;
};

var	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
	defaultView = document.defaultView || {},
	toString = Object.prototype.toString;

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

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

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

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

	isXMLDoc: function( elem ) {
		return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
			!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
	},

	globalEval: function( data ) {
		if ( data && /\S/.test(data) ) {
			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;

			head.insertBefore( script, head.firstChild );
			head.removeChild( script );
		}
	},

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

	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;

		} 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 ) {
		if ( jQuery.isFunction( value ) )
			value = value.call( elem, i );

		return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
			value + "px" :
			value;
	},

	className: {
		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;
			});
		},

		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(" ") :
					"";
		},

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

	swap: function( elem, options, callback ) {
		var old = {};
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		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;

		if ( name == "opacity" && !jQuery.support.opacity ) {
			ret = jQuery.attr( style, "opacity" );

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

		if ( name.match( /float/i ) )
			name = styleFloat;

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

		else if ( defaultView.getComputedStyle ) {

			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 );

			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 ];


			if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
				var left = style.left, rsLeft = elem.runtimeStyle.left;

				elem.runtimeStyle.left = elem.currentStyle.left;
				style.left = ret || 0;
				ret = style.pixelLeft + "px";

				style.left = left;
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret;
	},

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

		if ( typeof context.createElement === "undefined" )
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

		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;

			if ( typeof elem === "string" ) {
				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 + ">";
				});

				var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();

				var wrap =
					!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>" ] ||

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

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

					!jQuery.support.htmlSerialize &&
					[ 1, "div<div>", "</div>" ] ||

					[ 0, "", "" ];

				div.innerHTML = wrap[1] + elem + wrap[2];

				while ( wrap[0]-- )
					div = div.lastChild;

				if ( !jQuery.support.tbody ) {

					var hasBody = /<tbody/i.test(elem),
						tbody = !tags.indexOf("<table") && !hasBody ?
							div.firstChild && div.firstChild.childNodes :

						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 ] );

					}

				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 ) {
		if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
			return undefined;

		var notxml = !jQuery.isXMLDoc( elem ),
			set = value !== undefined;

		name = notxml && jQuery.props[ name ] || name;

		if ( elem.tagName ) {

			var special = /href|src|style/.test( name );

			if ( name == "selected" && elem.parentNode )
				elem.parentNode.selectedIndex;

			if ( name in elem && notxml && !special ) {
				if ( set ){
					if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
						throw "type property can't be changed";

					elem[ name ] = value;
				}

				if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
					return elem.getAttributeNode( name ).nodeValue;

				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 )
				elem.setAttribute( name, "" + value );

			var attr = !jQuery.support.hrefNormalized && notxml && special
					? elem.getAttribute( name, 2 )
					: elem.getAttribute( name );

			return attr === null ? undefined : attr;
		}


		if ( !jQuery.support.opacity && name == "opacity" ) {
			if ( set ) {
				elem.zoom = 1;

				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;
			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++ )
			if ( array[ i ] === elem )
				return i;

		return -1;
	},

	merge: function( first, second ) {
		var i = 0, elem, pos = first.length;
		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 = [];

		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 = [];

		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 );
	}
});


var userAgent = navigator.userAgent.toLowerCase();

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 ) {
			jQuery( "*", this ).add([this]).each(function(){
				jQuery.event.remove(this);
				jQuery.removeData(this);
			});
			if (this.parentNode)
				this.parentNode.removeChild( this );
		}
	},

	empty: function() {
		jQuery(this).children().remove();

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

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 ];

		if ( !id )
			id = elem[ expando ] = ++uuid;

		if ( name && !jQuery.cache[ id ] )
			jQuery.cache[ id ] = {};

		if ( data !== undefined )
			jQuery.cache[ id ][ name ] = data;

		return name ?
			jQuery.cache[ id ][ name ] :
			id;
	},

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

		var id = elem[ expando ];

		if ( name ) {
			if ( jQuery.cache[ id ] ) {
				delete jQuery.cache[ id ][ name ];

				name = "";

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

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

		} else {
			try {
				delete elem[ expando ];
			} catch(e){
				if ( elem.removeAttribute )
					elem.removeAttribute( expando );
			}

			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;

	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;
				}
			}
		}

		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" ) {
				var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
					match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}

			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 ( 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){
			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;
};

try {
	Array.prototype.slice.call( document.documentElement.childNodes );

} 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;
	};
}

(function(){
	var form = document.createElement("form"),
		id = "script" + (new Date).getTime();
	form.innerHTML = "<input name='" + id + "'/>";

	var root = document.documentElement;
	root.insertBefore( form, root.firstChild );

	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(){

	var div = document.createElement("div");
	div.appendChild( document.createComment("") );

	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function(match, context){
			var results = context.getElementsByTagName(match[1]);

			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;
		};
	}

	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>";

	if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
		return;
	}

	Sizzle = function(query, context, extra, seed){
		context = context || document;

		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>";

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

	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;

	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 );
};

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 = {

	add: function(elem, types, handler, data) {
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		if ( elem.setInterval && elem != window )
			elem = window;

		if ( !handler.guid )
			handler.guid = this.guid++;

		if ( data !== undefined ) {
			var fn = handler;

			handler = this.proxy( fn );

			handler.data = data;
		}

		var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
				return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
					jQuery.event.handle.apply(arguments.callee.elem, arguments) :
					undefined;
			});
		handle.elem = elem;

		jQuery.each(types.split(/\s+/), function(index, type) {
			var namespaces = type.split(".");
			type = namespaces.shift();
			handler.type = namespaces.slice().sort().join(".");

			var handlers = events[type];

			if ( jQuery.event.specialAll[type] )
				jQuery.event.specialAll[type].setup.call(elem, data, namespaces);

			if (!handlers) {
				handlers = events[type] = {};

				if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
					if (elem.addEventListener)
						elem.addEventListener(type, handle, false);
					else if (elem.attachEvent)
						elem.attachEvent("on" + type, handle);
				}
			}

			handlers[handler.guid] = handler;

			jQuery.event.global[type] = true;
		});

		elem = null;
	},

	guid: 1,
	global: {},

	remove: function(elem, types, handler) {
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

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

		if ( events ) {
			if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
				for ( var type in events )
					this.remove( elem, type + (types || "") );
			else {
				if ( types.type ) {
					handler = types.handler;
					types = types.type;
				}

				jQuery.each(types.split(/\s+/), function(index, type){
					var namespaces = type.split(".");
					type = namespaces.shift();
					var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

					if ( events[type] ) {
						if ( handler )
							delete events[type][handler.guid];

						else
							for ( var handle in events[type] )
								if ( namespace.test(events[type][handle].type) )
									delete events[type][handle];

						if ( jQuery.event.specialAll[type] )
							jQuery.event.specialAll[type].teardown.call(elem, namespaces);

						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];
						}
					}
				});
			}

			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" );
			}
		}
	},

	trigger: function( event, data, elem, bubbling ) {
		var type = event.type || event;

		if( !bubbling ){
			event = typeof event === "object" ?
				event[expando] ? event :
				jQuery.extend( jQuery.Event(type), event ) :
				jQuery.Event(type);

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

			if ( !elem ) {
				event.stopPropagation();
				if ( this.global[type] )
					jQuery.each( jQuery.cache, function(){
						if ( this.events && this.events[type] )
							jQuery.event.trigger( event, data, this.handle.elem );
					});
			}


			if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
				return undefined;

			event.result = undefined;
			event.target = elem;

			data = jQuery.makeArray(data);
			data.unshift( event );
		}

		event.currentTarget = elem;

		var handle = jQuery.data(elem, "handle");
		if ( handle )
			handle.apply( elem, data );

		if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
			event.result = false;

		if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
			this.triggered = true;
			try {
				elem[ type ]();
			} 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) {
		var all, handlers;

		event = arguments[0] = jQuery.event.fix( event || window.event );
		event.currentTarget = this;

		var namespaces = event.type.split(".");
		event.type = namespaces.shift();

		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];

			if ( all || namespace.test(handler.type) ) {
				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;

		var originalEvent = event;
		event = jQuery.Event( originalEvent );

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

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

		if ( event.target.nodeType == 3 )
			event.target = event.target.parentNode;

		if ( !event.relatedTarget && event.fromElement )
			event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

		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);
		}

		if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
			event.which = event.charCode || event.keyCode;

		if ( !event.metaKey && event.ctrlKey )
			event.metaKey = event.ctrlKey;

		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); };
		proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
		return proxy;
	},

	special: {
		ready: {
			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 ){
	if( !this.preventDefault )
		return new jQuery.Event(src);

	if( src && src.type ){
		this.originalEvent = src;
		this.type = src.type;
	}else
		this.type = src;

	this.timeStamp = now();

	this[expando] = true;
};

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

jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;

		var e = this.originalEvent;
		if( !e )
			return;
		if (e.preventDefault)
			e.preventDefault();
		e.returnValue = false;
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;

		var e = this.originalEvent;
		if( !e )
			return;
		if (e.stopPropagation)
			e.stopPropagation();
		e.cancelBubble = true;
	},
	stopImmediatePropagation:function(){
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};
var withinElement = function(event) {
	var parent = event.relatedTarget;
	while ( parent && parent != this )
		try { parent = parent.parentNode; }
		catch(e) { parent = this; }

	if( parent != this ){
		event.type = event.data;
		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 ) {
		var args = arguments, i = 1;

		while( i < args.length )
			jQuery.event.proxy( fn, args[i++] );

		return this.click( jQuery.event.proxy( fn, function(event) {
			this.lastToggle = ( this.lastToggle || 0 ) % i;

			event.preventDefault();

			return args[ this.lastToggle++ ].apply( this, arguments ) || false;
		}));
	},

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

	ready: function(fn) {
		bindReady();

		if ( jQuery.isReady )
			fn.call( document, jQuery );

		else
			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: [],
	ready: function() {
		if ( !jQuery.isReady ) {
			jQuery.isReady = true;

			if ( jQuery.readyList ) {
				jQuery.each( jQuery.readyList, function(){
					this.call( document, jQuery );
				});

				jQuery.readyList = null;
			}

			jQuery(document).triggerHandler("ready");
		}
	}
});

var readyBound = false;

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

	if ( document.addEventListener ) {
		document.addEventListener( "DOMContentLoaded", function(){
			document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
			jQuery.ready();
		}, false );

	} else if ( document.attachEvent ) {
		document.attachEvent("onreadystatechange", function(){
			if ( document.readyState === "complete" ) {
				document.detachEvent( "onreadystatechange", arguments.callee );
				jQuery.ready();
			}
		});

		if ( document.documentElement.doScroll && window == window.top ) (function(){
			if ( jQuery.isReady ) return;

			try {
				document.documentElement.doScroll("left");
			} catch( error ) {
				setTimeout( arguments.callee, 0 );
				return;
			}

			jQuery.ready();
		})();
	}

	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){

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

jQuery( window ).bind( 'unload', function(){
	for ( var id in jQuery.cache )
		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];

	if ( !all || !all.length || !a ) {
		return;
	}

	jQuery.support = {
		leadingWhitespace: div.firstChild.nodeType == 3,

		tbody: !div.getElementsByTagName("tbody").length,

		objectAll: !!div.getElementsByTagName("object")[0]
			.getElementsByTagName("*").length,

		htmlSerialize: !!div.getElementsByTagName("link").length,

		style: /red/.test( a.getAttribute("style") ),

		hrefNormalized: a.getAttribute("href") === "/a",

		opacity: a.style.opacity === "0.5",

		cssFloat: !!a.style.cssFloat,

		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 );

	if ( window[ id ] ) {
		jQuery.support.scriptEval = true;
		delete window[ id ];
	}

	root.removeChild( script );

	if ( div.attachEvent && div.fireEvent ) {
		div.attachEvent("onclick", function(){
			jQuery.support.noCloneEvent = false;
			div.detachEvent("onclick", arguments.callee);
		});
		div.cloneNode(true).fireEvent("onclick");
	}

	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({
	_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);
		}

		var type = "GET";

		if ( params )
			if ( jQuery.isFunction( params ) ) {
				callback = params;
				params = null;

			} else if( typeof params === "object" ) {
				params = jQuery.param( params );
				type = "POST";
			}

		var self = this;

		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function(res, status){
				if ( status == "success" || status == "notmodified" )
					self.html( selector ?
						jQuery("<div/>")
							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

							.find(selector) :

						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();
	}
});

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 ) {
		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,
		*/
		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: "*/*"
		}
	},

	lastModified: {},

	ajax: function( s ) {
		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

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

		if ( s.data && s.processData && typeof s.data !== "string" )
			s.data = jQuery.param(s.data);

		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";
		}

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

			if ( s.data )
				s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
			s.url = s.url.replace(jsre, "=" + jsonp + "$1");

			s.dataType = "script";

			window[ jsonp ] = function(tmp){
				data = tmp;
				success();
				complete();
				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();
			var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
			s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
		}

		if ( s.data && type == "GET" ) {
			s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

			s.data = null;
		}

		if ( s.global && ! jQuery.active++ )
			jQuery.event.trigger( "ajaxStart" );

		var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );

		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;

			if ( !jsonp ) {
				var done = false;

				script.onload = script.onreadystatechange = function(){
					if ( !done && (!this.readyState ||
							this.readyState == "loaded" || this.readyState == "complete") ) {
						done = true;
						success();
						complete();

						script.onload = script.onreadystatechange = null;
						head.removeChild( script );
					}
				};
			}

			head.appendChild(script);

			return undefined;
		}

		var requestDone = false;

		var xhr = s.xhr();

		if( s.username )
			xhr.open(type, s.url, s.async, s.username, s.password);
		else
			xhr.open(type, s.url, s.async);

		try {
			if ( s.data )
				xhr.setRequestHeader("Content-Type", s.contentType);

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

			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

			xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
				s.accepts[ s.dataType ] + ", */*" :
				s.accepts._default );
		} catch(e){}

		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
			xhr.abort();
			return false;
		}

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

		var onreadystatechange = function(isTimeout){
			if (xhr.readyState == 0) {
				if (ival) {
					clearInterval(ival);
					ival = null;
					if ( s.global && ! --jQuery.active )
						jQuery.event.trigger( "ajaxStop" );
				}
			} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;

				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" ) {
					try {
						data = jQuery.httpData( xhr, s.dataType, s );
					} catch(e) {
						status = "parsererror";
					}
				}

				if ( status == "success" ) {
					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;

					if ( !jsonp )
						success();
				} else
					jQuery.handleError(s, xhr, status);

				complete();

				if ( isTimeout )
					xhr.abort();

				if ( s.async )
					xhr = null;
			}
		};

		if ( s.async ) {
			var ival = setInterval(onreadystatechange, 13);

			if ( s.timeout > 0 )
				setTimeout(function(){
					if ( xhr && !requestDone )
						onreadystatechange( "timeout" );
				}, s.timeout);
		}

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

		if ( !s.async )
			onreadystatechange();

		function success(){
			if ( s.success )
				s.success( data, status );

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

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

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

			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
		}

		return xhr;
	},

	handleError: function( s, xhr, status, e ) {
		if ( s.error ) s.error( xhr, status, e );

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

	active: 0,

	httpSuccess: function( xhr ) {
		try {
			return !xhr.status && location.protocol == "file:" ||
				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
		} catch(e){}
		return false;
	},

	httpNotModified: function( xhr, url ) {
		try {
			var xhrRes = xhr.getResponseHeader("Last-Modified");

			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";

		if( s && s.dataFilter )
			data = s.dataFilter( data, type );

		if( typeof data === "string" ){

			if ( type == "script" )
				jQuery.globalEval( data );

			if ( type == "json" )
				data = window["eval"]("(" + data + ")");
		}

		return data;
	},

	param: function( a ) {
		var s = [ ];

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

		if ( jQuery.isArray(a) || a.jquery )
			jQuery.each( a, function(){
				add( this.name, this.value );
			});

		else
			for ( var j in a )
				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 s.join("&").replace(/%20/g, "+");
	}

});
var elemdisplay = {},
	timerId,
	fxAttrs = [
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		[ "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);
				}
			}

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

			for ( var i = 0, l = this.length; i < l; i++ ){
				this[i].style.display = "none";
			}

			return this;
		}
	},

	_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 ) {
					opt.display = jQuery.css(this, "display");

					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";

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

						if ( parts[1] )
							end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

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

			return true;
		});
	},

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

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

		this.each(function(){
			for ( var i = timers.length - 1; i >= 0; i-- )
				if ( timers[i].elem == this ) {
					if (gotoEnd)
						timers[i](true);
					timers.splice(i, 1);
				}
		});

		if (!gotoEnd)
			this.dequeue();

		return this;
	}

});

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;

		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 = {

	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 );

		if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
			this.elem.style.display = "block";
	},

	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;
	},

	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);
		}
	},

	show: function(){
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.show = true;

		this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());

		jQuery(this.elem).show();
	},

	hide: function(){
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.hide = true;

		this.custom(this.cur(), 0);
	},

	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 ) {
					this.elem.style.overflow = this.options.overflow;

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

				if ( this.options.hide )
					jQuery(this.elem).hide();

				if ( this.options.hide || this.options.show )
					for ( var p in this.options.curAnim )
						jQuery.attr(this.elem.style, p, this.options.orig[p]);

				this.options.complete.call( this.elem );
			}

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

			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);

			this.update();
		}

		return true;
	}

};

jQuery.extend( jQuery.fx, {
	speeds:{
		slow: 600,
 		fast: 200,
 		_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] ) {
			var offsetParent = this.offsetParent(),

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

			offset.top  -= num( this, 'marginTop'  );
			offset.left -= num( this, 'marginLeft' );

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

			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}

		return results;
	},

	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);
	}
});


jQuery.each( ['Left', 'Top'], function(i, name) {
	var method = 'scroll' + name;

	jQuery.fn[ method ] = function(val) {
		if (!this[0]) return null;

		return val !== undefined ?

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

			this[0] == window || this[0] == document ?
				self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
					jQuery.boxModel && document.documentElement[ method ] ||
					document.body[ method ] :
				this[0][ method ];
	};
});
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();

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

	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 ) {
		return this[0] == window ?
			document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
			document.body[ "client" + name ] :

			this[0] == document ?
				Math.max(
					document.documentElement["client" + name],
					document.body["scroll" + name], document.documentElement["scroll" + name],
					document.body["offset" + name], document.documentElement["offset" + name]
				) :

				size === undefined ?
					(this.length ? jQuery.css( this[0], type ) : null) :

					this.css( type, typeof size === "string" ? size : size + "px" );
	};

});
})();
jQuery.noConflict();

/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

$.ui = {
	version: "1.7.2",

	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

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

	hasScroll: function(el, a) {

		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

$.fn.extend({
	remove: function() {
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		return this.each(function() {
			var instance = $.data(this, name);

			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

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

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};



$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);

/**
 * Prototype for RPM javascript components
 * Copyright (c) 2009 New Relic, Inc.
 *
 * Pass your object prototypes or 'bundle of functions' into $.rpm.component to accessorize it with RPM components methods.
 *
 * Properties:
 * - debug: defaults false. Whether to print debug messages.
 *
 * Methods:
 * - log: takes an arbitary number of arguments, and if this.debug is true, outputs a namespaced, concatenated debug message to console.log.
 * - error: takes an arbitary number of arguments, and if this.debug is true, outputs a namespaced, concatenated debug message to console.error.
 *
*/

(function($) {

var NAMESPACE = 'rpm';

$[NAMESPACE] = $[NAMESPACE] || {};
$[NAMESPACE].component = function(prototype) {
  return $.extend({}, $[NAMESPACE].component.prototype, prototype);
};

$[NAMESPACE].component.prototype = {

  debug: (typeof RPM == 'undefined' || typeof RPM.debug == 'undefined')? false : RPM.debug,

  _log: function() {
    if(this.debug) {
      var args = Array.prototype.slice.apply(arguments), type = args.shift();

      if(this.component)
        args.unshift(this.component + ':');

      if(typeof console !== 'undefined' && console[type])
        console[type].apply(console, args);
    }
  },

  log: function() {
    var args = Array.prototype.slice.apply(arguments);
    args.unshift('log');
    this._log.apply(this, args);
  },

  error: function() {
    var args = Array.prototype.slice.apply(arguments);
    args.unshift('error');
    this._log.apply(this, args);
  }

};

})(jQuery);

/**
 * The jQuery ajaxState plugin allows you to register a page's state changes into its URL hash, restoring that state when the user refreshes or returns to the page. It was designed to stay out of your way as much as possible - typically only two lines need to be added to each interaction that needs its state saved.
 * Thomas Bukowski, started 2008-11-07.
 *
 * USAGE:
 * Call $.ajaxState.register with unique identifiers for each state that you want to maintain on the page. Everytime any of those states change, call $.ajaxState.change to notify the plugin of the change in state. When the user reloads or presses the back button, the plugin will automatically pick up the state from the URL and, for each identifier, call the function you've registered with $.ajaxState.register.
 * The function you register must be able to take a null value to undo or revert the state, unless you don't want to support returning from a meaningful state back to the empty/initial state.
 *
 * KNOWN ISSUES:
 * - If there are no states to apply to the URL, the hash is set to empty - a hanging hash in the URL - which is both cosmetically ugly and also causes the browser to jump to the top of the page.
 *
 * REVISION HISTORY:
 * 1.4:
 * - jQuery.ajaxState now on the RPM.component js stack.
 * 1.3:
 * - Backwards-incompatiable change: calling $.ajaxState.change(key, null) now clears the associated key's state from the URL, assigning the default state if available.
 * - The above change necessitates that an empty string ('') has exactly the same meaning as null. Your function will never receive an empty string (even if the hash value is #key=), as the '' will be converted into null.
 * 1.2:
 * - Added stopPolling function, which stops ajaxState from polling the URL hash for changes to apply.
 * 1.1.1:
 * - Debug mode. Run $.ajaxState.debug = true in your code or console.
 * - Added default return value for getState.
 * - register's block_default_apply now will block any restore from happening.
 * 1.1:
 * - Disabled plugin for IE.
 * - States format changed from JSON structure to string. NOTE: this plugin no longer requires Douglas Crockford's json2 library.
 * - State will always restore on page load - there is no longer the restoreImmediately option in the register function, since providing support for both is more complicated than I'd like it to be.
 * - Plugin now polls the location.hash parameter for changes, e.g. when the back button is pressed, and restores the state appropriately.
 * - Various bug fixes and code cleanup.
 * 1.0:
 * - Initial release.
*/

(function($) {

$.ajaxState = $.rpm.component({
  component: 'jQuery.ajaxState',
  version: '1.4',
  states: {}, // state instances
  lastHash: window.location.hash, // last processed location.hash value, for URL hash change polling
  pollingInterval: 250,
  pollingIntervalID: null,

  init: function() {
    if(!$.browser.msie) {
      $.ajaxState.parseURL();

      $($.ajaxState.startPolling);
    }
  },

  startPolling: function() {
    $.ajaxState.pollingIntervalID = setInterval(function() {
      if($.ajaxState.lastHash !== window.location.hash)
      {
        $.ajaxState.lastHash = window.location.hash;
        $.ajaxState.parseURL();
      }
    }, $.ajaxState.pollingInterval);
  },

  stopPolling: function() {
    if($.ajaxState.pollingIntervalID)
      clearInterval($.ajaxState.pollingIntervalID);
  },

  /**
   * Add a new state object in the states variable. All parameters are required.
  */
  newState: function(identifier, func, info, default_info) {
    if(typeof $.ajaxState.states[identifier] == 'undefined')
    {
      $.ajaxState.states[identifier] = {};
      $.ajaxState.states[identifier].func = func;
      $.ajaxState.states[identifier].info = info;
      $.ajaxState.states[identifier].default_info = default_info;
    }
    else if($.ajaxState.states[identifier])
    {
      $.ajaxState.states[identifier].func = func;
      $.ajaxState.states[identifier].default_info = default_info;
    }
  },

  getState: function(identifier, default_value) {
    default_value = default_value || '';
    return ($.ajaxState.states[identifier])? $.ajaxState.states[identifier].info : default_value;
  },

  /**
   * Register a new state instance that you'd like restored when the page refreshes. Do not call this
   * function in an window.onload function - instead, call it inline in the page, unless all your javascript is executed on/after load.
   * Calling this more than once will replace the state instance's function and default_info, but will not reset the state. Reregistering a state instance is UNTESTED and may have adverse effects, including infinite state restores.
  */
  register: function(identifier, func, default_info, block_default_apply) {
    if(typeof identifier == 'undefined' || typeof func == 'undefined' || !identifier || !func)
      return false;

    var default_info = (typeof default_info == 'undefined')? null : default_info,
        info = (default_info === null)? null : default_info,
        alreadyExists = ($.ajaxState.states[identifier])? true : false,
        previouslyHadInfo = ($.ajaxState.states[identifier] && !$.ajaxState.states[identifier].func);

    $.ajaxState.newState(identifier, func, info, default_info);

    if(previouslyHadInfo
        || (!block_default_apply && !alreadyExists && default_info !== null)
        || (!block_default_apply && alreadyExists && $.ajaxState.states[identifier].info !== null))
    {
      $(function() {
        $.ajaxState.restore(identifier, true);
      });
    }

    return true;
  },

  /**
   * Tell the plugin about a change in one of the registered state instances. The URL will be
   * updated to reflect the state change.
  */
  change: function(identifier, info, updateURL) {
    var updateURL = updateURL === undefined ? true : updateURL;
    if($.ajaxState.states[identifier] && $.ajaxState.states[identifier].func) {
      if($.ajaxState.states[identifier].blockNextChange)
      {
        delete $.ajaxState.states[identifier].blockNextChange;
        $.ajaxState.log('change:', 'blocked');
        return;
      }
      $.ajaxState.states[identifier].info = info;
      $.ajaxState.log('change:', identifier, info, $.ajaxState.states[identifier]);
      if(updateURL) $.ajaxState.updateURL();
    }
  },

  /**
   * Actually change the state of the page to a new one.
  */
  perform: function(identifier, info) {
    $.ajaxState.log('perform:', identifier, info);
    $.ajaxState.change(identifier, info, true);
    $.ajaxState.restore(identifier, true);
  },

  /**
   * Restore the state of a particular state instance by calling the function from the
   * $.ajaxState.register call.
  */
  restore: function(identifier, blockNextChange) {
    if($.ajaxState.states[identifier] && $.ajaxState.states[identifier].func) {
      if(blockNextChange)
        $.ajaxState.states[identifier].blockNextChange = true;
      $.ajaxState.log('restore:', identifier, $.ajaxState.states[identifier], ', blockNextChange: '+(blockNextChange?'true':'false'));
      $.ajaxState.states[identifier].func.apply(null, [$.ajaxState.states[identifier].info]);
    }
  },

  /**
   * Updates the URL with the states of the currently registered state instances
   * Instances will an empty info will not appear in the URL hash unless that instance already has a value in the URL.
  */
  updateURL: function() {
    if(!$.browser.msie) {
      var hash = [];

      $.each($.ajaxState.states, function(identifier) {
        if(this.info !== null)
          hash.push(identifier + '=' + encodeURIComponent(this.info));
      });
      $.ajaxState.log('updateURL:', hash);
      if((hash = hash.join('&')).length > 0)
        window.location = '#'+hash;
      else
        window.location.hash = ''; // prevents browser from going somewhere

      $.ajaxState.lastHash = window.location.hash;
    }
  },

  /**
   * Parse the URL and restore the state on the page
  */
  parseURL: function() {
    var hash_data = {},
        hash = $.trim(window.location.hash.substr(1));

    if(hash !== '')
    {
      var hash = hash.split('&');
      $.each(hash, function() {
        if(this.length) {
          var temp = this.split('=');

          if(temp.length == 2) {
            var value = $.trim(decodeURIComponent(temp[1]));

            if(value !== '')
              hash_data[temp[0]] = value;
          }
        }
      });
    }

    $.ajaxState.log('parsed URL hash:', hash_data);

    $.each($.ajaxState.states, function(identifier) {
      if(this.func === null)
      {
        delete $.ajaxState.states[identifier];
        return true;
      }

      if(typeof hash_data[identifier] != 'undefined')
      {
        this.info = hash_data[identifier];
        delete hash_data[identifier];
        $.ajaxState.restore(identifier, true);
      }
      else if(this.info !== null && this.info != this.default_info)
      {
        this.info = this.default_info; // default_info might be null and that is OK
        $.ajaxState.restore(identifier, true);
      }
    });

    $.each(hash_data, function(identifier) {
      $.ajaxState.newState(identifier, null, this, null);
      $.ajaxState.states[identifier].info = this;
    });
  }
});

})(jQuery);
jQuery.ajaxState.init();

RPM = {};
RPM.add_flash_message = function(type, key, message) {
  show_message(type, message);
};

RPM.remove_flash_message = function(key) {
  hide_messages('error');
};

if(typeof jQuery=="undefined"){throw"Unable to load Shadowbox, jQuery library not found"}var Shadowbox={};Shadowbox.lib={adapter:"jquery",getStyle:function(B,A){return jQuery(B).css(A)},setStyle:function(C,B,D){if(typeof B!="object"){var A={};A[B]=D;B=A}jQuery(C).css(B)},get:function(A){return(typeof A=="string")?document.getElementById(A):A},remove:function(A){jQuery(A).remove()},getTarget:function(A){return A.target},getPageXY:function(A){return[A.pageX,A.pageY]},preventDefault:function(A){A.preventDefault()},keyCode:function(A){return A.keyCode},addEvent:function(C,A,B){jQuery(C).bind(A,B)},removeEvent:function(C,A,B){jQuery(C).unbind(A,B)},append:function(B,A){jQuery(B).append(A)}};(function(A){A.fn.shadowbox=function(B){return this.each(function(){var E=A(this);var D=A.extend({},B||{},A.metadata?E.metadata():A.meta?E.data():{});var C=this.className||"";D.width=parseInt((C.match(/w:(\d+)/)||[])[1])||D.width;D.height=parseInt((C.match(/h:(\d+)/)||[])[1])||D.height;Shadowbox.setup(E,D)})}})(jQuery);
if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox, no base library adapter found"}(function(){var version="2.0";var options={animate:true,animateFade:true,animSequence:"wh",flvPlayer:"flvplayer.swf",modal:false,overlayColor:"#000",overlayOpacity:0.8,flashBgColor:"#000000",autoplayMovies:true,showMovieControls:true,slideshowDelay:0,resizeDuration:0.55,fadeDuration:0.35,displayNav:true,continuous:false,displayCounter:true,counterType:"default",counterLimit:10,viewportPadding:20,handleOversize:"resize",handleException:null,handleUnsupported:"link",initialHeight:160,initialWidth:320,enableKeys:true,onOpen:null,onFinish:null,onChange:null,onClose:null,skipSetup:false,errors:{fla:{name:"Flash",url:"http://www.adobe.com/products/flashplayer/"},qt:{name:"QuickTime",url:"http://www.apple.com/quicktime/download/"},wmp:{name:"Windows Media Player",url:"http://www.microsoft.com/windows/windowsmedia/"},f4m:{name:"Flip4Mac",url:"http://www.flip4mac.com/wmv_download.htm"}},ext:{img:["png","jpg","jpeg","gif","bmp"],swf:["swf"],flv:["flv"],qt:["dv","mov","moov","movie","mp4"],wmp:["asf","wm","wmv"],qtwmp:["avi","mpg","mpeg"],iframe:["asp","aspx","cgi","cfm","htm","html","pl","php","php3","php4","php5","phtml","rb","rhtml","shtml","txt","vbs"]}};var SB=Shadowbox;var SL=SB.lib;var default_options;var RE={domain:/:\/\/(.*?)[:\/]/,inline:/#(.+)$/,rel:/^(light|shadow)box/i,gallery:/^(light|shadow)box\[(.*?)\]/i,unsupported:/^unsupported-(\w+)/,param:/\s*([a-z_]*?)\s*=\s*(.+)\s*/,empty:/^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i};var cache=[];var gallery;var current;var content;var content_id="shadowbox_content";var dims;var initialized=false;var activated=false;var slide_timer;var slide_start;var slide_delay=0;var ua=navigator.userAgent.toLowerCase();var client={isStrict:document.compatMode=="CSS1Compat",isOpera:ua.indexOf("opera")>-1,isIE:ua.indexOf("msie")>-1,isIE7:ua.indexOf("msie 7")>-1,isSafari:/webkit|khtml/.test(ua),isWindows:ua.indexOf("windows")!=-1||ua.indexOf("win32")!=-1,isMac:ua.indexOf("macintosh")!=-1||ua.indexOf("mac os x")!=-1,isLinux:ua.indexOf("linux")!=-1};client.isBorderBox=client.isIE&&!client.isStrict;client.isSafari3=client.isSafari&&!!(document.evaluate);client.isGecko=ua.indexOf("gecko")!=-1&&!client.isSafari;var ltIE7=client.isIE&&!client.isIE7;var plugins;if(navigator.plugins&&navigator.plugins.length){var detectPlugin=function(plugin_name){var detected=false;for(var i=0,len=navigator.plugins.length;i<len;++i){if(navigator.plugins[i].name.indexOf(plugin_name)>-1){detected=true;break}}return detected};var f4m=detectPlugin("Flip4Mac");plugins={fla:detectPlugin("Shockwave Flash"),qt:detectPlugin("QuickTime"),wmp:!f4m&&detectPlugin("Windows Media"),f4m:f4m}}else{var detectPlugin=function(plugin_name){var detected=false;try{var axo=new ActiveXObject(plugin_name);if(axo){detected=true}}catch(e){}return detected};plugins={fla:detectPlugin("ShockwaveFlash.ShockwaveFlash"),qt:detectPlugin("QuickTime.QuickTime"),wmp:detectPlugin("wmplayer.ocx"),f4m:false}}var apply=function(o,e){for(var p in e){o[p]=e[p]}return o};var isLink=function(el){return el&&typeof el.tagName=="string"&&(el.tagName.toUpperCase()=="A"||el.tagName.toUpperCase()=="AREA")};SL.getViewportHeight=function(){var h=window.innerHeight;var mode=document.compatMode;if((mode||client.isIE)&&!client.isOpera){h=client.isStrict?document.documentElement.clientHeight:document.body.clientHeight}return h};SL.getViewportWidth=function(){var w=window.innerWidth;var mode=document.compatMode;if(mode||client.isIE){w=client.isStrict?document.documentElement.clientWidth:document.body.clientWidth}return w};SL.createHTML=function(obj){var html="<"+obj.tag;for(var attr in obj){if(attr=="tag"||attr=="html"||attr=="children"){continue}if(attr=="cls"){html+=' class="'+obj.cls+'"'}else{html+=" "+attr+'="'+obj[attr]+'"'}}if(RE.empty.test(obj.tag)){html+="/>"}else{html+=">";var cn=obj.children;if(cn){for(var i=0,len=cn.length;i<len;++i){html+=this.createHTML(cn[i])}}if(obj.html){html+=obj.html}html+="</"+obj.tag+">"}return html};var ease=function(x){return 1+Math.pow(x-1,3)};var animate=function(el,p,to,d,cb){var from=parseFloat(SL.getStyle(el,p));if(isNaN(from)){from=0}if(from==to){if(typeof cb=="function"){cb()}return }var delta=to-from;var op=p=="opacity";var unit=op?"":"px";var fn=function(ease){SL.setStyle(el,p,from+ease*delta+unit)};if(!options.animate&&!op||op&&!options.animateFade){fn(1);if(typeof cb=="function"){cb()}return }d*=1000;var begin=new Date().getTime();var end=begin+d;var timer=setInterval(function(){var time=new Date().getTime();if(time>=end){clearInterval(timer);fn(1);if(typeof cb=="function"){cb()}}else{fn(ease((time-begin)/d))}},10)};var clearOpacity=function(el){var s=el.style;if(client.isIE){if(typeof s.filter=="string"&&(/alpha/i).test(s.filter)){s.filter=s.filter.replace(/[\w\.]*alpha\(.*?\);?/i,"")}}else{s.opacity="";s["-moz-opacity"]="";s["-khtml-opacity"]=""}};var getComputedHeight=function(el){var h=Math.max(el.offsetHeight,el.clientHeight);if(!h){h=parseInt(SL.getStyle(el,"height"),10)||0;if(!client.isBorderBox){h+=parseInt(SL.getStyle(el,"padding-top"),10)+parseInt(SL.getStyle(el,"padding-bottom"),10)+parseInt(SL.getStyle(el,"border-top-width"),10)+parseInt(SL.getStyle(el,"border-bottom-width"),10)}}return h};var getPlayer=function(url){var m=url.match(RE.domain);var d=m&&document.domain==m[1];if(url.indexOf("#")>-1&&d){return"inline"}var q=url.indexOf("?");if(q>-1){url=url.substring(0,q)}if(RE.img.test(url)){return"img"}if(RE.swf.test(url)){return plugins.fla?"swf":"unsupported-swf"}if(RE.flv.test(url)){return plugins.fla?"flv":"unsupported-flv"}if(RE.qt.test(url)){return plugins.qt?"qt":"unsupported-qt"}if(RE.wmp.test(url)){if(plugins.wmp){return"wmp"}if(plugins.f4m){return"qt"}if(client.isMac){return plugins.qt?"unsupported-f4m":"unsupported-qtf4m"}return"unsupported-wmp"}else{if(RE.qtwmp.test(url)){if(plugins.qt){return"qt"}if(plugins.wmp){return"wmp"}return client.isMac?"unsupported-qt":"unsupported-qtwmp"}else{if(!d||RE.iframe.test(url)){return"iframe"}}}return"unsupported"};var handleClick=function(ev){var link;if(isLink(this)){link=this}else{link=SL.getTarget(ev);while(!isLink(link)&&link.parentNode){link=link.parentNode}}if(link){SB.open(link);if(gallery.length){SL.preventDefault(ev)}}};var toggleNav=function(id,on){var el=SL.get("shadowbox_nav_"+id);if(el){el.style.display=on?"":"none"}};var buildBars=function(cb){var obj=gallery[current];var title_i=SL.get("shadowbox_title_inner");title_i.innerHTML=obj.title||"";var nav=SL.get("shadowbox_nav");if(nav){var c,n,pl,pa,p;if(options.displayNav){c=true;var len=gallery.length;if(len>1){if(options.continuous){n=p=true}else{n=(len-1)>current;p=current>0}}if(options.slideshowDelay>0&&hasNext()){pa=slide_timer!="paused";pl=!pa}}else{c=n=pl=pa=p=false}toggleNav("close",c);toggleNav("next",n);toggleNav("play",pl);toggleNav("pause",pa);toggleNav("previous",p)}var counter=SL.get("shadowbox_counter");if(counter){var co="";if(options.displayCounter&&gallery.length>1){if(options.counterType=="skip"){var i=0,len=gallery.length,end=len;var limit=parseInt(options.counterLimit);if(limit<len){var h=Math.round(limit/2);i=current-h;if(i<0){i+=len}end=current+(limit-h);if(end>len){end-=len}}while(i!=end){if(i==len){i=0}co+='<a onclick="Shadowbox.change('+i+');"';if(i==current){co+=' class="shadowbox_counter_current"'}co+=">"+(++i)+"</a>"}}else{co=(current+1)+" "+SB.LANG.of+" "+len}}counter.innerHTML=co}cb()};var hideBars=function(anim,cb){var obj=gallery[current];var title=SL.get("shadowbox_title");var info=SL.get("shadowbox_info");var title_i=SL.get("shadowbox_title_inner");var info_i=SL.get("shadowbox_info_inner");var fn=function(){buildBars(cb)};var title_h=getComputedHeight(title);var info_h=getComputedHeight(info)*-1;if(anim){animate(title_i,"margin-top",title_h,0.35);animate(info_i,"margin-top",info_h,0.35,fn)}else{SL.setStyle(title_i,"margin-top",title_h+"px");SL.setStyle(info_i,"margin-top",info_h+"px");fn()}};var showBars=function(cb){var title_i=SL.get("shadowbox_title_inner");var info_i=SL.get("shadowbox_info_inner");var t=title_i.innerHTML!="";if(t){animate(title_i,"margin-top",0,0.35)}animate(info_i,"margin-top",0,0.35,cb)};var loadContent=function(){var obj=gallery[current];if(!obj){return }var changing=false;if(content){content.remove();changing=true}var p=obj.player=="inline"?"html":obj.player;if(typeof SB[p]!="function"){SB.raise("Unknown player "+obj.player)}content=new SB[p](content_id,obj);listenKeys(false);toggleLoading(true);hideBars(changing,function(){if(!content){return }if(!changing){SL.get("shadowbox").style.display=""}var fn=function(){resizeContent(function(){if(!content){return }showBars(function(){if(!content){return }SL.get("shadowbox_body_inner").innerHTML=SL.createHTML(content.markup(dims));toggleLoading(false,function(){if(!content){return }if(typeof content.onLoad=="function"){content.onLoad()}if(options.onFinish&&typeof options.onFinish=="function"){options.onFinish(gallery[current])}if(slide_timer!="paused"){SB.play()}listenKeys(true)})})})};if(typeof content.ready!="undefined"){var id=setInterval(function(){if(content){if(content.ready){clearInterval(id);id=null;fn()}}else{clearInterval(id);id=null}},100)}else{fn()}});if(gallery.length>1){var next=gallery[current+1]||gallery[0];if(next.player=="img"){var a=new Image();a.src=next.content}var prev=gallery[current-1]||gallery[gallery.length-1];if(prev.player=="img"){var b=new Image();b.src=prev.content}}};var setDimensions=function(height,width,resizable){resizable=resizable||false;var sb=SL.get("shadowbox_body");var h=height=parseInt(height);var w=width=parseInt(width);var view_h=SL.getViewportHeight();var view_w=SL.getViewportWidth();var border_w=parseInt(SL.getStyle(sb,"border-left-width"),10)+parseInt(SL.getStyle(sb,"border-right-width"),10);var extra_w=border_w+2*options.viewportPadding;if(w+extra_w>=view_w){w=view_w-extra_w}var border_h=parseInt(SL.getStyle(sb,"border-top-width"),10)+parseInt(SL.getStyle(sb,"border-bottom-width"),10);var bar_h=getComputedHeight(SL.get("shadowbox_title"))+getComputedHeight(SL.get("shadowbox_info"));var extra_h=border_h+2*options.viewportPadding+bar_h;if(h+extra_h>=view_h){h=view_h-extra_h}var drag=false;var resize_h=height;var resize_w=width;var handle=options.handleOversize;if(resizable&&(handle=="resize"||handle=="drag")){var change_h=(height-h)/height;var change_w=(width-w)/width;if(handle=="resize"){if(change_h>change_w){w=Math.round((width/height)*h)}else{if(change_w>change_h){h=Math.round((height/width)*w)}}resize_w=w;resize_h=h}else{var link=gallery[current];if(link){drag=link.player=="img"&&(change_h>0||change_w>0)}}}dims={height:h+border_h+bar_h,width:w+border_w,inner_h:h,inner_w:w,top:(view_h-(h+extra_h))/2+options.viewportPadding,resize_h:resize_h,resize_w:resize_w,drag:drag}};var resizeContent=function(cb){if(!content){return }setDimensions(content.height,content.width,content.resizable);if(cb){switch(options.animSequence){case"hw":adjustHeight(dims.inner_h,dims.top,true,function(){adjustWidth(dims.width,true,cb)});break;case"wh":adjustWidth(dims.width,true,function(){adjustHeight(dims.inner_h,dims.top,true,cb)});break;case"sync":default:adjustWidth(dims.width,true);adjustHeight(dims.inner_h,dims.top,true,cb)}}else{adjustWidth(dims.width,false);adjustHeight(dims.inner_h,dims.top,false);var c=SL.get(content_id);if(c){if(content.resizable&&options.handleOversize=="resize"){c.height=dims.resize_h;c.width=dims.resize_w}if(gallery[current].player=="img"&&options.handleOversize=="drag"){var top=parseInt(SL.getStyle(c,"top"));if(top+content.height<dims.inner_h){SL.setStyle(c,"top",dims.inner_h-content.height+"px")}var left=parseInt(SL.getStyle(c,"left"));if(left+content.width<dims.inner_w){SL.setStyle(c,"left",dims.inner_w-content.width+"px")}}}}};var adjustHeight=function(height,top,anim,cb){height=parseInt(height);var sb=SL.get("shadowbox_body");if(anim){animate(sb,"height",height,options.resizeDuration)}else{SL.setStyle(sb,"height",height+"px")}var s=SL.get("shadowbox");if(anim){animate(s,"top",top,options.resizeDuration,cb)}else{SL.setStyle(s,"top",top+"px");if(typeof cb=="function"){cb()}}};var adjustWidth=function(width,anim,cb){width=parseInt(width);var s=SL.get("shadowbox");if(anim){animate(s,"width",width,options.resizeDuration,cb)}else{SL.setStyle(s,"width",width+"px");if(typeof cb=="function"){cb()}}};var listenKeys=function(on){if(!options.enableKeys){return }SL[(on?"add":"remove")+"Event"](document,"keydown",handleKey)};var handleKey=function(e){var code=SL.keyCode(e);SL.preventDefault(e);if(code==81||code==88||code==27){SB.close()}else{if(code==37){SB.previous()}else{if(code==39){SB.next()}else{if(code==32){SB[(typeof slide_timer=="number"?"pause":"play")]()}}}}};var toggleLoading=function(on,cb){var loading=SL.get("shadowbox_loading");if(on){loading.style.display="";if(typeof cb=="function"){cb()}}else{var p=gallery[current].player;var anim=(p=="img"||p=="html");var fn=function(){loading.style.display="none";clearOpacity(loading);if(typeof cb=="function"){cb()}};if(anim){animate(loading,"opacity",0,options.fadeDuration,fn)}else{fn()}}};var fixTop=function(){SL.get("shadowbox_container").style.top=document.documentElement.scrollTop+"px"};var fixHeight=function(){SL.get("shadowbox_overlay").style.height=SL.getViewportHeight()+"px"};var hasNext=function(){return gallery.length>1&&(current!=gallery.length-1||options.continuous)};var toggleVisible=function(cb){var els,v=(cb)?"hidden":"visible";var hide=["select","object","embed"];for(var i=0;i<hide.length;++i){els=document.getElementsByTagName(hide[i]);for(var j=0,len=els.length;j<len;++j){els[j].style.visibility=v}}var so=SL.get("shadowbox_overlay");var sc=SL.get("shadowbox_container");var sb=SL.get("shadowbox");if(cb){SL.setStyle(so,{backgroundColor:options.overlayColor,opacity:0});if(!options.modal){SL.addEvent(so,"click",SB.close)}if(ltIE7){fixTop();fixHeight();SL.addEvent(window,"scroll",fixTop)}sb.style.display="none";sc.style.visibility="visible";animate(so,"opacity",parseFloat(options.overlayOpacity),options.fadeDuration,cb)}else{SL.removeEvent(so,"click",SB.close);if(ltIE7){SL.removeEvent(window,"scroll",fixTop)}sb.style.display="none";animate(so,"opacity",0,options.fadeDuration,function(){sc.style.visibility="hidden";sb.style.display="";clearOpacity(so)})}};Shadowbox.init=function(opts){if(initialized){return }if(typeof SB.LANG=="undefined"){SB.raise("No Shadowbox language loaded");return }if(typeof SB.SKIN=="undefined"){SB.raise("No Shadowbox skin loaded");return }apply(options,opts||{});var markup=SB.SKIN.markup.replace(/\{(\w+)\}/g,function(m,p){return SB.LANG[p]});var bd=document.body||document.documentElement;SL.append(bd,markup);if(ltIE7){SL.setStyle(SL.get("shadowbox_container"),"position","absolute");SL.get("shadowbox_body").style.zoom=1;var png=SB.SKIN.png_fix;if(png&&png.constructor==Array){for(var i=0;i<png.length;++i){var el=SL.get(png[i]);if(el){var match=SL.getStyle(el,"background-image").match(/url\("(.*\.png)"\)/);if(match){SL.setStyle(el,{backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src="+match[1]+",sizingMethod=scale);"})}}}}}for(var e in options.ext){RE[e]=new RegExp(".("+options.ext[e].join("|")+")s*$","i")}var id;SL.addEvent(window,"resize",function(){if(id){clearTimeout(id);id=null}id=setTimeout(function(){if(ltIE7){fixHeight()}resizeContent()},50)});if(!options.skipSetup){SB.setup()}initialized=true};Shadowbox.loadSkin=function(skin,dir){if(!(/\/$/.test(dir))){dir+="/"}skin=dir+skin+"/";document.write('<link rel="stylesheet" type="text/css" href="'+skin+'skin.css">');document.write('<script type="text/javascript" src="'+skin+'skin.js"><\/script>')};Shadowbox.loadLanguage=function(lang,dir){if(!(/\/$/.test(dir))){dir+="/"}document.write('<script type="text/javascript" src="'+dir+"shadowbox-"+lang+'.js"><\/script>')};Shadowbox.loadPlayer=function(players,dir){if(typeof players=="string"){players=[players]}if(!(/\/$/.test(dir))){dir+="/"}for(var i=0,len=players.length;i<len;++i){document.write('<script type="text/javascript" src="'+dir+"shadowbox-"+players[i]+'.js"><\/script>')}};Shadowbox.setup=function(links,opts){if(!links){var links=[];var a=document.getElementsByTagName("a"),rel;for(var i=0,len=a.length;i<len;++i){rel=a[i].getAttribute("rel");if(rel&&RE.rel.test(rel)){links[links.length]=a[i]}}}else{if(!links.length){links=[links]}}var link;for(var i=0,len=links.length;i<len;++i){link=links[i];if(typeof link.shadowboxCacheKey=="undefined"){link.shadowboxCacheKey=cache.length;SL.addEvent(link,"click",handleClick)}cache[link.shadowboxCacheKey]=this.buildCacheObj(link,opts)}};Shadowbox.buildCacheObj=function(link,opts){var href=link.href;var o={el:link,title:link.getAttribute("title"),player:getPlayer(href),options:apply({},opts||{}),content:href};var opt,l_opts=["player","title","height","width","gallery"];for(var i=0,len=l_opts.length;i<len;++i){opt=l_opts[i];if(typeof o.options[opt]!="undefined"){o[opt]=o.options[opt];delete o.options[opt]}}var rel=link.getAttribute("rel");if(rel){var match=rel.match(RE.gallery);if(match){o.gallery=escape(match[2])}var params=rel.split(";");for(var i=0,len=params.length;i<len;++i){match=params[i].match(RE.param);if(match){if(match[1]=="options"){eval("apply(o.options, "+match[2]+")")}else{o[match[1]]=match[2]}}}}return o};Shadowbox.applyOptions=function(opts){if(opts){default_options=apply({},options);options=apply(options,opts)}};Shadowbox.revertOptions=function(){if(default_options){options=default_options;default_options=null}};Shadowbox.open=function(obj,opts){this.revertOptions();if(isLink(obj)){if(typeof obj.shadowboxCacheKey=="undefined"||typeof cache[obj.shadowboxCacheKey]=="undefined"){obj=this.buildCacheObj(obj,opts)}else{obj=cache[obj.shadowboxCacheKey]}}if(obj.constructor==Array){gallery=obj;current=0}else{var copy=apply({},obj);if(!obj.gallery){gallery=[copy];current=0}else{current=null;gallery=[];var ci;for(var i=0,len=cache.length;i<len;++i){ci=cache[i];if(ci.gallery){if(ci.content==obj.content&&ci.gallery==obj.gallery&&ci.title==obj.title){current=gallery.length}if(ci.gallery==obj.gallery){gallery.push(apply({},ci))}}}if(current==null){gallery.unshift(copy);current=0}}}obj=gallery[current];if(obj.options||opts){this.applyOptions(apply(apply({},obj.options||{}),opts||{}))}var match,r;for(var i=0,len=gallery.length;i<len;++i){r=false;if(gallery[i].player=="unsupported"){r=true}else{if(match=RE.unsupported.exec(gallery[i].player)){if(options.handleUnsupported=="link"){gallery[i].player="html";var s,a,oe=options.errors;switch(match[1]){case"qtwmp":s="either";a=[oe.qt.url,oe.qt.name,oe.wmp.url,oe.wmp.name];break;case"qtf4m":s="shared";a=[oe.qt.url,oe.qt.name,oe.f4m.url,oe.f4m.name];break;default:s="single";if(match[1]=="swf"||match[1]=="flv"){match[1]="fla"}a=[oe[match[1]].url,oe[match[1]].name]}var msg=SB.LANG.errors[s].replace(/\{(\d+)\}/g,function(m,i){return a[i]});gallery[i].content='<div class="shadowbox_message">'+msg+"</div>"}else{r=true}}else{if(gallery[i].player=="inline"){var match=RE.inline.exec(gallery[i].content);if(match){var el;if(el=SL.get(match[1])){gallery[i].content=el.innerHTML}else{SB.raise("Cannot find element with id "+match[1])}}else{SB.raise("Cannot find element id for inline content")}}}}if(r){gallery.splice(i,1);if(i<current){--current}else{if(i==current){current=i>0?current-1:i}}--i;len=gallery.length}}if(gallery.length){if(options.onOpen&&typeof options.onOpen=="function"){options.onOpen(obj)}if(!activated){setDimensions(options.initialHeight,options.initialWidth);adjustHeight(dims.inner_h,dims.top,false);adjustWidth(dims.width,false);toggleVisible(loadContent)}else{loadContent()}activated=true}};Shadowbox.change=function(num){if(!gallery){return }if(!gallery[num]){if(!options.continuous){return }else{num=num<0?(gallery.length-1):0}}if(typeof slide_timer=="number"){clearTimeout(slide_timer);slide_timer=null;slide_delay=slide_start=0}current=num;if(options.onChange&&typeof options.onChange=="function"){options.onChange(gallery[current])}loadContent()};Shadowbox.next=function(){this.change(current+1)};Shadowbox.previous=function(){this.change(current-1)};Shadowbox.play=function(){if(!hasNext()){return }if(!slide_delay){slide_delay=options.slideshowDelay*1000}if(slide_delay){slide_start=new Date().getTime();slide_timer=setTimeout(function(){slide_delay=slide_start=0;SB.next()},slide_delay);toggleNav("play",false);toggleNav("pause",true)}};Shadowbox.pause=function(){if(typeof slide_timer=="number"){var time=new Date().getTime();slide_delay=Math.max(0,slide_delay-(time-slide_start));if(slide_delay){clearTimeout(slide_timer);slide_timer="paused"}toggleNav("pause",false);toggleNav("play",true)}};Shadowbox.close=function(){if(!activated){return }listenKeys(false);toggleVisible(false);if(content){content.remove();content=null}if(typeof slide_timer=="number"){clearTimeout(slide_timer)}slide_timer=null;slide_delay=0;if(options.onClose&&typeof options.onClose=="function"){options.onClose(gallery[current])}activated=false};Shadowbox.clearCache=function(){for(var i=0,len=cache.length;i<len;++i){if(cache[i].el){SL.removeEvent(cache[i].el,"click",handleClick);delete cache[i].el.shadowboxCacheKey}}cache=[]};Shadowbox.getPlugins=function(){return plugins};Shadowbox.getOptions=function(){return options};Shadowbox.getCurrent=function(){return gallery[current]};Shadowbox.getVersion=function(){return version};Shadowbox.getClient=function(){return client};Shadowbox.getContent=function(){return content};Shadowbox.getDimensions=function(){return dims};Shadowbox.raise=function(e){if(typeof options.handleException=="function"){options.handleException(e)}else{throw e}}})();
if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox language file, base library not found."}Shadowbox.LANG={code:"en",of:"of",loading:"loading",cancel:"Cancel",next:"Next",previous:"Previous",play:"Play",pause:"Pause",close:"Close",errors:{single:'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',shared:'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',either:'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'}};
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.html=function(D,C){this.id=D;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;this.width=this.obj.width?parseInt(this.obj.width,10):500};Shadowbox.html.prototype={markup:function(C){return{tag:"div",id:this.id,cls:"html",html:this.obj.content}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.iframe=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):B.getViewportHeight();this.width=this.obj.width?parseInt(this.obj.width,10):B.getViewportWidth()};Shadowbox.iframe.prototype={markup:function(E){var C={tag:"iframe",id:this.id,name:this.id,height:"100%",width:"100%",frameborder:"0",marginwidth:"0",marginheight:"0",scrolling:"auto"};if(D.isIE){C.allowtransparency="true";if(!D.isIE7){C.src='javascript:false;document.write("");'}}return C},onLoad:function(){var C=(D.isIE)?B.get(this.id).contentWindow:window.frames[this.id];C.location=this.obj.content},remove:function(){var C=B.get(this.id);if(C){B.remove(C);if(D.isGecko){delete window.frames[this.id]}}}}})();


NRRPM = window.NRRPM = {};

/* working spinner helpers */
SPINNER = '<img class="spinner" src="/images/busy.gif" />';

function replaceWith_working_spinner(obj)
{
  jQuery(obj).replaceWith(SPINNER);
}

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  notes: {
    enabled: false
  },

  notes_v2: {
    enabled: false
  }

});

})(jQuery);


(function($) {

RPM.guarded_refresh = function(options) {
  options = options == undefined ? {} : options;
  options.interval = options.interval !== undefined ? options.interval : 300;
  options.appendRefreshLink = options.appendRefreshLink !== undefined ? options.appendRefreshLink : true;

  if(options.message == '')
    options.message = null;
  else
    options.message = options.message !== undefined ? options.message : "<strong>You are currently offline.</strong> Data on this page is no longer current.";

  RPM.guarded_refresh.options = options;

  RPM.guarded_refresh.setTimeout();
};

RPM.guarded_refresh.PING_URL = '/browser/ping';

RPM.guarded_refresh.enabled = true;
RPM.guarded_refresh.enable = function() {
  RPM.guarded_refresh.enabled = true;
  RPM.guarded_refresh.setTimeout();
};
RPM.guarded_refresh.disable = function() {
  RPM.guarded_refresh.enabled = false;
  RPM.guarded_refresh.clearTimeout();
};
RPM.guarded_refresh.toggle = function() {
  if(!RPM.guarded_refresh.options) return;

  if(RPM.guarded_refresh.enabled)
    RPM.guarded_refresh.disable();
  else
    RPM.guarded_refresh.enable();
};

RPM.guarded_refresh.timeoutId = null;
RPM.guarded_refresh.setTimeout = function(interval) {
  interval = interval == undefined ? RPM.guarded_refresh.options.interval : interval;

  if(RPM.guarded_refresh.options) {
    RPM.guarded_refresh.clearTimeout();
    RPM.guarded_refresh.timeoutId = window.setTimeout(RPM.guarded_refresh.tryRefresh, interval * 1000);
  }
};
RPM.guarded_refresh.clearTimeout = function() {
  if(RPM.guarded_refresh.timeoutId) {
    window.clearTimeout(RPM.guarded_refresh.timeoutId);
    RPM.guarded_refresh.timeoutId = null;
  }
};

RPM.guarded_refresh.tryRefresh = function() {
  if(RPM.guarded_refresh.enabled)
    RPM.guarded_refresh.checkConnectivity(RPM.guarded_refresh.success, RPM.guarded_refresh.failure);
};

RPM.guarded_refresh.checkConnectivity = function(success_callback, failure_callback) {
  $.ajax({
    url: RPM.guarded_refresh.PING_URL,
    cache: false,
    success: success_callback,
    error: failure_callback,
    timeout: 10 * 1000    // 10 seconds
  });
};

RPM.guarded_refresh.success = function(data, textStatus) {
  RPM.guarded_refresh.disable();
  window.location.reload();
};

RPM.guarded_refresh.failure = function(XMLHttpRequest, textStatus, errorThrown) {
  if(RPM.guarded_refresh.options.message != null) {
    RPM.remove_flash_message('guarded_refresh_failure');

    var message = RPM.guarded_refresh.options.message;
    if(RPM.guarded_refresh.options.appendRefreshLink)
      message += ' <a href="#" onclick="RPM.guarded_refresh.tryRefresh(); return false;">Refresh this page</a> when you\'re reconnected to the Internet.';

    RPM.add_flash_message('error', 'guarded_refresh_failure', message);
  }

  RPM.guarded_refresh.setTimeout();
};

})(jQuery);

/**
 * FusionCharts: Flash Player detection and Chart embedding.
 * Version: 1.2 (1st November, 2007) - Added Player detection, New conditional fixes for IE, New FORM fixes for IE
 * Version: 1.1 (29th June, 2007) - Added Player detection, New conditional fixes for IE
 *
 * Morphed from SWFObject (http://blog.deconcept.com/swfobject/) under MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof infosoftglobal == "undefined") var infosoftglobal = new Object();
if(typeof infosoftglobal.FusionChartsUtil == "undefined") infosoftglobal.FusionChartsUtil = new Object();
infosoftglobal.FusionCharts = function(swf, id, w, h, debugMode, registerWithJS, c, scaleMode, lang, detectFlashVersion, autoInstallRedirect){
	if (!document.getElementById) { return; }

	this.initialDataSet = false;

	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();

	if(swf) { this.setAttribute('swf', swf); }
	if(id) { this.setAttribute('id', id); }
	if(w) { this.setAttribute('width', w); }
	if(h) { this.setAttribute('height', h); }

	if(c) { this.addParam('bgcolor', c); }

	this.addParam('quality', 'high');

	this.addParam('allowScriptAccess', 'always');

	this.addVariable('chartWidth', w);
	this.addVariable('chartHeight', h);

	debugMode = debugMode ? debugMode : 0;
	this.addVariable('debugMode', debugMode);
	this.addVariable('DOMId', id);
	registerWithJS = registerWithJS ? registerWithJS : 0;
	this.addVariable('registerWithJS', registerWithJS);

	scaleMode = scaleMode ? scaleMode : 'noScale';
	this.addVariable('scaleMode', scaleMode);

	lang = lang ? lang : 'EN';
	this.addVariable('lang', lang);

	this.detectFlashVersion = detectFlashVersion?detectFlashVersion:1;
	this.autoInstallRedirect = autoInstallRedirect?autoInstallRedirect:1;

	this.installedVer = infosoftglobal.FusionChartsUtil.getPlayerVersion();

	if (!window.opera && document.all && this.installedVer.major > 7) {
		infosoftglobal.FusionCharts.doPrepUnload = true;
	}
}

infosoftglobal.FusionCharts.prototype = {
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},
	getAttribute: function(name){
		return this.attributes[name];
	},
	addParam: function(name, value){
		this.params[name] = value;
	},
	getParams: function(){
		return this.params;
	},
	addVariable: function(name, value){
		this.variables[name] = value;
	},
	getVariable: function(name){
		return this.variables[name];
	},
	getVariables: function(){
		return this.variables;
	},
	getVariablePairs: function(){
		var variablePairs = new Array();
		var key;
		var variables = this.getVariables();
		for(key in variables){
			variablePairs.push(key +"="+ variables[key]);
		}
		return variablePairs;
	},
	getSWFHTML: function() {
		var swfNode = "";
		if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
			swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"  ';
			swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
			var params = this.getParams();
			 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
			var pairs = this.getVariablePairs().join("&");
			 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
			swfNode += '/>';
		} else { // PC IE
			swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
			swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
			var params = this.getParams();
			for(var key in params) {
			 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
			}
			var pairs = this.getVariablePairs().join("&");
			if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
			swfNode += "</object>";
		}
		return swfNode;
	},
  redrawChart: function(){
    var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
    if(chartObj && typeof chartObj.redrawChart == 'function')
      chartObj.redrawChart();
  },
  setDataURL: function(strDataURL){
    if (this.initialDataSet==false){
      this.addVariable('dataURL',strDataURL);
      this.initialDataSet = true;
    }else{
      var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
      chartObj.setDataURL(strDataURL);
    }
  },
  setDataXML: function(strDataXML){
    if (this.initialDataSet==false){
      this.addVariable('dataXML',strDataXML);
      this.initialDataSet = true;
    }else{
      var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
      chartObj.setDataXML(strDataXML);
    }
  },
  getDataXML: function(){
    var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
    if(typeof chartObj.getDataXML == 'function')
      return chartObj.getDataXML();
    else
      return 'getDataXML not defined on this chart object.';
  },
	setTransparent: function(isTransparent){
		if(typeof isTransparent=="undefined") {
			isTransparent=true;
		}
		if(isTransparent)
			this.addParam('WMode', 'transparent');
		else
			this.addParam('WMode', 'window');
	},

	render: function(elementId){
		if((this.detectFlashVersion==1) && (this.installedVer.major < 8)){
			if (this.autoInstallRedirect==1){
				var installationConfirm = window.confirm("You need Adobe Flash Player 8 (or above) to view the charts. It is a free and lightweight installation from Adobe.com. Please click on Ok to install the same.");
				if (installationConfirm){
					window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
				}else{
					return false;
				}
			}else{
				return false;
			}
		}else{
			var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
			n.innerHTML = this.getSWFHTML();

			if(!document.embeds[this.getAttribute('id')] && !window[this.getAttribute('id')])
		      	window[this.getAttribute('id')]=document.getElementById(this.getAttribute('id'));
			return true;
		}
	}
}

/* ---- detection functions ---- */
infosoftglobal.FusionChartsUtil.getPlayerVersion = function(){
	var PlayerVersion = new infosoftglobal.PlayerVersion([0,0,0]);
	if(navigator.plugins && navigator.mimeTypes.length){
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			PlayerVersion = new infosoftglobal.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
		}
	}else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){
		var axo = 1;
		var counter = 3;
		while(axo) {
			try {
				counter++;
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
				PlayerVersion = new infosoftglobal.PlayerVersion([counter,0,0]);
			} catch (e) {
				axo = null;
			}
		}
	} else {
		try{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		}catch(e){
			try {
				var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
				PlayerVersion = new infosoftglobal.PlayerVersion([6,0,21]);
				axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
			} catch(e) {
				if (PlayerVersion.major == 6) {
					return PlayerVersion;
				}
			}
			try {
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			} catch(e) {}
		}
		if (axo != null) {
			PlayerVersion = new infosoftglobal.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
		}
	}
	return PlayerVersion;
}
infosoftglobal.PlayerVersion = function(arrVersion){
	this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
	this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
	this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
/* Fix for video streaming bug */
infosoftglobal.FusionChartsUtil.cleanupSWFs = function() {
	var objects = document.getElementsByTagName("OBJECT");
	for (var i = objects.length - 1; i >= 0; i--) {
		objects[i].style.display = 'none';
		for (var x in objects[i]) {
			if (typeof objects[i][x] == 'function') {
				objects[i][x] = function(){};
			}
		}
	}
}
if (infosoftglobal.FusionCharts.doPrepUnload) {
	if (!infosoftglobal.unloadSet) {
		infosoftglobal.FusionChartsUtil.prepUnload = function() {
			__flash_unloadHandler = function(){};
			__flash_savedUnloadHandler = function(){};
			window.attachEvent("onunload", infosoftglobal.FusionChartsUtil.cleanupSWFs);
		}
		window.attachEvent("onbeforeunload", infosoftglobal.FusionChartsUtil.prepUnload);
		infosoftglobal.unloadSet = true;
	}
}
/* Add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}
/* Add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* Function to return Flash Object from ID */
infosoftglobal.FusionChartsUtil.getChartObject = function(id)
{
  var chartRef=null;
  if (navigator.appName.indexOf("Microsoft Internet")==-1) {
    if (document.embeds && document.embeds[id])
      chartRef = document.embeds[id];
	else
	chartRef  = window.document[id];
  }
  else {
    chartRef = window[id];
  }
  if (!chartRef)
	chartRef  = document.getElementById(id);

  return chartRef;
}
/* Aliases for easy usage */
var getChartFromId = infosoftglobal.FusionChartsUtil.getChartObject;
var FusionCharts = infosoftglobal.FusionCharts;

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  /**
   * helper functions for notes
   * requires jquery
   * thomas bukowski, 2008-10-21
   */
  notes_helper: (function(){
    var _object = {
      snap_chart: function(swf, dataUrl, options) {
        RPM.guarded_refresh.disable();

        var params = $H({ 'swf' : swf, 'context_url' : get_complete_url(), 'app_name': $('#agent_popup option:selected').text(), 'app_id': $('#agent_popup option:selected').attr('value') }).merge(get_time_window_with_end_time());
		if (options != null) params = params.merge(options);
        Shadowbox.open({
      	  player: 'html',
      	  content: '<img class="spinner" src="/images/busy.gif" style="display: block; margin: 2em auto; text-align: center;" />',
      	  width: 520,
      	  height: 550
      	},
      	{
      	  animate: false,
      	  animateFade: false,
      	  enableKeys: false,
      	  viewportPadding: 10,
      	  onFinish: function() {
      	    $('#shadowbox').css('top', '30px');
      	    $('#shadowbox_body').css('height', 'auto');
      	  },
      	  onClose: function() {
            $('#shadowbox_body_inner').empty();
            RPM.guarded_refresh.enable();
      	  }
      	});

        $.get('/accounts/' + accountId + '/notes/new', params.toObject(), function(data) {
		  window.snapping_chart_url = dataUrl;
          $('#shadowbox_body_inner').html(data);
        });

      	return false;
      },

  	  submit_note: function(action_after) {
  	  	$('#chart_data').attr('value', getChartFromId('snapping_chart').getDataXML());
    		$('#action_after').attr('value', action_after);
    		$('#working_spinner').replaceWith(SPINNER);
  	  },

      print_note: function() {
        if($.browser.msie)
        {
          alert('Printing in IE isn\'t supported at the moment.');
          return;
        }

        var charts = $('.chart.rendered embed, .chart.rendered object');

        $('body').prepend(
          $('<div id="chart_bitmap_shadowbox" class="shadowbox"></div>').prepend(
            $('<div id="chart_bitmap_please_wait">Please wait while the chart bitmaps are generated.<strong><span>0</span> of '+charts.length+' completed...</strong></div>')
          )
        );

        charts.each(function(i) {
          window.NRRPM.chart_helper.generate_chart_bitmap(this.id);
        });

        var done_func = function() {
          var done = $('.chart.bitmapped').length;

          if(done == charts.length)
          {
            window.print();
            $('#chart_bitmap_please_wait').html($('<strong>When printing has finished, <a href="#">return to note</a>.</strong>'));
            $('#chart_bitmap_please_wait strong a').click(function() {
              $('#chart_bitmap_please_wait').remove();
              $('#chart_bitmap_shadowbox').remove();
              window.NRRPM.notes_helper.undo_print_state();
              return false;
            });
          }
          else
          {
            $('#chart_bitmap_please_wait span').text(done);
            window.setTimeout(done_func, 100);
          }
        };

        window.setTimeout(done_func, 100);
      },

      undo_print_state: function() {
        $('.chart.bitmapped embed, .chart.bitmapped object').each(function() {
          window.NRRPM.chart_helper.remove_chart_bitmap(this.id);
        });
      }
    };

    return _object;
  })()

});

})(jQuery);
/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  /**
    * helpers functions for charts
    * requires jquery
    * thomas bukowski, 2008-10-19
    */
  chart_helper: (function(){

    var chart_list = {};

    var chart_saveAsImage_callback = {};

    var resize_timeout = null;
    $(window).resize(function() {
      if(resize_timeout == null)
      {
        resize_timeout = setTimeout(function() {
          resize_timeout = null;
          jQuery.each(chart_list, function(k, v) {
            _object.resize_chart(v);
          });
        }, 250);
      }
    });

    var png_encoder_ready_state = false;
    var png_encoder_swf = null;

    var _object = {
      enable_fluid_charts: true,

      enable_png_encoder: false,

      enable_transparent_flash_charts: true,

      /**
       * Encodes a PNG, given a FusionCharts-generated bitmap snapshot of the graph.
       * Returns a base64-encoded PNG string which can then be set to the src of an <img>.
      */
      encode_png: function(width, height, bitmap_data)
      {
        if(!png_encoder_ready_state)
          return false;

        return 'data:image/png;base64,'+png_encoder_swf.get(0).encode_png(width, height, bitmap_data);
      },

      /**
       * Sets a flag saying that the PNG encoder is ready to encode some PNGs.
       * Called by AS3_PNG_Encoder.swf once it has finished loading.
      */
      png_encoder_ready: function()
      {
        png_encoder_ready_state = true;
      },

      /**
       * Attaches the PNG encoder to the footer.
      */
      attach_png_encoder: function()
      {
        if(!png_encoder_swf)
        {
          $('#universe').css('position', 'relative').append($('<div id="png_encoder_swf"></div>'));
          swfobject.embedSWF("/fusion_charts/AS3_PNG_Encoder.swf", "png_encoder_swf", "10", "10", "9.0.0", '', {}, {allowscriptaccess: 'always'});
          png_encoder_swf = $('#png_encoder_swf').css({position: 'absolute', bottom: -11, right: 0, visibility: 'hidden'});
        }
      },

      /**
       * Replaces the Flash object with a PNG and removes the popup action panel.
       * FusionCharts calls this function after it finishes the snapshot process,
       * which is itself initiated by generate_chart_bitmap.
      */
      replace_chart_with_png: function(domid, width, height, bitmap_data)
      {
        if(png_encoder_ready_state && $('#'+domid).length)
        {
          $('#'+domid).hide();
          $('#'+domid).parent().prepend($('<img />').css({
            display: 'block',
            width: width+'px',
            height: height+'px'
          }).attr('src', _object.encode_png(width, height, bitmap_data)));

          $('#'+domid).parent()
            .removeClass('bitmapping')
            .addClass('bitmapped')
            .css('height', height+'px')
            .children('.action_panel').hide();

          if(typeof chart_saveAsImage_callback[domid] == 'function')
            chart_saveAsImage_callback[domid](domid);
        }
      },

      /**
       * Calls saveAsImage, a function exposed by FusionCharts that will then
       * initiate the snapshot process inside Flash. After the process is complete, the
       * replace_chart_with_png function is called from within Flash.
       * Also removes the chart from the fluid resizing list.
      */
      generate_chart_bitmap: function(id, completion_callback)
      {
        if(png_encoder_ready_state)
        {
          $('#'+id).parent().removeClass('rendered');
          chart_saveAsImage_callback[id] = completion_callback;
          getChartFromId(id).saveAsImage();
        }
      },

      /**
       * Remove the chart bitmap and restore the flash file (typically call after printing is
       * complete)
      */
      remove_chart_bitmap: function(id) {
        var chart = $('#'+id);

        chart.show();
        chart.parent().addClass('rendered').removeClass('bitmapping bitmapped');
        chart.siblings('img').remove();
        chart.siblings('.action_panel').show();
      },

      /**
       * gets the FusionCharts object from the chart
       *
       * @param {string | DOM Object | jQuery Object} chart_div The id of the containing div for the chart, or a reference to the chart, obtained through prototype's $() or jQuery.
       *
       * @return {boolean} The FusionCharts object for that chart, or false if the object wasn't found in the DOM
       */
      get_fusioncharts_object: function(chart_div) {
        if(typeof chart_div == 'string')
          chart_div = $('#'+chart_div).get(0);
        else if(typeof chart_div == 'object' && typeof chart_div.jquery == 'string')
          chart_div = chart_div.get(0);

        return (chart_div.FusionChartObj)? chart_div.FusionChartObj : false;
      },

      chart_rendered: function(id) {
        var chart = getChartFromId(id).parentNode.addClassName('rendered');
      },

  	  add_time_to_data_url: function(dataUrl)
  	  {
  	  	var time_window = get_time_window_as_object(null);

  	  	if(dataUrl.indexOf('?') == -1)
  	  	  dataUrl += '?';

  			dataUrl += '&' + $.param(time_window);
        return dataUrl;
  	  },

      create_chart: function(swf, id, w, h, debugMode, registerWithJS, divId, dataUrl, snappable, is_fluid, chart_title)
      {
        snappable = (snappable == null)? true : snappable;
        is_fluid  = (is_fluid  == null)? true : is_fluid;
        chart_title = (chart_title == null) ? '' : chart_title;

        registerWithJS = 1;

        var container = $('#'+divId);
        if(container.length == 0)
        {
          throw new Error('The element reference by ID divId (#'+divId+') must already exist in the DOM.');
          return;
        }
        container.empty();

        var chart = new FusionCharts(swf, id, w, h, debugMode, registerWithJS, '#ffffff');
        /* FusionCharts claims that their getChartFromId javascript function does this, but
         * actually it just returns a reference to the DOM object */
        container.get(0).FusionChartObj = chart;

        chart.addVariable('chartWidth',  (String(w).search('%') > -1) ? container.width()-8: w);
        chart.addVariable('chartHeight', (String(h).search('%') > -1) ? container.height() : h);

        if (dataUrl == null) {
          chart.setDataXML('<chart/>');
        }
        else
        {
          chart.originalDataUrl = dataUrl;
          dataUrl = escape(_object.add_time_to_data_url(dataUrl));

          chart.setDataURL(dataUrl);

        }
    		chart.setTimeWindow = function(time_window)
  			{
  				var url = this.originalDataUrl + '&' + time_window.toQueryString();
  				this.setDataURL(url);
  			};

  			if(_object.enable_transparent_flash_charts)
          chart.setTransparent(true);

        chart.render(divId);
        if(_object.enable_fluid_charts && is_fluid)
          chart_list[id] = container.get(0);

        if (h > 160) {
          container.append($('<div class="logo"><img src="/images/new_relic_rpm_transparent.png" /></div>'));
        }

        if (window.NRRPM.notes.enabled && snappable)
        {
          var actionPanel = $('<div class="action_panel"><ul class="clearfix"></ul></div>');

          actionPanel.children('ul').append(
            $('<li></li>').append(
              $('<a href="#"><img src="/images/16x16/comment_edit.png" class="inline" />Add to Note</a>').click(function() {
                window.NRRPM.notes_helper.snap_chart(swf, chart.originalDataUrl);
                return false;
              })
            )
          );

          container.append(actionPanel);
        }

        if (window.NRRPM.notes_v2.enabled && snappable)
        {
          var actionPanel = $('<ul class="action_bar disrespect_visited clearfix"></ul>');

          actionPanel.append(
            $('<li></li>').append(
              $('<a href="#"><img src="/images/16x16/comment_edit.png" class="inline" />Add to Note</a>').click(function() {
                window.RPM.new_note(swf, chart.originalDataUrl, {'chart_title': chart_title});
                return false;
              })
            )
          );

          container.append(actionPanel);
        }

        return chart;
      },

      resize_chart: function(chart) {
        if(chart.parentNode && chart.hasClassName('rendered') && typeof chart.FusionChartObj.redrawChart == 'function')
          chart.FusionChartObj.redrawChart();
      },

      set_chart_time_window: function(chart_div, time_window) {
        var chart = _object.get_fusioncharts_object(chart_div);

        if(chart)
        {
          chart.setTimeWindow(time_window);
          return true;
        }
        else
          return false;
      },

      pie_chart_type: 'Pie2D',
      multiseries_combo_chart_type: 'MSCombiDY2D',
      multiseries_line_chart_type: 'MSLine',
      horizontal_bar_chart_type: 'Bar2D',
      drag_line_chart_type: 'DragLine',

      generate_chart: function(options){//chart_type, width, height, params, chart_id) {
        var
          chart_type = options.chart_type,
          height = options.height || 250,
          width = options.width || '100%',
          params = options.params,
          chart_id = options.chart_id || "chart_"+(new Date()).getTime();

        var swf = '/fusion_charts/'+chart_type+'.swf';

        var dataUrl = '/' + params.controller + '/' + params.action;
        delete params.controller;
        delete params.action;

        dataUrl += '?' + $.param(params);

        window.NRRPM.chart_helper.create_chart(swf, chart_id, width, height, 0, 1, "div_"+chart_id, dataUrl);
      }
    }; // END actual object

    $(function() {
      if(!$.browser.msie && _object.enable_png_encoder)
        _object.attach_png_encoder();
    });

    return _object;
  })()

});

})(jQuery);

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  /**
   * time window dynamically updating fusionchart graphs
   * requires jquery
   * thomas bukowski, 2008-10-17
   */
  dynamic_time_window: (function()
  {
    var TIME_WINDOW_SELECTOR = '#time_window_popup';
    var TIME_WINDOW_FORM = '#time_window_popup';
    var TIME_WINDOW_PING_URL = '/browser/set_time_window';

    var original_time_window = null; // holds time window at page load

    var _object = {
      enabled: false,
      callbacks: {},

      get_current_time_window: function() {
        return $(TIME_WINDOW_SELECTOR).val();
      },

      change_time: function(params) {
        /** update session with new time window
         * must be synchronously done before (or after) chart refreshes
         * (here, it's done before the chart refreshes, since it's unclear if there is a
         * way to monitor when all the charts have finished refreshing)
         * the reason is that each chart XML request also returns a session cookie
         * and those session cookies must not overwrite the one from this ajax request
         * This is an ajax request which may update the calendar controls on the page to
         * reflect the new time selection.
         */
        _object.toggle_working_spinner('show');
		    params.set('update_time_control', time_control_requires_update());

		    if($('#max_time_window_duration').length)
		    {
          var max_time_window_duration = $F('max_time_window_duration');
          if (max_time_window_duration) {
            params.set('max_time_window_duration', max_time_window_duration);
          }
        }
		    params = get_account_agent_params(params);
		    new Ajax.Request(TIME_WINDOW_PING_URL, {asynchronous:true, evalScripts:true, parameters:params.toObject()});
	    },

      update_page: function() {
	  		if (window.NRRPM_dynamic_time_update)
			{
				window.NRRPM_dynamic_time_update();
				_object.toggle_working_spinner('hide');
				return;
			}
		    _object.toggle_working_spinner('hide');

		    var new_time_window = get_time_window(null);
		    var success = true;

		    $('.chart').each(function(i) {
  		    var chart = window.NRRPM.chart_helper.get_fusioncharts_object(this.id);

  		    if(success && chart) {
  		      success = success & window.NRRPM.chart_helper.set_chart_time_window(this.id, new_time_window);
  		    }
  		    else
  		      success = false;
  		  });

		    $.each(this.callbacks, function() {
		      this.apply(_object, [$, new_time_window]);
		    });

  		  if(!success && typeof failure_callback == 'function')
  		    failure_callback(params.toQueryString());
      }, // END update_chart()

      register_callback: function(key, func) {
        this.callbacks[key] = func;
      },

      unregister_callback: function(key) {
        if(this.callbacks[key])
          delete this.callbacks[key];
      },

      toggle_working_spinner: function(force) {
        var spinner = $('#time_window_spinner');

        if(spinner.length == 0)
        {
          spinner = $('<img id="time_window_spinner" class="spinner" src="/images/busy.gif" />').hide();
          $('#time_window_label').before(spinner);
        }

        if(force == 'show')
          spinner.show();
        else if(force == 'hide')
          spinner.hide();
        else
          spinner.toggle();
      }

    }; // END actual object

    $(function() {
      if(_object.enabled) {
        original_time_window = _object.get_current_time_window();
      }
    });

    return _object;
  })()

});

})(jQuery);

(function($) {

  window.NRRPM = $.extend(window.NRRPM, {

    /**
    * Custom dashboard helper
    * sdaubin, 2009-03-10
    */
    dashboard_helper: {
      restore: function(revision) {
        $('#dashboard_source').attr('value', revision.source);
        window.NRRPM.tabs_helper.change_tab('#edit_dashboard', 'edit');
      },

      resize: function() {
        console.log("resize() called before autoresize() was called. Call autoresize() to set up the DOM for resizing before calling resize().");
      },

      setup_autoresize: function() {
        if($('body').hasClass('autoresize-applied')) return; // only bind once

        var body = $('body');
        var wrapper = $('<div id="universe_wrapper"></div>');
        var universe = $('#universe');

        var document_height = $(document).height();
        var footer_offset = $('#dashboard_update_buttons_bottom').offset()['top'];
        var footer_height = $('#footer').outerHeight(true);
        footer_offset += footer_height;

        var dashboard_source = $('#dashboard_source');
        var dashboard_help = $('#accordion').wrap("<div></div>");

        body.addClass('autoresize').addClass('autoresize-applied');
        universe.wrap(wrapper);

        var resize = function() {
          if(!$('body').hasClass('autoresize')) return;

          var window_height = $(window).height();

          var top = dashboard_source.offset()['top'];
          var bottom = document_height - footer_offset;
          var new_height = window_height - top - bottom;
          dashboard_source.height(new_height);

          var top = dashboard_help.offset()['top'];
          var bottom = document_height - footer_offset;
          var new_height = window_height - top - bottom;
          dashboard_help.height(new_height);

          $("#accordion").accordion("resize");

          var form = $("#metric_selector_form");
          var container_height = form.parent().height();
          var results = $("#metric_selector_results");

          var non_results_rows = form.find('div.row:not(:eq(1)), div.row:eq(1) label');
          var non_results_height = 0;
          $.each(non_results_rows, function() {
            non_results_height += $(this).outerHeight(true);
          });

          var new_height = container_height - non_results_height;
          results.height(new_height);
        };
        NRRPM.dashboard_helper.resize = resize;

        var resize_timeout = null;
        $(window).resize(function() {
          if(resize_timeout == null)
          {
            resize_timeout = setTimeout(function() {
              resize_timeout = null;
              resize();
            }, 250);
          }
        });
      }
    }

  });

})(jQuery);

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  /**
   * helper functions for sending emails
   * requires jquery
   * sdaubin, 2009-01-26
   */
  email_helper: (function(){
    var _object = {
      new_email: function(new_email_url) {
        Shadowbox.open({
      	  player: 'html',
      	  content: '<img class="spinner" src="/images/busy.gif" style="display: block; margin: 2em auto; text-align: center;" />',
      	  width: 520,
      	  height: 'auto'
      	},
      	{
      	  animate: false,
      	  animateFade: false,
      	  enableKeys: false,
      	  viewportPadding: 10,
      	  onFinish: function() {
      	    $('#shadowbox').css('top', '30px');
      	    $('#shadowbox_body').css('height', 'auto');
      	  },
      	  onClose: function() {
            $('#shadowbox_body_inner').empty();
      	  }
      	});

        $.get(new_email_url, null, function(data) {
          $('#shadowbox_body_inner').html(data);
        });

      	return false;
      }
    };

    return _object;
  })()

});

})(jQuery);

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  /**
   * helper functions for tab bar + tabs
   * requires jquery
   * thomas bukowski, 2008-11-07
  */
  tabs_helper: (function() {

    $.fn.getClassForTab = function() {
      if(this.length)
        return $.trim(this.attr('class').toLowerCase().replace(/(current|nocache|disabled)/ig, ''));
      else
        return '';
    };

    var _object = {
      change_tab: function(ul_id, li_class, update, already_rendered) {
        var context = $(ul_id+' li.'+li_class+' a');

        if(context.length != 1) return false;

        if(!already_rendered)
          context.click();
        else
        {
          _object.cleanup_tab_contents(update);
          _object.tab_change_after(context, li_class, update, true);
        }

        return true;
      },

      tab_change_before: function(context, li_class, update, loading) {
        $(context).parent().parent().children('.current').removeClass('current');

        if($('#'+update+'_'+li_class).length == 0) {
          $('#'+update).append($('<div id="'+update+'_'+li_class+'"></div>'));
        }
        var contents_html = $('#'+update+'_'+li_class).show();

        loading = $.trim(loading);

        if(loading.length > 0) {
          contents_html.html(loading);
        }
      },

      tab_change_after: function(context, li_class, update, block_state_change) {
        var context = $(context);

        var ul_id = context.parent().parent().attr('id');
        if(!block_state_change && ul_id && ul_id.length > 0) {
          var li_class = context.parent().getClassForTab();
          li_class = li_class == '' ? null : li_class;
          $.ajaxState.change('tab-'+ul_id, li_class);
        }
        context.parent().addClass('current');
      },

      tab_change_complete: function(ul_id, li_class, update) {
        $(ul_id+' li.'+li_class+' a:first img.spinner').remove();
      },

      tab_change_condition: function(context_obj, li_class, update) {
        var context = $(context_obj);
        var ul_id = '#'+context.parent().parent().attr('id');
        var contents_html = $('#'+update+'_'+li_class);
        var current_li_class = $(ul_id+' li.current').getClassForTab();


        _object.cleanup_tab_contents(update);

        $(ul_id+' li.current:first a:first img.spinner').remove();

        _object.save_current_tab(ul_id, current_li_class, update);

        if(_object.restore_tab(ul_id, li_class, update)) {
          return false;
        }
        else {
          context.append(SPINNER);
          return true;
        }
      },

      save_current_tab: function(ul_id, li_class, update) {
        var li = $(ul_id+' li.current');
        if(li.length == 1) {
          if(li.hasClass('nocache')) {
            $('#'+update+'_'+li_class).remove();
          }
          else {
            $('#'+update+'_'+li_class).hide();
          }
          return true;
        }
        return false;
      },

      restore_tab: function(ul_id, li_class, update) {
        var context = $(ul_id+' li.'+li_class+' a:first');
        var contents_html = $('#'+update+'_'+li_class);

        if(!context.parent().hasClass('nocache') && contents_html.not(':empty').length == 1) {
          _object.tab_change_before(context, li_class, update);

          contents_html.show();

          _object.tab_change_after(context, update);

          return true;
        }
        return false;
      },

      cleanup_tab_contents: function(update) {
        $('#'+update+'__intro').hide();
      }
    };

    return _object;
  })()

});

})(jQuery);

(function($) {

window.NRRPM = $.extend(window.NRRPM, {

  form_helper: (function(){
    var original_submit_values = {};

    var _object = {
      disable_submit: function(selector, with_message) {
        original_submit_values[selector] = $(selector).attr('value');
        var with_message = with_message ? with_message : 'Loading...';
        $(selector).attr('disabled', 'disabled').attr('value', with_message).after(SPINNER);
      },

      reenable_submit: function(selector, with_message) {
        $(selector).attr('disabled', '').attr('value', original_submit_values[selector]).next('img.spinner').remove();
      },

      disable_fieldset: function(selector) {
        $(selector).addClass('disabled').find('input, button, select, textarea').attr('disabled', 'disabled');
      },

      reenable_fieldset: function(selector) {
        $(selector).removeClass('disabled').find('input, button, select, textarea').attr('disabled', '');
      },

      disable_select: function(selector) {
        $(selector).attr('disabled', 'disabled');
      },

      reenable_select: function(selector) {
        $(selector).attr('disabled', '');
      }
    };

    return _object;
  })()

});

})(jQuery);


function get_account_agent_params_without_tw(additional_params, check_url)
{
  var additional_params = additional_params || {};
	var h = new Hash().merge(additional_params);

	var check_url = check_url || false;

	if(check_url && (/\/accounts\/[\d]+\/agents\/[\d]+\//ig).test(location.pathname)) {
	  return h;
	}

  if(typeof agentId   != 'undefined' && agentId   != null) h.set('agent', agentId);
  if(typeof accountId != 'undefined' && accountId != null) h.set('account_id', accountId);

	return h;
}
function get_account_agent_params(additional_params, check_url)
{
	var h = new Hash().merge(additional_params).merge(get_time_window());
  return get_account_agent_params_without_tw(h, check_url);
}

/**
 * Returns the offset of the local timezone from the RPM user's timezone setting in seconds.
 */
function get_timezone_offset()
{
	var curdate = new Date();
	var local_offset = -curdate.getTimezoneOffset() * 60; // convert minutes to seconds
	var rpm_offset = $F('tzoffset');
  return parseInt(local_offset) - parseInt(rpm_offset);
}

/**
 * Returns true if the time control html needs to be updated to accurately reflect the current time selection.
 */
function time_control_requires_update()
{
	var end_time = $F('time_window_end_time');
	if (!end_time.empty()) // add end time if it is set
	{
		var date_long = Date.parse(end_time);
		var date = new Date();

		return !isNaN(date_long);
	}
	return false;
}

function get_time_window_with_end_time(){
	return get_time_window(null, { include_end_time: true });
}

function get_time_window(popup, options)
{
	options = $H(options ? options : { include_end_time : false });
    popup = (popup)? popup : $('time_window_popup');
	if (!popup) return $H({});

	var params = $H(popup.serialize().toQueryParams());
	var end_time = $F('time_window_end_time');
	if (!end_time.empty()) // add end time if it is set
	{
		var date_long = Date.parse(end_time);
		var date = new Date();

		if (isNaN(date_long))
		{
			date.setTime(parseInt(end_time) * 1000);
		}
		else
		{
      date.setTime(date_long + get_timezone_offset()*1000);
		}
		params.set('tw[end]', date.getTime() / 1000);
	}
	else if (options.get('include_end_time'))
	{
		var date = new Date();
		params.set('tw[end]', parseInt(date.getTime() / 1000) - 60 ); // take off the last minute
	}
	return params;
}

function get_time_window_as_object(popup, options) {
  return get_time_window(popup, options).toObject();
}

/**
 * Called when a FusionChart is rendered.
 * @param {Object} id
 */
function FC_Rendered(id)
{
  if(NRRPM && NRRPM.chart_helper) NRRPM.chart_helper.chart_rendered(id);
}

function is_live()
{
	var end_time = $F('time_window_end_time');
	return end_time.empty();
}

function set_time_window(popup)
{
  var params = get_account_agent_params_without_tw(get_time_window(popup), true);
	if(!NRRPM.dynamic_time_window.enabled)
	  set_tw_params(params.toObject());
	else
    NRRPM.dynamic_time_window.change_time(params);
}

function set_tw_params(params) {
  window.location.href =
  location.pathname +
  replace_querystring_tw_params(params) +
  location.hash;
}

/*
Pass in an Object of parameters to merge into the querystring, replacing parameters with the same key and dropping any *time window* parameters (tw[dur], tw[end]) not in the passed-in params. Returns the processed querystring with a '?' in front
*/
function replace_querystring_tw_params(params) {
  var $ = jQuery,
      TW_PARAM_KEYS = {'tw[dur]': true, 'tw[end]': true};

  if($.param(params) == '')
    return location.search;

  if(location.search == '' || location.search == '?')
    return '?'+$.param(params);

  var i, querystring = {},
      sections = unescape(location.search.slice(1)).split('&');

  for(i = 0; i < sections.length; i++) {
    var section = sections[i].split('=', 2);

    if(TW_PARAM_KEYS.hasOwnProperty(section[0]) && !params.hasOwnProperty(section[0])) {
      delete querystring[section];
    }
    else if(section.length == 1) {
      querystring[section] = '';
    }
    else {
      querystring[section[0]] = section[1];
    }
  }

  return '?'+$.param($.extend(querystring, params));
}

/**
 * Adjust a date time for the calendar control to account for differences between the user's timezone setting
 * and the local machine timezone setting.
 *
 * @param {Object} date_string a Date object or the # of seconds since 1970
 */
function get_date_with_timezone_offset(date_string)
{
	var date;
	if (date_string instanceof Date)
	{
		date = date_string;
	}
	else
	{
		var dateInt = parseInt(date_string);
		date = new Date();
		date.setTime(dateInt * 1000);
	}

	date.setTime(date.getTime() - get_timezone_offset()*1000);
	return date;
}

/* Display a flash message at the top of the page.  This will create the flash div if it does not already exist.
 */
function show_messages(messages)
{
	if (arguments.length == 2) {
		show_message(arguments[0], arguments[1]);
	}
	else {
		messages = new Hash(messages);
	}
	hide_messages(messages.keys());

	messages.each(function(pair) {
		show_message(pair.key, pair.value);

	});
}

/**
 * Hides the flash message divs.  If messages_to_leave_open is given (as a string or an array), those
 * messages will be left visible.
 * @param {Object} messages_to_leave_open
 */
function hide_messages(messages_to_leave_open){
	var messageIds = ['info', 'error', 'warning', 'notice'];
	if (messages_to_leave_open)
	{
		if (messages_to_leave_open.camelize) // if this is a string, just remove it
			messageIds = messageIds.without(messages_to_leave_open);
		else
			messageIds = messageIds.reject(
			    function(id){return messages_to_leave_open.indexOf(id) > -1});
	}
	messageIds.each(
		function(id)
		{
			id = 'flash_' + id;
			if ($(id)) $(id).hide();
		});
}

/* Display a flash message at the top of the page.  This will create the flash div if it does not already exist.
 */
function show_message(type, message)
{
	var id = 'flash_' + type;
	var flash_div = $(id);

	if (flash_div)
	{
		flash_div.hide();
		flash_div.innerHTML = message;
	}
	else
	{
		flash_div = new Element('div', { 'class': 'flash ' + type, 'id': id });
		flash_div.hide();
		flash_div.innerHTML = message;
		var content_div = $('content');
		content_div.insertBefore(flash_div, content_div.firstChild);
	}

	jQuery('#'+id).slideDown(500);
}

function show_flash(type, message)
{
	var id = show_message(type, message);
}


function show_working_message()
{
	show_message('info', "<img src='/images/busy.gif'/> Working");
}

function set_agent(popup)
{
  var value = popup.options[popup.selectedIndex].value;

  var params = new Hash({ 'agent' : value, 'referrer' : window.location.toString() });
  url = "/data_access/set_agent?" + params.toQueryString();
  window.location = url;
}

function set_page(popup) {
  var url = unescape(popup.options[popup.selectedIndex].value);
  window.location = unescape(url);
}

function render_chart(chart_type, data_url, div_id, width, height) {
  NRRPM.chart_helper.create_chart("/fusion_charts/" + chart_type + ".swf", div_id + "_chart", width, height, "0", "1", div_id, data_url);
}

function select_tab(tab) {
  tab = tab + '_tab';
  $$('li.tab').each(function(value, index) {
	  if(value.id == tab) {
		  value.addClassName('selected');
	  }
	  else {
		  value.removeClassName('selected');
  	}
	});
}

function process_checkbox(box, host_box_id) {
	if(box.hasClassName('host')) {
		$(host_box_id).select('input').each(function(value) {
			value.checked = box.checked;
		});
	}
	else {
		if(box.checked) {
			$(host_box_id).checked = true;
		}
		else {
			var last_selected = true;
			box.adjacent('input').each(function(value) {
				if(value.checked) {
					last_selected = false;
				}
			});
			$(host_box_id).checked = !last_selected;
		}
	}
}

function toggle_collapse(element) {
	if(Element.hasClassName(element, "collapse")) {
		Element.removeClassName(element, "collapse");
		Element.addClassName(element, "expand");
	} else {
		Element.removeClassName(element, "expand");
		Element.addClassName(element, "collapse");
	}
}

function select_checkboxes(element, all_none) {
	elements = document.getElementsByTagName(element);
	for(i = 0; i < elements.length; i++) {
		if(elements[i].type == 'checkbox') {
			elements[i].checked = all_none;
		}
	}
}

function show_change_sub() {
  $('subscriptions').show();
}

/**
 * Returns d if d is a number, otherwise d is treated as a relative dimension (ie 50%),
 * and the value returned is d * (size of the body) for the given orientation.
 *
 * @param {String} orientation the orienation of the dimension value, either width or height
 */
function fix_dimension(element, d, orientation)
{
	if (isNaN(d))
	{
		if (element && element.parentNode)
		{
			try {

				var bodyDimension = window.document.body[get_client_orientation(orientation)] - 100;
				var percentage = get_dimension_percentage(element.parentNode, orientation);
				d = bodyDimension * percentage;
			}
			catch (e)
			{
				return d;
			}
		}
	}
	return d;
}

/**
 *
 * @param {Object} element
 * @param {String} orientation the orienation of the dimension value, either width or height
 */
function get_dimension_percentage(element, orientation)
{
	var d = element[orientation];
	d = d.substring(0, d.length - 1);
	return parseFloat(d) / 100;
}

/**
 * Returns clientWidth if o is width and clientHeight is o is height.
 * @param {String} o
 */
function get_client_orientation(o)
{
	var orientation = o.toLowerCase();
	return 'client' + orientation.substring(0,1).toUpperCase() + orientation.substring(1);
}

/**
 * Create a FusionChart, working around an IE bug related to relative dimensions.
 */
if(typeof NRRPM.chart_helper != 'undefined')
  create_fusion_chart = NRRPM.chart_helper.create_chart;

function get_complete_url()
{
  var url = window.location.pathname;

  if(window.location.search.length > 0)
    url += window.location.search;

  var timewindow = get_time_window_with_end_time().toQueryString();
  if(timewindow.length > 0) // some windows don't have a time window, e.g. scalability analysis
  {
    if(url.indexOf('?') > -1)
      url += '&'+timewindow;
    else
      url += '?'+timewindow;
  }

  var hash = encodeURIComponent(decodeURIComponent(window.location.hash.substring(1)));
  if(hash.length > 0)
    url += '#'+hash;

  return url;
}

/* Removed by KMF due to js error created */

/*
var SelectAllCheckboxesObserver = Class.create({
  initialize: function(checkAllCheckbox, list) {
  	list = list.without(checkAllCheckbox);

    checkAllCheckbox.observe("click", function(event) {
		list.each(function(item) {
			item.checked = checkAllCheckbox.checked;
		});
    });

	for (i = 0; i < list.length; i++) {
		list[i].observe("click", function(event) {
			if (this.checked)
			{
				var unchecked_item = list.find(function(item) { return item.checked == false;});
				checkAllCheckbox.checked = unchecked_item == null;
			}
			else
			{
				checkAllCheckbox.checked = false;
			}
		});
	}
  }
});
*/

/* Table helper */

function sort_table_using_form(column, sort_dir, column_working_image_id, sort_by_field_id, sort_dir_field_id) {
	$(column_working_image_id).show();

	$(sort_by_field_id).value = column;
	$(sort_dir_field_id).value = sort_dir;
	$(sort_by_field_id).form.onsubmit();
}


/* Transaction Tracer */


/**
 * Dynamically shows/hides a sql explain plan.
 *
 * @param {Object} element The html hyperlink that was clicked to toggle the explain
 * @param {int} segment_id
 * @param {String} url The url used to fetch the explain plan for the current segment
 * @param {String} busy_image
 */
function show_segment_sql(element, segment_id, url, busy_image)
{
	var sql_explain_id = 'segment_explain_' + segment_id;
	if ($(sql_explain_id)) {
		Effect.toggle(sql_explain_id, 'blind', { duration: 0.5 });
	}
	else {
		var column = element.getOffsetParent();
		var row = column.parentNode;
		var newRow = new Element('tr');
		row.insert({after: newRow});
		var newColumn = new Element('td', { colspan: row.cells.length});
		newRow.insert(newColumn);

		var sqlDiv = new Element('div', {id:sql_explain_id}).update("Fetching the SQL explain plan <img src='" + busy_image +"'>");
		sqlDiv.className = 'explain_segment';
		newColumn.insert(sqlDiv);

		new Ajax.Updater(sql_explain_id, url, {asynchronous:true, evalScripts:true});
	}
}

/* Removed by KMF due to js error created */

/*
if(typeof Shadowbox !== 'undefined') {
Shadowbox.loadSkin('classic', '/skin'); // use the "classic" skin
window.onload = Shadowbox.init;
}
*/

jQuery.preload = function(images) {
  jQuery(function() {
    jQuery.each(images, function(){
        jQuery('<img/>')[0].src = this;
    });
  });
};

jQuery(function($) {
  if(jQuery.tablesorter) {

    jQuery.tablesorter.addParser({
      id: "numericWithUnits",
      is: function(s) {
        return /^[0-9\.]+ ?[a-z]+$/i.test($.trim(s));
      },
      format: function(s) {
        return $.tablesorter.formatFloat(s.replace(new RegExp(/ ?[a-z]+$/ig),""));
      },
      type: "numeric"
    });

    jQuery.tablesorter.addParser({
      id: "numericWithSeparator",
      is: function(s) {
        return /^([0-9]+,)*[0-9]+(\.[0-9]+)?$/i.test($.trim(s));
      },
      format: function(s) {
        return $.tablesorter.formatFloat(s.replace(',',''));
      },
      type: "numeric"
    });

    jQuery.tablesorter.addParser({
      id: "float",
      is: function(s) {
        return /^[0-9]*\.[0-9]+$/i.test($.trim(s));
      },
      format: function(s) {
        return $.tablesorter.formatFloat(s);
      },
      type: "numeric"
    });

    jQuery.tablesorter.addParser({
      id: "apdex",
      is: function(s) {
        return false; // do not autodetect this parser
      },
      format: function(s) {
        if(/NS/i.test(s))
          return 0;
        else
          return $.tablesorter.formatFloat(s.replace(new RegExp(/^([0-9\.]+).+$/g),"$1"));
      },
      type: "numeric"
    });

    $.tablesorter.addWidget({
      id: "highlightSortedColumns",
      format: function(table) {
        $(table).find('td.sorted').removeClass('sorted');

        var headers = $(table).find('thead:first-child th');
        var index = headers.index(headers.filter('.headerSortDown,.headerSortUp'));

        if(index > -1) {
          $(table).find('tbody tr td:nth-child('+(index+1)+')').addClass('sorted');
        }
      }
    });

    $.tablesorter.addWidget({
      id: "ajaxState",
      format: function(table) {
        var key = 'sort';

        if($(table).data('ajaxState')) {
          $.ajaxState.change(key, table.config.sortList[0].join(','));
        }
        else {
          $(table).data('ajaxState', key);
          $.ajaxState.register(key, function(value) {
            var values = value.split(',');
            $(table).trigger('sorton', [[values]]);
          });
        }
      }
    });
  }
});

