/* Copyright (c) 2007-2010 SPIL GAMES.  DO NOT COPY THIS CODE. */
;/*!
 * jQuery JavaScript Library v1.3.1
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-01-21 20:42:16 -0500 (Wed, 21 Jan 2009)
 * Revision: 6158
 */
(function(){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Return a 'clean' array
			jQuery.makeArray( this ) :

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

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

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

		ret.context = this.context;

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

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

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

		return this;
	},

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

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

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

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

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

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

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

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

		var ret = "";

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

		return ret;
	},

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

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

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

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

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

		return this;
	},

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

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

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

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

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

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

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

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

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

			return this.pushStack( /[^+>] [^+>]/.test( selector ) ?
				jQuery.unique( elems ) :
				elems, "find", selector );
		}
	},

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

		// Need to set the expando to null on the cloned set if it exists
		// removeData doesn't work here, IE removes it from the original as well
		// this is primarily for IE but the data expando shouldn't be copied over in any browser
		var clone = ret.find("*").andSelf().each(function(){
			if ( this[ expando ] !== undefined )
				this[ expando ] = null;
		});

		// Copy the events from the original to the clone
		if ( events === true )
			this.find("*").andSelf().each(function(i){
				if (this.nodeType == 3)
					return;
				var events = jQuery.data( this, "events" );

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

		// Return the cloned set
		return ret;
	},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

					return values;				
				}

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

			}

			return undefined;
		}

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

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

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

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

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

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

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

	html: function( value ) {
		return value === undefined ?
			(this[0] ?
				this[0].innerHTML :
				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,
				extra = this.length > 1 ? fragment.cloneNode(true) : fragment;

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

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

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

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

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

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

function now(){
	return +new Date;
}

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

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

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

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

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

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

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

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

			}

	// Return the modified object
	return target;
};

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

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

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

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

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

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

	// Evalulates a script in a global context
	globalEval: function( data ) {
		data = jQuery.trim( data );

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

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

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

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

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

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

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

		return object;
	},

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

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

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

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

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

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

		callback.call( elem );

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

	css: function( elem, name, force ) {
		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;
				var padding = 0, border = 0;
				jQuery.each( which, function() {
					padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
					border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
				});
				val -= Math.round(padding + border);
			}

			if ( jQuery(elem).is(":visible") )
				getWH();
			else
				jQuery.swap( elem, props, getWH );

			return Math.max(0, val);
		}

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

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

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

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

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

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

		else if ( defaultView.getComputedStyle ) {

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

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

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

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

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

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

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

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

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

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

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

		return ret;
	},

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

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

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

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

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

			if ( !elem )
				return;

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

				// Trim whitespace, otherwise indexOf won't work as expected
				var tags = jQuery.trim( elem ).toLowerCase();

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

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

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

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

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

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

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

					[ 0, "", "" ];

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

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

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

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

						// String was a bare <thead> or <tfoot>
						wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
							div.childNodes :
							[];

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

					}

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

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

		});

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

		return ret;
	},

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

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

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

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

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

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

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

					elem[ name ] = value;
				}

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

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

				return elem[ name ];
			}

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

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

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

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

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

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

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

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

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

		if ( set )
			elem[ name ] = value;

		return elem[ name ];
	},

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

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

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

		return ret;
	},

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

		return -1;
	},

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

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

		return first;
	},

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

		try {

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

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

		} catch( e ) {
			ret = array;
		}

		return ret;
	},

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

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

		return ret;
	},

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

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

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

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

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

var userAgent = navigator.userAgent.toLowerCase();

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

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

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

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

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

		return this.each(function(){
			for ( var i = 0, length = args.length; i < length; i++ )
				jQuery( args[ i ] )[ original ]( this );
		});
	};
});

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

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

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

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

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

	empty: function() {
		// Remove element nodes and prevent memory leaks
		jQuery( ">*", this ).remove();

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

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

jQuery.extend({
	cache: {},

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

		var id = elem[ expando ];

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

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

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

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

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

		var id = elem[ expando ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	if ( !checkSet ) {
		checkSet = set;
	}

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

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

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

	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;

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

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

		expr = expr.replace(/\s*,\s*/, "");

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

		old = expr;
	}

	return curLoop;
};

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

			if ( typeof part === "string" ) {
				Sizzle.filter( part, checkSet, true );
			}
		},
		">": function(checkSet, part, isXML){
			if ( typeof part === "string" && !/\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] = typeof part === "string" ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( typeof part === "string" ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},
		"": function(checkSet, part, isXML){
			var doneName = "done" + (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" + (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" && !isXML ) {
				return context.getElementsByName(match[1]);
			}
		},
		TAG: function(match, context){
			return context.getElementsByTagName(match[1]);
		}
	},
	preFilter: {
		CLASS: function(match, curLoop, inplace, result, not){
			match = " " + match[1].replace(/\\/g, "") + " ";

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

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

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

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

			return match;
		},
		ATTR: function(match){
			var name = match[1].replace(/\\/g, "");
			
			if ( Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

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

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

			var doneName = match[0];
			
			if ( parent && (!parent[ doneName ] || !elem.nodeIndex) ) {
				var count = 1;

				for ( var node = parent.firstChild; node; node = node.nextSibling ) {
					if ( node.nodeType == 1 ) {
						node.nodeIndex = count++;
					}
				}

				parent[ doneName ] = count - 1;
			}

			if ( type == "first" ) {
				return elem.nodeIndex == 1;
			} else if ( type == "last" ) {
				return elem.nodeIndex == parent[ doneName ];
			} else if ( type == "only" ) {
				return parent[ doneName ] == 1;
			} else if ( type == "nth" ) {
				var add = false, first = match[2], last = match[3];

				if ( first == 1 && last == 0 ) {
					return true;
				}

				if ( first == 0 ) {
					if ( elem.nodeIndex == last ) {
						add = true;
					}
				} else if ( (elem.nodeIndex - last) % first == 0 && (elem.nodeIndex - last) / first >= 0 ) {
					add = true;
				}

				return add;
			}
		},
		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;
			}
		},
		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 match.test( elem.className );
		},
		ATTR: function(elem, match){
			var result = Expr.attrHandle[ match[1] ] ? Expr.attrHandle[ match[1] ]( elem ) : elem[ match[1] ] || elem.getAttribute( match[1] ), 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 :
				!match[4] ?
				result :
				type === "!=" ?
				value != check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},
		POS: function(elem, match, i, array){
			var name = match[2], filter = Expr.setFilters[ name ];

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

var origPOS = Expr.match.POS;

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

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

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

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

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

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

		return ret;
	};
}

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

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

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

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

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

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

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

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

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

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

				results = tmp;
			}

			return results;
		};
	}

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

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

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

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

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

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

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			elem = elem[dir];
			var match = false;

			while ( elem && elem.nodeType ) {
				var done = elem[doneName];
				if ( done ) {
					match = checkSet[ done ];
					break;
				}

				if ( elem.nodeType === 1 && !isXML )
					elem[doneName] = i;

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

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			elem = elem[dir];
			var match = false;

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

				if ( elem.nodeType === 1 ) {
					if ( !isXML )
						elem[doneName] = i;

					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

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

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

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

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

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

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

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

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

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

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

Sizzle.selectors.filters.hidden = function(elem){
	return "hidden" === elem.type ||
		jQuery.css(elem, "display") === "none" ||
		jQuery.css(elem, "visibility") === "hidden";
};

Sizzle.selectors.filters.visible = function(elem){
	return "hidden" !== elem.type &&
		jQuery.css(elem, "display") !== "none" &&
		jQuery.css(elem, "visibility") !== "hidden";
};

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

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

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

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

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

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

	return cur;
};

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

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

	return r;
};

return;

window.Sizzle = Sizzle;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	guid: 1,
	global: {},

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

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

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

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

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

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

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

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

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

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

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

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

			// Handle triggering a single element

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

		event.currentTarget = elem;

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

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

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

		this.triggered = false;

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

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

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

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

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

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

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

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

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

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

				if( event.isImmediatePropagationStopped() )
					break;

			}
		}
	},

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

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

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

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

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

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

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

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

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

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

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

		return event;
	},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	jQuery.each(elems, function(){
		if ( this.fn.call(this.elem, event, this.fn.data) === false )
			stop = false;
	});

	return stop;
}

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

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

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

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

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

var readyBound = false;

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

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

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

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

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

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

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

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

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

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

	jQuery.support = {};

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

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

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

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

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

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

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

	root.removeChild( script );

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

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

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

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

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

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

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

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

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

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

		var self = this;

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

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

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

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

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

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

var jsc = now();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			head.appendChild(script);

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

		var requestDone = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				// Fire the complete handlers
				complete();

				if ( isTimeout )
					xhr.abort();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return this;
	}

});

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

jQuery.extend({

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

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

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

		return opt;
	},

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

	timers: [],

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

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

});

jQuery.fx.prototype = {

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

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

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

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

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

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

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

		t.elem = this.elem;

		if ( t() && jQuery.timers.push(t) == 1 ) {
			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 );
				}
			}, 13);
		}
	},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return true;
	}

};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

		return results;
	},

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


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

		return val !== undefined ?

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

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

	var tl = i ? "Left"  : "Top",  // top or left
		br = i ? "Right" : "Bottom"; // bottom or right

	// innerHeight and innerWidth
	jQuery.fn["inner" + name] = function(){
		return this[ name.toLowerCase() ]() +
			num(this, "padding" + tl) +
			num(this, "padding" + br);
	};

	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function(margin) {
		return this["inner" + name]() +
			num(this, "border" + tl + "Width") +
			num(this, "border" + br + "Width") +
			(margin ?
				num(this, "margin" + tl) + num(this, "margin" + br) : 0);
	};
	
	var type = name.toLowerCase();

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

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

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

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

});})();

;/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */

;(function($) {

$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150
		}, options);

		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };

		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;

		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);

	var blockSubmit;

	// prevent form submit in opera when selecting with return key
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});

	// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {

			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;

			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;

			case KEY.ESC:
				select.hide();
				break;

			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});


	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;

		var v = selected.result;
		previousValue = v;

		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
			}
			v += options.multipleSeparator;
		}

		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}

	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}

		var currentValue = $input.val();

		if ( !skipPrevCheck && currentValue == previousValue )
			return;

		previousValue = currentValue;

		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};

	function trimWords(value) {
		if ( !value ) {
			return [""];
		}
		var words = value.split( options.multipleSeparator );
		var result = [];
		$.each(words, function(i, value) {
			if ( $.trim(value) )
				result[i] = $.trim(value);
		});
		return result;
	}

	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		return words[words.length - 1];
	}

	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue){
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else
							$input.val( "" );
					}
				}
			);
		}
		if (wasVisible)
			// position cursor at end of input field
			$.Autocompleter.Selection(input, input.value.length, input.value.length);
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data && data.length) {
			success(term, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){

			var extraParams = {
				//timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});

			$.ajax({
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				data: extraParams,
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			failure(term);
		}
	};

	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: false,
	cacheLength: 10,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { return row[0]; },
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;

	function matchSubset(s, sub) {
		if (!options.matchCase)
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){
			length++;
		}
		data[q] = value;
	}

	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;

		// track all options for minChars = 0
		stMatchSets[""] = [];

		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;

			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] )
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};

			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}

	// populate any existing data
	setTimeout(populate, 25);

	function flush(){
		data = {};
		length = 0;
	}

	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/*
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}
				return csub;
			} else
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};

	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});

		if( options.width > 0 )
			element.css("width", options.width);

		needsInit = false;
	}

	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};

	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}

	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}

	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}

	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});

                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }

            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.Autocompleter.Selection = function(field, start, end) {
	if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	} else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

})(jQuery);
;/**
 * Ajax Queue Plugin
 * 
 * Homepage: http://jquery.com/plugins/project/ajaxqueue
 * Documentation: http://docs.jquery.com/AjaxQueue
 */

/**

<script>
$(function(){
	jQuery.ajaxQueue({
		url: "test.php",
		success: function(html){ jQuery("ul").append(html); }
	});
	jQuery.ajaxQueue({
		url: "test.php",
		success: function(html){ jQuery("ul").append(html); }
	});
	jQuery.ajaxSync({
		url: "test.php",
		success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); }
	});
	jQuery.ajaxSync({
		url: "test.php",
		success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); }
	});
});
</script>
<ul style="position: absolute; top: 5px; right: 5px;"></ul>

 */
/*
 * Queued Ajax requests.
 * A new Ajax request won't be started until the previous queued 
 * request has finished.
 */

/*
 * Synced Ajax requests.
 * The Ajax request will happen as soon as you call this method, but
 * the callbacks (success/error/complete) won't fire until all previous
 * synced requests have been completed.
 */


(function($) {
	
	var ajax = $.ajax;
	
	var pendingRequests = {};
	
	var synced = [];
	var syncedData = [];
	
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings));
		
		var port = settings.port;
		
		switch(settings.mode) {
		case "abort": 
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return pendingRequests[port] = ajax.apply(this, arguments);
		case "queue": 
			var _old = settings.complete;
			settings.complete = function(){
				if ( _old )
					_old.apply( this, arguments );
				jQuery([ajax]).dequeue("ajax" + port );;
			};
		
			jQuery([ ajax ]).queue("ajax" + port, function(){
				ajax( settings );
			});
			return;
		case "sync":
			var pos = synced.length;
	
			synced[ pos ] = {
				error: settings.error,
				success: settings.success,
				complete: settings.complete,
				done: false
			};
		
			syncedData[ pos ] = {
				error: [],
				success: [],
				complete: []
			};
		
			settings.error = function(){ syncedData[ pos ].error = arguments; };
			settings.success = function(){ syncedData[ pos ].success = arguments; };
			settings.complete = function(){
				syncedData[ pos ].complete = arguments;
				synced[ pos ].done = true;
		
				if ( pos == 0 || !synced[ pos-1 ] )
					for ( var i = pos; i < synced.length && synced[i].done; i++ ) {
						if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error );
						if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success );
						if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete );
		
						synced[i] = null;
						syncedData[i] = null;
					}
			};
		}
		return ajax.apply(this, arguments);
	};
	
})(jQuery);
;/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-22 01:45:56 +0200 (Son, 22 Jul 2007) $
 * $Rev: 2447 $
 *
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);
;/*
 * Thickbox 3 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "/img/pixel.gif";

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(o).2S(9(){1u(\'a.18, 3n.18, 3i.18\');1w=1p 1t();1w.L=2H});9 1u(b){$(b).s(9(){6 t=X.Q||X.1v||M;6 a=X.u||X.23;6 g=X.1N||P;19(t,a,g);X.2E();H P})}9 19(d,f,g){3m{3(2t o.v.J.2i==="2g"){$("v","11").r({A:"28%",z:"28%"});$("11").r("22","2Z");3(o.1Y("1F")===M){$("v").q("<U 5=\'1F\'></U><4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}n{3(o.1Y("B")===M){$("v").q("<4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}3(1K()){$("#B").1J("2B")}n{$("#B").1J("2z")}3(d===M){d=""}$("v").q("<4 5=\'K\'><1I L=\'"+1w.L+"\' /></4>");$(\'#K\').2y();6 h;3(f.O("?")!==-1){h=f.3l(0,f.O("?"))}n{h=f}6 i=/\\.2s$|\\.2q$|\\.2m$|\\.2l$|\\.2k$/;6 j=h.1C().2h(i);3(j==\'.2s\'||j==\'.2q\'||j==\'.2m\'||j==\'.2l\'||j==\'.2k\'){1D="";1G="";14="";1z="";1x="";R="";1n="";1r=P;3(g){E=$("a[@1N="+g+"]").36();25(D=0;((D<E.1c)&&(R===""));D++){6 k=E[D].u.1C().2h(i);3(!(E[D].u==f)){3(1r){1z=E[D].Q;1x=E[D].u;R="<1e 5=\'1X\'>&1d;&1d;<a u=\'#\'>2T &2R;</a></1e>"}n{1D=E[D].Q;1G=E[D].u;14="<1e 5=\'1U\'>&1d;&1d;<a u=\'#\'>&2O; 2N</a></1e>"}}n{1r=1b;1n="1t "+(D+1)+" 2L "+(E.1c)}}}S=1p 1t();S.1g=9(){S.1g=M;6 a=2x();6 x=a[0]-1M;6 y=a[1]-1M;6 b=S.z;6 c=S.A;3(b>x){c=c*(x/b);b=x;3(c>y){b=b*(y/c);c=y}}n 3(c>y){b=b*(y/c);c=y;3(b>x){c=c*(x/b);b=x}}13=b+30;1a=c+2G;$("#8").q("<a u=\'\' 5=\'1L\' Q=\'1o\'><1I 5=\'2F\' L=\'"+f+"\' z=\'"+b+"\' A=\'"+c+"\' 23=\'"+d+"\'/></a>"+"<4 5=\'2D\'>"+d+"<4 5=\'2C\'>"+1n+14+R+"</4></4><4 5=\'2A\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4>");$("#Z").s(G);3(!(14==="")){9 12(){3($(o).N("s",12)){$(o).N("s",12)}$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1D,1G,g);H P}$("#1U").s(12)}3(!(R==="")){9 1i(){$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1z,1x,g);H P}$("#1X").s(1i)}o.1h=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}n 3(I==3k){3(!(R=="")){o.1h="";1i()}}n 3(I==3j){3(!(14=="")){o.1h="";12()}}};16();$("#K").C();$("#1L").s(G);$("#8").r({Y:"T"})};S.L=f}n{6 l=f.2r(/^[^\\?]+\\??/,\'\');6 m=2p(l);13=(m[\'z\']*1)+30||3h;1a=(m[\'A\']*1)+3g||3f;W=13-30;V=1a-3e;3(f.O(\'2j\')!=-1){1E=f.1B(\'3d\');$("#15").C();3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4></4><U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\' > </U>")}n{$("#B").N();$("#8").q("<U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\'> </U>")}}n{3($("#8").r("Y")!="T"){3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\'>1l</a> 1k 1j 1s</4></4><4 5=\'F\' J=\'z:"+W+"p;A:"+V+"p\'></4>")}n{$("#B").N();$("#8").q("<4 5=\'F\' 3c=\'3b\' J=\'z:"+W+"p;A:"+V+"p;\'></4>")}}n{$("#F")[0].J.z=W+"p";$("#F")[0].J.A=V+"p";$("#F")[0].3a=0;$("#1H").11(d)}}$("#Z").s(G);3(f.O(\'37\')!=-1){$("#F").q($(\'#\'+m[\'26\']).1T());$("#8").24(9(){$(\'#\'+m[\'26\']).q($("#F").1T())});16();$("#K").C();$("#8").r({Y:"T"})}n 3(f.O(\'2j\')!=-1){16();3($.1q.35){$("#K").C();$("#8").r({Y:"T"})}}n{$("#F").34(f+="&1y="+(1p 33().32()),9(){16();$("#K").C();1u("#F a.18");$("#8").r({Y:"T"})})}}3(!m[\'1A\']){o.21=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}}}}31(e){}}9 1m(){$("#K").C();$("#8").r({Y:"T"})}9 G(){$("#2Y").N("s");$("#Z").N("s");$("#8").2X("2W",9(){$(\'#8,#B,#1F\').2V("24").N().C()});$("#K").C();3(2t o.v.J.2i=="2g"){$("v","11").r({A:"1Z",z:"1Z"});$("11").r("22","")}o.1h="";o.21="";H P}9 16(){$("#8").r({2U:\'-\'+20((13/2),10)+\'p\',z:13+\'p\'});3(!(1V.1q.2Q&&1V.1q.2P<7)){$("#8").r({38:\'-\'+20((1a/2),10)+\'p\'})}}9 2p(a){6 b={};3(!a){H b}6 c=a.1B(/[;&]/);25(6 i=0;i<c.1c;i++){6 d=c[i].1B(\'=\');3(!d||d.1c!=2){39}6 e=2a(d[0]);6 f=2a(d[1]);f=f.2r(/\\+/g,\' \');b[e]=f}H b}9 2x(){6 a=o.2M;6 w=1S.2o||1R.2o||(a&&a.1Q)||o.v.1Q;6 h=1S.1P||1R.1P||(a&&a.2n)||o.v.2n;1O=[w,h];H 1O}9 1K(){6 a=2K.2J.1C();3(a.O(\'2I\')!=-1&&a.O(\'3o\')!=-1){H 1b}}',62,211,'|||if|div|id|var||TB_window|function||||||||||||||else|document|px|append|css|click||href|body||||width|height|TB_overlay|remove|TB_Counter|TB_TempArray|TB_ajaxContent|tb_remove|return|keycode|style|TB_load|src|null|unbind|indexOf|false|title|TB_NextHTML|imgPreloader|block|iframe|ajaxContentH|ajaxContentW|this|display|TB_closeWindowButton||html|goPrev|TB_WIDTH|TB_PrevHTML|TB_iframeContent|tb_position||thickbox|tb_show|TB_HEIGHT|true|length|nbsp|span|Math|onload|onkeydown|goNext|Esc|or|close|tb_showIframe|TB_imageCount|Close|new|browser|TB_FoundURL|Key|Image|tb_init|name|imgLoader|TB_NextURL|random|TB_NextCaption|modal|split|toLowerCase|TB_PrevCaption|urlNoQuery|TB_HideSelect|TB_PrevURL|TB_ajaxWindowTitle|img|addClass|tb_detectMacXFF|TB_ImageOff|150|rel|arrayPageSize|innerHeight|clientWidth|self|window|children|TB_prev|jQuery|frameborder|TB_next|getElementById|auto|parseInt|onkeyup|overflow|alt|unload|for|inlineId||100||unescape|1000|round|hspace|TB_closeAjaxWindow|TB_title|undefined|match|maxHeight|TB_iframe|bmp|gif|png|clientHeight|innerWidth|tb_parseQuery|jpeg|replace|jpg|typeof|which|keyCode|event|tb_getPageSize|show|TB_overlayBG|TB_closeWindow|TB_overlayMacFFBGHack|TB_secondLine|TB_caption|blur|TB_Image|60|tb_pathToImage|mac|userAgent|navigator|of|documentElement|Prev|lt|version|msie|gt|ready|Next|marginLeft|trigger|fast|fadeOut|TB_imageOff|hidden||catch|getTime|Date|load|safari|get|TB_inline|marginTop|continue|scrollTop|TB_modal|class|TB_|45|440|40|630|input|188|190|substr|try|area|firefox'.split('|'),0,{}))
;/*! jquery.swfobject.license.txt *//*

jQuery SWFObject Plugin v1.0.3 <http://jquery.thewikies.com/swfobject/>
Copyright (c) 2008 Jonathan Neal
This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
This software is released under the GPL License <http://www.opensource.org/licenses/gpl-2.0.php>

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>

jQuery v1.2.6 <http://jquery.com/>
Copyright (c) 2008 John Resig
This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
This software is released under the GPL License <http://www.opensource.org/licenses/gpl-2.0.php>

*//*jslint
	passfail: false,
	white: true,
	browser: true,
	widget: false,
	sidebar: false,
	rhino: false,
	safe: false,
	adsafe: false,
	debug: false,
	evil: false,
	cap: false,
	on: false,
	fragment: false,
	laxbreak: false,
	forin: true,
	sub: false,
	css: false,
	undef: true,
	nomen: false,
	eqeqeq: true,
	plusplus: false,
	bitwise: true,
	regexp: false,
	onevar: true,
	strict: false
*//*global
	jQuery,
	ActiveXObject
*/

(function ($) {
	/* $.flashPlayerVersion */
	$.flashPlayerVersion = function () {
		var flashVersion, activeX = null, fp6Crash = false, shockwaveFlash = 'ShockwaveFlash.ShockwaveFlash';

		// If Internet Explorer
		if (!(flashVersion = navigator.plugins['Shockwave Flash'])) {
			try {
				activeX = new ActiveXObject(shockwaveFlash + '.7');
			}
			catch (errorA) {
				try {
					activeX = new ActiveXObject(shockwaveFlash + '.6');

					flashVersion = [6, 0, 21];

					activeX.AllowScriptAccess = 'always';
				}
				catch (errorB) {
					if (flashVersion && flashVersion[0] === 6) {
						fp6Crash = true;
					}
				}

				if (!fp6Crash) {
					try {
						activeX = new ActiveXObject(shockwaveFlash);
					}
					catch (errorC) {
						flashVersion = 'X 0,0,0';
					}
				}
			}

			if (!fp6Crash && activeX) {
				try {
					// Will crash fp6.0.21/23/29
					flashVersion = activeX.GetVariable('$version');
				}
				catch (errorD) {}
			}
		}
		// If NOT Internet Explorer
		else {
			flashVersion = flashVersion.description;
		}

        // nez. ( FIX for development version of Shockvawe Flash eg. 'Shockwave Flash 10.1 d52' WITH 'd' symbol )
        //flashVersion = flashVersion.match(/^[A-Za-z\s]*?(\d+)(\.|,)(\d+)(\s+r|,)(\d+)/);
		flashVersion = flashVersion.match(/^[A-Za-z\s]*?(\d+)(\.|,)(\d+)(\s+r|\s+d|,)(\d+)/);
		return [flashVersion[1] * 1, flashVersion[3] * 1, flashVersion[5] * 1];
	}();



	/* $.flashExpressInstaller */
	$.flashExpressInstaller = 'expressInstall.swf';



	/* $.hasFlashPlayer */
	$.hasFlashPlayer = ($.flashPlayerVersion[0] !== 0);



	/* $.hasFlashPlayerVersion */
	$.hasFlashPlayerVersion = function (options) {
		var flashVersion = $.flashPlayerVersion;

		options = (/string|integer/.test(typeof options)) ? options.toString().split('.') : options;

		return (options) ? (flashVersion[0] >= (options.major || options[0] || flashVersion[0]) && flashVersion[1] >= (options.minor || options[1] || flashVersion[1]) && flashVersion[2] >= (options.release || options[2] || flashVersion[2])) : (flashVersion[0] !== 0);
	};



	/* $.flash */
	$.flash = function (options) {
		// Check if Flash is installed, return false if isn't
		var noflashplayer = false;
		if (!$.hasFlashPlayer) {
		    noflashplayer = true;
		}

		// Create the swf filename variable, <param> attributes, dom sandbox, 4 array caches, and 4 free caches
		var movieFilename = options.url || '', contentType = options.type || 'swf', paramAttributes = options.params || {}, buildDOM = document.createElement('body'), aArr, bArr, cArr, dArr, a, b, c, d;
var movieFilenameParams = options.urlParams || false;
		delete options.urlParams;
		if (typeof(movieFilenameParams) == 'object'){
      str = [];
      for (up in movieFilenameParams){
        str.push(up +'='+movieFilenameParams[up]);
      };
      movieFilenameParams = str.join('&');
    };

		// Set the default height and width if not already set
		options.height = options.height || 180;
		options.width = options.width || 320;

		// Inject ExpressInstall if "hasVersion" is requested and the version requirement is not met
		if (noflashplayer || ( options.hasVersion && !$.hasFlashPlayerVersion(options.hasVersion) )) {
			$.extend(options, {
				id: 'SWFObjectExprInst',
				height: Math.max(options.height, 137),
				width: Math.max(options.width, 214)
			});

			movieFilename = options.expressInstaller || $.flashExpressInstaller;

			paramAttributes = {
				flashvars: {
					MMredirectURL: window.location.href,
					MMplayerType: ($.browser.msie && $.browser.win) ? 'ActiveX' : 'PlugIn',
					MMdoctitle: document.title.slice(0, 47) + ' - Flash Player Installation'
				}
			};
		}

		// Append flashvars to param if already specified separately
		if (options.flashvars && typeof paramAttributes === 'object') {
			$.extend(paramAttributes, {
				flashvars: options.flashvars
			});
		}

		// Delete the reformatted constructors
		for (a in (b = ['url', 'type', 'expressInstall', 'hasVersion', 'params', 'flashvars'])) {
			delete options[b[a]];
		}

		// Create the OBJECT tag attributes
		aArr = [];
		for (a in options) {
			if (typeof options[a] === 'object') {
				bArr = [];
				for (b in options[a]) {
					bArr.push(b.replace(/([A-Z])/, '-$1').toLowerCase() + ':' + options[a][b] + ';');
				}
				options[a] = bArr.join('');
			}
			aArr.push(a + '="' + options[a] + '"');
		}
		options = aArr.join(' ');
  //      console.log(options);
		// Create the PARAM tags
		if (typeof paramAttributes === 'object') {
			aArr = [];
			for (a in paramAttributes) {
				if (typeof paramAttributes[a] === 'object') {
					bArr = [];
					for (b in paramAttributes[a]) {
						if (typeof paramAttributes[a][b] === 'object') {
							cArr = [];
							for (c in paramAttributes[a][b]) {
								if (typeof paramAttributes[a][b][c] === 'object') {
									dArr = [];
									for (d in paramAttributes[a][b][c]) {
										dArr.push(d.replace(/([A-Z])/, '-$1').toLowerCase() + ':' + paramAttributes[a][b][c][d] + ';');
									}
									paramAttributes[a][b][c] = dArr.join('');
								}
								cArr.push(c + '{' + paramAttributes[a][b][c] + '}');
							}
							paramAttributes[a][b] = cArr.join('');
						}
						bArr.push(window.escape(b) + '=' + window.escape(paramAttributes[a][b]));
					}
					paramAttributes[a] = bArr.join('&amp;');
				}
				aArr.push('<PARAM NAME="' + a + '" VALUE="' + paramAttributes[a] + '">');
			}
			paramAttributes = aArr.join('');
		}
//        console.log(paramAttributes);
        if (contentType == 'swf') {
            // Unify the visual display between all browsers
            if (!(/style=/.test(options))) {
            	options += ' style="vertical-align:text-top;"';
            }

            if (!(/style=(.*?)vertical-align/.test(options))) {
            	options = options.replace(/style="/, 'style="vertical-align:text-top;');
            }
        }

    	// Specify the object and param tags between browsers
		if ($.browser.msie) {
            if (contentType == 'swf') {
                options += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
                paramAttributes = '<PARAM NAME="movie" VALUE="' + movieFilename + '">' + paramAttributes;
            } else {
if (movieFilenameParams){
                  if (movieFilename.indexOf('?') == -1) movieFilename += '?'+movieFilenameParams;else movieFilename += '&' + movieFilenameParams;
                };
                options += ' classid="clsid:233C1507-6A77-46A4-9443-F871F945D258" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=11,0,0,0"';
                paramAttributes = '<param name=PlayerVersion value=11><PARAM NAME="src" VALUE="' + movieFilename + '">' + paramAttributes;
            }
		}
		else {
            if (contentType == 'swf') {
                options += ' type="application/x-shockwave-flash" data="' + movieFilename + '"';
            } else {
if (movieFilenameParams){
                  if (movieFilename.indexOf('?') == -1) movieFilename += '?'+movieFilenameParams;else movieFilename += '&'+movieFilenameParams;
                };
                options += ' codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=11,0,0,0" type="application/x-director" data="' + movieFilename + '"';
                paramAttributes = '<param name=PlayerVersion value=11><PARAM NAME="src" VALUE="' + movieFilename + '">' + paramAttributes;
            }
		}


        /* IE and Shockwave/Flash do not like inner HTML trick that oryginal jquery.swfobject was doing
         *
         * Old code to which above comment was directed: return '<OBJECT ' + options + '>' + paramAttributes + '</OBJECT>';
         * The template file gameframe_flash.ctp expects this function to return false if flash is not installed.
         * To make sure it returns false the line below was copied from the teens jquery.swfobject.js (20091217).
         */
        return noflashplayer == true ? false : '<OBJECT ' + options + '>' + paramAttributes + '</OBJECT>';

	};

	/* $.fn.flash */
	$.fn.flash = function (options) {
		if (!$.hasFlashPlayer) {
			return this;
		}

		var a = 0, each;

		while ((each = this.eq(a++))[0]) {
			each.html($.flash($.extend({}, options)));

			if (each[0].firstChild.getAttribute('id') === 'SWFObjectExprInst') {
				a = this.length;
			}
		}

		return this;
	};
}(jQuery));

;/**
 * @author alexander.farkas
 * @version 1.21
 */
(function($){
    $.extend({
        manageAjax: function(o){
            o = $.extend({
                manageType: 'normal',
                maxReq: 0,
                blockSameRequest: false,
				global: true
            }, o);
            return new $.ajaxManager(o);
        },
        ajaxManager: function(o){
            this.opt = o;
            this.queue = [];
        }
    });
    $.extend($.ajaxManager.prototype, {
        add: function(o){
			var quLen = this.queue.length, s = this.opt, q = this.queue, self = this, i, j;
			o = $.extend({}, s, o);
            var cD = (o.data && typeof o.data != "string") ? $.param(o.data) : o.data;
            if (s.blockSameRequest) {
                var toPrevent = false;
                for (i = 0; i < quLen; i++) {
                    if (q[i] && q[i].data === cD && q[i].url === o.url && q[i].type === o.type) {
                        toPrevent = true;
                        break;
                    }
                }
                if (toPrevent) {
                    return false;
                }
            }
            q[quLen] = {
                fnError: o.error,
                fnSuccess: o.success,
                fnComplete: o.complete,
                fnAbort: o.abort,
                error: [],
                success: [],
                complete: [],
                done: false,
                queued: false,
                data: cD,
                url: o.url,
                type: o.type,
                xhr: null
            };

            o.error = function(){
                if (q[quLen]) {
                    q[quLen].error = arguments;
                }
            };
            o.success = function(){
                if (q[quLen]) {
                    q[quLen].success = arguments;
                }
            };
            o.abort = function(){
                if (q[quLen]) {
                    q[quLen].abort = arguments;
                }
            };

            function startCallbacks(num, opts){
                if (q[num].fnError && q[num].error.length) {
                    q[num].fnError.apply(opts || $, q[num].error);
                }
                if (q[num].fnSuccess && !q[num].error.length) {
					q[num].fnSuccess.apply(opts || $, q[num].success);
                }
                if (q[num].fnComplete) {
                    q[num].fnComplete.apply(opts || $, q[num].complete);
                }
                self.abort(num, true);
            }

            o.complete = function(){
                if (!q[quLen]) {
                    return;
                }
                q[quLen].complete = arguments;
                q[quLen].done = true;
                switch (s.manageType) {
                    case 'sync':
                        if (quLen === 0 || !q[quLen - 1]) {
                            var curQLen = q.length;
                            for (i = quLen; i < curQLen; i++) {
                                if (q[i]) {
                                    if (q[i].done) {
										startCallbacks(i, this);
                                    }
                                    else {
                                        break;
                                    }
                                }

                            }
                        }
                        break;
                    case 'queue':
                        if (quLen === 0 || !q[quLen - 1]) {
                            var curQLen = q.length;
                            for (i = 0, j = 0; i < curQLen; i++) {
                                if (q[i] && q[i].queued) {
                                    q[i].xhr = jQuery.ajax(q[i].xhr);
                                    q[i].queued = false;
                                    break;
                                }
                            }
                        }
                        startCallbacks(quLen, this);
                        break;
                    case 'abortOld':
                        startCallbacks(quLen, this);
                        for (i = quLen; i >= 0; i--) {
                            if (q[i]) {
                                self.abort(i);
                            }
                        }
                        break;
                    default:
                        startCallbacks(quLen, this);
                        break;
                }
            };

            if (s.maxReq) {
                if (s.manageType != 'queue') {
                    for (i = quLen, j = 0; i >= 0; i--) {
                        if (j >= s.maxReq) {
                            this.abort(i);
                        }
                        if (q[i]) {
                            j++;
                        }
                    }
                }
                else {
                    for (i = 0, j = 0; i <= quLen && !q[quLen].queued; i++) {
                        if (q[i] && !q[i].queued)
                            j++;
                        if (j > s.maxReq)
                            q[quLen].queued = true;
                    }
                }
            }
            q[quLen].xhr = (q[quLen].queued) ? o : jQuery.ajax(o);
            return quLen;
        },
        cleanUp: function(){
            this.queue = [];
        },
        abort: function(num, completed){
            var qLen = this.queue.length, s = this.opt, q = this.queue, self = this, i;
            function del(num){
                if (!q[num]) {
                    return;
                }
                ((!completed && q[num].fnAbort) && q[num].fnAbort.apply($, [num]));
                if (!q[num]) {
                    return;
                }
                if (q[num].xhr) {
                    if (typeof q[num].xhr.abort != 'undefined') {
                        q[num].xhr.abort();
                    }
                    if (typeof q[num].xhr.close != 'undefined') {
                        q[num].xhr.close();
                    }
                    q[num].xhr = null;
                }
				// Handle the global AJAX counter

				if ( s.global && $.active && ! --$.active){
					$.event.trigger( "ajaxStop" );
				}
                q[num] = null;
            }
            if (!num && num !== 0) {
                for (i = 0; i < qLen; i++) {
                    del(i);
                }
                this.cleanUp();
            }
            else {
                del(num);
                var allowCleaning = true;
                for (i = qLen; i >= 0; i--) {
                    if (q[i]) {
                        allowCleaning = false;
                        break;
                    }
                }
                if (allowCleaning) {
                    this.cleanUp();
                }
            }
        }
    });
})(jQuery);

;/**
 * Spil Games Prelader and preroll - jQuery plugin
 * @author: Rafał Jońca
 * @requires: Progress Bar Plugin for jQuery
 *
 * Usage: $(target).spiPreloader(options);
 *
 * Current limitation: there may be only ONE active preloader on page!
 *
 * Options are commented below.
 *
 */
(function($){
    var settings = {
        adWidth: 300, // Main ad box width.
        adHeight: 250, // Main ad box height.
        showAd: true, // when set to false, game will be shown without any preroll or preloader
        forcePreroll: false, // set to true to force use of preroll instead of preloader for Flash games; have no meaning for Shockwave
		usePercentsInPreroll: true, // set to false if you want to use seconds text instead of percents
		loadingBar: true, // set to false to disable showing the progress bar
        fileType: 'swf', // swf or dcr
		contentId: '#flashobj', // DOM element containing the game
		preloadId: '#flashobj_mc', // the object element with game

		beforeCallback: null, // function called before inserting a game (function receives settings array)
        afterCallback: null, // function called after inserting a game (function receives settings array)
        skipCallback:null,
        gameInsertCallback: null, // function inserting the game on page using JS (function receives settings array)

        loadingText: "Loading game...",
        afterLoadingText: "Game loaded. Click here to start the game\u2026",
        progressbarText: 'The game will start in %d seconds',
        closeText: 'Close the advertisement and go on to the game.',
		advertisementText: 'Advertisement',

        tickInterval: 200, // update interval for progressbar and percents
        progressTime: 15000, // default ad serving time
		showSkipTime: 0, // time after which to show the skip game link (0 means show at the beginning of the game)
		barWidth: 300, // progress bar width
		adType: 'iframe', // iframe, javascript
		// ad code to insert, used only when adType = iframe
        adCode: ''
    };

    var percent = 0;
	var timeElapsed = 0;
	var linkShowTimeElapsed = 0;
	var that = this;
	var flashLoadTries = 0;
	var skipTextInserted = false;
	var skipLinkInserted = false;
	var neoedgeAd = false;
    var intervalHandle, target, check98PercentHandle, preTimer, preloaderWidth, preloaderHeight, preroll, neoedgeHandler;

	var cleanupAndShowGame = function() {
		if (intervalHandle != null) {
			clearInterval(intervalHandle);
			intervalHandle = null;
		}
		if (neoedgeHandler != null) {
			clearTimeout(neoedgeHandler);
			neoedgeHandler = null;
		}
	    if (check98PercentHandle != null) {
	        clearTimeout(check98PercentHandle);
	        check98PercentHandle = null;
	    }

		$(target).hide();

		if (settings.afterCallback != null) {
            settings.afterCallback.call(that, settings);
		}

		if (settings.fileType != 'swf' || settings.forcePreroll) {
			settings.gameInsertCallback.call(that);
		} else {
			$(settings.contentId).css({width: preloaderWidth, height: preloaderHeight});
		}
	};
	
	var skipad = function(){
        if (settings.skipCallback != null) {
            settings.skipCallback.call(that, settings);
		};
        cleanupAndShowGame();
    };
	

	var skipTextAddOrDecrement = function(afterLoading) {
		skipTextInserted = afterLoading?false:skipTextInserted;
		if (linkShowTimeElapsed <= 0 && !skipTextInserted) {
			if (preroll) {
				if (!skipLinkInserted) {
					$('#ap_skiptext').empty().append($('<a href="javascript:void(0);">'+settings.closeText+'</a>').click(skipad));
					skipLinkInserted = true;
				}
			} else if (afterLoading) {
				if (!skipLinkInserted) {
					$('#ap_skiptext').empty().append($('<a href="javascript:void(0);">'+settings.afterLoadingText+'</a>').click(skipad));
					skipLinkInserted = true;
				}
			} else {
				$('#ap_skiptext').empty().append(settings.loadingText);
			}
			skipTextInserted = true;
			return;
		} else if (linkShowTimeElapsed > 0 && !preroll && !afterLoading && !skipTextInserted) {
			$('#ap_skiptext').empty().append(settings.loadingText);
			skipTextInserted = true;
		}
		linkShowTimeElapsed -= settings.tickInterval;
	};

	var insertAd = function() {
		$(target).css({width: (settings.adWidth+'px')});

		$(target).prepend('<div id="ap_adtext">'+settings.advertisementText+'</div>');

		if (settings.adType == 'iframe') {
			$(target).append('<div id="ap_adframe"></div>');
			$('#ap_adframe').css({width: (settings.adWidth+'px'),height:(settings.adHeight+'px')});
			$('#ap_adframe').append(settings.adCode);
		} else {
			$('#ap_adframe').css({width: (settings.adWidth+'px'),height:(settings.adHeight+'px')});
		}

		if (settings.loadingBar && !neoedgeAd) {
			$(target).append('<div id="ap_progressbar"></div>');
			$('#ap_progressbar').css('width', settings.barWidth+'px');
			if (preroll && !settings.usePercentsInPreroll) {
				$("#ap_progressbar").reportprogress(0, 100, sprintf(settings.progressbarText, Math.ceil(settings.progressTime/1000)), settings.barWidth);
			} else {
				$("#ap_progressbar").reportprogress(0, 100, '0%', settings.barWidth);
			}
		}

		if (!neoedgeAd) {
			$(target).append('<div id="ap_skiptext"></div>');
		}
		skipTextAddOrDecrement();
	};

	var progressUpdatePreroll = function() {
		timeElapsed += settings.tickInterval;
		percent = Math.round(100*timeElapsed/settings.progressTime);

		if (settings.usePercentsInPreroll) {
			$("#ap_progressbar").reportprogress(percent, 100, percent+'%');
		} else {
			$("#ap_progressbar").reportprogress(percent, 100, sprintf(settings.progressbarText, Math.ceil((settings.progressTime-timeElapsed)/1000)));
		}

		skipTextAddOrDecrement();

        if (percent >= 100){
			if (!neoedgeAd) {
				cleanupAndShowGame();
			}
        }
	};

	var check98Percent = function (oldvalue) {
		var loaded = $(settings.preloadId)[0].PercentLoaded();
		if (oldvalue == loaded) {
			if (!neoedgeAd) {
				cleanupAndShowGame();
			}
	        if (check98PercentHandle != null) {
	            clearTimeout(sometime);
	            check98PercentHandle = null;
	        }
	    }
	};

	var progressUpdatePreloader = function() {
		var fromTimer = parseInt((settings.progressTime - preTimer) * 100 / settings.progressTime);

		var loaded = $(settings.preloadId)[0].PercentLoaded();
		if (loaded < 0) {
		    loaded = 100;
		}
		percent = fromTimer < loaded ? fromTimer : loaded;
		$("#ap_progressbar").reportprogress(percent, 100, percent+'%');
		preTimer -= settings.tickInterval;
		if (fromTimer >= 100) {
		    check98PercentHandle = setTimeout(function(){ check98Percent(loaded);}, 2500);
		}
		if (percent < 100) {
		    if (loaded >= 100) {
				skipTextAddOrDecrement(true);
		    } else {
				skipTextAddOrDecrement();
			}
		} else if (!neoedgeAd) {
			cleanupAndShowGame();
		}
	};

	var startPreloader;
	startPreloader = function() {
		flashLoadTries++;
        try {
            var loaded_temp = $(settings.preloadId)[0].PercentLoaded();
            intervalHandle = setInterval(progressUpdatePreloader, settings.tickInterval);
            insertAd();
        } catch (e) {
            if (flashLoadTries <= 3) {
                setTimeout(startPreloader, 1000);
            } else {
				if (!neoedgeAd) {
					cleanupAndShowGame();
				}
            }
        }
	};

	var showAd = function() {
		if (settings.beforeCallback != null) {
            settings.beforeCallback.call(that, settings);
		}

		linkShowTimeElapsed = settings.showSkipTime;

		if (settings.fileType != 'swf' || settings.forcePreroll) {
			preroll = true;
			intervalHandle = setInterval(progressUpdatePreroll, settings.tickInterval);
			insertAd();
		} else {
			settings.gameInsertCallback.call(that);
			preloaderHeight = $(settings.contentId).css('height');//height();
			preloaderWidth = $(settings.contentId).css('width');//width();
			$(settings.contentId).css({width: '0px', height: '0px'});
			preroll = false;
			startPreloader();
			preTimer = settings.progressTime;
		}
	};

	// returns a neoedge player handler
	$.spiPreloaderNeoEdge = function(timeout) {
		return function(_cmd) {
			if (_cmd == "AD_STARTED") {
				// tell the game page to wait for ad complete event
				if (parent) neoedgeAd = true;
				// start ad timeout
				neoedgeHandler = setTimeout(cleanupAndShowGame, timeout || 30000);
			}
			if (_cmd == "AD_COMPLETED") {
				cleanupAndShowGame();
			}
		};
	};

    $.fn.spiPreloader = function(options){
		target = $(this);
        $.extend(settings, options);
        if (settings.showAd == true) {
            showAd();
        } else {
			if (settings.beforeCallback != null) {
			    settings.beforeCallback.call(that, settings);
			}
            settings.gameInsertCallback.call(that, settings);
			if (settings.afterCallback != null) {
			    settings.afterCallback.call(that, settings);
			}
        }
	};
})(jQuery);

;/*
 * Progress Bar Plugin for jQuery
 * Version: Alpha 2
 * Release: 2007-02-26
 */
(function($) {
	//Main Method
	$.fn.reportprogress = function(val,maxVal,text, bw) {
		var max=100;
		var barWidth = bw || 300;
		if(maxVal)
			max=maxVal;
		return this.each(
			function(){
				var div=$(this);
				var innerdiv=div.find(".progress");

				if(innerdiv.length!=1){
					innerdiv=$("<div class='progress'></div>");
					div.append("<div class='text'>&nbsp;</div>");
					$("<span class='text'>&nbsp;</span>").css("width",div.css('width')).appendTo(innerdiv);
					//$("<span class='text'>&nbsp;</span>").css("width", barWidth+"px").appendTo(innerdiv);
					div.append(innerdiv);
				}
				var width=Math.round(val/max*100);
				innerdiv.css("width",width+"%");
				if (text) {
					div.find(".text").html(text);
				}
			}
		);
	};
})(jQuery);

;/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
;/**
 * dEllipsis - jQuery plugin - text cutoff
 * 
 * @author damian
 */
;(function() {
$.fn.dEllipsis = function(options){
    var target = this;
    var defaults = {
        //common number of words in single row - for reduce script itterations (less words means more itterations)
        wordsInRow:1, 
        overflowElement: 'p', //element which holds texts
        textElement: 'p span', //text element
        wordDelimiter: ' ',
        textEnd: '...',
        shortSteps: false, //if true force subtracting one word per iteration
        wrapInWidth: false
    };
    var options = $.extend(defaults, options);
    var initialize = function(){
        target = $.makeArray(target);
        $(target).each(function(){
            overflowElementHeight = 0;
            if (options.wrapInWidth){
                overflowElementSize = parseInt($(this).find(options.overflowElement).offset().left)
                    + parseInt($(this).find(options.overflowElement).width()
                );
                textElementSize = parseInt($(this).find(options.textElement).offset().left)
                     + parseInt($(this).find(options.textElement).width()
                );
                if (textElementSize > overflowElementSize){
                    if ($(this).find(options.textElement).prev().length){
                        $(this).find(options.textElement).before('<br />');
                    } else {
                        //if we have single word and it is too long
                        while(overflowElementSize < textElementSize) {
                            $(this).find(options.textElement).text(
                                $(this).find(options.textElement).text().substring(
                                    0,
                                    $(this).find(options.textElement).text().length
                                     - (options.textEnd.length + 1)
                                ) + options.textEnd
                            );
                            textElementSize = parseInt($(this).find(options.textElement).offset().left) + 
                                parseInt($(this).find(options.textElement).width()
                            );
                        }
                    };
                };
            };
            
            if($(this).find(options.overflowElement).css('height')!='auto'){
                overflowElementHeight = parseInt($(this).find(options.overflowElement).css('height'));
            } else {
                overflowElementHeight = parseInt($(this).find(options.overflowElement).height());
            };
            while (overflowElementHeight < parseInt($(this).find(options.textElement).height())){
                var wordCount = Math.round(Math.abs(((parseInt($(this).find(options.textElement).height()) - parseInt(overflowElementHeight)) / parseInt($(this).find(options.textElement).css('font-size').slice(0,-2)))))*-1*options.wordsInRow;
                var exactWordCount = $(this).find(options.textElement).text().split(options.wordDelimiter).length;
                if (wordCount > -2 && exactWordCount > 2 && !options.shortSteps) {
                    wordCount = -2;
                }
                $(this).find(options.textElement).text($(this).find(options.textElement).text().split(options.wordDelimiter).slice(0,wordCount).join(options.wordDelimiter)+options.textEnd);
            };
        });  
    };
    return initialize();
};
})(jQuery);
;;(function() {
jQuery.fn.imgError = function(settings) {

    var settings = $.extend({
        noimage: '/img/noimage_small.gif'
    }, settings);
    var images = [];
    var noimagePath = settings.noimage || '';
    var self = this;
    
    return this.each(function(i, val){
        var image = new Image();
        $(image)
        .error(function(){
            try{
                if( noimagePath != '' && $('img[src="'+$(this).attr('src')+'"]').attr('src') != noimagePath ) {
                    var a = $(self).eq(i)[0].attributes;
                    var attrs = [];
                    var old = { w: $(self).eq(i).width(), h: $(self).eq(i).height() };
                    var newImg = $('<img src="' + noimagePath + '" />');
                    $(a).each(function(i,val){
                        if(val.nodeName.toLowerCase() != 'src') {
                            if( val.nodeValue != '' && val.nodeValue != null && val.nodeValue != 'undefined' && val.nodeValue !== false )
                                $(newImg).attr(val.nodeName, val.nodeValue);
                        };
                    });
                    $(self).eq(i).before( newImg ).remove();
                };
            }catch(ex){};
        })
        .attr('src', $(this).attr('src'));
    });
}
})(jQuery);

;// sprintf functions
function str_repeat(i,m){for(var o=[];m>0;o[--m]=i);return(o.join(''))};
function sprintf(){var i=0,a,f=arguments[i++],o=[],m,p,c,x;while(f){if(m=/^[^\x25]+/.exec(f))o.push(m[0]);else if(m=/^\x25{2}/.exec(f))o.push('%');else if(m=/^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)){if(((a=arguments[m[1]||i++])==null)||(a==undefined))throw("Too few arguments.");if(/[^s]/.test(m[7])&&(typeof(a)!='number'))throw("Expecting number but found "+typeof(a));switch(m[7]){case'b':a=a.toString(2);break;case'c':a=String.fromCharCode(a);break;case'd':a=parseInt(a);break;case'e':a=m[6]?a.toExponential(m[6]):a.toExponential();break;case'f':a=m[6]?parseFloat(a).toFixed(m[6]):parseFloat(a);break;case'o':a=a.toString(8);break;case's':a=((a=String(a))&&m[6]?a.substring(0,m[6]):a);break;case'u':a=Math.abs(a);break;case'x':a=a.toString(16);break;case'X':a=a.toString(16).toUpperCase();break}a=(/[def]/.test(m[7])&&m[2]&&a>0?'+'+a:a);c=m[3]?m[3]=='0'?'0':m[3].charAt(1):' ';x=m[5]-String(a).length;p=m[5]?str_repeat(c,x):'';o.push(m[4]?a+p:p+a)}else throw("Huh ?!");f=f.substring(m[0].length)}return o.join('')};
    

;_spiHBreturnHotbox = function(data, cName) {
    var cookieName = cName || '_spiHB';
    var hbc = $.cookie(cookieName);
    try {
        if (hbc == null || hbc.indexOf('|') == -1) {
            hbc = new Array();
        } else {
            hbc = hbc.split('|');
            for (var i = 0; i < hbc.length; ++i) {
                hbc[i] = hbc[i].split('%');
            }
        }
    } catch(e) {
        hbc = new Array();
    }
    var toShow = -1;
    for (var i = 0; i < data.length; ++i) {
    	data[i].options.boxid = parseInt(data[i].options.boxid);
    	data[i].options.capping = parseInt(data[i].options.capping);
        if (data[i].options.capping > 0) {
            var isInCookie = false;
            for (var j = 0; i < hbc.length; ++j) {
                try {
                    if (hbc[j][0] == data[i].options.boxid && hbc[j][1] < data[i].options.capping) {
                        isInCookie = true;
                        toShow = i;
                        break;
                    } else if (hbc[j][0] == data[i].options.boxid && hbc[j][1] >= data[i].options.capping) {
                        isInCookie = true;
                        break;
                    }
                } catch(ex) {
                    break;
                }
            }
            if (!isInCookie) {
                toShow = i;
                break;
            } else if (isInCookie && toShow != -1) {
                break;
            }
        } else if (data[i].options.capping == -1) {
            toShow = i;
            break;
        }
    }
    if (toShow == -1) {
        toShow = 0;
        hbc = new Array();
    }
    var hbcp = '';
    try {
        for (var i = 0; i < data.length; ++i) {
            if (data[i].options.capping > 0) {
                var isInCookie = false;
                for (var j = 0; i < hbc.length; ++j) {
                    if (hbc[j][0] == data[i].options.boxid) {
                        if (toShow == i) {
                            hbc[j][1] = parseInt(hbc[j][1]) + 1;
                        }
                        hbcp += '|' + hbc[j][0] + '%' + hbc[j][1];
                        isInCookie = true;
                        break;
                    }
                }
                if (!isInCookie) {
                    if (toShow == i) {
                        hbcp += '|' + data[i].options.boxid + '%1';
                    } else {
                        hbcp += '|' + data[i].options.boxid + '%0';
                    }
                }
            }
        }
    } catch(ex) {
        hbcp = '';
    }
    $.cookie(cookieName, hbcp.substr(1), {
        expires: 14,
        path: '/'
    });
    return data[toShow];
};


_spiHBRenderCode = function(data) {
	$('.hotbox .main').displayHotbox(data);
};

_spiHBRenderNewHotbox = function(data) {
    $(data).each(function(){
        $('#hotboxRotator').append('<li></li>');
        $('#hotboxRotator li:last').displayNewHotbox(this);
        $('#hotboxRotator li:last img.hotboxImage').ifixpng();
    });
    $('#hotboxRotator').dcarousel({
        auto: 5,
        visible:1,
        size:3,
        scroll:1,
        width:231
    });


};
//display HB only
;(function($){
$.fn.displayHotbox = function(options){
    var sender = $(this);
	var options = options;
	var hotboxElements = [];
	
    createImg = function(element){
		//create image
		$(sender).append('<div id="'+Math.round(Math.random()*100000)+'" class="imageContainer hb" style="position:absolute;"><img class="hotboxImage"></div>');
		//append css / attr
		if (element.css) for(var el in element.css){
				$(sender).find('div.imageContainer:last, div.imageContainer:last img').css(el, element.css[el]);
		};
		if (element.attr) for(var el in element.attr){
			$(sender).find('div.imageContainer:last img').attr(el, element.attr[el]);
		};
	};
	
	createText = function(element){
		//create text
		$(sender).append('<div id="'+Math.round(Math.random()*100000)+'" class="textContainer hb" style="position:absolute;"><p class="hotboxText">'+element.value+'</p></div>');		        		
		//append css / attr
		if (element.css) for(var el in element.css){
				$(sender).find('div.textContainer:last').css(el, element.css[el]);
		};		
	};
	
	createButton = function(element){
		$(sender).append('<div id="'+Math.round(Math.random()*100000)+'" class="buttonContainer hb" style="position:absolute;"><img class="hotboxImage btn" src="/img/hb_play_btn.gif"><p class="hotboxText btn">'+hb_play_btn+'</p></div>');		
		// append css / attr
		if (element.css) for(var el in element.css){
				$(sender).find('div.buttonContainer:last').css(el, element.css[el]);
		};
	};
    createElements = function(){
		tmpElements = options.elements || null;
		if (options.options.type == 'popup'){
			popupWo = 'window.open(\'' + options.options.url + '\', \'popup\', \'width=' + options.options.width + ',height=' + options.options.height + ',top=0,left=0, resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no\')';
			$(sender).append('<a id="hbLink" href="#" title="'+options.options.alt+'" onclick="'+popupWo+'">&nbsp;</a>');
		}else{
			$(sender).append('<a id="hbLink" href="'+options.options.url+'" title="'+options.options.alt+'">&nbsp;</a>');
			if (options.options.type == 'blank') $(sender).find('a#hbLink').attr('target','blank');
		};
		
		if (tmpElements){
			for(var i in tmpElements){
				tmpObject = tmpElements[i];
				switch (tmpObject.type){
					case 'img':
						createImg(tmpObject);
						break;
					case 'text':
						createText(tmpObject);
						break;
					case 'button':
						createButton(tmpObject);
						break;
				};
			};
		};
	};
	try{
		createElements();
	}catch(e){};
}
})(jQuery);

//display HB only
;(function($){
$.fn.displayNewHotbox = function(options){
    var sender = $(this);
	var options = options;
	var hotboxElements = [];
	
    createImg = function(element){
		//create image
		$(sender).append('<div id="'+Math.round(Math.random()*100000)+'" class="imageContainer hb" style="position:absolute;"><img class="hotboxImage"></div>');
		//append css / attr
		if (element.css) for(var el in element.css){
				$(sender).find('div.imageContainer:last').css(el, element.css[el]);
		};
		if (element.attr) for(var el in element.attr){
			$(sender).find('div.imageContainer:last img').attr(el, element.attr[el]);
		};
	};
	
	createText = function(element){
		//create text
		$(sender).append('<div id="'+Math.round(Math.random()*100000)+'" class="textContainer hb" style="position:absolute;"><p class="hotboxText">'+element.value+'</p></div>');		        		
		//append css / attr
		if (element.css) for(var el in element.css){
				$(sender).find('div.textContainer:last, div.textContainer:last p:last').css(el, element.css[el]);
		};		
	};
	
	createButton = function(element){
		$(sender).append('<div id="'+Math.round(Math.random()*100000)+'" class="buttonContainer hb" style="position:absolute;"><img class="hotboxImage btn" src="/img/hb_play_btn.gif"><p class="hotboxText btn">'+hb_play_btn+'</p></div>');		
		// append css / attr
		if (element.css) for(var el in element.css){
				$(sender).find('div.buttonContainer:last').css(el, element.css[el]);
		};
	};
    createElements = function(){
		tmpElements = options.elements || null;
		if (options.options.type == 'popup'){
			popupWo = 'window.open(\'' + options.options.url + '\', \'popup\', \'width=' + options.options.width + ',height=' + options.options.height + ',top=0,left=0, resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no\')';
			$(sender).append('<a id="hbLink" href="#" title="'+options.options.alt+'" onclick="'+popupWo+'">&nbsp;</a>');
		}else{
			$(sender).append('<a id="hbLink" href="'+options.options.url+'" title="'+options.options.alt+'" >&nbsp;</a>');
			if (options.options.type == 'blank') $(sender).find('a#hbLink').attr('target','blank');
		};
		
		if (tmpElements){
			for(var i in tmpElements){
				tmpObject = tmpElements[i];
				switch (tmpObject.type){
					case 'img':
						createImg(tmpObject);
						break;
					case 'text':
						createText(tmpObject);
						break;
					case 'button':
						createButton(tmpObject);
						break;
				};
			};
		};
	};
	try{
		createElements();
	}catch(e){};
}
})(jQuery);
;var actualWidth=0;
var actualHeight=0;
var startWidth=0;
var startHeight=0;
var ratio=1.1;
zoom=function(c){
    var a=$("div#flashobj");
    actualWidth=$(a).width();
    actualHeight=$(a).height();
    startWidth=actualWidth;
    startHeight=actualHeight;
    switch(c){
        case 1:
            var b=actualWidth;
            actualWidth=Math.ceil(ratio*actualWidth);
            actualHeight=Math.ceil((actualHeight*actualWidth)/b);
            break;
        case -1:
            var b=actualWidth;actualWidth=Math.ceil(actualWidth/ratio);
            actualHeight=Math.ceil((actualHeight*actualWidth)/b);
            break;
    };
    if(actualWidth>835 || startWidth>835){
        diff=actualWidth-startWidth;
        if (actualWidth < 838){
            $("div.mainContent").width(980);
            $("div.catcontainerLeft").width(835);
            $(a).width(actualWidth);
            $(a).height(actualHeight);
            $('.wrapperleft, .wrapperright').width(Math.round($(document).width() / 2) );
            return false;
        } 
        $("div.mainContent").width(parseInt($("div.mainContent").width())+diff);
        $("div.catcontainerLeft").width(parseInt($("div.catcontainerLeft").width())+diff);
        $('.wrapperleft').width(($(document).width() +(980 - $("div.mainContent").width()))/2);
        $('.wrapperright').width(($(document).width() +(980 - $("div.mainContent").width()))/2);
    };
    $(a).width(actualWidth);
    $(a).height(actualHeight);
};

resetZoom=function(){
    if(startWidth>0&&startHeight>0){
        var a=$("#flashobj");
        actualWidth=0;
        actualHeight=0;
        $(a).width(GameWidth);
        $(a).height(GameHeight);
        $("div.mainContent").width(980);
        $("div.catcontainerLeft").width(835);
         $('.wrapperleft, .wrapperright').width(Math.round($(document).width() / 2) );
    };
};
fixsize=function(){}
;;$(function(){
    var clearText = function(thefield){
	   if (thefield.defaultValue==thefield.value)thefield.value = "";
    };
    $('a[rel~="external"]').attr('target','_blank');
    $('img.logo').ifixpng();

	if (!$.browser.msie)$('div.bookmarkButton').hide();
    markMenu();
    var clearText = function(thefield){
        if (thefield.defaultValue==thefield.value)thefield.value = "";
    };

   $('input#searchtext').focus(function(){
       clearText(this);
   });

	$('div.search span').click(function(){$('form#search2').submit();return false;});

	$('form#search2').submit(function(){return checkSFValid(this, 'search', 2);});

	$('a#searchlink').click(function(){
	   $('form#search2').submit();
	   return false;
	});
});

$(window).load(function(){
	$("img[src*=/100x75/]").imgError({noimage:'/img/noimage_small.gif'});
	$("img[src*=/100X75/]").imgError({noimage:'/img/noimage_small.gif'});
    $("img[src*=/200x120/]").imgError({noimage:'/img/noimage.gif'});
    $("img[src*=/200X120/]").imgError({noimage:'/img/noimage.gif'});
	$("img[src*=/cimg/subcatthumbnails/]").imgError({noimage:'/img/noimage.gif'});

    $('div.tab, img.bottomLogo').ifixpng();
});
CreateBookmarkLink = function(c){
var d=document.location.href;
if(window.sidebar&&!document.all){
    window.sidebar.addPanel(c,d,"")
}else{
    if(window.external){
        window.external.AddFavorite(d,c)
    }else{
        if(window.opera&&window.print){return false}}}};

function upFrame(contenturl, width, height, gamename) {
    var ha = window.open('', 'po1234', 'width=' + width + ',height=' + height + ',top=0,left=0,resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no');
    ha.document.writeln('<html><head><title>' + gamename + '</title><style type="text/css">' + 'body {padding: 0px; margin: 0px; border: 0px;}' + '</style></head><body onLoad="self.focus();">' + '<iframe src="' + contenturl + '" width="100%" height="100%" frameborder="0" scrolling="no" marginwidth="0" marginheight="0">' + '&nbsp;</iframe></body></html>');
    ha.document.close();
};
;checkPlugins = function(){
    var d = '/plugin_check.html';
    var c = window.open(d, "cp", "width=400,height=350,scrollbar=no,resizable=no");
    centerWindow(c, 400, 350)
};
centerWindow = function(l, p, o){
    var e = screen.availHeight;
    var m = screen.availWidth;
    var h = m / 2 - p / 2;
    var k = e / 2 - o / 2;
    try {
        l.moveTo(h, k)
    } 
    catch (n) {
    }
};
var actShockwave_version = 10;
var actFlash_version = 10;
var ShockMode = 0;
checkShockwave = function(){
    if (navigator.mimeTypes && navigator.mimeTypes["application/x-director"] && navigator.mimeTypes["application/x-director"].enabledPlugin) {
        if (navigator.plugins && navigator.plugins["Shockwave for Director"] && (versionIndex = navigator.plugins["Shockwave for Director"].description.indexOf(".")) != -1) {
            var b = navigator.plugins["Shockwave for Director"].description.substring(versionIndex - 2, versionIndex);
            versionIndex = parseInt(b);
            if (versionIndex >= actShockwave_version) {
                ShockMode = 1
            }
        }
    }
    else {
        if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0 && (navigator.userAgent.indexOf("Windows 95") >= 0 || navigator.userAgent.indexOf("Windows 98") >= 0 || navigator.userAgent.indexOf("Windows NT") >= 0)) {
            document.write("<SCRIPT LANGUAGE=VBScript> \n");
            document.write("on error resume next \n");
            document.write('ShockMode = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.1")))\n');
            document.write("</SCRIPT> \n")
        }
    }
    if (ShockMode) {
        return true
    }
    else {
        if (!(navigator.appName && navigator.appName.indexOf("Netscape") >= 0 && navigator.appVersion.indexOf("2.") >= 0)) {
            return false
        }
    }
};
var flashinstalled = 0;
var flashversion = 0;
MSDetect = "false";
checkFlash = function() {
    if (navigator.plugins && navigator.plugins.length) {
        x = navigator.plugins["Shockwave Flash"];
        if (x) {
            flashinstalled = 2;
            if (x.description) {
                y = x.description;
                var re = /[^\d]+(\d+).*/;
                flashversion = re.exec(y)[1];
            }
        } else flashinstalled = 1;
        if (navigator.plugins["Shockwave Flash 2.0"]) {
            flashinstalled = 2;
            flashversion = 2;
        }
    } else if (navigator.mimeTypes && navigator.mimeTypes.length) {
        x = navigator.mimeTypes['application/x-shockwave-flash'];
        if (x && x.enabledPlugin) flashinstalled = 2;
        else flashinstalled = 1;
    } else MSDetect = "true";
    document.write('<SCRIPT LANGUAGE=VBScript\>\n');
    document.write('on error resume next \n');
    document.write('If MSDetect = "true" Then\n');
    document.write('   For iii = 2 to actFlash_version\n');
    document.write('      If Not(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & iii))) Then\n');
    document.write('      \n');
    document.write('      Else\n');
    document.write('          flashinstalled = 2\n');
    document.write('          flashversion = iii\n');
    document.write('      End If\n');
    document.write('   Next\n');
    document.write('End If\n');
    document.write('If flashinstalled = 0 Then\n');
    document.write('   flashinstalled = 1\n');
    document.write('End If\n');
    document.write('</SCRIPT\> \n');
    if (flashinstalled != 0 && flashversion >= actFlash_version) {
        return true;
    }
    return false;
};
checkJava = function(){
    return navigator.javaEnabled()
};

function getFlashMovieObject(b){
    if (window.document[b]) {
        return window.document[b]
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[b]) {
            return document.embeds[b]
        }
    }
    else {
        return document.getElementById(b)
    }
}
;;var intCheckCookies = function(){
    $.cookie('_spill_tst_cookie', 123);
    tmp = parseInt($.cookie('_spill_tst_cookie'));
    $.cookie('_spill_tst_cookie', null);
    if (tmp == 123){return 1;};
    return 0;
};
var intUrlSet = function(){
    if(intCheckCookies() == 1){
        $.cookie('_intSPIL', document.location.href,{expires:10,path:'/'});
    };
};
var intUrlGet = function(url){
    if((intCheckCookies() == 1) && ($.cookie('_intSPIL') != null)){
        top.location.href = $.cookie('_intSPIL');
        return true;
    }else{
        top.location.href = url;
        return true;
    }
};
;/**
 * dTooltip - jQuery plugin - left/right tooltip
 *
 * @author damian
 */
;(function() {
$.fn.dTooltip = function(options){
    var target = this; var targetWidth = 0; var targetHeight = 0;
    var displayDiv = null;

    var defaults = {
        displayDiv: 'dtooltip',
        content:'dtooltip',
        track:false,
        displayDivHeight: 123,
        displayDivWidth: 174,
        position:'right',
        x: 10,
        y: 0,
        eventHandler: 'li',
        pngFix: true,
        drawItemCallback: false,
        ellipsis:false,
        langStrings: {
            rating: 'Rating:'
        }
    };

    var options = $.extend(defaults, options);

    var tooltipEventMouseEnter = function(event,displayDiv){
        try{
            $(displayDiv).show();
        }catch(ex){}
    };

    var tooltipEventMouseLeave = function(event,displayDiv){
        try{
            $(displayDiv).hide();
        }catch(ex){}
    };

    var initialize = function(){
    try{
        if (parseInt($('#'+options.displayDiv).length) == 0){
            $(document.body).append('<div id="'+options.displayDiv+'"></div>');
        };
        $(target).find(options.eventHandler).mouseenter(function(event){
            displayDiv = $('#'+options.displayDiv);
            coords = $(this).offset();
            if (options.track == false){
                if (options.position == 'right'){
                    _top = Math.round(parseInt(coords.top) + (0.5 * parseInt($(this).height()) - (0.5 * parseInt(options.displayDivHeight))) )+parseInt(options.y);
                    _left = Math.round(parseInt(coords.left) - parseInt(options.displayDivWidth) )+parseInt(options.x);
                     $(displayDiv).removeClass('dtooltipLeft').addClass('dtooltipRight');
                }else{
                    _top = Math.round(parseInt(coords.top) + (0.5 * parseInt($(this).height()) - (0.5 * parseInt(options.displayDivHeight))) )+parseInt(options.y);
                    _left = Math.round(parseInt(coords.left) + parseInt($(this).width()) )+parseInt(options.x);
                    $(displayDiv).removeClass('dtooltipRight').addClass('dtooltipLeft');
                }
            }else{
                $(target).find(options.eventHandler).mousemove(function(event){
                    if (options.position == 'right'){
                        _top = event.pageY+options.y;
                        _left = event.pageX+options.x;
                    }else{
                        _top = event.pageY+options.y;
                        _left = event.pageX+options.x;
                    };
                    $(displayDiv).css('top',_top+'px');
                    $(displayDiv).css('left',_left+'px');
                });
                if (options.position == 'right'){
                    _top = event.pageY+options.y;
                    _left = event.pageX+options.x;
                }else{
                    _top = event.pageY+options.y;
                    _left = event.pageX+options.x;
                };
            };
            $(displayDiv).css('top',_top+'px');
            $(displayDiv).css('left',_left+'px');
                callback = eval(options.drawItemCallback);
                tooltipitem = callback(event,this);
                if(options.content != options.displayDiv){
                    if($(displayDiv).find(options.content).html() != tooltipitem){
                        $(displayDiv).find(options.content).find('*').remove();
                        $(displayDiv).find(options.content).append(tooltipitem);
                    };

                }else{
                    if($(displayDiv).html() != tooltipitem){
                        $(displayDiv).find('*').remove();
                        $(displayDiv).append(tooltipitem);
                    }
                }
            $(displayDiv).show();
            if (options.ellipsis != false){
                $(displayDiv).dEllipsis(options.ellipsis);
            };
            if (options.pngFix){
                $('#'+options.displayDiv).ifixpng();
                $('#'+options.displayDiv).find('*').ifixpng();
            }
        });
        $(target).find(options.eventHandler).mouseleave(function(){
                $(displayDiv).hide();
        });
    }catch(ex){};
    };
    initialize();
};
})(jQuery);
var drawPopularItem = function(event,eventHandler){
    var rating = $(eventHandler).find('span.tooltipHiddenRating').text();
    rating = parseInt( parseInt(rating) / 10 ) *14;
    return '<span class="tooltipOverflow"><span class="dtooltip">'+$(eventHandler).find('a.tooltipHidden:first').text()+'</span></span><img class="dtooltip2" src="'+$(eventHandler).find('img.tooltipHidden:first').attr('src')+'" /><span class="dtooltipRating"><span class="hearts2" style="background-position: right -' +rating+ 'px">&nbsp;</span></span>';
};

var drawNeboxItem = function(event,eventHandler){
    var ratingText = $(eventHandler).parent().find('span.tooltipHiddenRating:first').text();
    var rating = $(eventHandler).parent().find('span.tooltipHiddenRating:last').text();
    var thisTitle = $(eventHandler).parent().find('span.gameTitle').text();
    rating = parseInt( parseInt(rating) / 10 ) *14;
    var originalTitle = $(eventHandler).parent().find('span.tooltipHiddenOriginalTitle').text();
    if(originalTitle!=thisTitle && originalTitle!='') {
        var response = '<span class="dtooltipTitle">(' + originalTitle + ')</span>';
    } else {
        var response = '';
    }
    response = response + '<span class="dtooltipDescription">'+$(eventHandler).parent().find('span.tooltipHidden:first').text()+'</span><span class="dtooltip">('+$(eventHandler).parent().find('span.tooltipHidden:last').text()+')</span><span class="dtooltipRating">'+ratingText+': <span class="hearts" style="background-position: right -' +rating+ 'px">&nbsp;</span></span>';
    return response;
};

var drawGalleryGameItem = function(event, eventHandler) {
    return '<span class="dtooltipTotalImages">'+$(eventHandler).parent().find('span.totalImages').text()+'</span>'+
           '<span class="dtooltipDescription">'+$(eventHandler).parent().find('span.description').text()+'</span>';
}

var drawAchievementItem = function(event, eventHandler){

    //console.log( eventHandler );
    var str = '<span class="dtooltipAchievement_awardname">'+$(eventHandler).parent().find('span.awname:first').text()+'</span>' +
              '<span class="dtooltipAchievement_description">'+$(eventHandler).parent().find('span.desc:first').text()+'</span>' +
              '<span class="dtooltipAchievement_points">'+$(eventHandler).parent().find('span.points:first').text()+'</span>' +
              '<span class="dtooltipAchievement_gametitle">'+$(eventHandler).parent().find('span.game:first').html()+'</span>';


    return str;
};


var drawVirtualItem = function(event,eventHandler){
    return '<span class="dtooltipDescription">'+$(eventHandler).parent().find('span.tooltipHidden:first').text()+'</span>';
};

var drawProfileItem = function(event, eventHandler) {
    var title = $(eventHandler).parent().find('span.tooltipHidden:first').text();
    var text = $(eventHandler).parent().find('span.tooltipHidden:last').text();
    var points = $(eventHandler).parent().find('span.tooltipHiddenRating:first').text();
    return '<span class="dtooltipDescription">'+title+'</span><span class="dtooltip">'+text+'</span><span class="dtooltipRating">'+points+'</span>';
};
var drawProfileGalleryGamePage = function(event, eventHandler) {
    var avatar = $(eventHandler).parent().find('span.tooltipAvatar').html();
    var username = $(eventHandler).parent().find('span.tooltipUsername').text();
    var title = $(eventHandler).parent().find('span.tooltipTitle').text();
    var ratingValue = $(eventHandler).parent().find('span.tooltipRatingValue').text();
    ratingValue = (parseInt(ratingValue)) * 14;
    var render = '' +
        '<span class="dtooltipAvatar dtooltipCommonUGC" style="display: block; height: 50px;">' + avatar + '</span>' +
        '<span class="dtooltipDescription dtooltipDescriptionUGC dtooltipCommonUGC" style="position: absolute; top: 32px; left: 66px;">' + username + '</span>' +
        '<span class="dtooltip dtooltipCommonUGC" style="position: absolute; top: 46px; left: 66px; width: 130px;">' + title + '</span>' +
        '<span class="dtooltipRating dtooltipCommonUGC">' +
        '<span class="hearts heartsUGC" style="background-position: left -' + ratingValue + 'px">&nbsp;</span>&nbsp;</span>' +
        '';
    return render;
};
var drawProfileGalleryOverview = function(event, eventHandler) {
    var description = $(eventHandler).parent().find('span.tooltipDescription').text();
    var title = $(eventHandler).parent().find('span.tooltipTitle').text();
    var ratingValue = $(eventHandler).parent().find('span.tooltipRatingValue').text();
    ratingValue = parseInt(ratingValue) * 14;
    var render = '' +
        '<span class="dtooltipDescription dtooltipDescriptionUGC dtooltipCommonUGC">' + title + '</span>' +
        '<span class="dtooltip dtooltipCommonUGC">' + description + '</span>' +
        '<span class="dtooltipRating dtooltipCommonUGC dtooltipHeartsUGC">' +
        '<span class="hearts heartsUGC" style="background-position: left -' + ratingValue + 'px">&nbsp;</span>&nbsp;</span>' +
        '';
    return render;
};
var drawProfileGalleryPage = function(event, eventHandler) {
    var title = $(eventHandler).parent().find('span.tooltipTitle').text();
    var ratingValue = $(eventHandler).parent().find('span.tooltipRatingValue').text();
    ratingValue = parseInt(ratingValue) * 14;
    var render = '' +
        '<span class="dtooltipDescription dtooltipDescriptionUGC dtooltipCommonUGC">' + title + '</span>' +
        '<span class="dtooltipRating dtooltipCommonUGC dtooltipHeartsUGC">' +
        '<span class="hearts heartsUGC" style="background-position: left -' + ratingValue + 'px">&nbsp;</span>&nbsp;</span>' +
        '';
    return render;
};

var drawLevelBarItem = function(event,eventHandler){
    return '<span class="dtooltipDescription">'+$(eventHandler).parent().find('span.tooltipHidden:first').text()+'</span>';
};
;/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */

(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};

	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/img/pixel.gif';
	};

	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale,src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */

	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };

	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */

	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };

	/**
	 * positions selected item relatively
	 */

	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

$(function(){
    $(".pngfix").ifixpng();
});

;;var markMenu = function(){
    tmp = document.location.href.split(document.domain);
    $('.leftNavigation ul li a[href="'+tmp[1]+'"]').addClass('currentOne');
    try{
        tmp = tmp[1].split(',');
        if ($.isArray(tmp)){
            tmp2 = tmp[1].split('.');
            $('.leftNavigation ul li a[href="'+tmp[0]+'.'+tmp2[1]+'"]').addClass('currentOne');
        };
    }catch(ex){};
        
};
;function trackIt(trackingPath){
    try {
        pageTracker._trackPageview(decodeURI(trackingPath.replace(/\+/g,' '))+'');
    } catch(e) {}
};

var trackExtViewar = function(siteid, gameid) {
    var i = new Image(1, 1);
    i.src = 'http://api.viewar.org/vw/pb/1/add/'+siteid+'/1/'+gameid+'/1';
    var delay = 500;
    i.onload = i.onerror = function() {delay = 0;}; // If image loaded, end the while below.
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay) { 
        ;
    } // Not elegant, but stops the browser for max half a second.
};

function trackAllEvents(eventdata, tracker) {
    trackIt(eventdata.path);
    trackEvents(eventdata, tracker);
};
function trackEvents(eventdata, tracker) {
    try {
        var track = tracker || GA_tracker_aggregated;
        trackEvent({category:'portal-partner', action:eventdata.action, label:eventdata.label }, track);
        trackEvent({category:'partner-portal', action:eventdata.label, label:eventdata.action }, track);
    } catch (e) {}
}
function trackEvent(eventdata, tracker) {
    try {
        tracker._trackEvent(eventdata.category, eventdata.action, eventdata.label);
    } catch (e) {}
};

;/**
 * dcarousel - jQuery plugin - carousel
 *   
 * @author damian
 */
;(function() {
$.fn.dcarousel = function(options){
    var target = this;
    var timeoutObj;
    var position = 0;
    
    var defaults = {
        auto:1,
        size:1,
        scroll:1,
        width:100,
        beforeAnimate:'',
        afterAnimate:''    
    };
    
    var options = $.extend(defaults, options);
    
    var setPos = function(_position){
        stopAnimate();
        position = _position;
        animate();
    };
    
    var resettimeout = function(){
        clearTimeout(timeoutObj);
        timeoutObj = setTimeout(function(){ animate()},options.auto *1000);
    };
    
    var stopAnimate = function(){
        clearTimeout(timeoutObj);
    };
    
    var startAnimate = function(){
        timeoutObj = setTimeout(function(){ animate()},options.auto *1000);
    };
    
    var animate = function(){
        if (timeoutObj) stopAnimate();
        if (position == options.size){position=0};
        $(target).find('li').find('a').unbind('mouseenter').unbind('mouseleave');
        $(target).find('li').eq(position).find('a').mouseenter(function(){
            stopAnimate();
        }).mouseleave(function(){
            startAnimate();
        });
        $('.rotatorButtons li, .rotatorButtons li a').removeClass('current');
        $('.rotatorButtons li').eq(position).addClass('current').find('a').addClass('current');
        pos(position);
        position++;
        startAnimate();
    };
    
    
    var pos = function(i){
        $(target).animate({'left':-1 * i * options.width},500);
    };
    
    var initialize = function(){
    try{
        $(target).bind('animate',function(){animate()});
        $(target).bind('setPos',function(event,data){setPos(data)});
        $(target).bind('stopAnimate',function(){stopAnimate()});
        $(target).bind('startAnimate',function(){startAnimate()});
        $(target).bind('resetTimeout',function(){resetTimeout()});
        i = 0;
        $('.rotatorButtons li a').each(function(){
            $(this).attr('No',i).click(function(){
                $(target).trigger('setPos',[$(this).attr('No')]);
                 return false;
            });
            i++;
        });
        animate();
    }catch(ex){};
    };
    return initialize();
};
})(jQuery);
;
(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.

        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

        if(o.circular) {
            ul.prepend(tLi.slice(tl-v-1+1).clone())
              .append(tLi.slice(0,v).clone());
            o.start += v;
        }

        var li = $("li", ul), itemLength = li.size(), curr = o.start;
        div.css("visibility", "visible");

        li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

        li.css({width: li.width(), height: li.height()});
        ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

        if(o.btnPrev)
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });

        if(o.btnNext)
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        if(o.auto)
            setInterval(function() {
                go(curr+o.scroll);
            }, o.auto+o.speed);

        function vis() {
            return li.slice(curr).slice(0,v);
        };

        function go(to) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
                    } else if(to>=itemLength-v+1) { // If last, then goto first
                        ul.css(animCss, -( (v) * liSize ) + "px" );
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                running = true;

                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
            return false;
        };
    });
};

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);
;var loadOrderingBar = function(url_template, sorting, viewtype) {
    var url = window.location;
    url = url.toString();
    var myarray = url.split(",");
    // if(myarray[2]==20||myarray[2]==40||myarray[2]==80){var
    // default_limit=myarray[2];} else { var default_limit=20;}
    // var limit = $('.results_limiter').val() || default_limit;
    var limit = 25;
    if(viewtype==1) limit = 7;
    if (sorting == undefined) {
        $('.results_limiter').change(function() {
            window.location = sprintf(url_template, limit);
            return false;
        });
    } else {
        $('#sort_by_1').click(function() {
            window.location = sprintf(url_template, limit, 1, viewtype);
            return false;
        });
        $('#sort_by_2').click(function() {
            window.location = sprintf(url_template, limit, 2, viewtype);
            return false;
        });
        $('#sort_by_3').click(function() {
            window.location = sprintf(url_template, limit, 3, viewtype);
            return false;
        });
        $('.results_limiter').change(function() {
            window.location = sprintf(url_template, $(this).val(), sorting);
            return false;
        });
        $('#sort_by_' + sorting).parent('li.anchor').addClass('active');
        $('#sort_by_' + sorting).addClass('active');
    }
    /*
     * if(myarray[3] != undefined){ if(myarray[3] != 0 ){ var sorting_kind =
     * myarray[3].split(".");
     * $('#sort_by_'+sorting_kind).parent('li.anchor').addClass('active');
     * $('#sort_by_'+sorting_kind).addClass('active'); } }
     */
};
var clickViewtypeBar = function(url_template, sorting, viewtype) {
    var url = window.location;
    url = url.toString();
    var myarray = url.split(",");
    var limit = 25;
    if(viewtype==1) limit = 7;
    window.location = sprintf(url_template,  limit, sorting, viewtype);
    return false;
}
;/**
 * pRating - jQuery plugin - rating I like/I hate
 *
 * @author Piotr (based on nez's code)
 * @param object settings
 * @requires jquery, jquery.cookie.js and sprintf.js
 */
;jQuery.fn.pRating = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'Piotr',
        version: '1.0',
        url: '/rt/pr/%d/add/%d/%d/%d',
        outputtype: 'xml',
        method: 'POST',
        timeout: 2000,
        api: 1,
        itemtype: 1, // 1 -> game
        siteid: 0,
        gameid: 0,
        visibility: 0,
        ratingCookie: {
            name: '_spilVote[%s][%s]',
            options: {
                path: '/',
                expires: 1
            }
        },
        buttonLike: '#i-like-this-game',
        buttonDontLike: '#i-dont-like-this-game',
        buttonRatingHearts: '#rating-display',
        buttonThanks: '#rating-question',
        langstrings: {
            ilikeit: 'I like this game',
            ihateit: 'I don\'t like this game',
            thanks: 'Thanks for your rating!',
            saveerror: 'Oops! An error.. try again later!',
            alreadyrated: 'You can\'t vote right now'
        }
    }, settings);

    var self = $(this);

    if(!settings.siteid && !settings.gameid) {
        return false;
    } else {
        settings.ratingCookie.name = sprintf(settings.ratingCookie.name, settings.siteid, settings.gameid);
    };

    var canRate = function() {
        var cookieData = $.cookie( settings.ratingCookie.name ) || '';
        if (cookieData=='') return true;
        return (cookieData == settings.siteid +"|"+ settings.gameid) ? false : true;
    };

    var checkAlreadyRated = function() {
        if( canRate() === false ) {
            putMessage({message: '', placeholder: settings.langstrings.buttonThanks});
            setRatingState(false);
        } else {
            setRatingState(true);
        };
    };

    var addToCookie = function(){
        if( canRate() === true ) {
            var cookieValue = settings.siteid +"|"+ settings.gameid;
            $.cookie( settings.ratingCookie.name, ''+cookieValue, settings.ratingCookie.options );
        }
    };

    var setRatingState = function(state) {
        var rating1 = rating2 = '';
        if(state){
            rating1 = 'rating-hidden';
            rating2 = 'rating-show';
        } else {
            rating1 = 'rating-show';
            rating2 = 'rating-hidden';
        }
        $(settings.buttonLike).removeClass(rating1).addClass(rating2);
        $(settings.buttonDontLike).removeClass(rating1).addClass(rating2);
        $(settings.buttonRatingHearts).removeClass(rating2).addClass(rating1);
    };

    var putMessage = function(messageData) {
        var message = messageData.message || '';
        var placeholder = messageData.placeholder || settings.buttonThanks;
        if (message != '' && placeholder) {

            if(settings.visibility==0) {
                $("#game-rating").height('50px');
                $(placeholder + ' .middle').html(message + '<span class="minwidth"></span>');
                window.setTimeout(function(){$(placeholder + ' .middle').hide();$("#game-rating").height('30px');}, 10000);
            } else {
                $(placeholder + ' .middle').html(message + '<span class="minwidth"></span>');
                window.setTimeout(function(){$(placeholder + ' .middle').css('visibility', 'hidden');}, 10000);
            }
        } else {
            if(settings.visibility==0) {
                $(placeholder + ' .middle').hide();
                $("#game-rating").height('30px');
            } else {
                $(placeholder + ' .middle').css('visibility', 'hidden');
            }
        };
    };

    var handleResponse = function(data, message) {
        var errorcode = $('errorcode', data).text();
        if (errorcode != '' && errorcode != 0){
            putMessage({message: settings.langstrings.saveerror, placeholder: settings.buttonThanks});
        } else {
            putMessage({message: settings.langstrings.thanks, placeholder: settings.langstrings.buttonThanks});
            addToCookie();
        };
        setRatingState(false);
    };

    var handleError = function() {
        putMessage({message: settings.langstrings.saveerror, placeholder: settings.buttonThanks});
        setRatingState(false);
    };

    var sendRating = function(rating) {
        if( $.profilar.loggedIn() == false ) {
            var myData = {
                rating: rating
            };
        } else {
            var myData = {
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash,
                rating: rating
            };
        }
        try {
            $.ajax({
                url: sprintf(settings.url, settings.api, settings.siteid, settings.itemtype, settings.gameid),
                global: false,
                type: settings.method,
                dataType: settings.outputtype,
                success: handleResponse,
                error: handleError,
                timeout: settings.timeout,
                data: myData
            });
        } catch(e) {
            showMessage({message: settings.langstrings.saveerror});
        }
    };

   return this.each( function(){
        checkAlreadyRated();
        $( settings.buttonLike, self).click(function() {
            if ( canRate() === true ){
                sendRating(10);
            } else {
                putMessage({message: settings.langstrings.alreadyrated, placeholder: settings.buttonThanks});
                setRatingState(false);
            };
            return false;
        });
        $( settings.buttonDontLike, self).click(function() {
            if ( canRate() === true ){
                sendRating(0);
            } else {
                putMessage({message: settings.langstrings.alreadyrated, placeholder: settings.buttonThanks});
                setRatingState(false);
            };
            return false;
        });
        $( settings.buttonRatingHearts, self ).click(function(){ return false; });
    });
}
;// BOOKMARK LINK (for IE)
function CreateBookmarkLink(url, title){
    if (window.sidebar && !document.all) {
        window.sidebar.addPanel(title, url, "");
    }
    else 
        if (window.external) {
            window.external.AddFavorite(url, title);
        }
        else 
            if (window.opera && window.print) {
                return false;
            }
};
/*
 
 ie bookmark was not requested in task
 also there was icon missing in mockup
$(function(){
    if( $.browser.msie == true ) {
        $('li.iebookmark').show();
    }
});
*/
;;
function getAbsoluteLeft(htmlObject) {
    var xPos = htmlObject.offsetLeft;
    var temp = htmlObject.offsetParent;
    while (temp != null) {
        xPos += temp.offsetLeft;
        temp = temp.offsetParent;
    };
    return xPos;
};

var _isFF = false;
var _isIE = false;
var _isOpera = false;
var _isKHTML = false;
var _isMacOS = false;
if (navigator.userAgent.indexOf('Macintosh') != -1) _isMacOS = true;
if ((navigator.userAgent.indexOf('Safari') != -1) || (navigator.userAgent.indexOf('Konqueror') != -1)) {
    var _KHTMLrv = parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Safari') + 7, 5));
    if (_KHTMLrv > 525) {
        _isFF = true;
        var _FFrv = 1.9;
    } else _isKHTML = true;
} else if (navigator.userAgent.indexOf('Opera') != -1) {
    _isOpera = true;
    _OperaRv = parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Opera') + 6, 3))
} else if (navigator.appName.indexOf("Microsoft") != -1) {
    _isIE = true;
    if (navigator.appVersion.indexOf("MSIE 8.0") != -1 && document.compatMode != "BackCompat") _isIE = 8;
} else {
    _isFF = true;
    var _FFrv = parseFloat(navigator.userAgent.split("rv:")[1]);
};

dhtmlxEventable = function (obj) {
    obj.dhx_SeverCatcherPath = "";
    obj.attachEvent = function (name, catcher, callObj) {
        name = 'ev_' + name.toLowerCase();
        if (!this[name]) this[name] = new this.eventCatcher(callObj || this);
        return (name + ':' + this[name].addEvent(catcher));
    };
    obj.callEvent = function (name, arg0) {
        name = 'ev_' + name.toLowerCase();
        if (this[name]) return this[name].apply(this, arg0);
        return true;
    };
    obj.checkEvent = function (name) {
        return ( !! this['ev_' + name.toLowerCase()]);
    };
    obj.eventCatcher = function (obj) {
        var dhx_catch = [];
        var z = function () {
            var res = true;
            for (var i = 0; i < dhx_catch.length; i++) {
                if (dhx_catch[i] != null) {
                    var zr = dhx_catch[i].apply(obj, arguments);
                    res = res && zr;
                }
            };
            return res;
        };
        z.addEvent = function (ev) {
            if (typeof(ev) != "function") ev = eval(ev);
            if (ev) return dhx_catch.push(ev) - 1;
            return false;
        };
        z.removeEvent = function (id) {
            dhx_catch[id] = null;
        };
        return z;
    };
    obj.detachEvent = function (id) {
        if (id != false) {
            var list = id.split(':');
            this[list[0]].removeEvent(list[1]);
        }
    }
};

//v.2.1 build 90226
/*
Copyright DHTMLX LTD. http://www.dhtmlx.com
You allowed to use this component or parts of it under GPL terms
To use it on other terms or get Professional edition of the component please contact us at sales@dhtmlx.com
*/

function dhtmlxSlider(parentNod, size, skin, vertical, min, max, value, step) {
    if (_isIE) try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch(e) {};
    if (!parentNod) {
        var z = "slider_div_" + (new Date()).valueOf() + Math.random(1000);
        var parentNod = document.createElement("div");
        parentNod.setAttribute("id", z);
        document.body.appendChild(parentNod);
    } else if (typeof(parentNod) != "object") parentNod = document.getElementById(parentNod);
    if (typeof(size) == "object") {
        skin = size.skin;
        min = size.min;
        max = size.max;
        step = size.step;
        vertical = size.vertical;
        value = size.value;
        size = size.size;
    };
    this.size = size;
    this.value = value || 0;
    this.vMode = vertical || false;
    this.skin = skin || "";
    this.parent = parentNod;
    this.isInit = false;
    this.value = value || min || 0;
    this.inputPriority = true;
    this.stepping = false;
    this.imgURL = window.dhx_globalImgPath || "/img/zoomslider/";
    this._def = [min, max, step, value, size];
    dhtmlxEventable(this);
    return this;
};
dhtmlxSlider.prototype.createStructure = function () {
    if (this.con) {
        this.con.parentNode.removeChild(this.con);
        this.con = null;
    };
    if (this.vMode) {
        this._sW = "height";
        this._sH = "width";
        this._sL = "top";
        this._sT = "left";
        var skinImgPath = this.imgURL;
    } else {
        this._sW = "width";
        this._sH = "height";
        this._sL = "left";
        this._sT = "top";
        var skinImgPath = this.imgURL;
    };
    this.con = document.createElement("DIV");
    this.con.onselectstart = function () {
        return false;
    };
    this.con._etype = "slider";
    this.con.className = "dhtmlxSlider" + (this.skin ? "_" + this.skin: this.skin);
    //this.con.style.background = "url(" + skinImgPath + "bg.gif)";
    this.drag = document.createElement("DIV");
    this.drag._etype = "drag";
    this.drag.className = "selector";
    this.drag.style.backgroundImage = "url(" + skinImgPath + "selector.gif)";
    var leftSide = document.createElement("DIV");
    leftSide.className = "leftSide";
    leftSide.style.background = "url(" + skinImgPath + "leftside_bg.gif)";
    this.leftZone = document.createElement("DIV");
    this.leftZone.className = "leftZone";
    this.leftZone.style.background = "url(" + skinImgPath + "leftzone_bg.gif)";
    this.leftZone.style.width = Math.abs(this.value) + 'px';
    var rightSide = document.createElement("DIV");
    rightSide.className = "rightSide";
    rightSide.style.background = "url(" + skinImgPath + "rightside_bg.gif)";
    this.rightZone = document.createElement("DIV");
    this.rightZone.className = "rightZone";
    this.rightZone.style.background = "url(" + skinImgPath + "rightzone_bg.gif)";
    this.con.appendChild(leftSide);
    this.con.appendChild(this.leftZone);
    this.con.appendChild(this.rightZone);
    this.con.appendChild(rightSide);
    this.con.appendChild(this.drag);
    this.parent.appendChild(this.con);
    if (!this.parent.parentNode || !this.parent.parentNode.tagName) document.body.appendChild(this.parent);
    if (this.vMode) {
        this._sW = "height";
        this._sH = "width";
        this._sL = "top";
        this._sT = "left";
        this.con.style.width = this.con.offsetHeight + 'px';
        for (var i = 0; i < this.con.childNodes.length; i++) {
            this.con.childNodes[i].style.fontSize = "0";
            var tmp = this.con.childNodes[i].offsetWidth;
            this.con.childNodes[i].style.width = this.con.childNodes[i].offsetHeight + 'px';
            this.con.childNodes[i].style.height = tmp + 'px';
            tmp = this.con.childNodes[i].offsetLeft;
            this.con.childNodes[i].style.left = this.con.childNodes[i].offsetTop + 'px';
            this.con.childNodes[i].style.top = tmp + 'px';
        };
        rightSide.style.top = this.size - rightSide.offsetHeight + 'px';
        this.zoneSize = this.size - rightSide.offsetHeight;
        this.dragLeft = this.drag.offsetTop;
        this.dragWidth = this.drag.offsetHeight;
        this.rightZone.style.height = this.zoneSize + 'px';
    } else {
        this.zoneSize = this.size - rightSide.offsetWidth;
        /* FIXME: +3+12 dirty fix slider was going too much to the right */
        this.dragLeft = this.drag.offsetLeft+3;
        this.dragWidth = this.drag.offsetWidth+12;
        this.rightZone.style.width = this.zoneSize + 'px';
    };
    this.con.style[this._sW] = this.size + "px";
    this.con.onmousedown = this._onMouseDown;
    this.con.onmouseup = this.con.onmouseout = function () {
        clearInterval(this.that._int);
    };
    this.con.that = this;
    this._aCalc(this._def);
    this.setValue(this.value);
};
dhtmlxSlider.prototype._aCalc = function (def) {
    if (!this.isInit) return;
    this.shift = def[0] || 0;
    this.limit = (def[1] || 100) - this.shift;
    this._mod = (def[4] - this.dragLeft * 2 - this.dragWidth) / this.limit;
    this._step = (def[2] || 1);
    this.step = this._step * this._mod;
    this._xlimit = def[4] - this.dragLeft * 2 - this.dragWidth;
    if (!this.posX) this.posX = this._xlimit * ((def[3] || 0) - this.shift) / this.limit;
    this._applyPos(true);
    return this;
};
dhtmlxSlider.prototype.setMin = function (val) {
    this._def[0] = val;
    this._aCalc(this._def);
};
dhtmlxSlider.prototype.setMax = function (val) {
    this._def[1] = val;
    this._aCalc(this._def);
};
dhtmlxSlider.prototype.setStep = function (val) {
    this._def[2] = val;
    this._aCalc(this._def);
};
dhtmlxSlider.prototype._applyPos = function (skip) {
    if (!this.isInit) return;
    if (this.posX < 0) this.posX = 0;
    if (this.value < (this._def[0] || 0)) this.value = this._def[0] || 0;
    if (this.value > this._def[1]) this.value = this._def[1];
    if (this.posX > this._xlimit) this.posX = this._xlimit;
    if (this.step != 1) this.posX = Math.round(this.posX / this.step) * this.step;
    var a_old = this.drag.style[this._sL];
    this.drag.style[this._sL] = this.posX + this.dragLeft * 1 + "px";
    this.leftZone.style[this._sW] = this.posX + this.dragLeft * 1 + "px";
    this.rightZone.style[this._sL] = this.posX + this.dragLeft * 1 + 1 + "px";
    this.rightZone.style[this._sW] = this.zoneSize - (this.posX + this.dragLeft * 1) + "px";
    var nw = this.getValue();
    if (this._link) {
        if (this._linkBoth) this._link.value = nw;
        else this._link.innerHTML = nw;
    };
    skip = false; // NEZ 13.07.2009
    if ((!skip) && this.checkEvent("onChange") && (a_old != this.drag.style[this._sL])) this.callEvent("onChange", [nw, this]);
    this.value = this.getValue();
    if (!this._dttp) this._setTooltip(nw);
};
dhtmlxSlider.prototype._setTooltip = function (nw) {
    this.con.title = nw;
};
dhtmlxSlider.prototype.setSkin = function (skin) {
    this.skin = (skin ? skin: "");
    if (this.isInit) this.createStructure();
};
dhtmlxSlider.prototype.startDrag = function (e) {
    if (this._busy) return;
    if ((e.button === 0) || (e.button === 1)) {
        this.drag_mx = e.clientX;
        this.drag_my = e.clientY;
        this.drag_cx = this.posX;
        this.d_b_move = document.body.onmousemove;
        this.d_b_up = document.body.onmouseup;
        var _c = this;
        document.body.onmouseup = function (e) {
            _c.stopDrag(e || event);
            _c = null;
        };
        document.body.onmousemove = function (e) {
            _c.onDrag(e || event);
        };
        this._busy = true;
    }
};
dhtmlxSlider.prototype.onDrag = function (e) {
    if (this._busy) {
        if (!this.vMode) this.posX = this.drag_cx + e.clientX - this.drag_mx;
        else this.posX = this.drag_cx + e.clientY - this.drag_my;
        this._applyPos();
    }
};
dhtmlxSlider.prototype.stopDrag = function (e) {
    var e = e || event;
    document.body.onmousemove = this.d_b_move ? this.d_b_move: null;
    document.body.onmouseup = this.d_b_up ? this.d_b_up: null;
    this.d_b_move = this.d_b_up = null;
    this._busy = false;
    this.callEvent("onSlideEnd", [this.getValue()]);
};
dhtmlxSlider.prototype.getValue = function () {
    if ((!this._busy) && (this.inputPriority)) return Math.round(this.value / this._step) * this._step;
    return Math.round((Math.round((this.posX / this._mod) / this._step) * this._step + this.shift * 1) * 10000) / 10000;
};
dhtmlxSlider.prototype.setValue = function (val) {
    this.value = val;
    this._applyPos(this.posX = (Math.round(((val || 0) - this.shift) * this._mod)));
};
dhtmlxSlider.prototype._getActionElement = function (nod) {
    if (nod._etype) return nod;
    if (nod.parentNode) return this._getActionElement(nod.parentNode);
    return null;
};
dhtmlxSlider.prototype._onMouseDown = function (e) {
    e = e || event;
    var that = this.that;
    var nod = that._getActionElement(_isIE ? e.srcElement: e.target);
    switch (nod._etype) {
    case "slider":
        if (that.vMode) var z = e.clientY - (getAbsoluteTop(that.con) - document.body.scrollTop);
        else var z = e.clientX - (getAbsoluteLeft(that.con) - document.body.scrollLeft);
        var posX = that.posX;
        that.posX = z - that.dragLeft - that.dragWidth / 2;
        that.direction = that.posX > posX ? 1 : -1;
        if (that.stepping) {
            clearInterval(that._int);
            that.setValue(that.value + that._step * that.direction);
            that._int = setInterval(function () {
                that.setValue(that.value + that._step * that.direction);
            },
            600);
        } else {
            that._busy = true;
            that._applyPos();
            that._busy = false;
            that.callEvent("onSlideEnd", [that.getValue()]);
        };
        break;
    case "drag":
        that.startDrag(e || event);
        break;
    };
    return false;
};
dhtmlxSlider.prototype.setOnChangeHandler = function (func) {
    this.attachEvent("onChange", func);
};
dhtmlxSlider.prototype._linkFrom = function () {
    this.setValue(parseFloat(this._link.value));
};
dhtmlxSlider.prototype.linkTo = function (obj) {
    obj = (typeof(obj) != "object") ? document.getElementById(obj) : obj;
    this._link = obj;
    var name = obj.tagName.toString().toLowerCase();
    this._linkBoth = (((name == "input") || (name == "select") || (name == "textarea")) ? 1 : 0);
    if (this._linkBoth) {
        var self = this;
        var f = function () {
            if (this._nextSlider) window.clearTimeout(this._nextSlider);
            this._nextSlider = window.setTimeout(function () {
                self._linkFrom();
            },
            500);
        };
        obj.onblur = obj.onkeypress = obj.onchange = f;
    };
    this._applyPos();
};
dhtmlxSlider.prototype.enableTooltip = function (mode) {
    this._dttp = (!convertStringToBoolean(mode));
    this._setTooltip(this._dttp ? "": this.getValue());
};
dhtmlxSlider.prototype.setImagePath = function (path) {
    this.imgURL = path;
};
dhtmlxSlider.prototype.init = function () {
    this.isInit = true;
    this.createStructure();
};
dhtmlxSlider.prototype.setInputPriority = function (mode) {
    this.inputPriority = mode;
};
dhtmlxSlider.prototype.setSteppingMode = function (mode) {
    this.stepping = mode;
};

;$.Autocompleter.defaults.parse = function(data){
    eval("var results ="+data);
    parsed = [];
    try{
        $.each(results.searchar.resultset.result, function(){
            parsed.push({
                data:[this.suggestion],
                value:this.suggestion,
                result:this.suggestion
            });
        })
    }catch(e){// if error do nothing
    }
    return parsed
};

$.Autocompleter.defaults.getPhrase = function(){
    return $('#searchtext').val();
};

;if (typeof SPI == "undefined" || !SPI) { var SPI = {_settings: {}, _langStrings: {}, _templates: {}, _tplCache: {}}; }

SPI.log = function (msg) {
    if (window.console && console.log) {
        console.log(msg);
    } else {
        alert(msg);
    }
};

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
// From http://ejohn.org/blog/javascript-micro-templating/
// Modyfications by Rafał Jońca, Spil Games, 2009
SPI.render = function render(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
        SPI._tplCache[str] = SPI._tplCache[str] || render(document.getElementById(str).innerHTML) :

        // Generate a reusable function that will serve as a template
        // generator (and which will be cached).
        new Function("obj",
            "var p=[],print=function(){p.push.apply(p,arguments);};" +

            // Introduce the data as local variables using with(){}
            "with(obj){p.push('" +

            // Convert the template into pure JavaScript
            str
                .split("'").join("\\'") // Added by RJ
                .replace(/[\r\t\n]/g, " ")
                .split("<%").join("\t")
                .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                .replace(/\t=(.*?)%>/g, "',$1,'")
                .split("\t").join("');")
                .split("%>").join("p.push('")
                .split("\r").join("\\'")
                .split("\\\\'").join("\\'") // Added by RJ
            + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
};

SPI.addslashes = function (x){return x.replace(/('|"|\\)/g,"\\$1")};
SPI.str_repeat = function (i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); };
SPI.sprintf = function () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
		if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? SPI.str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
};

SPI.getAndUpdateConfig = function(app, local, update) {
    var x = ['settings', 'langStrings', 'templates'];
	update = update || {};
    for (var i in x) {
        local[x[i]] = local[x[i]] || {};
        jQuery.extend(true, local[x[i]], SPI[('_'+x[i])][app] || {}, update[x[i]] || {});
    }
};

SPI.escape = function(string) {
    return jQuery('<div/>').text(string).html();
};

SPI.ltrim = function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
};

SPI.rtrim = function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
};

SPI.trim = function(str, chars) {
	return SPI.ltrim(SPI.rtrim(str, chars), chars);
};

SPI.typeOf = function(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length')) &&
                    typeof value.splice === 'function') {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
};

SPI.iff = function(condition, val1, val2) {
    if (condition) {
        return val1;
    }
    return val2;
};

SPI.paginatorString = function(totalRes, curPage, elemPerPage, surround, handler, strings) {
    curPage = curPage || 1;
    elemPerPage = elemPerPage || 20;
    surround = surround || 9;

    var totalPages = Math.ceil(totalRes / elemPerPage);

    if (totalPages <= 1) {
        return '';
    }

    var ret = '';
    var naviStart = Math.min(curPage-Math.floor(surround/2), Math.ceil(totalRes/elemPerPage - surround));
    var naviStart = Math.max(naviStart, 1);

    if (curPage == 1) {
            ret += '<span class="paginationButtonPrev paginationButtonPreviousPage"><span class="disabled">'+strings.prev+'</span></span>';
    }

    if (curPage > 1) {
        ret += '<span class="paginationButtonPrev paginationButtonPreviousPage"><a href="#' + (Math.max(1, curPage-1)) + '">'+strings.prev+'</a></span>';
    }

    for(var i=naviStart; i<=totalPages && i<=surround+naviStart; i++) {
        if (i == curPage) {
            ret += '<span class="number">' + i + '</span>';
        } else {
            ret += '<span class="number"><a  class="pagingNumbers" href="#' + i + '">' + i +'</a></span>';
        }
    }

    if (curPage < totalPages) {
        ret += '<span class="paginationButtonNext paginationButtonNextPage"><a href="#' + (Math.min(curPage+1, totalPages)) + '">'+strings.next+'</a></span>';
    }

    if (curPage == totalPages) {
        ret += '<span class="paginationButtonNext paginationButtonNextPage"><span class="disabled">'+strings.next+'</span></span>';
    }

    if (handler) {
        ret = $(ret);

	$('a', ret).click(function(){
           handler.call(this, parseInt($(this).attr('href').replace(/[^\#]*#/,'')));
           return false;
        });
    }

    return ret;
};

SPI.flashMessage = (function(){
    var cookieName = '_profilar_fmessage';
    var that = {};
    that.get = function() {
        var cookieValue = $.cookie( cookieName ) || '';
        that.clear();
        return (cookieValue.split('|'));
    };
    that.set = function(message, error) {
        that.clear();
        var isError = error || false;
        $.cookie( cookieName, message+'|'+isError);
    };
    that.clear = function() {
        $.cookie( cookieName, null );
    };
    return that;
})();

SPI.number_format = function(number, decimals, dec_point, thousands_sep) {

        var decimals = decimals || 0;
        var dec_point = dec_point || SPI._settings.global.number_format_decimalseparator;
        var thousands_sep = thousands_sep || SPI._settings.global.number_format_thousandsseparator;

        var n = number, prec = decimals;
        var toFixedFix = function (n,prec) {
            var k = Math.pow(10,prec);
            return (Math.round(n*k)/k).toString();
        };
        n = !isFinite(+n) ? 0 : +n;
        prec = !isFinite(+prec) ? 0 : Math.abs(prec);
        var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
        var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
        var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
        var abs = toFixedFix(Math.abs(n), prec);
        var _, i;
        if (abs >= 1000) {
            _ = abs.split(/\D/);
            i = _[0].length % 3 || 3;

            _[0] = s.slice(0,i + (n < 0)) +
                  _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
            s = _.join(dec);
        } else {
            s = s.replace('.', dec);
        }
        var decPos = s.indexOf(dec);
        if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
            s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
        }
        else if (prec >= 1 && decPos === -1) {
            s += dec+new Array(prec).join(0)+'0';
        }
        return s;
};

/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 * Changes by Rafał Jońca
 */
SPI.formatDate = function(date, langStrings, day) {
	var s = langStrings || SPI._langStrings.relative_date; // if langStrings variable provided - use it // nez.
	var lowestIsDay = day || false; // if set to TRUE - smallest unit will be DAY (so smallest will be 'Today' instead of minutes) // nez.
	var diff = ((new Date()).getTime() / 1000 - date),
		day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff)) return '';

	// nez.
    if( lowestIsDay === true ) {
	   if( diff < 86400 || day_diff < 1 ) return s[13];
	}

	if (diff < 0 || day_diff < 0) return s[0];
	if (day_diff >= 730) return SPI.sprintf(s[12], Math.ceil( day_diff / 365 ));

	if (day_diff == 0) return diff < 60 && s[0] ||
			diff < 120 && s[1] ||
			diff < 3600 && SPI.sprintf(s[2], Math.floor( diff / 60 )) ||
			diff < 7200 && s[3] ||
			diff < 86400 && SPI.sprintf(s[4], Math.floor( diff / 3600 ));

	return day_diff == 1 && s[5] ||
		day_diff < 7 && SPI.sprintf(s[6], day_diff) ||
		day_diff < 14 && s[7] ||
		day_diff < 31 && SPI.sprintf(s[8], Math.ceil( day_diff / 7 )) ||
		day_diff < 60 && s[9] ||
		day_diff < 365 && SPI.sprintf(s[10], Math.ceil( day_diff / 30 )) ||
		day_diff < 730 && s[11];
};

SPI.formatAbsDate = function(date, isTimestamp, template) {
	isTimestamp = isTimestamp === undefined ? true : isTimestamp;
	template = template === undefined ? SPI._langStrings.formatabsdate : template;
	var day, month, year;
	if (isTimestamp) {
		var tmp = new Date();
		tmp.setTime(parseInt(date)*1000);
		day = tmp.getDate();
		month = tmp.getMonth()+1;
		year = tmp.getFullYear();
	} else {
		day = date.substr(6,2);
		month = date.substr(4,2);
		year = date.substr(0,4);
	}
	return SPI.sprintf(template, year, month, day);
};

SPI.cutStringPlease = function(string, limit, specialchars, ending) {
    var limit = limit || 0;
    var specialchars = specialchars || false;
    var ending = ending || '...';

    if( limit == 0 ) { return string; }

    if( specialchars == true ) {
        string = this.escape(string);
    }

    if( string.length > limit ) {
        string = string.substring(0, limit-1) + '' + ending;
    }
    return string;
};

SPI.getURLparam = function(name){
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      return (results == null) ? '' : results[1];
};

SPI.reloadSite = function(url) {
    var url = url || SPI.getURLparam('r') || SPI._settings.global.static_domain || '/';
    try{ top.location.href=url; } catch(e){};
};

SPI.handlers = (function() {
	var that = {};
	var callbacks = {};

	that.clear = function(bucket) {
		if (bucket === undefined) {
			callbacks = {};
		} else {
			delete callbacks[bucket];
		}
	};

	that.add = function(bucket, callback) {
		if (callbacks[bucket] === undefined) {
			callbacks[bucket] = [];
		}
		callbacks[bucket].push(callback);
	};

	that.run = function(bucket, _arguments, debug) {
		if (callbacks[bucket] === undefined) {
			return;
		}
		for (var i in callbacks[bucket]) {
			try {
				callbacks[bucket][i].apply(this, _arguments === undefined? []:_arguments);
			} catch (e) {
				if (debug === true) throw e;
			}
		}
		that.clear(bucket);
	};

	return that;
})();

SPI.switchObjects = function(showOrHide, elements) {
    var elements = elements || $('object:visible, #flashobj_mc');
    var show = showOrHide || 'show';
    if( $(elements).length>0 ) {
        switch( show.toLowerCase() ) {
            default:
            case 'show':
                $(elements).each(function(){$(this).css('visibility','visible')});
            break;
            case 'hide':
                $(elements).each(function(){$(this).css('visibility','hidden')});
            break;
        }
    }
};

SPI.rand = function(n) {
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
};

;/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

/**
 * Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
 * (instance method extending String object). As per RFC 4648, no newlines are added.
 *
 * @param utf8encode optional parameter, if set to true Unicode string is encoded to UTF8 before 
 *                   conversion to base64; otherwise string is assumed to be 8-bit characters
 * @return           base64-encoded string
 */ 
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

String.prototype.encodeBase64 = function(utf8encode) {  // http://tools.ietf.org/html/rfc4648
  utf8encode =  (typeof utf8encode == 'undefined') ? false : utf8encode;
  var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
   
  plain = utf8encode ? this.encodeUTF8() : this;
  
  c = plain.length % 3;  // pad string to length of multiple of 3
  if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
  // note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
  
  for (c=0; c<plain.length; c+=3) {  // pack three octets into four hexets
    o1 = plain.charCodeAt(c);
    o2 = plain.charCodeAt(c+1);
    o3 = plain.charCodeAt(c+2);
      
    bits = o1<<16 | o2<<8 | o3;
      
    h1 = bits>>18 & 0x3f;
    h2 = bits>>12 & 0x3f;
    h3 = bits>>6 & 0x3f;
    h4 = bits & 0x3f;

    // use hextets to index into b64 string
    e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  }
  coded = e.join('');  // join() is far faster than repeated string concatenation
  
  // replace 'A's from padded nulls with '='s
  coded = coded.slice(0, coded.length-pad.length) + pad;
   
  return coded;
};

/**
 * Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
 * (instance method extending String object). As per RFC 4648, newlines are not catered for.
 *
 * @param utf8decode optional parameter, if set to true UTF8 string is decoded back to Unicode  
 *                   after conversion from base64
 * @return           decoded string
 */ 
String.prototype.decodeBase64 = function(utf8decode) {
  utf8decode =  (typeof utf8decode == 'undefined') ? false : utf8decode;
  var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;

  coded = utf8decode ? this.decodeUTF8() : this;
  
  for (var c=0; c<coded.length; c+=4) {  // unpack four hexets into three octets
    h1 = b64.indexOf(coded.charAt(c));
    h2 = b64.indexOf(coded.charAt(c+1));
    h3 = b64.indexOf(coded.charAt(c+2));
    h4 = b64.indexOf(coded.charAt(c+3));
      
    bits = h1<<18 | h2<<12 | h3<<6 | h4;
      
    o1 = bits>>>16 & 0xff;
    o2 = bits>>>8 & 0xff;
    o3 = bits & 0xff;
    
    d[c/4] = String.fromCharCode(o1, o2, o3);
    // check for padding
    if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
    if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
  }
  plain = d.join('');  // join() is far faster than repeated string concatenation
   
  return utf8decode ? plain.decodeUTF8() : plain; 
};

/**
 * Encode multi-byte Unicode string into utf-8 multiple single-byte characters 
 * (BMP / basic multilingual plane only) (instance method extending String object).
 *
 * Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
 *
 * @return encoded string
 */
String.prototype.encodeUTF8 = function() {
  // use regular expressions & String.replace callback function for better efficiency 
  // than procedural approaches
  var str = this.replace(
      /[\u0080-\u07ff]/g,  // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
      function(c) { 
        var cc = c.charCodeAt(0);
        return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f); }
    );
  str = str.replace(
      /[\u0800-\uffff]/g,  // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
      function(c) { 
        var cc = c.charCodeAt(0); 
        return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f); }
    );
  return str;
};

/**
 * Decode utf-8 encoded string back into multi-byte Unicode characters
 * (instance method extending String object).
 *
 * @return decoded string
 */
String.prototype.decodeUTF8 = function() {
  var str = this.replace(
      /[\u00c0-\u00df][\u0080-\u00bf]/g,                 // 2-byte chars
      function(c) {  // (note parentheses for precence)
        var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f;
        return String.fromCharCode(cc); }
    );
  str = str.replace(
      /[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g,  // 3-byte chars
      function(c) {  // (note parentheses for precence)
        var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f); 
        return String.fromCharCode(cc); }
    );
  return str;
};

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

;////////////////////////////////////////////////////////////////////////////////////////
// Big Integer Library v. 5.1
// Created 2000, last modified 2007
// Leemon Baird
// www.leemon.com
//
// Version history:
//
// v 5.1  8 Oct 2007 
//   - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters
//   - added functions GCD and randBigInt, which call GCD_ and randBigInt_
//   - fixed a bug found by Rob Visser (see comment with his name below)
//   - improved comments
//
// This file is public domain.   You can use it for any purpose without restriction.
// I do not guarantee that it is correct, so use it at your own risk.  If you use 
// it for something interesting, I'd appreciate hearing about it.  If you find 
// any bugs or make any improvements, I'd appreciate hearing about those too.
// It would also be nice if my name and address were left in the comments.
// But none of that is required.
//
// This code defines a bigInt library for arbitrary-precision integers.
// A bigInt is an array of integers storing the value in chunks of bpe bits, 
// little endian (buff[0] is the least significant word).
// Negative bigInts are stored two's complement.
// Some functions assume their parameters have at least one leading zero element.
// Functions with an underscore at the end of the name have unpredictable behavior in case of overflow, 
// so the caller must make sure the arrays must be big enough to hold the answer.
// For each function where a parameter is modified, that same 
// variable must not be used as another argument too.
// So, you cannot square x by doing multMod_(x,x,n).  
// You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
//
// These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
// For most functions, if it needs a BigInt as a local variable it will actually use
// a global, and will only allocate to it only when it's not the right size.  This ensures
// that when a function is called repeatedly with same-sized parameters, it only allocates
// memory on the first call.
//
// Note that for cryptographic purposes, the calls to Math.random() must 
// be replaced with calls to a better pseudorandom number generator.
//
// In the following, "bigInt" means a bigInt with at least one leading zero element,
// and "integer" means a nonnegative integer less than radix.  In some cases, integer 
// can be negative.  Negative bigInts are 2s complement.
// 
// The following functions do not modify their inputs.
// Those returning a bigInt, string, or Array will dynamically allocate memory for that value.
// Those returning a boolean will return the integer 0 (false) or 1 (true).
// Those returning boolean or int will not allocate memory except possibly on the first time they're called with a given parameter size.
// 
// bigInt  add(x,y)               //return (x+y) for bigInts x and y.  
// bigInt  addInt(x,n)            //return (x+n) where x is a bigInt and n is an integer.
// string  bigInt2str(x,base)     //return a string form of bigInt x in a given base, with 2 <= base <= 95
// int     bitSize(x)             //return how many bits long the bigInt x is, not counting leading zeros
// bigInt  dup(x)                 //return a copy of bigInt x
// boolean equals(x,y)            //is the bigInt x equal to the bigint y?
// boolean equalsInt(x,y)         //is bigint x equal to integer y?
// bigInt  expand(x,n)            //return a copy of x with at least n elements, adding leading zeros if needed
// Array   findPrimes(n)          //return array of all primes less than integer n
// bigInt  GCD(x,y)               //return greatest common divisor of bigInts x and y (each with same number of elements).
// boolean greater(x,y)           //is x>y?  (x and y are nonnegative bigInts)
// boolean greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y?
// bigInt  int2bigInt(t,n,m)      //return a bigInt equal to integer t, with at least n bits and m array elements
// bigInt  inverseMod(x,n)        //return (x**(-1) mod n) for bigInts x and n.  If no inverse exists, it returns null
// int     inverseModInt(x,n)     //return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
// boolean isZero(x)              //is the bigInt x equal to zero?
// boolean millerRabin(x,b)       //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime (as opposed to definitely composite)?
// bigInt  mod(x,n)               //return a new bigInt equal to (x mod n) for bigInts x and n.
// int     modInt(x,n)            //return x mod n for bigInt x and integer n.
// bigInt  mult(x,y)              //return x*y for bigInts x and y. This is faster when y<x.
// bigInt  multMod(x,y,n)         //return (x*y mod n) for bigInts x,y,n.  For greater speed, let y<x.
// boolean negative(x)            //is bigInt x negative?
// bigInt  powMod(x,y,n)          //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
// bigInt  randBigInt(n,s)        //return an n-bit random BigInt (n>=1).  If s=1, then the most significant of those n bits is set to 1.
// bigInt  randTruePrime(k)       //return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
// bigInt  str2bigInt(s,b,n,m)    //return a bigInt for number represented in string s in base b with at least n bits and m array elements
// bigInt  sub(x,y)               //return (x-y) for bigInts x and y.  Negative answers will be 2s complement
// bigInt  trim(x,k)              //return a copy of x with exactly k leading zero elements
//
//
// The following functions each have a non-underscored version, which most users should call instead.
// These functions each write to a single parameter, and the caller is responsible for ensuring the array 
// passed in is large enough to hold the result. 
//
// void    addInt_(x,n)          //do x=x+n where x is a bigInt and n is an integer
// void    add_(x,y)             //do x=x+y for bigInts x and y
// void    copy_(x,y)            //do x=y on bigInts x and y
// void    copyInt_(x,n)         //do x=n on bigInt x and integer n
// void    GCD_(x,y)             //set x to the greatest common divisor of bigInts x and y, (y is destroyed).  (This never overflows its array).
// boolean inverseMod_(x,n)      //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
// void    mod_(x,n)             //do x=x mod n for bigInts x and n. (This never overflows its array).
// void    mult_(x,y)            //do x=x*y for bigInts x and y.
// void    multMod_(x,y,n)       //do x=x*y  mod n for bigInts x,y,n.
// void    powMod_(x,y,n)        //do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation.  0**0=1.
// void    randBigInt_(b,n,s)    //do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
// void    randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
// void    sub_(x,y)             //do x=x-y for bigInts x and y. Negative answers will be 2s complement.
//
// The following functions do NOT have a non-underscored version. 
// They each write a bigInt result to one or more parameters.  The caller is responsible for
// ensuring the arrays passed in are large enough to hold the results. 
//
// void addShift_(x,y,ys)       //do x=x+(y<<(ys*bpe))
// void carry_(x)               //do carries and borrows so each element of the bigInt x fits in bpe bits.
// void divide_(x,y,q,r)        //divide x by y giving quotient q and remainder r
// int  divInt_(x,n)            //do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
// int  eGCD_(x,y,d,a,b)        //sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
// void halve_(x)               //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement.  (This never overflows its array).
// void leftShift_(x,n)         //left shift bigInt x by n bits.  n<bpe.
// void linComb_(x,y,a,b)       //do x=a*x+b*y for bigInts x and y and integers a and b
// void linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
// void mont_(x,y,n,np)         //Montgomery multiplication (see comments where the function is defined)
// void multInt_(x,n)           //do x=x*n where x is a bigInt and n is an integer.
// void rightShift_(x,n)        //right shift bigInt x by n bits.  0 <= n < bpe. (This never overflows its array).
// void squareMod_(x,n)         //do x=x*x  mod n for bigInts x,n
// void subShift_(x,y,ys)       //do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
//
// The following functions are based on algorithms from the _Handbook of Applied Cryptography_
//    powMod_()           = algorithm 14.94, Montgomery exponentiation
//    eGCD_,inverseMod_() = algorithm 14.61, Binary extended GCD_
//    GCD_()              = algorothm 14.57, Lehmer's algorithm
//    mont_()             = algorithm 14.36, Montgomery multiplication
//    divide_()           = algorithm 14.20  Multiple-precision division
//    squareMod_()        = algorithm 14.16  Multiple-precision squaring
//    randTruePrime_()    = algorithm  4.62, Maurer's algorithm
//    millerRabin()       = algorithm  4.24, Miller-Rabin algorithm
//
// Profiling shows:
//     randTruePrime_() spends:
//         10% of its time in calls to powMod_()
//         85% of its time in calls to millerRabin()
//     millerRabin() spends:
//         99% of its time in calls to powMod_()   (always with a base of 2)
//     powMod_() spends:
//         94% of its time in calls to mont_()  (almost always with x==y)
//
// This suggests there are several ways to speed up this library slightly:
//     - convert powMod_ to use a Montgomery form of k-ary window (or maybe a Montgomery form of sliding window)
//         -- this should especially focus on being fast when raising 2 to a power mod n
//     - convert randTruePrime_() to use a minimum r of 1/3 instead of 1/2 with the appropriate change to the test
//     - tune the parameters in randTruePrime_(), including c, m, and recLimit
//     - speed up the single loop in mont_() that takes 95% of the runtime, perhaps by reducing checking
//       within the loop when all the parameters are the same length.
//
// There are several ideas that look like they wouldn't help much at all:
//     - replacing trial division in randTruePrime_() with a sieve (that speeds up something taking almost no time anyway)
//     - increase bpe from 15 to 30 (that would help if we had a 32*32->64 multiplier, but not with JavaScript's 32*32->32)
//     - speeding up mont_(x,y,n,np) when x==y by doing a non-modular, non-Montgomery square
//       followed by a Montgomery reduction.  The intermediate answer will be twice as long as x, so that
//       method would be slower.  This is unfortunate because the code currently spends almost all of its time
//       doing mont_(x,x,...), both for randTruePrime_() and powMod_().  A faster method for Montgomery squaring
//       would have a large impact on the speed of randTruePrime_() and powMod_().  HAC has a couple of poorly-worded
//       sentences that seem to imply it's faster to do a non-modular square followed by a single
//       Montgomery reduction, but that's obviously wrong.
////////////////////////////////////////////////////////////////////////////////////////

//globals
bpe=0;         //bits stored per array element
mask=0;        //AND this with an array element to chop it down to bpe bits
radix=mask+1;  //equals 2^bpe.  A single 1 bit to the left of the last bit of mask.

//the digits for converting to different bases
digitsStr='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-';

//initialize the global variables
for (bpe=0; (1<<(bpe+1)) > (1<<bpe); bpe++);  //bpe=number of bits in the mantissa on this platform
bpe>>=1;                   //bpe=number of bits in one element of the array representing the bigInt
mask=(1<<bpe)-1;           //AND the mask with an integer to get its bpe least significant bits
radix=mask+1;              //2^bpe.  a single 1 bit to the left of the first bit of mask
one=int2bigInt(1,1,1);     //constant used in powMod_()

//the following global variables are scratchpad memory to 
//reduce dynamic memory allocation in the inner loop
t=new Array(0);
ss=t;       //used in mult_()
s0=t;       //used in multMod_(), squareMod_() 
s1=t;       //used in powMod_(), multMod_(), squareMod_() 
s2=t;       //used in powMod_(), multMod_()
s3=t;       //used in powMod_()
s4=t; s5=t; //used in mod_()
s6=t;       //used in bigInt2str()
s7=t;       //used in powMod_()
T=t;        //used in GCD_()
sa=t;       //used in mont_()
mr_x1=t; mr_r=t; mr_a=t;                                      //used in millerRabin()
eg_v=t; eg_u=t; eg_A=t; eg_B=t; eg_C=t; eg_D=t;               //used in eGCD_(), inverseMod_()
md_q1=t; md_q2=t; md_q3=t; md_r=t; md_r1=t; md_r2=t; md_tt=t; //used in mod_()

primes=t; pows=t; s_i=t; s_i2=t; s_R=t; s_rm=t; s_q=t; s_n1=t; 
  s_a=t; s_r2=t; s_n=t; s_b=t; s_d=t; s_x1=t; s_x2=t, s_aa=t; //used in randTruePrime_()

////////////////////////////////////////////////////////////////////////////////////////

//return array of all primes less than integer n
function findPrimes(n) {
  var i,s,p,ans;
  s=new Array(n);
  for (i=0;i<n;i++)
    s[i]=0;
  s[0]=2;
  p=0;    //first p elements of s are primes, the rest are a sieve
  for(;s[p]<n;) {                  //s[p] is the pth prime
    for(i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p]
      s[i]=1;
    p++;
    s[p]=s[p-1]+1;
    for(;s[p]<n && s[s[p]]; s[p]++) var corrector=0; //find next prime (where s[p]==0)
  }
  ans=new Array(p);
  for(i=0;i<p;i++)
    ans[i]=s[i];
  return ans;
};

//does a single round of Miller-Rabin base b consider x to be a possible prime?
//x is a bigInt, and b is an integer
function millerRabin(x,b) {
  var i,j,k,s;

  if (mr_x1.length!=x.length) {
    mr_x1=dup(x);
    mr_r=dup(x);
    mr_a=dup(x);
  }

  copyInt_(mr_a,b);
  copy_(mr_r,x);
  copy_(mr_x1,x);

  addInt_(mr_r,-1);
  addInt_(mr_x1,-1);

  //s=the highest power of two that divides mr_r
  k=0;
  for (i=0;i<mr_r.length;i++)
    for (j=1;j<mask;j<<=1)
      if (x[i] & j) {
        s=(k<mr_r.length+bpe ? k : 0); 
         i=mr_r.length;
         j=mask;
      } else
        k++;

  if (s)                
    rightShift_(mr_r,s);

  powMod_(mr_a,mr_r,x);

  if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
    j=1;
    while (j<=s-1 && !equals(mr_a,mr_x1)) {
      squareMod_(mr_a,x);
      if (equalsInt(mr_a,1)) {
        return 0;
      }
      j++;
    }
    if (!equals(mr_a,mr_x1)) {
      return 0;
    }
  }
  return 1;  
};

//returns how many bits long the bigInt is, not counting leading zeros.
function bitSize(x) {
  var j,z,w;
  for (j=x.length-1; (x[j]==0) && (j>0); j--);
  for (z=0,w=x[j]; w; (w>>=1),z++);
  z+=bpe*j;
  return z;
};

//return a copy of x with at least n elements, adding leading zeros if needed
function expand(x,n) {
  var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0);
  copy_(ans,x);
  return ans;
};

//return a k-bit true random prime using Maurer's algorithm.
function randTruePrime(k) {
  var ans=int2bigInt(0,k,0);
  randTruePrime_(ans,k);
  return trim(ans,1);
};

//return a new bigInt equal to (x mod n) for bigInts x and n.
function mod(x,n) {
  var ans=dup(x);
  mod_(ans,n);
  return trim(ans,1);
};

//return (x+n) where x is a bigInt and n is an integer.
function addInt(x,n) {
  var ans=expand(x,x.length+1);
  addInt_(ans,n);
  return trim(ans,1);
};

//return x*y for bigInts x and y. This is faster when y<x.
function mult(x,y) {
  var ans=expand(x,x.length+y.length);
  mult_(ans,y);
  return trim(ans,1);
};

//return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
function powMod(x,y,n) {
  var ans=expand(x,n.length);  
  powMod_(ans,trim(y,2),trim(n,2),0);  //this should work without the trim, but doesn't
  return trim(ans,1);
};

//return (x-y) for bigInts x and y.  Negative answers will be 2s complement
function sub(x,y) {
  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1)); 
  sub_(ans,y);
  return trim(ans,1);
};

//return (x+y) for bigInts x and y.  
function add(x,y) {
  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1)); 
  add_(ans,y);
  return trim(ans,1);
};

//return (x**(-1) mod n) for bigInts x and n.  If no inverse exists, it returns null
function inverseMod(x,n) {
  var ans=expand(x,n.length); 
  var s;
  s=inverseMod_(ans,n);
  return s ? trim(ans,1) : null;
};

//return (x*y mod n) for bigInts x,y,n.  For greater speed, let y<x.
function multMod(x,y,n) {
  var ans=expand(x,n.length);
  multMod_(ans,y,n);
  return trim(ans,1);
};

//generate a k-bit true random prime using Maurer's algorithm,
//and put it into ans.  The bigInt ans must be large enough to hold it.
function randTruePrime_(ans,k) {
  var c,m,pm,dd,j,r,B,divisible,z,zz,recSize;

  if (primes.length==0)
    primes=findPrimes(30000);  //check for divisibility by primes <=30000

  if (pows.length==0) {
    pows=new Array(512);
    for (j=0;j<512;j++) {
      pows[j]=Math.pow(2,j/511.-1.);
    }
  }

  //c and m should be tuned for a particular machine and value of k, to maximize speed
  c=0.1;  //c=0.1 in HAC
  m=20;   //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
  recLimit=20; //stop recursion when k <=recLimit.  Must have recLimit >= 2

  if (s_i2.length!=ans.length) {
    s_i2=dup(ans);
    s_R =dup(ans);
    s_n1=dup(ans);
    s_r2=dup(ans);
    s_d =dup(ans);
    s_x1=dup(ans);
    s_x2=dup(ans);
    s_b =dup(ans);
    s_n =dup(ans);
    s_i =dup(ans);
    s_rm=dup(ans);
    s_q =dup(ans);
    s_a =dup(ans);
    s_aa=dup(ans);
  }

  if (k <= recLimit) {  //generate small random primes by trial division up to its square root
    pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k)
    copyInt_(ans,0);
    for (dd=1;dd;) {
      dd=0;
      ans[0]= 1 | (1<<(k-1)) | Math.floor(Math.random()*(1<<k));  //random, k-bit, odd integer, with msb 1
      for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k)
        if (0==(ans[0]%primes[j])) {
          dd=1;
          break;
        }
      }
    }
    carry_(ans);
    return;
  }

  B=c*k*k;    //try small primes up to B (or all the primes[] array if the largest is less than B).
  if (k>2*m)  //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
    for (r=1; k-k*r<=m; )
      r=pows[Math.floor(Math.random()*512)];   //r=Math.pow(2,Math.random()-1);
  else
    r=.5;

  //simulation suggests the more complex algorithm using r=.333 is only slightly faster.

  recSize=Math.floor(r*k)+1;

  randTruePrime_(s_q,recSize);
  copyInt_(s_i2,0);
  s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe));   //s_i2=2^(k-2)
  divide_(s_i2,s_q,s_i,s_rm);                        //s_i=floor((2^(k-1))/(2q))

  z=bitSize(s_i);

  for (;;) {
    for (;;) {  //generate z-bit numbers until one falls in the range [0,s_i-1]
      randBigInt_(s_R,z,0);
      if (greater(s_i,s_R))
        break;
    }                //now s_R is in the range [0,s_i-1]
    addInt_(s_R,1);  //now s_R is in the range [1,s_i]
    add_(s_R,s_i);   //now s_R is in the range [s_i+1,2*s_i]

    copy_(s_n,s_q);
    mult_(s_n,s_R); 
    multInt_(s_n,2);
    addInt_(s_n,1);    //s_n=2*s_R*s_q+1
    
    copy_(s_r2,s_R);
    multInt_(s_r2,2);  //s_r2=2*s_R

    //check s_n for divisibility by small primes up to B
    for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++)
      if (modInt(s_n,primes[j])==0) {
        divisible=1;
        break;
      }      

    if (!divisible)    //if it passes small primes check, then try a single Miller-Rabin base 2
      if (!millerRabin(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_ 
        divisible=1;

    if (!divisible) {  //if it passes that test, continue checking s_n
      addInt_(s_n,-3);
      for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--);  //strip leading zeros
      for (zz=0,w=s_n[j]; w; (w>>=1),zz++);
      zz+=bpe*j;                             //zz=number of bits in s_n, ignoring leading zeros
      for (;;) {  //generate z-bit numbers until one falls in the range [0,s_n-1]
        randBigInt_(s_a,zz,0);
        if (greater(s_n,s_a))
          break;
      }                //now s_a is in the range [0,s_n-1]
      addInt_(s_n,3);  //now s_a is in the range [0,s_n-4]
      addInt_(s_a,2);  //now s_a is in the range [2,s_n-2]
      copy_(s_b,s_a);
      copy_(s_n1,s_n);
      addInt_(s_n1,-1);
      powMod_(s_b,s_n1,s_n);   //s_b=s_a^(s_n-1) modulo s_n
      addInt_(s_b,-1);
      if (isZero(s_b)) {
        copy_(s_b,s_a);
        powMod_(s_b,s_r2,s_n);
        addInt_(s_b,-1);
        copy_(s_aa,s_n);
        copy_(s_d,s_b);
        GCD_(s_d,s_n);  //if s_b and s_n are relatively prime, then s_n is a prime
        if (equalsInt(s_d,1)) {
          copy_(ans,s_aa);
          return;     //if we've made it this far, then s_n is absolutely guaranteed to be prime
        }
      }
    }
  }
};

//Return an n-bit random BigInt (n>=1).  If s=1, then the most significant of those n bits is set to 1.
function randBigInt(n,s) {
  var a,b;
  a=Math.floor((n-1)/bpe)+2; //# array elements to hold the BigInt with a leading 0 element
  b=int2bigInt(0,0,a);
  randBigInt_(b,n,s);
  return b;
};

//Set b to an n-bit random BigInt.  If s=1, then the most significant of those n bits is set to 1.
//Array b must be big enough to hold the result. Must have n>=1
function randBigInt_(b,n,s) {
  var i,a;
  for (i=0;i<b.length;i++)
    b[i]=0;
  a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt
  for (i=0;i<a;i++) {
    b[i]=Math.floor(Math.random()*(1<<(bpe-1)));
  }
  b[a-1] &= (2<<((n-1)%bpe))-1;
  if (s==1)
    b[a-1] |= (1<<((n-1)%bpe));
};

//Return the greatest common divisor of bigInts x and y (each with same number of elements).
function GCD(x,y) {
  var xc,yc;
  xc=dup(x);
  yc=dup(y);
  GCD_(xc,yc);
  return xc;
}

//set x to the greatest common divisor of bigInts x and y (each with same number of elements).
//y is destroyed.
function GCD_(x,y) {
  var i,xp,yp,A,B,C,D,q,sing;
  if (T.length!=x.length)
    T=dup(x);

  sing=1;
  while (sing) { //while y has nonzero elements other than y[0]
    sing=0;
    for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0
      if (y[i]) {
        sing=1;
        break;
      }
    if (!sing) break; //quit when y all zero elements except possibly y[0]

    for (i=x.length;!x[i] && i>=0;i--);  //find most significant element of x
    xp=x[i];
    yp=y[i];
    A=1; B=0; C=0; D=1;
    while ((yp+C) && (yp+D)) {
      q =Math.floor((xp+A)/(yp+C));
      qp=Math.floor((xp+B)/(yp+D));
      if (q!=qp)
        break;
      t= A-q*C;   A=C;   C=t;    //  do (A,B,xp, C,D,yp) = (C,D,yp, A,B,xp) - q*(0,0,0, C,D,yp)      
      t= B-q*D;   B=D;   D=t;
      t=xp-q*yp; xp=yp; yp=t;
    }
    if (B) {
      copy_(T,x);
      linComb_(x,y,A,B); //x=A*x+B*y
      linComb_(y,T,D,C); //y=D*y+C*T
    } else {
      mod_(x,y);
      copy_(T,x);
      copy_(x,y);
      copy_(y,T);
    } 
  }
  if (y[0]==0)
    return;
  t=modInt(x,y[0]);
  copyInt_(x,y[0]);
  y[0]=t;
  while (y[0]) {
    x[0]%=y[0];
    t=x[0]; x[0]=y[0]; y[0]=t;
  }
};

//do x=x**(-1) mod n, for bigInts x and n.
//If no inverse exists, it sets x to zero and returns 0, else it returns 1.
//The x array must be at least as large as the n array.
function inverseMod_(x,n) {
  var k=1+2*Math.max(x.length,n.length);

  if(!(x[0]&1)  && !(n[0]&1)) {  //if both inputs are even, then inverse doesn't exist
    copyInt_(x,0);
    return 0;
  }

  if (eg_u.length!=k) {
    eg_u=new Array(k);
    eg_v=new Array(k);
    eg_A=new Array(k);
    eg_B=new Array(k);
    eg_C=new Array(k);
    eg_D=new Array(k);
  }

  copy_(eg_u,x);
  copy_(eg_v,n);
  copyInt_(eg_A,1);
  copyInt_(eg_B,0);
  copyInt_(eg_C,0);
  copyInt_(eg_D,1);
  for (;;) {
    while(!(eg_u[0]&1)) {  //while eg_u is even
      halve_(eg_u);
      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2
        halve_(eg_A);
        halve_(eg_B);      
      } else {
        add_(eg_A,n);  halve_(eg_A);
        sub_(eg_B,x);  halve_(eg_B);
      }
    }

    while (!(eg_v[0]&1)) {  //while eg_v is even
      halve_(eg_v);
      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2
        halve_(eg_C);
        halve_(eg_D);      
      } else {
        add_(eg_C,n);  halve_(eg_C);
        sub_(eg_D,x);  halve_(eg_D);
      }
    }

    if (!greater(eg_v,eg_u)) { //eg_v <= eg_u
      sub_(eg_u,eg_v);
      sub_(eg_A,eg_C);
      sub_(eg_B,eg_D);
    } else {                   //eg_v > eg_u
      sub_(eg_v,eg_u);
      sub_(eg_C,eg_A);
      sub_(eg_D,eg_B);
    }
  
    if (equalsInt(eg_u,0)) {
      if (negative(eg_C)) //make sure answer is nonnegative
        add_(eg_C,n);
      copy_(x,eg_C);

      if (!equalsInt(eg_v,1)) { //if GCD_(x,n)!=1, then there is no inverse
        copyInt_(x,0);
        return 0;
      }
      return 1;
    }
  }
};

//return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
function inverseModInt(x,n) {
  var a=1,b=0,t;
  for (;;) {
    if (x==1) return a;
    if (x==0) return 0;
    b-=a*Math.floor(n/x);
    n%=x;

    if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
    if (n==0) return 0;
    a-=b*Math.floor(x/n);
    x%=n;
  }
}

//this deprecated function is for backward compatibility only. 
function inverseModInt_(x,n) {
   return inverseModInt(x,n);
};


//Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
//     v = GCD_(x,y) = a*x-b*y
//The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
function eGCD_(x,y,v,a,b) {
  var g=0;
  var k=Math.max(x.length,y.length);
  if (eg_u.length!=k) {
    eg_u=new Array(k);
    eg_A=new Array(k);
    eg_B=new Array(k);
    eg_C=new Array(k);
    eg_D=new Array(k);
  }
  while(!(x[0]&1)  && !(y[0]&1)) {  //while x and y both even
    halve_(x);
    halve_(y);
    g++;
  }
  copy_(eg_u,x);
  copy_(v,y);
  copyInt_(eg_A,1);
  copyInt_(eg_B,0);
  copyInt_(eg_C,0);
  copyInt_(eg_D,1);
  for (;;) {
    while(!(eg_u[0]&1)) {  //while u is even
      halve_(eg_u);
      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2
        halve_(eg_A);
        halve_(eg_B);      
      } else {
        add_(eg_A,y);  halve_(eg_A);
        sub_(eg_B,x);  halve_(eg_B);
      }
    }

    while (!(v[0]&1)) {  //while v is even
      halve_(v);
      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2
        halve_(eg_C);
        halve_(eg_D);      
      } else {
        add_(eg_C,y);  halve_(eg_C);
        sub_(eg_D,x);  halve_(eg_D);
      }
    }

    if (!greater(v,eg_u)) { //v<=u
      sub_(eg_u,v);
      sub_(eg_A,eg_C);
      sub_(eg_B,eg_D);
    } else {                //v>u
      sub_(v,eg_u);
      sub_(eg_C,eg_A);
      sub_(eg_D,eg_B);
    }
    if (equalsInt(eg_u,0)) {
      if (negative(eg_C)) {   //make sure a (C)is nonnegative
        add_(eg_C,y);
        sub_(eg_D,x);
      }
      multInt_(eg_D,-1);  ///make sure b (D) is nonnegative
      copy_(a,eg_C);
      copy_(b,eg_D);
      leftShift_(v,g);
      return;
    }
  }
};


//is bigInt x negative?
function negative(x) {
  return ((x[x.length-1]>>(bpe-1))&1);
};


//is (x << (shift*bpe)) > y?
//x and y are nonnegative bigInts
//shift is a nonnegative integer
function greaterShift(x,y,shift) {
  var kx=x.length, ky=y.length;
  k=((kx+shift)<ky) ? (kx+shift) : ky;
  for (i=ky-1-shift; i<kx && i>=0; i++) 
    if (x[i]>0)
      return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
  for (i=kx-1+shift; i<ky; i++)
    if (y[i]>0)
      return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
  for (i=k-1; i>=shift; i--)
    if      (x[i-shift]>y[i]) return 1;
    else if (x[i-shift]<y[i]) return 0;
  return 0;
};

//is x > y? (x and y both nonnegative)
function greater(x,y) {
  var i;
  var k=(x.length<y.length) ? x.length : y.length;

  for (i=x.length;i<y.length;i++)
    if (y[i])
      return 0;  //y has more digits

  for (i=y.length;i<x.length;i++)
    if (x[i])
      return 1;  //x has more digits

  for (i=k-1;i>=0;i--)
    if (x[i]>y[i])
      return 1;
    else if (x[i]<y[i])
      return 0;
  return 0;
};

//divide x by y giving quotient q and remainder r.  (q=floor(x/y),  r=x mod y).  All 4 are bigints.
//x must have at least one leading zero element.
//y must be nonzero.
//q and r must be arrays that are exactly the same length as x. (Or q can have more).
//Must have x.length >= y.length >= 2.
function divide_(x,y,q,r) {
  var kx, ky;
  var i,j,y1,y2,c,a,b;
  copy_(r,x);
  for (ky=y.length;y[ky-1]==0;ky--); //ky is number of elements in y, not including leading zeros

  //normalize: ensure the most significant element of y has its highest bit set  
  b=y[ky-1];
  for (a=0; b; a++)
    b>>=1;  
  a=bpe-a;  //a is how many bits to shift so that the high order bit of y is leftmost in its array element
  leftShift_(y,a);  //multiply both by 1<<a now, then divide both by that at the end
  leftShift_(r,a);

  //Rob Visser discovered a bug: the following line was originally just before the normalization.
  for (kx=r.length;r[kx-1]==0 && kx>ky;kx--); //kx is number of elements in normalized x, not including leading zeros

  copyInt_(q,0);                      // q=0
  while (!greaterShift(y,r,kx-ky)) {  // while (leftShift_(y,kx-ky) <= r) {
    subShift_(r,y,kx-ky);             //   r=r-leftShift_(y,kx-ky)
    q[kx-ky]++;                       //   q[kx-ky]++;
  }                                   // }

  for (i=kx-1; i>=ky; i--) {
    if (r[i]==y[ky-1])
      q[i-ky]=mask;
    else
      q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]);	

    //The following for(;;) loop is equivalent to the commented while loop, 
    //except that the uncommented version avoids overflow.
    //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
    //  while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
    //    q[i-ky]--;    
    for (;;) {
      y2=(ky>1 ? y[ky-2] : 0)*q[i-ky];
      c=y2>>bpe;
      y2=y2 & mask;
      y1=c+q[i-ky]*y[ky-1];
      c=y1>>bpe;
      y1=y1 & mask;

      if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i]) 
        q[i-ky]--;
      else
        break;
    }

    linCombShift_(r,y,-q[i-ky],i-ky);    //r=r-q[i-ky]*leftShift_(y,i-ky)
    if (negative(r)) {
      addShift_(r,y,i-ky);         //r=r+leftShift_(y,i-ky)
      q[i-ky]--;
    }
  }

  rightShift_(y,a);  //undo the normalization step
  rightShift_(r,a);  //undo the normalization step
};

//do carries and borrows so each element of the bigInt x fits in bpe bits.
function carry_(x) {
  var i,k,c,b;
  k=x.length;
  c=0;
  for (i=0;i<k;i++) {
    c+=x[i];
    b=0;
    if (c<0) {
      b=-(c>>bpe);
      c+=b*radix;
    }
    x[i]=c & mask;
    c=(c>>bpe)-b;
  }
};

//return x mod n for bigInt x and integer n.
function modInt(x,n) {
  var i,c=0;
  for (i=x.length-1; i>=0; i--)
    c=(c*radix+x[i])%n;
  return c;
};

//convert the integer t into a bigInt with at least the given number of bits.
//the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
//Pad the array with leading zeros so that it has at least minSize elements.
//There will always be at least one leading 0 element.
function int2bigInt(t,bits,minSize) {   
  var i,k;
  k=Math.ceil(bits/bpe)+1;
  k=minSize>k ? minSize : k;
  buff=new Array(k);
  copyInt_(buff,t);
  return buff;
};

//return the bigInt given a string representation in a given base.  
//Pad the array with leading zeros so that it has at least minSize elements.
//If base=-1, then it reads in a space-separated list of array elements in decimal.
//The array will always have at least one leading zero, unless base=-1.
function str2bigInt(s,base,minSize) {
  var d, i, j, x, y, kk;
  var k=s.length;
  if (base==-1) { //comma-separated list of array elements in decimal
    x=new Array(0);
    for (;;) {
      y=new Array(x.length+1);
      for (i=0;i<x.length;i++)
        y[i+1]=x[i];
      y[0]=parseInt(s,10);
      x=y;
      d=s.indexOf(',',0);
      if (d<1) 
        break;
      s=s.substring(d+1);
      if (s.length==0)
        break;
    }
    if (x.length<minSize) {
      y=new Array(minSize);
      copy_(y,x);
      return y;
    }
    return x;
  }

  x=int2bigInt(0,base*k,0);
  for (i=0;i<k;i++) {
    d=digitsStr.indexOf(s.substring(i,i+1),0);
    if (base<=36 && d>=36)  //convert lowercase to uppercase if base<=36
      d-=26;
    if (d<base && d>=0) {   //ignore illegal characters
      multInt_(x,base);
      addInt_(x,d);
    }
  }

  for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros
  k=minSize>k+1 ? minSize : k+1;
  y=new Array(k);
  kk=k<x.length ? k : x.length;
  for (i=0;i<kk;i++)
    y[i]=x[i];
  for (;i<k;i++)
    y[i]=0;
  return y;
}

//is bigint x equal to integer y?
//y must have less than bpe bits
function equalsInt(x,y) {
  var i;
  if (x[0]!=y)
    return 0;
  for (i=1;i<x.length;i++)
    if (x[i])
      return 0;
  return 1;
};

//are bigints x and y equal?
//this works even if x and y are different lengths and have arbitrarily many leading zeros
function equals(x,y) {
  var i;
  var k=x.length<y.length ? x.length : y.length;
  for (i=0;i<k;i++)
    if (x[i]!=y[i])
      return 0;
  if (x.length>y.length) {
    for (;i<x.length;i++)
      if (x[i])
        return 0;
  } else {
    for (;i<y.length;i++)
      if (y[i])
        return 0;
  }
  return 1;
};

//is the bigInt x equal to zero?
function isZero(x) {
  var i;
  for (i=0;i<x.length;i++)
    if (x[i])
      return 0;
  return 1;
};

//convert a bigInt into a string in a given base, from base 2 up to base 95.
//Base -1 prints the contents of the array representing the number.
function bigInt2str(x,base) {
  var i,t,s="";

  if (s6.length!=x.length) 
    s6=dup(x);
  else
    copy_(s6,x);

  if (base==-1) { //return the list of array contents
    for (i=x.length-1;i>0;i--)
      s+=x[i]+',';
    s+=x[0];
  }
  else { //return it in the given base
    while (!isZero(s6)) {
      t=divInt_(s6,base);  //t=s6 % base; s6=floor(s6/base);
      s=digitsStr.substring(t,t+1)+s;
    }
  }
  if (s.length==0)
    s="0";
  return s;
};

//returns a duplicate of bigInt x
function dup(x) {
  var i;
  buff=new Array(x.length);
  copy_(buff,x);
  return buff;
}

//do x=y on bigInts x and y.  x must be an array at least as big as y (not counting the leading zeros in y).
function copy_(x,y) {
  var i;
  var k=x.length<y.length ? x.length : y.length;
  for (i=0;i<k;i++)
    x[i]=y[i];
  for (i=k;i<x.length;i++)
    x[i]=0;
};

//do x=y on bigInt x and integer y.  
function copyInt_(x,n) {
  var i,c;
  for (c=n,i=0;i<x.length;i++) {
    x[i]=c & mask;
    c>>=bpe;
  }
}

//do x=x+n where x is a bigInt and n is an integer.
//x must be large enough to hold the result.
function addInt_(x,n) {
  var i,k,c,b;
  x[0]+=n;
  k=x.length;
  c=0;
  for (i=0;i<k;i++) {
    c+=x[i];
    b=0;
    if (c<0) {
      b=-(c>>bpe);
      c+=b*radix;
    }
    x[i]=c & mask;
    c=(c>>bpe)-b;
    if (!c) return; //stop carrying as soon as the carry_ is zero
  }
};

//right shift bigInt x by n bits.  0 <= n < bpe.
function rightShift_(x,n) {
  var i;
  var k=Math.floor(n/bpe);
  if (k) {
    for (i=0;i<x.length-k;i++) //right shift x by k elements
      x[i]=x[i+k];
    for (;i<x.length;i++)
      x[i]=0;
    n%=bpe;
  }
  for (i=0;i<x.length-1;i++) {
    x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n));
  }
  x[i]>>=n;
};

//do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
function halve_(x) {
  var i;
  for (i=0;i<x.length-1;i++) {
    x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1));
  }
  x[i]=(x[i]>>1) | (x[i] & (radix>>1));  //most significant bit stays the same
};

//left shift bigInt x by n bits.
function leftShift_(x,n) {
  var i;
  var k=Math.floor(n/bpe);
  if (k) {
    for (i=x.length; i>=k; i--) //left shift x by k elements
      x[i]=x[i-k];
    for (;i>=0;i--)
      x[i]=0;  
    n%=bpe;
  }
  if (!n)
    return;
  for (i=x.length-1;i>0;i--) {
    x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));
  }
  x[i]=mask & (x[i]<<n);
};

//do x=x*n where x is a bigInt and n is an integer.
//x must be large enough to hold the result.
function multInt_(x,n) {
  var i,k,c,b;
  if (!n)
    return;
  k=x.length;
  c=0;
  for (i=0;i<k;i++) {
    c+=x[i]*n;
    b=0;
    if (c<0) {
      b=-(c>>bpe);
      c+=b*radix;
    }
    x[i]=c & mask;
    c=(c>>bpe)-b;
  }
};

//do x=floor(x/n) for bigInt x and integer n, and return the remainder
function divInt_(x,n) {
  var i,r=0,s;
  for (i=x.length-1;i>=0;i--) {
    s=r*radix+x[i];
    x[i]=Math.floor(s/n);
    r=s%n;
  }
  return r;
};

//do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
//x must be large enough to hold the answer.
function linComb_(x,y,a,b) {
  var i,c,k,kk;
  k=x.length<y.length ? x.length : y.length;
  kk=x.length;
  for (c=0,i=0;i<k;i++) {
    c+=a*x[i]+b*y[i];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k;i<kk;i++) {
    c+=a*x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
};

//do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
//x must be large enough to hold the answer.
function linCombShift_(x,y,b,ys) {
  var i,c,k,kk;
  k=x.length<ys+y.length ? x.length : ys+y.length;
  kk=x.length;
  for (c=0,i=ys;i<k;i++) {
    c+=x[i]+b*y[i-ys];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k;c && i<kk;i++) {
    c+=x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
};

//do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
//x must be large enough to hold the answer.
function addShift_(x,y,ys) {
  var i,c,k,kk;
  k=x.length<ys+y.length ? x.length : ys+y.length;
  kk=x.length;
  for (c=0,i=ys;i<k;i++) {
    c+=x[i]+y[i-ys];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k;c && i<kk;i++) {
    c+=x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
};

//do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
//x must be large enough to hold the answer.
function subShift_(x,y,ys) {
  var i,c,k,kk;
  k=x.length<ys+y.length ? x.length : ys+y.length;
  kk=x.length;
  for (c=0,i=ys;i<k;i++) {
    c+=x[i]-y[i-ys];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k;c && i<kk;i++) {
    c+=x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
};

//do x=x-y for bigInts x and y.
//x must be large enough to hold the answer.
//negative answers will be 2s complement
function sub_(x,y) {
  var i,c,k,kk;
  k=x.length<y.length ? x.length : y.length;
  for (c=0,i=0;i<k;i++) {
    c+=x[i]-y[i];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k;c && i<x.length;i++) {
    c+=x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
};

//do x=x+y for bigInts x and y.
//x must be large enough to hold the answer.
function add_(x,y) {
  var i,c,k,kk;
  k=x.length<y.length ? x.length : y.length;
  for (c=0,i=0;i<k;i++) {
    c+=x[i]+y[i];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k;c && i<x.length;i++) {
    c+=x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
};

//do x=x*y for bigInts x and y.  This is faster when y<x.
function mult_(x,y) {
  var i;
  if (ss.length!=2*x.length)
    ss=new Array(2*x.length);
  copyInt_(ss,0);
  for (i=0;i<y.length;i++)
    if (y[i])
      linCombShift_(ss,x,y[i],i);   //ss=1*ss+y[i]*(x<<(i*bpe))
  copy_(x,ss);
};

//do x=x mod n for bigInts x and n.
function mod_(x,n) {
  if (s4.length!=x.length)
    s4=dup(x);
  else
    copy_(s4,x);
  if (s5.length!=x.length)
    s5=dup(x);  
  divide_(s4,n,s5,x);  //x = remainder of s4 / n
};

//do x=x*y mod n for bigInts x,y,n.
//for greater speed, let y<x.
function multMod_(x,y,n) {
  var i;
  if (s0.length!=2*x.length)
    s0=new Array(2*x.length);
  copyInt_(s0,0);
  for (i=0;i<y.length;i++)
    if (y[i])
      linCombShift_(s0,x,y[i],i);   //s0=1*s0+y[i]*(x<<(i*bpe))
  mod_(s0,n);
  copy_(x,s0);
};

//do x=x*x mod n for bigInts x,n.
function squareMod_(x,n) {
  var i,j,d,c,kx,kn,k;
  for (kx=x.length; kx>0 && !x[kx-1]; kx--);  //ignore leading zeros in x
  k=kx>n.length ? 2*kx : 2*n.length; //k=# elements in the product, which is twice the elements in the larger of x and n
  if (s0.length!=k) 
    s0=new Array(k);
  copyInt_(s0,0);
  for (i=0;i<kx;i++) {
    c=s0[2*i]+x[i]*x[i];
    s0[2*i]=c & mask;
    c>>=bpe;
    for (j=i+1;j<kx;j++) {
      c=s0[i+j]+2*x[i]*x[j]+c;
      s0[i+j]=(c & mask);
      c>>=bpe;
    }
    s0[i+kx]=c;
  }
  mod_(s0,n);
  copy_(x,s0);
};

//return x with exactly k leading zero elements
function trim(x,k) {
  var i,y;
  for (i=x.length; i>0 && !x[i-1]; i--);
  y=new Array(i+k);
  copy_(y,x);
  return y;
};

//do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation.  0**0=1.
//this is faster when n is odd.  x usually needs to have as many elements as n.
function powMod_(x,y,n) {
  var k1,k2,kn,np;
  if(s7.length!=n.length)
    s7=dup(n);

  //for even modulus, use a simple square-and-multiply algorithm,
  //rather than using the more complex Montgomery algorithm.
  if ((n[0]&1)==0) {
    copy_(s7,x);
    copyInt_(x,1);
    while(!equalsInt(y,0)) {
      if (y[0]&1)
        multMod_(x,s7,n);
      divInt_(y,2);
      squareMod_(s7,n); 
    }
    return;
  }

  //calculate np from n for the Montgomery multiplications
  copyInt_(s7,0);
  for (kn=n.length;kn>0 && !n[kn-1];kn--);
  np=radix-inverseModInt(modInt(n,radix),radix);
  s7[kn]=1;
  multMod_(x ,s7,n);   // x = x * 2**(kn*bp) mod n

  if (s3.length!=x.length)
    s3=dup(x);
  else
    copy_(s3,x);

  for (k1=y.length-1;k1>0 & !y[k1]; k1--);  //k1=first nonzero element of y
  if (y[k1]==0) {  //anything to the 0th power is 1
    copyInt_(x,1);
    return;
  }
  for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1);  //k2=position of first 1 bit in y[k1]
  for (;;) {
    if (!(k2>>=1)) {  //look at next bit of y
      k1--;
      if (k1<0) {
        mont_(x,one,n,np);
        return;
      }
      k2=1<<(bpe-1);
    }    
    mont_(x,x,n,np);

    if (k2 & y[k1]) //if next bit is a 1
      mont_(x,s3,n,np);
  }
};

//do x=x*y*Ri mod n for bigInts x,y,n, 
//  where Ri = 2**(-kn*bpe) mod n, and kn is the 
//  number of elements in the n array, not 
//  counting leading zeros.  
//x must be large enough to hold the answer.
//It's OK if x and y are the same variable.
//must have:
//  x,y < n
//  n is odd
//  np = -(n^(-1)) mod radix
function mont_(x,y,n,np) {
  var i,j,c,ui,t;
  var kn=n.length;
  var ky=y.length;

  if (sa.length!=kn)
    sa=new Array(kn);

  for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
  //this function sometimes gives wrong answers when the next line is uncommented
  //for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y

  copyInt_(sa,0);

  //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large keys
  for (i=0; i<kn; i++) {
    t=sa[0]+x[i]*y[0];
    ui=((t & mask) * np) & mask;  //the inner "& mask" is needed on Macintosh MSIE, but not windows MSIE
    c=(t+ui*n[0]) >> bpe;
    t=x[i];

    //do sa=(sa+x[i]*y+ui*n)/b   where b=2**bpe
    for (j=1;j<ky;j++) { 
      c+=sa[j]+t*y[j]+ui*n[j];
      sa[j-1]=c & mask;
      c>>=bpe;
    }    
    for (;j<kn;j++) { 
      c+=sa[j]+ui*n[j];
      sa[j-1]=c & mask;
      c>>=bpe;
    }    
    sa[j-1]=c & mask;
  }

  if (!greater(n,sa))
    sub_(sa,n);
  copy_(x,sa);
};
;function generateNonce(c) {
    var f = new Array(c);
    var e = Math.floor(Math.random() * 18446744073709552000);
    var d = Math.floor(e / 4294967296);
    var a = e % 4294967296;
    for (var b = 0; b < 4; b++) {
        f[b] = (d >>> b * 8) & 255
    }
    for (var b = 0; b < 4; b++) {
        f[b + 4] = (a >>> b * 8) & 255
    }
    return f
};
function Cipher(e, a) {
    var d = 4;
    var h = a.length / d - 1;
    var g = [[], [], [], []];
    for (var f = 0; f < 4 * d; f++) {
        g[f % 4][Math.floor(f / 4)] = e[f]
    }
    g = AddRoundKey(g, a, 0, d);
    for (var c = 1; c < h; c++) {
        g = SubBytes(g, d);
        g = ShiftRows(g, d);
        g = MixColumns(g, d);
        g = AddRoundKey(g, a, c, d)
    }
    g = SubBytes(g, d);
    g = ShiftRows(g, d);
    g = AddRoundKey(g, a, h, d);
    var b = new Array(4 * d);
    for (var f = 0; f < 4 * d; f++) {
        b[f] = g[f % 4][Math.floor(f / 4)]
    }
    return b
};
function SubBytes(b, a) {
    for (var d = 0; d < 4; d++) {
        for (var e = 0; e < a; e++) {
            b[d][e] = Sbox[b[d][e]]
        }
    }
    return b
};
function ShiftRows(d, a) {
    var b = new Array(4);
    for (var e = 1; e < 4; e++) {
        for (var f = 0; f < 4; f++) {
            b[f] = d[e][(f + e) % a]
        }
        for (var f = 0; f < 4; f++) {
            d[e][f] = b[f]
        }
    }
    return d
};
function MixColumns(h, f) {
    for (var j = 0; j < 4; j++) {
        var e = new Array(4);
        var d = new Array(4);
        for (var g = 0; g < 4; g++) {
            e[g] = h[g][j];
            d[g] = h[g][j] & 128 ? h[g][j] << 1 ^ 283 : h[g][j] << 1
        }
        h[0][j] = d[0] ^ e[1] ^ d[1] ^ e[2] ^ e[3];
        h[1][j] = e[0] ^ d[1] ^ e[2] ^ d[2] ^ e[3];
        h[2][j] = e[0] ^ e[1] ^ d[2] ^ e[3] ^ d[3];
        h[3][j] = e[0] ^ d[0] ^ e[1] ^ e[2] ^ d[3]
    }
    return h
};
function AddRoundKey(f, a, d, b) {
    for (var e = 0; e < 4; e++) {
        for (var g = 0; g < b; g++) {
            f[e][g] ^= a[d * 4 + g][e]
        }
    }
    return f
};
function KeyExpansion(f) {
    var d = 4;
    var b = f.length / 4;
    var g = b + 6;
    var e = new Array(d * (g + 1));
    var h = new Array(4);
    for (var c = 0; c < b; c++) {
        var a = [f[4 * c], f[4 * c + 1], f[4 * c + 2], f[4 * c + 3]];
        e[c] = a
    }
    for (var c = b; c < (d * (g + 1)); c++) {
        e[c] = new Array(4);
        for (var j = 0; j < 4; j++) {
            h[j] = e[c - 1][j]
        }
        if (c % b == 0) {
            h = SubWord(RotWord(h));
            for (var j = 0; j < 4; j++) {
                h[j] ^= Rcon[c / b][j]
            }
        } else {
            if (b > 6 && c % b == 4) {
                h = SubWord(h)
            }
        }
        for (var j = 0; j < 4; j++) {
            e[c][j] = e[c - b][j] ^ h[j]
        }
    }
    return e
};
function SubWord(a) {
    for (var b = 0; b < 4; b++) {
        a[b] = Sbox[a[b]]
    }
    return a
};
function RotWord(a) {
    var c = a[0];
    for (var b = 0; b < 3; b++) {
        a[b] = a[b + 1]
    }
    a[3] = c;
    return a
};
var Sbox = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22];
var Rcon = [[0, 0, 0, 0], [1, 0, 0, 0], [2, 0, 0, 0], [4, 0, 0, 0], [8, 0, 0, 0], [16, 0, 0, 0], [32, 0, 0, 0], [64, 0, 0, 0], [128, 0, 0, 0], [27, 0, 0, 0], [54, 0, 0, 0]];
function AESEncryptCtr(d, u, q) {
    var o = 16;
    if (! (q == 128 || q == 192 || q == 256)) {
        return ""
    }
    d = d.encodeUTF8();
    var e = 8;
    var j = generateNonce(o);
    var a = String.fromCharCode(e + 8);
    for (var l = 0; l < e; l++) {
        a += String.fromCharCode(j[l])
    }
    for (var l = 0; l < 8; l++) {
        a += String.fromCharCode(0)
    }
    var f = KeyExpansion(u);
    var v = Math.ceil(d.length / o);
    var n = new Array(v);
    for (var r = 0; r < v; r++) {
        for (var p = 0; p < 4; p++) {
            j[15 - p] = (r >>> p * 8) & 255
        }
        for (var p = 0; p < 4; p++) {
            j[15 - p - 4] = (r / 4294967296 >>> p * 8)
        }
        var m = Cipher(j, f);
        var h = r < v - 1 ? o: (d.length - 1) % o + 1;
        var s = new Array(h);
        for (var l = 0; l < h; l++) {
            s[l] = m[l] ^ d.charCodeAt(r * o + l);
            s[l] = String.fromCharCode(s[l])
        }
        n[r] = s.join("")
    }
    var g = a + n.join("");
    g = g.encodeBase64();
    return g
};
function AESGetKey(a, d) {
    if (! (d == 128 || d == 192 || d == 256)) {
        return ""
    }
    a = a.encodeUTF8();
    var f = d / 8;
    var e = new Array(f);
    for (var c = 0; c < f; c++) {
        e[c] = isNaN(a.charCodeAt(c)) ? 0 : a.charCodeAt(c)
    }
    var b = Cipher(e, KeyExpansion(e));
    b = b.concat(b.slice(0, f - 16));
    return b
};
function AESBigKey(e, d) {
    if (! (d == 128 || d == 192 || d == 256)) {
        return ""
    }
    var g = d / 8;
    var c = new Array(g);
    var f = bigInt2str(e, 16);
    for (var b = Math.ceil(f.length / 2); b > 0; b--) {
        var a = f.substring(f.length - 2, f.length);
        c[b - 1] = parseInt(a, 16);
        f = f.substring(0, f.length - 2)
    }
    if (e.length > g) {
        c = c.slice(0, g - 1)
    } else {
        if (e.length < g) {
            for (b = e.length; b < g; b++) {
                c[b] = 0
            }
        }
    }
    var f = "";
    for (b = 0; b < c.length; b++) {
        f += c[b] + ", "
    }
    return c
};
;/**
 * Spil Games Profilar - jQuery plugin
 * @author: Rafał Jońca
 * @requires: jQuery Cookie Plugin
 * @requires: Base64 library
 * @requires: BigInt library
 * @requires: AES library
 * @requires: opensocial-jquery loaded as jQueryOS
 *
 * TODO: try to refactor similar callback fragments
 */
jQuery.profilar = (function($){
        var DHExchange = (function() {
            var _that = {};
            var sieveSize = 4000;
            var sieve0 = ( - 1 * sieveSize);
            var sieve = [];
            var lastPrime = 0;
            var primes;
            var Primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021];
            var _p=0, _q=0, _c=0, _z=0, _d=0, sharedKey=0;
            var forUser = '';

            _that.reset = function() {
            _p=0; _q=0; _c=0; _z=0; _d=0; sharedKey=0; forUser='';
            };

            var nextPrime = function(c) {
            var d;
            if (c == Primes[lastPrime] && lastPrime < Primes.length - 1) {
            return Primes[++lastPrime];
            }
            if (c < Primes[Primes.length - 1]) {
                for (d = Primes.length - 2; d > 0; d--) {
                    if (Primes[d] <= c) {
                        lastPrime = d + 1;
                        return Primes[d + 1];
                    }
                }
            }
            var b, a;
            c++;
            if ((c & 1) == 0) {
                c++;
            }
            for (;;) {
                if (c - sieve0 > sieveSize || c < sieve0) {
                    for (d = sieveSize - 1; d >= 0; d--) {
                        sieve[d] = 0;
                    }
                    sieve0 = c;
                    primes = Primes.concat();
                }
                if (sieve[c - sieve0] == 0) {
                    for (d = 0; d < primes.length; d++) {
                        if ((b = primes[d]) && c % b == 0) {
                            for (a = c - sieve0; a < sieveSize; a += b) {
                                sieve[a] = b;
                            }
                            c += 2;
                            primes[d] = 0;
                            break;
                        }
                    }
                    if (d >= primes.length) {
                        return c;
                    }
                } else {
                    c += 2;
                }
            }
            };

            var generatePrime = function() {
                var prime = 0;
                do {
                    prime = nextPrime(Math.floor(Math.random() * 1000000));
                } while (prime < 16385);
                return int2bigInt(prime, 128, 2);
            };

            _that.initialized = function(user) {
                return sharedKey != 0 && forUser == user;
            };

            _that.initKey = function() {
                _that.reset();
                _p = generatePrime();
                _q = generatePrime();
                _c = generatePrime();
                _d = powMod(_p, _c, _q);
                return {p: bigInt2str(_p, 10), q: bigInt2str(_q, 10), d: bigInt2str(_d, 10)};
            };

            _that.generateSharedKey = function(z) {
                _z = str2bigInt(z, -1, 8 * bpe);
                sharedKey = powMod(_z, _c, _q);
            };

            _that.encryptMessage = function(text) {
                return AESEncryptCtr(new String(text), AESBigKey(sharedKey, 128), 128);
            };

            return _that;
        })();

        // -------------------

        var RW_FIELDS = ['gender', 'givenname', 'surname', 'streetaddress', 'postcode', 'city', 'state', 'country', 'dob', 'email', 'language', 'fbc_id', 'gfc_id', 'parentemail'];
        var RO_FIELDS = RW_FIELDS.concat(['ip', 'siteid', 'channel', 'username', 'regdate', 'lastlogin', 'age', 'activated', 'deleted', 'banned']);
        var WR_FIELDS = RW_FIELDS.concat(['password']);
        var RO_PUB_FIELDS = ['username', 'channel', 'siteid', 'gender', 'city', 'state', 'country', 'age', 'language', 'regdate', 'lastlogin'];

        var RW_PREFS = ['avatar', 'privacy', 'mygames', 'myrecent'];

        var that = this;
        var settings = {
url: '/pr/pb/1/', // URL to proxied
     cookieName: '_profilar', // cookie to store login|authkey|rememeberme
     cookieLevel: '_SPI_level', // used only when removing all cookies
     cookieDomain: null, // eg. .a10.com
     cookieExpire: 30, // in days
     sessionCookie: '_profilarS', // session cookie (cache)
     sessionCookieExpire: 10, // session cookie expire time (null or time in minutes)
     autoLogin: false, // if to use remember me by default
     asyncTimeout: 5000, // default timeout
     session_cache: [], // array with cached profilar data
     prefs_cache: [], // array with cached profilar user preferences
     siteId: null,
     channelId: null,
     fbcApiKey: null, // public API key from Facebook
     gfcApiKey: null, // public API key from Google Friend Connect (Consumer Key)
     prefsLevel: 'site', // possible values: global, channel, site
     debug: false // set to true to see unencrypted messages in FireBug
        };

        var userData = {};
        var userPref = {};
        var userName = '';
        var provider = '';
        var authKey = '';
        var initHandlers = [], loginHandlers = [];

        var escapeForXML = function(string) {
            return $('<div/>').text(string).html();
        };

        // Helper for packaging strings in XML.
        var packagetoXml = function(data) {
            return '<?xml version="1.0" encoding="UTF-8"?><profilar>' + data + "</profilar>";
        };

        // Helper for sending and retrieving data as XML.
        var ajaxPost = function(data, success, error, async) {
            if (async == undefined) {
                async = true;
            }

            $.ajax({
type: 'POST',
async: async,
global: false,
timeout: settings.asyncTimeout,
dataType: 'xml',
url: settings.url,
contentType: "text/xml;charset=UTF-8",
data: packagetoXml(data),
success: success,
error: error
});
};

// Converts error info from XML to JavaScript object.
var convertError = function(errorObj) {
    var fields = errorObj.find('*'), ret = {};
    for (var i=0; i<fields.length; ++i) {
        if (fields[i].tagName.toLowerCase() == 'suggestions') {
            ret[fields[i].tagName.toLowerCase()] = [];
            $('username', fields[i]).each(function() { ret[fields[i].tagName.toLowerCase()].push($(this).text()); });
        } else {
            ret[fields[i].tagName.toLowerCase()] = $(fields[i]).text();
        }
    }
    return ret;
};

// Returns XML for getting preferences on selected level or on default level, if no selection made.
var getPrefLevelXml = function(level) {
    level = level !== undefined? level : settings.prefsLevel;
    if (level == 'global') return '';
    if (level == 'channel') return "<channel>" + settings.channelId + "</channel>";
    if (level == 'site') return "<siteid>" + settings.siteId + "</siteid><channel>" + settings.channelId + "</channel>";
    throw new Error("Not valid preference access level");
};

// Returns user id for Facebook Connect (without signature checking) or null if not exists.
that.getFbcUserId = function() {
    return $.cookie(settings.fbcApiKey + '_user');
};

// Returns true, if Google Friend Connect cookie for this site exists.
that.isGfcAuthorized = function() {
    return $.cookie('fcauth' + settings.gfcApiKey) ? true : false;
};

// Returns user id for Google Friend Connect or null if not exists.
// Because of possible Ajax call value is returned to callback.
// CAUTION: requires separate setup of jqueryOS values, but this normally will be done anyway for Sign In etc.
that.getGfcUserId = function(callback) {
    var gfcHash = $.cookie('fcauth' + settings.gfcApiKey);
    if (gfcHash) {
        $.ajax({
url: '/people/@viewer/@self',
dataType: 'data',
success: function(data) {
callback.call(this, data[0].id);
},
error: function() {
callback.call(this, null);
}
});
} else {
    callback.call(this, null);
}
};

// Sets one of user data values or if only first parameter set, the whole user data object.
that.set = function(key, value) {
    if (value === undefined) {
        userData = key;
    } else {
        userData[key] = value;
    }
};

// Gets the whole user data object or only an selected value (if it is not set, will return empty string).
that.get = function(key) {
    if (key == 'username') return userName;
    return key !== undefined ? (userData[key] === undefined ? '' : userData[key]): userData;
};

// Sets one of user preferences or if only first parameter set, the whole user preferences object.
that.setPref = function(key, value) {
    if (value === undefined) {
        userPref = key;
    } else {
        userPref[key] = value;
    }
};

// Gets the whole user preferences object or only an selected preference (if it is not set, will return empty string).
that.getPref = function(key) {
    return key !== undefined ? (userPref[key] === undefined ? '' : userPref[key]): userPref;
};

var createProfilarCookie = function() {
    var tmp = [userName.encodeBase64(true), authKey, that.autoLogin()?'1':'0'];
    if (provider != '') {
        tmp.push(provider);
    }
    if (settings.debug && window.console !== undefined) console.log(tmp);
    $.cookie(settings.cookieName, tmp.join('|').encodeBase64(), {path: '/', expires: that.autoLogin()?settings.cookieExpire:null, domain: settings.cookieDomain});
};

// If user is authenitcated and profilar sends new hash, update cookie and internal code to use new one (for signed hashes).
var updateHashIfNeeded = function(data) {
    if (!authKey) return; // if not logged in do nothing
    var newAuthKey = $('authenticate', data).text();
    if (newAuthKey && newAuthKey != authKey) { // if hash changed, update...
        authKey = newAuthKey;
        createProfilarCookie();
    }
};

// Send XML message without encryption to profilar and calls callback with data and eventual error on return.
that.customMessage = function(msg, callback, async) {
    ajaxPost(msg,
            function(data) { // called on success
            updateHashIfNeeded(data);
            var errors = [];
            $('error', data).each(function() {
                errors.push(convertError($(this)));
                });
            if (errors.length > 0) {
            callback.call(this, data, errors);
            } else {
            callback.call(this, data, null);
            }
            },
            function() { // called on error
            callback.call(this, null, [{code:'500'}]);
            },
            async
            );
};

// Send XML message with encryption to profilar and calls callback with data and eventual error on return.
// If user is not logged in, you have to provide username to get secure communication.
// The key exchange won't be done if it was done for that user already.
that.customSafeMessage = function(msg, callback, _userName) {
    _userName = _userName ? _userName : userName;
    if (settings.debug && window.console !== undefined) console.log(msg);

    var _fun = function() {
        that.customMessage('<username>' + escapeForXML(_userName) + "</username><ciphertext>" + DHExchange.encryptMessage(packagetoXml(msg)) + "</ciphertext>", callback);
    };

    if (!DHExchange.initialized(_userName)) {
        // Key Exchange step
        var keys = DHExchange.initKey(), z=0;
        ajaxPost('<keyexchange><username>' + escapeForXML(_userName) + "</username><p>" + keys.p + "</p><q>" + keys.q + "</q><d>" + keys.d + '</d></keyexchange>',
                function(data) {
                var z = $('z', data).text();
                if (z) {
                DHExchange.generateSharedKey(z);
                _fun();
                } else {
                callback.call(this, null, [{code:'500'}]);
                }
                },
                function() {
                callback.call(this, null, [{code:'500'}]);
                }
                );
    } else {
        _fun();
    }
};

var createSessionCookie = function() {
    var data = [userName.encodeBase64(true)];
    for (var c in settings.session_cache) {
        var tmp = userData[settings.session_cache[c]];
        data.push(tmp ? tmp.encodeBase64(true) : '');
    }
    for (var c in settings.prefs_cache) {
        var tmp = userPref[settings.prefs_cache[c]];
        data.push(tmp ? tmp.encodeBase64(true) : '');
    }

    var expires;
    if (settings.sessionCookieExpire) {
        expires = new Date();
        expires.setTime(expires.getTime()+settings.sessionCookieExpire*60000);
    } else {
        expires = null;
    }

    $.cookie(settings.sessionCookie, data.join('|').encodeBase64(), {path: '/', expires: expires});
};

// Removes from the browser the cookie related to session data.
that.clearSessionCache = function() {
    $.cookie(settings.sessionCookie, null, {path: '/', expires: -1});
};

// Resets all internal data to its initial state (as after init() call) and removes all profilar cookies.
that.clearAll = function() {
    that.clearSessionCache();
    $.cookie(settings.cookieName, null, {path: '/', expires: -1, domain: settings.cookieDomain});
    $.cookie(settings.cookieLevel, null, {path: '/', expires: -1});
    authKey = '';
    userName = '';
    provider = '';
    userData = {};
    userPref = {};
};

var loggedInCheck = function(_userName, _authKey, callback, fromInit) {
    var cookie = $.cookie(settings.sessionCookie);
    if (cookie) {
        try {
            var cookieData = cookie.decodeBase64().split('|');
            var tmpUserName = cookieData.shift().decodeBase64(true);
            if (_userName.toLowerCase() != tmpUserName.toLowerCase()) {
                throw new Error("Usernames do not match");
            }
            userName = _userName;
            authKey = _authKey;
            for (var c in settings.session_cache) {
                if (cookieData[c] != '') {
                    that.set(settings.session_cache[c], cookieData[c].decodeBase64(true));
                }
            }
            for (var c in settings.prefs_cache) {
                if (cookieData[parseInt(c)+settings.session_cache.length] != '') {
                    that.setPref(settings.prefs_cache[c], cookieData[parseInt(c)+settings.session_cache.length].decodeBase64(true));
                }
            }
            if (callback) callback.call(this, that.checkActivation(true));
            if (fromInit === true) {
                runInitHandlers(true);
            } else if (fromInit === false) {
                runLoginHandlers();
            }
            return;
        } catch(e) {
            if (settings.debug && window.console !== undefined) console.log(e);
            // Do nothing -> go to next stage
        }
    }

    var prefsXml = settings.prefs_cache.length?('<'+ settings.prefs_cache.join('/><') +'/>'):'';
    if (prefsXml) {
        prefsXml = '<getprefs>'+getPrefLevelXml()+prefsXml+'</getprefs>';
    }

    // check validity
    ajaxPost(
            '<authenticate><hash>'+_authKey+'</hash></authenticate><request><username/><'+ settings.session_cache.join('/><') +'/></request>' + prefsXml,
            function(data) {
            if ($('request username', data).text().toLowerCase() == _userName.toLowerCase()) {
            userName = _userName;
            authKey = _authKey;
            $('profilar request', data).children().each(
                function() {
                var tag = this.tagName.toLowerCase();
                if (tag != 'username') {
                that.set(tag, $(this).text());
                }
                }
                );
            $('profilar getprefs', data).children().each(
                function() {
                var tag = this.tagName.toLowerCase();
                if (tag != 'username') {
                that.setPref(tag, $(this).text());
                }
                }
                );
            createSessionCookie();
            if (callback) callback.call(this, that.checkActivation(true));
            if (fromInit === true) {
                runInitHandlers(true);
            }
            } else {
                that.clearAll();
                if (callback) callback.call(this, false);
                if (fromInit === true) {
                    runInitHandlers(false);
                }
            }
            },
            function() {
                that.clearAll();
            }
    );
};

// Returns true if user is currently logged in.
// If callback is provided, it once more do the whole login check and initializes session data.
that.loggedIn = function(callback) {
    if (callback) {
        loggedInCheck(userName, authKey, callback);
    } else {
        return that.checkActivation(userName !== '' && authKey !== '');
    }
};

that.realLoggedIn = function() {
    return userName !== '' && authKey !== '';
};

// Without parameter returns current state of remember me functionality.
// With parameter sets the remember me to mentioned state => true lub false.
that.autoLogin = function(enabled) {
    if (enabled === undefined) {
        return settings.autoLogin;
    }
    settings.autoLogin = enabled;
};

// Add function that will be called after init as a callback.
that.addInitHandler = function(callback) {
    initHandlers.push(callback);
};

// Add function that will be called after login (when you logged in after init) as a callback.
that.addLoginHandler = function(callback) {
    loginHandlers.push(callback);
};

var runInitHandlers = function(logged) {
    logged = that.checkActivation(logged);

    for (var i in initHandlers) {
        try {
            initHandlers[i].call(this, logged);
        } catch (e) {
            if (settings.debug) throw e;
        }
    }
};

var runLoginHandlers = function(errors) {
    for (var i in loginHandlers) {
        try {
            loginHandlers[i].call(this, errors);
        } catch (e) {
            if (settings.debug) throw e;
        }
    }
};

// Initializes plugin, if cookies exist, it loads the data from them
// Callback is optional, but should be used in all non trivial cases,
// because function may use asynchronous AJAX call if necessary.
// Callback gets one parameter -> boolean if the user is logged in after init.
that.init = function(options, callback){
    $.extend(settings, options);
    if (settings.siteId == null || settings.channelId == null) {
        throw new Error('You have to set siteId and channelId in the init() call!');
    }

    var cookie = $.cookie(settings.cookieName);
    if (!cookie) {
        that.clearSessionCache(); // for safety remove other cookies if they exist...
        $.cookie(settings.cookieLevel, null, {path: '/', expires: -1}); // for safety remove other cookies if they exist...
        if (callback) callback.call(this, false);
        runInitHandlers(false);
        return; // no cookie, not logged in
    }

    try {
        var cookieData = cookie.decodeBase64().split('|');
        if (cookieData.length == 3 || cookieData.length == 4) {
            that.autoLogin(cookieData[2] === '1');
            if (cookieData.length == 4) {
                provider = cookieData[3];
            } else {
                provider = '';
            }
            loggedInCheck(cookieData[0].decodeBase64(true), cookieData[1], callback, true);
        } else {
            throw new Error('Three or four elements expected!');
        }
    } catch(e) {
        that.clearAll();
        if (callback) callback.call(this, false);
        runInitHandlers(false);
    }
};

// Log in user using secure communication and when everything ok, sets profilar and session cookies.
// Set strict to true, if you want to login only to portal the user registered from.
that.login = function(login, password, autoLogin, callback, strict) {
    if (strict) {
        strictXml = "<siteid>" + settings.siteId + "</siteid><channel>" + settings.channelId + "</channel><strict>1</strict>";
    } else {
        strictXml = '';
    }

    var prefsXml = settings.prefs_cache.length?('<'+ settings.prefs_cache.join('/><') +'/>'):'';
    if (prefsXml) {
        prefsXml = '<getprefs>'+getPrefLevelXml()+prefsXml+'</getprefs>';
    }

    that.customSafeMessage(
            '<authenticate><username>' + escapeForXML(login) + "</username><password>" + escapeForXML(password) + "</password>" + strictXml +"</authenticate><request><" + settings.session_cache.join('/><') +'/></request>'+ prefsXml,
            function(data, errors) {
            if (!errors) {
            authKey = $('authenticate', data).text();
            if (!authKey) {
            if (callback) callback.call(this, [{code: '500'}]);
            runLoginHandlers([{code: '500'}]);
            }
            userName = login;
            that.autoLogin(autoLogin);
            createProfilarCookie();
            $('profilar request', data).children().each(
                function() {
                var tag = this.tagName.toLowerCase();
                if (tag != 'username') {
                that.set(tag, $(this).text());
                }
                }
                );
            $('profilar getprefs', data).children().each(
                function() {
                var tag = this.tagName.toLowerCase();
                if (tag != 'username') {
                that.setPref(tag, $(this).text());
                }
                }
                );
            createSessionCookie();
            if (callback) callback.call(this);
            runLoginHandlers();
            } else {
                if (callback) callback.call(this, errors);
                runLoginHandlers(errors);
            }
            },
            login
                );
};

//Logs in user in the samy way function login(...) does (take a look for reference)
//but takes into account parental confirmation (age limit and activated flag)
//to be more precise: in case of successfull authorization user age and activation status are fetched
//from profilar and then there is a parental check condition applied and in case of failure user gets logged out
that.loginActivated = function(login, password, autoLogin, confirmationAge, callback, strict) {
    that.login(login, password, autoLogin, function(errors) {
            if (errors) {
            callback.call(this, errors);
            return;
            }

            that.load(function(errors) {
                if (errors) {
                that.clearAll();
                callback.call(this, errors);
                return;
                }

                var age = $.profilar.get('age');
                var activated = $.profilar.get('activated');

                if (parseInt(age) <= parseInt(confirmationAge) && !activated) {
                that.clearAll();
                callback.call(this, [{code: '401', message: 'Unauthorized', username: login, operation: 'authenticate', element: 'activated'}]);
                return;
                }

                callback.call(this);
                }, ['age', 'activated']);
    }, strict);
};

that.checkActivation = function(logged) {
    if (logged) {
        var age = that.get('age');
        var activated = that.get('activated');

        if (age === '' || activated === '') {
            that.load(function(errors) {
                    if (errors) {
                    logged = false;
                    }

                    age = $.profilar.get('age');
                    activated = $.profilar.get('activated');

                    if (activated == '') {
                    activated = false;
                    }

                    // Save in cache
                    that.set('age', age);
                    that.set('activated', activated);
                    }, ['age', 'activated'], false);
        }

        if (logged) {
            if (that.needActivation()) {
                logged = false;
            }
        }
    }

    return logged;
};

that.needActivation = function() {
    var maxParentsEmailAge = SPI._settings.myprofile.maxParentsEmailAge;
    var age = that.get('age');
    var activated = that.get('activated');

    if (age === '' || activated === '') {
        return false;
    }

    // FIXME This logic is for backward compatibility. There is a "bug" that causes grown up users are ALWAYS active
    if (parseInt(age) < parseInt(maxParentsEmailAge) && !activated) {
        return true;
    }

    return false;
};

that.needParentsConfirmation = function() {
    var maxParentsEmailAge = SPI._settings.myprofile.maxParentsEmailAge;
    var age = that.get('age');

    if (parseInt(age) < parseInt(maxParentsEmailAge)) {
        return true;
    }

    return false;
};

// Use it only when you are sure that user is not logged in (cookie overwrite!).
// Callback function will get true, if login-hash pair is ok (as in normal login).
that.loginUsingHash = function(login, hash, autoLogin, callback) {
    userName = login;
    authKey = hash;
    that.autoLogin(autoLogin);
    createProfilarCookie();
    loggedInCheck(login, hash, callback, false);
};

that.loginUsingRelaying = function(_provider, autoLogin, callback, strict) {
    if (strict) {
        strictXml = "<siteid>" + settings.siteId + "</siteid><channel>" + settings.channelId + "</channel><strict>1</strict>";
    } else {
        strictXml = '';
    }

    var prefsXml = settings.prefs_cache.length?('<'+ settings.prefs_cache.join('/><') +'/>'):'';
    if (prefsXml) {
        prefsXml = '<getprefs>'+getPrefLevelXml()+prefsXml+'</getprefs>';
    }

    var providerXml;
    if (_provider == 'fbc') {
        providerXml = '<fbc_api_key>' + settings.fbcApiKey + '</fbc_api_key>';
    } else if (_provider == 'gfc') {
        providerXml = '<gfc_api_key>' + settings.gfcApiKey + '</gfc_api_key>';
    } else {
        throw new Error('Unsupported provider!');
    }

    that.customMessage(
            '<authenticate>' + providerXml + strictXml +"</authenticate><request><" + settings.session_cache.join('/><') +'/></request>'+ prefsXml,
            function(data, errors) {
            if (!errors) {
            authKey = $('authenticate', data).text();
            provider = _provider;
            if (!authKey) {
            if (callback) callback.call(this, [{code: '500'}]);
            runLoginHandlers([{code: '500'}]);
            }
            $('profilar request', data).children().each(
                function() {
                var tag = this.tagName.toLowerCase();
                if (tag != 'username') {
                that.set(tag, $(this).text());
                } else {
                userName = $(this).text();
                }
                }
                );
            $('profilar getprefs', data).children().each(
                function() {
                var tag = this.tagName.toLowerCase();
                if (tag != 'username') {
                that.setPref(tag, $(this).text());
                }
                }
                );
            that.autoLogin(autoLogin);
            createProfilarCookie();
            createSessionCookie();
            if (callback) callback.call(this);
            runLoginHandlers();
            } else {
                if (callback) callback.call(this, errors);
                runLoginHandlers(errors);
            }
            }
    );
};

// Checks if username is available. DummyEmail is optional, system will randomly generate one, if not provided.
// Callback will get value true if name is free. If it is taken, it will get array with suggested names.
// If there will be other error, array with errors will be returned.
that.isUsernameAvailable = function(login, callback, dummyEmail) {
    dummyEmail = dummyEmail ? dummyEmail : 'nmvdsjfsjkfh39df'+parseInt(Math.random()*1000000)+'@spilgames.com';
    that.customMessage(
            '<register><simulate>1</simulate><username>' + escapeForXML(login) + "</username><siteid>" + settings.siteId + "</siteid><channel>" + settings.channelId + "</channel><email>" + dummyEmail + "</email></register>",
            function(data, errors) {
            if (!errors) {
            callback.call(this, true);
            } else if (errors[0].code == '409') {
            callback.call(this, errors[0].suggestions);
            } else if (errors[0].code == '406') {
            callback.call(this, []);
            } else {
            callback.call(this, errors);
            }
            }
            );
};

// Checks if email is available. DummyLogin is optional, system will randomly generate one, if not provided.
// Callback will get value true if email is free. If it is taken, it will get false.
// If there will be other error, array with errors will be returned.
that.isEmailAvailable = function(email, callback, dummyLogin) {
    dummyLogin = dummyLogin ? dummyLogin : 'asce'+parseInt(Math.random()*1000000);
    that.customMessage(
            '<register><simulate>1</simulate><username>' + escapeForXML(dummyLogin) + "</username><siteid>" + settings.siteId + "</siteid><channel>" + settings.channelId + "</channel><email>" + email + "</email></register>",
            function(data, errors) {
            if (!errors) {
            callback.call(this, true);
            } else if (errors[0].code == '409' || errors[0].code == '406') {
            callback.call(this, false);
            } else {
            callback.call(this, errors);
            }
            }
            );
};

// Registration function also log in user and set all cookies!
// Registration also may send to the service the profile data if needed (but not preferences).
// Callback will get error array if there is an error or nothing if ok.
// Options:
//   provider - if provider parameter is set, password is not taken into account.
//   notLoginAfterReg - if set to true, will not login user automatically after register
that.register = function(login, password, email, callback, profileData, options) {
    options = options === undefined ? {} : options;
    var encFields = '';
    for (var c in profileData) {
        encFields += "<" + c + ">" + escapeForXML(profileData[c]) + "</" + c + ">";
    }

    var providerXml;
    if (options.provider == 'fbc') {
        providerXml = '<fbc_api_key>' + settings.fbcApiKey + '</fbc_api_key>';
    } else if (options.provider == 'gfc') {
        providerXml = '<gfc_api_key>' + settings.gfcApiKey + '</gfc_api_key>';
    } else {
        providerXml = "<password>" + escapeForXML(password) + "</password>";
    }

    var setPefs = '';
    setPrefs = ((options.privacy === undefined)?'':('<setprefs>'+getPrefLevelXml()+'<privacy>'+options.privacy+'</privacy></setprefs>'));

    var triggerEmails = '';
    var _fun = function(eventId, errors){};

    if(options._ConfirmationEmail) {
        triggerEmails += triggerEvent(options._ConfirmationEmail, _fun, true);
    }

    /*if(options._wait_email) {
      triggerEmails += triggerEvent(options._wait_email, _fun, true);
      }*/

    if(options._email) {
        triggerEmails += triggerEvent(options._email, _fun, true);
    }


    var msg_ = '<register><username>' + escapeForXML(login) + "</username>" + providerXml + "<siteid>" + settings.siteId + "</siteid><channel>" + settings.channelId + "</channel><email>" + escapeForXML(email) + "</email>" + encFields + "</register>"
        + '<authenticate>' + (options.provider?'':('<username>' + escapeForXML(login) + "</username>")) + providerXml + "</authenticate>" + setPrefs + triggerEmails;
    that.customSafeMessage( msg_,
            function(data, errors) {
            if (errors){
            var cnt = 0;
            for (i=0; i > errors.length-1; i++){
            if (errors[i].operation == 'register')
            cnt++;
            }
            }
            if (cnt == 0) {
            _authKey = $('authenticate', data).text();
            if ($('register', data).text() == login && _authKey) {
            if (!options.notLoginAfterReg) {
            authKey = _authKey;
            userName = login;
            provider = options.provider;
            that.autoLogin(false);
            that.set(profileData);
            createProfilarCookie();
            createSessionCookie();
            if (callback) callback.call(this);
            runLoginHandlers();
            } else {
            if (callback) callback.call(this);
            }
            } else { // Below shouldn't happen, because no error was found
                if (callback) callback.call(this, [{code:'500'}]);
                if (!options.notLoginAfterReg) runLoginHandlers([{code:'500'}]);
            }
            } else { // Encountered an error.
                if (callback) callback.call(this, errors);
                if (!options.notLoginAfterReg) runLoginHandlers(errors);
            }
            },
            login
                );
};

// After unregistering the logged in user is also logged out!
// This function does not automatically remove user from subscribing lists.
// If you need, do the unsunscription before the user unregister.
that.unregister = function(login, password, callback) {
    that.customSafeMessage(
            '<deregister><username>' + escapeForXML(login) + "</username><password>" + escapeForXML(password) + "</password></deregister>",
            function(data, errors) {
            if (!errors) {
            if ($('deregister', data).text() == login) {
            that.clearAll();
            DHExchange.reset();
            if (callback) callback.call(this);
            } else {
            if (callback) callback.call(this, errors);
            }
            } else {
            if (callback) callback.call(this, errors);
            }
            },
            login
            );
};

// Sends to service the currently set profile data. Requires repeat of password.
// By default sends all set and writable profile data, but using include (array),
// you can limit sending to only mentioned fields.
// If logging in was using provider, password is not taken into account (may be empty).
that.submit = function(password, callback, include) {
    include = include ? include : WR_FIELDS;

    var encFields = '';
    for (var c in include) {
        var val = that.get(include[c]);
        if (userData[include[c]] === undefined) continue; // If value is not set, do not send it.
        encFields += "<" + include[c] + ">" + escapeForXML(val) + "</" + include[c] + ">";
    }

    var providerXml;
    if (provider == 'fbc') {
        providerXml = '<fbc_api_key>' + settings.fbcApiKey + '</fbc_api_key>';
    } else if (provider == 'gfc') {
        providerXml = '<gfc_api_key>' + settings.gfcApiKey + '</gfc_api_key>';
    } else {
        providerXml = "<password>" + escapeForXML(password) + "</password>";
    }

    that.customSafeMessage(
            '<authenticate><hash>' + authKey + "</hash>" + providerXml + "</authenticate><modify>" + encFields + '</modify>',
            function(data, errors) {
            if (!errors) {
            createSessionCookie();
            if (callback) callback.call(this);
            } else {
            if (callback) callback.call(this, errors);
            }
            }
            );
};

// Sends to service the currently set preference data.
// By default sends all set and writable preferences data, but using include (array),
// you can limit sending to only mentioned fields.
// If you want to save data to different level than default, mention level as third parameter.
that.submitPref = function(callback, include, level) {
    include = include ? include : RW_PREFS;

    var encFields = '';
    for (var c in include) {
        var val = that.getPref(include[c]);
        if (userPref[include[c]] === undefined) continue; // If value is not set, do not send it.
        encFields += "<" + include[c] + ">" + escapeForXML(val) + "</" + include[c] + ">";
    }

    that.customMessage(
            '<authenticate><hash>' + authKey + "</hash></authenticate><setprefs>"+ getPrefLevelXml(level) + encFields + '</setprefs>',
            function(data, errors) {
            if (!errors) {
            createSessionCookie();
            if (callback) callback.call(this);
            } else {
            if (callback) callback.call(this, errors);
            }
            }
            );
};

// Loads profile data (all available). If you want to read only selected fields,
// mention them as second parameter (as array of names).
that.load = function(callback, include, async) {
    include = include ? include : RO_FIELDS;

    that.customMessage(
            '<authenticate><hash>'+authKey+'</hash></authenticate><request><' + include.join('/><') + "/></request>",
            function(data, errors) {
            if (!errors) {
            $('profilar request', data).children().each(
                function() {
                that.set(this.tagName.toLowerCase(), $(this).text());
                }
                );
            if (callback) callback.call(this);
            } else {
            if (callback) callback.call(this, errors);
            }
            },
            async
            );
};

// Loads preferences data (all available). If you want to read only selected fields,
// mention them as second parameter (as array of names).
// If you want to load data from different level as default, mention level as third parameter.
that.loadPref = function(callback, include, level) {
    include = include ? include : RW_PREFS;

    that.customMessage(
            '<authenticate><hash>'+authKey+'</hash></authenticate><getprefs>' + getPrefLevelXml(level) + '<' + include.join('/><') + "/></getprefs>",
            function(data, errors) {
            if (!errors) {
            $('profilar getprefs', data).children().each(
                function() {
                that.setPref(this.tagName.toLowerCase(), $(this).text());
                }
                );
            if (callback) callback.call(this);
            } else {
            if (callback) callback.call(this, errors);
            }
            }
            );
};

// Loads public profile data (all available) for users mentioned as first parameter.
// If you want to read only selected fields, mention them as third parameter (as array of names).
// Callback gets two parameters: data array with profile data objects
// and array with error objects for users that we cannot be read public profile.
// If you want to load data from different level as default, mention level as fourth parameter.
that.loadExternalProfiles = function(usernames, callback, include, level) {
    include = include ? include : RO_PUB_FIELDS;
    var includeXml = '<' + include.join('/><') + "/>";

    var levelXml = getPrefLevelXml(level);

    var requestXml = [];
    for (var u in usernames) {
        requestXml.push('<request>' + levelXml + '<username>' + escapeForXML(usernames[u]) + '</username><' + include.join('/><') + "/></request>");
    }

    that.customMessage(
            requestXml.join(''),
            function(data, errors) {
            var parsedData = [];
            $('profilar request', data).each(function() {
                var tmpData = {};
                $(this).children().each(
                    function() {
                    tmpData[this.tagName.toLowerCase()] = $(this).text();
                    }
                    );
                parsedData.push(tmpData);
                });
            callback.call(this, parsedData, errors);
            }
            );
};

// Loads public preferencres data (all available) for users mentioned as first parameter.
// If you want to read only selected fields, mention them as third parameter (as array of names).
// Callback gets two parameters: data array with preference data objects
// and array with error objects for users that we cannot be read preferences.
// If you want to load data from different level as default, mention level as fourth parameter.
that.loadExternalPrefs = function(usernames, callback, include, level) {
    include = include ? include : RW_PREFS;
    var includeXml = '<' + include.join('/><') + "/>";
    var levelXml = getPrefLevelXml(level);

    var requestXml = [];
    for (var u in usernames) {
        requestXml.push('<getprefs>' + levelXml + '<username>' + escapeForXML(usernames[u]) + '</username><' + include.join('/><') + "/></getprefs>");
    }

    that.customMessage(
            requestXml.join(''),
            function(data, errors) {
            var parsedData = [];
            $('profilar getprefs', data).each(function() {
                var tmpData = {};
                $(this).children().each(
                    function() {
                    tmpData[this.tagName.toLowerCase()] = $(this).text();
                    }
                    );
                parsedData.push(tmpData);
                });
            callback.call(this, parsedData, errors);
            }
            );
};

/**
 * Options:
 * - cheetah_ebm -- object with ids for mailing (sample ids for cheetach: aid, eid)
 * - cheetah_sub -- object with ids for mailing subscription/unsubscribe (sample ids for cheetach: aid, pid, eid)
 * - email -- user email, required if username is not provided (default: current user email if loaded)
 * - userName -- user name, required if email is not provided (default: current user if it is logged in)
 * - safe -- use encrypted communication if set to true, requires setting userName (default: false)
 * - fields -- fields array to sent to the external service if event is using such system (default: empty array)
 * - modify -- field names that may be modified by the follow up for generated event (default: null)
 *
 * Callback:
 * - function called after communication.
 *   If everythig is OK, it gets one argument: generated eventid.
 *   When error occurs, it gets two arguments: null value for event id and errors array.
 *
 */
that.triggerEvent = function(options, callback, returnString) {
    options = $.extend({
cheetah_ebm: {},
cheetah_sub: {},
email: that.get('email'),
userName: userName,
safe: false,
fields: [],
modify: null
}, options);

var encFields = '';
for (var c in options.fields) {
    encFields += "<" + options.fields[c].name + ">" + (options.fields[c].intern ? ('<' + options.fields[c].value + '/>') : escapeForXML(options.fields[c].value)) + "</" + options.fields[c].name + ">";
}

var cheetahSub = '';
for (var c in options.cheetah_sub) {
    cheetahSub += "<" + c + ">" + escapeForXML(options.cheetah_sub[c]) + "</" + c + ">";
}

var cheetahEbm = '';
for (var c in options.cheetah_ebm) {
    cheetahEbm += "<" + c + ">" + escapeForXML(options.cheetah_ebm[c]) + "</" + c + ">";
}

var encModify = '';
if (options.modify) {
    encModify = "<modify><" + options.modify.join("/><") + "/></modify>";
}
returnString = returnString || false;

var _fun = function(data, errors) {
    if (!errors) {
        var eventId = $('trigger', data).text();
        if (callback) {
            if (eventId) {
                callback.call(this, eventId);
            } else {
                callback.call(this, null, [{code:'500'}]);
            }
        }
    } else {
        if (callback) callback.call(this, null, errors);
    }
};

var _msg = '<trigger>';
_msg += options.userName ? ('<username>' + escapeForXML(options.userName) + "</username>") : '';
_msg += options.email ? ("<email>" + escapeForXML(options.email) + "</email>") : '';
_msg += cheetahEbm ? ("<cheetah_ebm>" + cheetahEbm + "</cheetah_ebm>") : '';
_msg += cheetahSub ? ("<cheetah_sub>" + cheetahSub + "</cheetah_sub>") : '';
_msg += encFields ? "<fields>" + encFields +"</fields>" : '';
_msg += encModify + "</trigger>";

if(returnString) {
    return (_msg);
}


if (options.safe) {
    that.customSafeMessage(_msg, _fun, options.userName);
} else {
    that.customMessage(_msg, _fun);
}
};

/**
 * Parameters:
 * - _eventId -- id of event for which the follow up should occur
 * - _userName -- user for which the foolow up occurs, may be empty if user is logged in
 * - callback - optional callback function called when the response come back:
 *   If everythig is OK, it gets one argument: generated eventid.
 *   When error occurs, it gets two arguments: null value for event id and errors array.
 * - _eventKey is required if you want to use follow up to modify some fields, it should contain event key generated when event was triggered
 * - modify -- object with keys and values for fields to modify as a follow up (only fields mentioned in event creation can be set!)
 *
 */
that.eventFollowUp = function(_eventId, _userName, callback, _eventKey, modify) {
    _userName = _userName ? _userName : userName;
    modify = modify === undefined ? {} : modify;

    var encModify = '';
    for (var c in modify) {
        encModify += "<" + c + ">" + escapeForXML(modify[c]) + "</" + c + ">";
    }

    that.customSafeMessage(
            '<followup><username>' + escapeForXML(_userName) + "</username><eventid>" + escapeForXML(_eventId) + "</eventid>" + (_eventKey ? ("<eventkey>" + escapeForXML(_eventKey) + "</eventkey>") : '') + (encModify ? ("<modify>" + encModify +"</modify>") : '') + "</followup>",
            function(data, errors) {
            if (!errors) {
            var eventId = $('followup', data).text();
            if (callback) {
            if (eventId) {
            callback.call(this, eventId);
            } else {
            callback.call(this, null, [{code:'500'}]);
            }
            }
            } else {
            if (callback) callback.call(this, null, errors);
            }
            }, _userName
            );
};

// You can drab username and authKey for usage in other services requiring authenticated user.
that.forService = function() {
    if (that.realLoggedIn()) {
        return {username: userName, hash: authKey};
    } else {
        return {username: '', hash: ''};
    }
};

return that;
})(jQuery);

;var userprofiledebug = 1;

// errors display ----------------------------------------------------------

var __showError = function( errorsObj, pagetype, options ) {

    var options = $.extend(true, {
        errorElement: null,
        isAlert: false,
        callback: null,
        debug: true
    }, options);

    var mesg = '';
    var page = pagetype || null;
    if( page == null ) {
        alert('No pagetype provided!');
        return false;
    }

    if( typeof errorsObj != 'object' ) {
        mesg = errorsObj;
    } else {
        // get only FIRST
        var codeObj = errorsObj[0];
        if( codeObj.code == '500' ) {
        	mesg = SPI._langStrings.userprofile.errorcode_503+'';
        } else {
	        if( !codeObj.element ) { codeObj.element = '__empty'; }  // when no operation defined
	        // HACK:
	        codeObj.operation = codeObj.operation.replace('.','_');
	        // texts declaration:
	        var lstrings = {
	            /*
	            'profilebox': {
	                'authenticate':
	                    'username': {
	                        'code_401': 'Wrong username'
	                    },
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.password_wrong
	                    }
	                }
	            },*/
	            'register': { // page type
	                'register': { // operation
	                    'password': { // element
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    },
	                    'username': {
	                        'code_406': SPI._langStrings.userprofile.validation.username_notacceptable,
	                        'code_409': SPI._langStrings.userprofile.errorcode_409
	                    },
	                    'email': {
	                        'code_409': SPI._langStrings.userprofile.validation.registration_email_exists
	                    }
	                }
	            },
	            'unregister': {
	                'authenticate': {
	                    'username': {
	                        'code_401': SPI._langStrings.userprofile.validation.username_wrong // not used
	                    },
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong // not used
	                    }
	                },
	                'deregister': {
	                    'username': {
	                        'code_401': SPI._langStrings.userprofile.validation.username_wrong // not used
	                    },
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong // not used
	                    }
	                }
	            },
	            'new_password': {
	                'followup': {
	                    '__empty': {
	                        'code_404': SPI._langStrings.userprofile.validation.new_password_reset_passlink_used,
	                        'code_503': SPI._langStrings.userprofile.errorcode_503
	                    }

	                },
	                'followup_modify': {
	                    'password': {
	                        'code_406': SPI._langStrings.userprofile.validation.new_password_password_not_acceptable
	                    }
	                }
	            },
	            'changepass': {
	                'authenticate': {
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong,
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    }
	                },
	                'modify': {
	                    'password': {
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    }
	                }
	            },
	            'forgot_password': {
	                'trigger': {
	                    'email': {
	                        'code_404': SPI._langStrings.userprofile.validation.forgot_password_email_not_exists
	                    }
	                }
	            },
	            'profile': {
	                'authenticate': {
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong,
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    }
	                },
	                'modify': {
                        'email': {
                            'code_409': SPI._langStrings.userprofile.validation.email_exists
                        }
                    }
	            },
	            'emailconfirm': {
	                'followup': {
		                '__empty': { // when no operation defined
		                    'code_404': 'Your email was already confirmed or used url is not valid.',
	                        'code_503': SPI._langStrings.userprofile.errorcode_503
		                }
		            }
	            }
	        };
	        try {
	            mesg = eval('lstrings.'+page+'.'+codeObj.operation+'.'+codeObj.element+'.code_'+codeObj.code);
	        } catch(e) {
	            if( options.debug ) {
	                try {
	                    mesg = 'Undefined error: '+page+'/'+codeObj.operation+'/'+codeObj.element+'/'+codeObj.code;
	                } catch(e){
	                    mesg = 'Undefined!';
	                }
	            }
	        }

	    }

	    // CHANGEPASS (oldpass) HACK

	    if( typeof codeObj == 'object' && page == 'changepass' && codeObj.operation == 'authenticate' && codeObj.element == 'password' ) {
	        codeObj.element = 'old_password';
	    }


    }

    if( mesg != '' ) {
        if( options.isAlert === true ) {
            alert( '' + mesg );
        } else {
            if( options.errorElement != null && options.errorElement.length ) {
                options.errorElement.empty().html('' + mesg).show();
            } else {
                if( codeObj && codeObj.element && $('#'+pagetype+' #f_'+codeObj.element+'_error').length > 0 ) {
                    $('#'+pagetype+' #f_'+codeObj.element+'_error div.errorbox div.content').empty().html('' + mesg+'').show();
                } else {
                    if( $('#'+pagetype+' .validationErrors').length > 0 ) {
                        $('#'+pagetype+' .validationErrors:first').addClass('error').html('' + mesg).show();
                    }
                }
            }
        }
    }

    if( options.callback != null && typeof options.callback == 'function' ) {
        if (page == 'forgot_password' || page == 'new_password') {
            options.callback.call(this, mesg);
        } else if (page == 'register') {
        	options.callback.call(this, codeObj);
        } else {
            options.callback.call(this);
        }
    }

};

// forms switch ------------------------------------------------------------
var showForm = function(formType) {
    switch(formType) {
        default:
        case 'register':
            $("div#register").show();
        break;
        case 'profile':
            $("div#profile-update").show();
        break;
        case 'changepass':
            $("div#pass-change").show();
        break;
    }
};

// age check ---------------------------------------------------------------
var ageCheck = function(birthdate, min_age) {
	var year  = parseInt(birthdate.year);
	var month = parseInt(birthdate.month) - 1;
	var day   = parseInt(birthdate.day);
	var theirDate = new Date((year + min_age), month, day);
	var today = new Date;
    return ( (today.getTime() - theirDate.getTime()) < 0) ? false : true;
};

// validation --------------------------------------------------------------
var validateEmail = function(value) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
};
var validateUsername = function(value) {
    return /^[a-z0-9-_]+$/i.test(value);
};
jQuery.checkUserprofileField = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: null,
        fieldName: null,
        fieldId: null,
        fieldValue: null,
        username_minLength: 3,
        password_minLength: 6
    }, settings);

    if( settings.formType == null || settings.fieldName == null || settings.fieldId == null || settings.fieldValue == null ) {
        if( settings.debug == true && window.console ) {
            console.log('Error: formType, fieldName, fieldId or fieldValue is empty');
        }
    } else {
        //----------------------------
        var errMesg = new Array();

        var fieldName = settings.fieldName;
        var fieldId = settings.fieldId;
        var fieldValue = settings.fieldValue;

        switch( settings.formType ) {

            case 'profile':

                switch( fieldName ) {
                	case 'old_password':
                    case 'password': if( fieldValue.length < settings.password_minLength ) { errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_isempty+''});} break;
                    case 'givenname': if( $.profilar.get('givenname').length>0 && fieldValue.length<1 ){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.firstname_isempty+''});} break;
                    case 'surname': if( $.profilar.get('surname').length>0 && fieldValue.length<1 ){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.lastname_isempty+''});} break;
                    case 'email': if(!validateEmail(fieldValue)){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.email_invalid+''});} break;
                }

            break;
            case 'register':

                switch( fieldName ) {
                    case 'username':
                        if( fieldValue.length < settings.username_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_minlength+''});
                        } else {
                            if( !validateUsername(fieldValue) ) {
                                errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_badchar+''});
                            } else {}
                        }
                    break;
                    case 'password':
                        if( fieldValue.length < settings.password_minLength ) { errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_minlength+'' });}
                    break;
                    case 'password_repeat':
                        if( fieldValue != $("#register input[name=password]").val() || fieldValue.length < settings.password_minLength ){ errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_mustmatch+'' });}
                    break;
                    case 'email': if(!validateEmail(fieldValue)){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.email_invalid+''});} break;
                    case 'dob_month': if(fieldValue=='-1'){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.dob_selectmonth+''});} break;
                    case 'dob_day': if(fieldValue=='-1'){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.dob_selectday+''});} break;
                    case 'dob_year': if(fieldValue=='-1'){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.dob_selectyear+''});} break;
                    case 'gender': if($("#register input[name=gender]:checked").length == 0){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.gender_choose+''});} break;
                    case 'parent_email':
                    	if($('div#up_registration_parent_email').is(':visible') && !validateEmail(fieldValue)){
                    		errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.parent_email_invalid+''});
                    	} else if ($('input#f_parent_email').val() == $('input#f_email').val()){
                    		errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.parent_email_eq_child_email+''});
                    	}
                    break;
                    case 'privacy_policy': if($('div.privacy_policy_check').is(':visible') && $("#register input[name=privacy_policy]:checked").length == 0){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.privacy_policy_unchecked+''});} break;
                }

            break;
            case 'changepass':

                switch( fieldName ) {
                    case 'old_password':
                        if( fieldValue.length < settings.password_minLength ) { errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.old_password_minlength+''});}
                    break;
                    case 'password':
                        if( fieldValue.length < settings.password_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_minlength+''});
                        }
                    break;
                    case 'password_repeat':
                        if( fieldValue == '' ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.changepass_password_repeat_minlength+'' });
                        } else {
                            if( fieldValue != $("#password input[name=password]").val()){ errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.changepass_password_mustmatch+'' });}
                        }
                    break;
                }
            break;
            case 'forgot_password':
                switch (fieldName) {
                    case 'email':
                        if (!validateEmail(fieldValue)) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.forgot_password_email_invalid+''});
                        }
                    break;
                }
            break;
            case 'new_password':
                switch (fieldName) {
                    case 'password':
                        if (fieldValue.length < settings.password_minLength) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.new_password_password_minlength+''});
                        }
                    break;
                    case 'password_repeat':
                        if (fieldValue == '') {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.new_password_password_repeat_minlength+''});
                        } else if (fieldValue != $('#new_password_form #f_password').val()) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.new_password_password_repeat_must_match+''});
                        }
                    break;
                }
            break;
            case 'unregister':
                switch( fieldName ) {
                    case 'username':
                        if( fieldValue.length < settings.username_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_minlength+''});
                        } else {
                            if( !validateUsername(fieldValue) ) {
                                errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_badchar+''});
                            } else {}
                        }
                    break;
                    case 'password':
                        if( fieldValue.length < settings.password_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_minlength+''});
                        }
                    break;
                }
            break;
        }

        //----------------------------

        var retVal = errMesg.length>0 ? false : true;
        return [ retVal, errMesg ];
    }
};

jQuery.nValidateUserprofileRT = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        classname: 'validateMe'
    }, settings);

    // special case for date validation
    $("#f_dob_year").parent().append('<div id="f_dob_error" class="error" style="color: rgb(255, 0, 0);"></div>').show();
    $('#f_dob_year, #f_dob_month, #f_dob_day').blur(function(){
        var cyear = parseInt( $("select[name=dob_year]").val() );
        var cmonth = parseInt( $("select[name=dob_month]").val() );
        var cday = parseInt( $("select[name=dob_day]").val() );
        var mesg = '';
        if( cyear > 0 && cmonth > 0 && cday > 0 ) {
            if( ageCheck( {year: cyear, month: cmonth, day: cday}, 14) == false ) {
                mesg = SPI._langStrings.userprofile.validation.too_young+'';
            }
            var dateOk = true;
            if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
                  dateOk = false;
            }
            if (cmonth == 2) { // check for february 29th
                  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
                  if (cday > 29 || (cday==29 && !isleap)) {
                        dateOk = false;
                  }
            }
            if( !dateOk ) {
                mesg = SPI._langStrings.userprofile.validation.invalid_date+'';
            }
        }

        if( mesg ) {
            $('div#f_dob_error').html('- '+mesg).show();
            $(this).addClass('validationError');
        } else {
            $(this).removeClass('validationError');
            $('div#f_dob_error').hide();
        }
	});

    $("."+settings.classname).each( function(){

        var self = $(this);
        var fieldName = $(self).attr('name');
        var fieldId = $(self).attr('id');
        $('#'+fieldId).parent().append('<div id="'+fieldId+'_error" class="error" style="color: rgb(255, 0, 0);"></div>').show();

        $(self).blur(function(){

            var fieldValue = $(self).val();
            var errMesg = new Array();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
            if( fieldTest[0] == false ) {
                errMesg = fieldTest[1];
            }

            if( errMesg.length > 0 ) {
                $('div#'+fieldId+'_error').html('- '+errMesg[0].mesg).show();
                $(this).addClass('validationError');
            } else {
                $(this).removeClass('validationError')
                $('div#'+fieldId+'_error').hide();
            }
        });
    });
};

jQuery.nValidateUserprofileOD = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register'
    }, settings);

    var errMesg = new Array(), errString = '';

    $(".validationError").removeClass('validationError');
    $('div[id$=_error]').empty().hide();

    $(".validateMe").each(function(){

        var fieldName = $(this).attr('name');
        var fieldId = $(this).attr('id');
        var fieldValue = $(this).val();

        var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
        if( fieldTest[0] == false ) {
            errMesg.push(fieldTest[1]);
        }

    });

    if( settings.formType == 'profile' || settings.formType == 'register' ) {
        // age check
        var cyear = parseInt( $("select[name=dob_year]").val() );
        var cmonth = parseInt( $("select[name=dob_month]").val() );
        var cday = parseInt( $("select[name=dob_day]").val() );
        if( cyear > 0 && cmonth > 0 && cday > 0 ) {
            if( ageCheck( {year: cyear, month: cmonth, day: cday}, 14) == false ) {
                errMesg.push([{id: 'f_dob_year', mesg: SPI._langStrings.userprofile.validation.too_young+''}]);
            }
            var dateOk = true;
            if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
                  dateOk = false;
            }
            if (cmonth == 2) { // check for february 29th
                  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
                  if (cday > 29 || (cday==29 && !isleap)) {
                        dateOk = false;
                  }
            }
            if( !dateOk ) {
                errMesg.push([{id: 'f_dob_day', mesg: SPI._langStrings.userprofile.validation.invalid_date+''}]);
            }
        }
    }


    if( errMesg.length > 0 ) {
        $(errMesg).each(function(i,val){
            $('div#'+val[0].id+'_error').html('- '+val[0].mesg).show();
            $('#'+val[0].id).addClass('validationError');
        });
        return false;
    }
    return true;

};

jQuery.nValidateRegistrationRT = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        classname: 'validateMe',
        notAllowedAge: 7,
        parentConfirmationAge: 14
    }, settings);

    /*
    var dateOkay = true;

    $('#f_dob_year, #f_dob_month, #f_dob_day').change(function(){
        validateDate();
    });
    $('#f_dob_year, #f_dob_month, #f_dob_day').blur(function(){
        validateDate();
    });
    */

    var validateDate = function(){
        var cyear = parseInt( $("select[name=dob_year]").val() );
        var cmonth = parseInt( $("select[name=dob_month]").val() );
        var cday = parseInt( $("select[name=dob_day]").val() );
        var mesg = '';
        $("#dob select.validationError").removeClass("validationError");
        if( cyear > 0 && cmonth > 0 && cday > 0 ) {
			if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false || ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == true) {
				if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false){
					mesg = SPI._langStrings.userprofile.validation.too_young+'';
				}
				$("#up_registration_parent_email input.validationError").removeClass('validationError');
				$('#up_registration_parent_email').hide();

                parentEmailOkay = true;
			}else if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == false ) {
				$('#up_registration_parent_email').show();
                $("#up_registration_parent_email input[name=parent_email]").trigger('focus');

                //assume that parents email is empty (not OK)
                parentEmailOkay = false;
			}
            var dateOk = true;
            if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
                  dateOk = false;
            }
            if (cmonth == 2) { // check for february 29th
                  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
                  if (cday > 29 || (cday==29 && !isleap)) {
                        dateOk = false;
                  }
            }
            if( !dateOk ) {
                mesg = SPI._langStrings.userprofile.validation.invalid_date+'';
                $("#dob input").addClass('validationError');
            }
            dateOkay = dateOk;
 			$('div#error_f_dob div#f_dob_age_or_date_error_text').empty().append(mesg);
            $('.dob_dmy').hide();
			if($('div#f_dob_age_or_date_error_text').text().length == 0) {
                $('#dob_validationCorrectImage').show();
                $('#dob_validationErrorImage').hide();
			} else {
                $('#dob_validationCorrectImage').hide();
                $('#dob_validationErrorImage').show();
                $("#dob select").addClass("validationError");
                dateOkay = false;
			}
        } else {
            if( cyear<=0 ) {
                $('#error_f_dob_year').show();
                $("#f_dob_year").addClass("validationError");
            } else {
                $('#error_f_dob_year').hide();
            }
            if( cmonth<=0 ) {
                $('#error_f_dob_month').show();
                $("#f_dob_month").addClass("validationError");
            } else {
                $('#error_f_dob_month').hide();
            }
            if( cday<=0 ) {
                $('#error_f_dob_day').show();
                $("#f_dob_day").addClass("validationError");
            } else {
                $('#error_f_dob_day').hide();
            }
            $('#dob_validationCorrectImage').hide();
            $('#dob_validationErrorImage').show();
            dateOkay = false;
        }

        updateNextButton();
	};

    var updateNextButton = function() {
        if (
            usernameOkay    === false ||
            emailOkay       === false ||
            passwordOkay    === false ||
            repeatOkay      === false ||
            parentEmailOkay === false
        ) {
            $("#registration_form .moveButtonRight").addClass("disabled").unbind('click');
        } else {
            $("#registration_form .moveButtonRight").removeClass("disabled").unbind('click').click(function(){executeBlurs(); saveActionReg();});
        }
    };


    $("."+settings.classname).each( function(){

        var self = $(this);
        var fieldName = $(self).attr('name');
		var fieldId = $(self).attr('id');

        $(self).blur(function(){

            var fieldValue = $(self).val();
            var errMesg = new Array();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
            if( fieldTest[0] == false ) {
                errMesg = fieldTest[1];
            }

            if( errMesg.length > 0 ) {
				if(fieldId != "f_dob_month" && fieldId != "f_dob_year" && fieldId != "f_dob_day") {
					$('div#'+fieldId+'_ok.ok').hide();
					$('div#'+fieldId+'_help div.reghelpbox').hide();
					$('div#'+fieldId+'_error div.regerrorbox').show();
					$('div#'+fieldId+'_error div.regerrorbox div.content').empty().append(errMesg[0].mesg);
				} else {
					$('div#f_dob_age_or_date_error_text div.regerrorbox').hide();
					$('div#f_dob_ok.ok').hide();
					$('div#f_dob_noselect_error_text div.regerrorbox').show();
					if($('div#f_dob_noselect_error_text div.regerrorbox div.content div#'+fieldId+'_error').text().length == 0){
						$('div#f_dob_noselect_error_text div.regerrorbox div.content').append('<div id="'+fieldId+'_error">'+errMesg[0].mesg+'</div>');
					}
					if($('div#f_dob_noselect_error_text div.content').text().length == 0) {
						$('div#f_dob_noselect_error_text div.regerrorbox').hide();
						$('div#'+fieldId+'_ok.ok').show();
					} else {
						$('div#f_dob_noselect_error_text div.regerrorbox').show();
					}
				}
				$(this).addClass('validationError');
            } else {
                $(this).removeClass('validationError');
				if(fieldId != "f_dob_month" && fieldId != "f_dob_year" && fieldId != "f_dob_day" && fieldName != 'gender') {
					if(fieldId != "f_email" && fieldId != "f_username"){
						$('div#'+fieldId+'_error div.regerrorbox').hide();
						$('div#'+fieldId+'_help div.reghelpbox').hide();
						$('div#'+fieldId+'_ok.ok').show();
					}
				} else if (fieldName == 'gender'){
					$('#register input[name='+fieldName+']').removeClass('validationError');
					$('div#f_male_error div.regerrorbox').hide();
					$('div#f_male_help div.reghelpbox').hide();
					$('div#f_male_ok.ok').show();
				}else {
					$('div#f_dob_error div#f_dob_noselect_error_text div.content div#'+fieldId+'_error').empty();
				}

            }
        });
    });
};



jQuery.nValidateRegistrationOD = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        notAllowedAge: 7,
        parentConfirmationAge: 14
    }, settings);
    var errMesg = new Array(), errString = '';
	var toReturn = true;

    $(".validationError").removeClass('validationError');

    $(".validateMe").each(function(){
        var fieldName = $(this).attr('name');
        var fieldId = $(this).attr('id');
        var fieldValue = $(this).val();

		var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
        });
        if( fieldTest[0] == false ) {
            errMesg.push(fieldTest[1]);
        }
    });

	var cyear = parseInt( $("select[name=dob_year]").val() );
	var cmonth = parseInt( $("select[name=dob_month]").val() );
	var cday = parseInt( $("select[name=dob_day]").val() );
    var mesg = '';
    $("#dob select.validationError").removeClass("validationError");
	if( cyear > 0 && cmonth > 0 && cday > 0 ) {
		if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false || ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == true) {
			if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false){
				mesg = SPI._langStrings.userprofile.validation.too_young+'';
				toReturn = false;
			}
			$("div#up_registration_parent_email input.validationError").removeClass('validationError');
			$('div#up_registration_parent_email').hide();
		}else if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == false ) {
			$('div#up_registration_parent_email').show();
            $("#up_registration_parent_email input[name=parent_email]").trigger('focus');
            if($("#up_registration_parent_email input[name=parent_email]").val() == ''){
                toReturn = false;
            }
		}
//		if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false ) {
//			mesg = SPI._langStrings.userprofile.validation.too_young+'';
// 			$('div#f_dob_error div#f_dob_age_or_date_error_text div.content').empty().append(mesg);
//			toReturn = false;
//		}
		var dateOk = true;
		if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
			  dateOk = false;
		}
		if (cmonth == 2) { // check for february 29th
			  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
			  if (cday > 29 || (cday==29 && !isleap)) {
					dateOk = false;
			  }
		}
		if( !dateOk ) {
			mesg = SPI._langStrings.userprofile.validation.invalid_date+'';
 			$('div#f_dob_error div#f_dob_age_or_date_error_text').empty().append(mesg);
            $("#dob input").addClass('validationError');
            $('#dob_validationCorrectImage').hide();
            $('#dob_validationErrorImage').show();
			toReturn = false;
		}
	} else {
        toReturn = false;
    }

    if( errMesg.length > 0 ) {
        $(errMesg).each(function(i,val){
			if(val[0].id != "f_dob_month" && val[0].id != "f_dob_year" && val[0].id != "f_dob_day") {
				$('div#'+val[0].id+'_ok.ok').hide();
				$('div#'+val[0].id+'_help div.reghelpbox').hide();
				$('div#'+val[0].id+'_error div.regerrorbox').show();
				$('div#'+val[0].id+'_error div.regerrorbox div.content').empty().append(val[0].mesg);
//				$('#'+val[0].id).not('input[type="radio"]').addClass('validationError');
				$('#'+val[0].id).addClass('validationError');
			}else {
				$('div#f_dob_noselect_error_text div.regerrorbox').show();
				if($('div#f_dob_noselect_error_text div.regerrorbox div.content div#'+val[0].id+'_error').text().length == 0){
					$('div#f_dob_noselect_error_text div.regerrorbox div.content').append('<div id="'+val[0].id+'_error">'+val[0].mesg+'</div>');
				}
				$('#'+val[0].id).addClass('validationError');
			}
        });

		if($('div#f_dob_error').children().length == 0) {
			$('div#f_dob_error').hide();
		} else {
			$('div#f_dob_error').show();
		}
		if($(".validationError").size() > 0){
			toReturn = false;
		}
    }

	if($('div#f_dob_error').children().length == 0) {
		$('div#f_dob_error').hide();
	} else {
		$('div#f_dob_error').show();
	}
    return toReturn;
};

jQuery.nValidateForgotPasswordRT = function(settings) {
    // default settings
    var settings = $.extend(true, {
        debug: false,
        classname: 'validateMe'
    }, settings);

    $("."+settings.classname).each( function(){
        var self = $(this);
        var fieldName = $(self).attr('name');
		var fieldId = $(self).attr('id');

        $(self).focus(function(){
            var fieldValue = $(self).val();

            if(fieldValue == ''){
                $('#'+fieldId+'_ok').hide();
                $('#'+fieldId+'_error').hide();
                $('#'+fieldId+'_help').show();

                //$(this).removeClass('validationError');
            }
        });

        $(self).blur(function(){
            var fieldValue = $(self).val();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });

            $('#'+fieldId+'_help').hide();

            if (fieldTest[0] == false) {
                var errorMessage = fieldTest[1][0].mesg;

                $('#'+fieldId+'_ok').hide();
                $('#'+fieldId+'_error .main .content').empty().append(errorMessage);
                $('#'+fieldId+'_error').show();

                $(this).addClass('validationError');
            } else {
                $('#'+fieldId+'_error').hide();
                $('#'+fieldId+'_ok').show();

                $(this).removeClass('validationError');
            }
        });
    });
};

jQuery.nValidateForgotPasswordOD = function(settings) {
    // default settings
    var settings = $.extend(true, {
        debug: false,
        classname: 'validateMe'
    }, settings);
    var isOK = true;

    $("."+settings.classname).each( function(){
        var self = $(this);
        var fieldName = $(self).attr('name');
		var fieldId = $(self).attr('id');
        var fieldValue = $(this).val();

		var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
        });

        $('#'+fieldId+'_help').hide();

        if (fieldTest[0] == false) {
            var errorMessage = fieldTest[1][0].mesg;

            $('#'+fieldId+'_ok').hide();
            $('#'+fieldId+'_error .main .content').empty().append(errorMessage);
            $('#'+fieldId+'_error').show();

            $(this).addClass('validationError');
            isOK = false;
        } else {
            $('#'+fieldId+'_error').hide();
            $('#'+fieldId+'_ok').show();

            $(this).removeClass('validationError');
        }
    });

    return isOK;
};

loadExternalPrefs_callback = function(prefsdata, prefserrors) {
	if(prefsdata.length == 0) {
		window.location = '/';
		return;
	}

	if(prefsdata[0].avatar !== undefined) {
		$('img.userAvatar').css('background-image',"url('"+SPI.sprintf(SPI._settings.global.avatar_url_big, prefsdata[0].avatar)+"')");
	} else {
		$('img.userAvatar').css('background-image',"url('/img/_/profile/dummy_big.jpg')");
	};
	$('div.avatar img.userAvatar').load(function () {
	  $('div.avatar img.userAvatar').css('visibility','visible');
	});

	var uname = new Array();
	uname.push(SPI.getURLparam("username"));

	$('div#maincontent div.breadcrumb h4,span#up_leftbox_username, #profilecontent span.username').text(uname[0]);
	$('div.navigation a').each(function(){
		$(this).attr('href', $(this).attr('href') + '?username='+uname[0]);
	});

	/* If privacy=="0" (public) then load public external profile data */
	if(prefsdata[0].privacy == "0") {
		$.profilar.loadExternalProfiles(uname, function(data, errors) {
			$('div#profilecontent').show();

			if(isNaN(data[0].age)) {
				$('td#up_leftbox_age').text('Unknown');
			} else {
				$('td#up_leftbox_age').text(data[0].age);
			};

			if(data[0].gender == "m") {
				$('td#up_leftbox_gender').text(SPI._langStrings.userprofile.male);
			} else {
				$('td#up_leftbox_gender').text(SPI._langStrings.userprofile.female);
			};
		}, ['username', 'gender', 'age']);

		SPI.handlers.run('userprofile', []);

	} else {
		// If it is your profile, redirect to profile page.
		if (uname[0] == $.profilar.forService().username) {
			SPI.reloadSite(SPI._settings.global.my_profile_page);
		}

		/* Display that the profile is private */

		$("#leftbox_privacybox,div#privateprofile").show();
		$("table#profileData").hide();
		$.profilar.loadExternalProfiles(uname, function(data, errors) {
			$('div#maincontent div.breadcrumb h4').text(data[0].username);
		}, ['username']);
	};

	// Filling awards
	SPI.achievements.init();
	SPI.achievements.getAchievementsCountForUser(function(data){
		try{
			tmp = data.hyscor.resultset.total || 0;
		}catch(e){
			tmp = 0;
		};
		$('div#userinfo span#awardsCount, #profilecontent span.awardsCount').html(tmp);
	},uname);

	// Filling points
	SPI.highscore.init();
	SPI.highscore.getUserLevel(function(data){
		try{
			tmp = data.hyscor.level || 0;
		}catch(e){
			tmp = 0;
		};
		fillPoints(tmp,false,true,false);
	},uname);

	$("#userinfo").show();
};



// NIE RUSZAC BO ZABIJE
jQuery.nValidateUserprofileOnDemand = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        notAllowedAge: 7,
        parentConfirmationAge: 14,
        layer: ''
    }, settings);

    var errMesg = new Array(), errString = '';
	var toReturn = true;

    $("div#"+settings.layer+" .validationError").removeClass('validationError');

    $("div#"+settings.layer+" .validateMe").each(function(){

        var fieldName = $(this).attr('name');
        var fieldId = $(this).attr('id');
        var fieldValue = $(this).val();

        var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
        if( fieldTest[0] == false ) {
            errMesg.push(fieldTest[1]);
        }

    });

    if( errMesg.length > 0 ) {
        $(errMesg).each(function(i,val){
        	displayError = val[0].mesg;
			$('div#'+val[0].id+'_ok.ok').hide();
			$('div#'+val[0].id+'_help div.reghelpbox').hide();
			$('div#'+val[0].id+'_error div.regerrorbox').show();
			$('div#'+val[0].id+'_error div.regerrorbox div.content').empty().append(displayError);
        	$('div#'+val[0].id).addClass('validationError');
        });
        toReturn = false;
    }

    return toReturn;
};

// NIE RUSZAC BO ZABIJE
jQuery.nValidateUserprofileRealtime = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        notAllowedAge: 7,
        parentConfirmationAge: 14,
        classname: 'validateMe'
    }, settings);

	var errors = [];
	errors[''+settings.layer] = [];

	var checkIfInErrors = function(errors,obj) {
        for( var i = 0 ; i<errors.length; i++ ) {
            if( errors[i].id == obj.id ) return true;
        }
        return false;
    };

    var removeError = function(errors, id) {
        for( var i = 0 ; i<errors.length; i++ ) {
            if( errors[i].id == id ){
                errors.splice(i, 1);
                $("#"+settings.layer+" #"+id).removeClass('validationError');
                return;
            };
        }
        return;
    };

    $("#"+settings.layer+" ."+settings.classname).each( function(){

        var self = $(this);
        var fieldName = $(self).attr('name');
        var fieldId = $(self).attr('id');

        $(self).blur(function(){
            //$('#'+settings.layer+' .validationErrors').hide();

            var fieldValue = $(self).val();
            var errMesg = new Array();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });

            if( fieldTest[0] == false ) {
                errMesg = fieldTest[1];
            }

            if( errMesg.length > 0 ) {
				$('div#'+fieldId+'_ok.ok').hide();
				$('div#'+fieldId+'_help div.reghelpbox').hide();
				$('div#'+fieldId+'_error div.regerrorbox').show();
				$('div#'+fieldId+'_error div.regerrorbox div.content').empty().append(errMesg[0].mesg);
				$(this).addClass('validationError');
            } else {
                $(this).removeClass('validationError');
				$('div#'+fieldId+'_error div.regerrorbox').hide();
				$('div#'+fieldId+'_help div.reghelpbox').hide();
				$('div#'+fieldId+'_ok.ok').show();
            }
        });
    });
};
;/*
    @desc common functions for whole SF
    @author macic
*/

// flash message
var hideFlashMessage = function() {
    var layer = $('div#flashMessage');
    if( layer.length>0 ) {
        layer.fadeOut('slow');
    }
};

var showNotificationForSignIn = function() {
    $("#topBox").hide();
    $("#middlePinkBox").hide();
    $("#bottomLeftBox").hide();
    $("#bottomRightBox1").hide();
    $("#bottomRightBox2").hide();
    $("#additionalBox").hide();

    $(".hidenotlogged").hide();

    $('<div class="bad"><div class="text">' + SPI._langStrings.sf_global.have_to_sign_in + '</div></div>').appendTo("#flashMessage");
    $("#flashMessage").show();
    $('a[name="show_login_popup"]').click();
};

var redirectToPublicGalleryImage = function(gamatarid) {
    window.location.href = SPI.sprintf(SPI._settings.myGallery.mygallery_url_details_game, gamatarid);
}

var redirectToParentsReminder = function() {
    window.location.href = SPI._settings.attention.parents_reminder_url;
};

var redirectToSelfReminder = function() {
    // TODO: redirect to self reminder landing page
};

var redirectToProfilePage = function() {
    window.location.href = SPI._settings.myprofile.pageurl;
};

var redirectToMainPage = function() {
    window.location.href = '/';
};

var showPublicProfile = function() {
    $("#publicContainer").removeAttr('style');
};

var showPrivateProfile = function() {
    $("#publicContainer").remove();
    $("#privateContainer").append(SPI.render('private_profile_tpl', {})).show();
};

var attachAvatarHovers = function(){
    $("div.ul_container ul li").hover(function(){
        $(this).addClass('hover');
        $(this).find('.button_group').show().width($(this).find('.button_middle').width() + 16);
    },
    function(){
        $(this).removeClass('hover');
        $(this).find('.button_group').hide();
    });
};

$(document).ready(function() {
    $.profilar.addInitHandler(function(){
        var state = $.profilar.loggedIn();
        changeLoginBox(state);
    });

    // displaying of the shadow box
    $('#shadow').ifixpng();
    $('#loginbox_top').ifixpng();
    $('#loginbox_content').ifixpng();
    $('#loginbox_bottom').ifixpng();

    $('a[name="show_login_popup"]').click(function(e) {
        e.preventDefault();
        // hide flash games
        $('#flashobj').css('visibility', 'hidden');
        $('select').css('visibility', 'hidden');
        $('#gameiframe_js').css('visibility', 'hidden');
        $('#shadow').css('width', $(window).width());
        $('#shadow').css('height', $(document).height());
        //set top margin of login box depend on window size
        setTopMarginForLoginBox();
        $('#shadow').css('display', 'block');

        // clearing of the errors
        $("div#shadow .error").css('display', 'none');
        $("div#shadow #loginslogan").css('display', 'block');
        $('div#shadow input').removeAttr('disabled')
        $('div#shadow input[name=username], div#shadow input[name=password]').val('');
        $('div#shadow input[name=remember]').removeAttr('checked');
    });

    $('.close_login_popup').click(function(e) {
        e.preventDefault();
        $('#shadow').css('display', 'none');
        // show flash games
        $('#flashobj').css('visibility', 'visible');
        $('select').css('visibility', 'visible');
        $('#gameiframe_js').css('visibility', 'visible');
    });

    // change the look of header login box
    // set to public - reusable in integrations
    changeLoginBox = function(state) {
        // nez -----------------------------------------------------------------
        $("div#user_navigation div.loading").hide();
        $("div#user_navigation div.loaded").show();
        //----------------------------------------------------------------------
        if(state) {
            // logged in user
            var avatar_id=$.profilar.getPref('avatar');
            if(avatar_id!='') {
                var normal_src = sprintf(SPI._settings.avatars.small_avatar, avatar_id);
                $("#avatarnormal").attr('src', normal_src);
            } else {
                $("#avatarnormal").attr('src', '/img/userprofile/dummy_small.gif');
            }
            $("#avatardummy").hide();
            $("#avatarnormal").show();
            $("#logout_links").hide();
            $("#login_links").show();
            var username = $.profilar.get('username');
            $("#userloggedin").text(username);

            // fill in my gallery number
            SPI.getUserGalery(username,function(data){
                $('#un_mygallery span').text(data.gamatar.resultset.total);
           },username);
            
            SPI.getUserGames(username,function(data){
                $('#un_mygames span').text(data.length);
           },username);
        } else {
            $("#avatarnormal").hide();
            $("#avatardummy").show()
            // not logged in user
            $("#login_links").hide();
            $("#logout_links").show();
        }
        adjustSize();
    }

    // adjust size of login header box
    var adjustSize = function(){
        $minWidth =
            $("#search_bar .buttonRight").width() +
            $("#search_bar .buttonLeft").width()  +
            $("#search_bar #searchtext").width()  -
            7;

        if ($("#user_navigation .body").width() < $minWidth) {
            $("#user_navigation .body").width($minWidth);
        }
    };

    // usage of popup login box
    var clickActionLoginBox = function() {

        // clear the errors and show the indicator of login
        $("div#shadow .error").css('display', 'none');
        $("div#shadow #loginslogan").css('display', 'block');
        $('div#shadow .loginIndicator').show();

        var username = $('div#shadow input[name=username]').removeAttr('disabled').val();
        var password = $('div#shadow input[name=password]').val();

        $('div#shadow input[name=username]').add('div#shadow input[name=password]').attr('disabled','true');
        $('div#shadow #logmein').unbind('click');

        var ok = true;

        // standard checks
        if( username.length < 3) {
            ok = false;
        } if (password.length < 6 || $('input#f_password_lb').is(':hidden') ) {
            ok = false;
        }

        if (ok) {
            $.profilar.login(username, password, $('div#shadow input[name=remember]')[0].checked, function(errors) {
                if (errors) {
                    var error = errors[0];
                    $('#loginslogan').css('display','none');
                    if (error.code == 403 && error.element == 'banned') {
                        $('#loginsalert_banned').css('display','block');
                    } else {
                        $('#loginsalert_auth').css('display','block');
                    }
                    $('div#shadow input[name=username]').add('div#shadow input[name=password]').removeAttr('disabled');
                    $('div#shadow #logmein').click(clickActionLoginBox);
                    $('div#shadow .loginIndicator').hide();
                } else {
                    $.profilar.checkActivation(true);

                    if ($.profilar.needActivation()) {
                        if ($.profilar.needParentsConfirmation()) {
                            redirectToParentsReminder();
                        } else {
                            redirectToSelfReminder();
                        }
                    } else {
                        window.location.reload();
                    }
                }
            });
        } else {
            $('#loginslogan').css('display','none');
            $('#loginsalert_auth').css('display','block');
            $('div#shadow input[name=username]').add('div#shadow input[name=password]').removeAttr('disabled');
            $('div#shadow #logmein').click(clickActionLoginBox);
            $('div#shadow .loginIndicator').hide();
        }
        return false;
    };

    // logout
    var clickActionLogout = function(){
        $.profilar.clearAll();
        window.location = '/';
        return false;
    };

    var setTopMarginForLoginBox = function() {
        var boxHeight = 415;
        var topMargin;
        var windowHeight;

        if (typeof(window.innerWidth) == 'number') {
            //Non-IE
            windowHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            windowHeight = document.body.clientHeight;
        } else {
            windowHeight = 0;
        }

        if (windowHeight > boxHeight) {
            topMargin = Math.floor((windowHeight - boxHeight) / 2);
        } else {
            topMargin = 0;
        }

        $("#shadow #loginbox_wrapper").attr(
            "style", "margin: " + topMargin + "px auto 0"
        );
    };

    // assign click to login button
    $('div#shadow #logmein').click(clickActionLoginBox);

    // assign enter button for login form
    $("div#shadow form input").keypress(function(e){
        if ((e.which && e.which == 13) || (e.keyCode &&  e.keyCode == 13)) {
            return clickActionLoginBox();
        } else {
            return true;
        }
    });

    // assign click to logout button
    $("#logoutbtn").click(clickActionLogout);

    var flashMessage = SPI.flashMessage.get();

    if( flashMessage.length==2 && flashMessage[0] != '' ) {
        var layer = $('div#flashMessage');
        if( layer.length>0 ) {
            layer.empty().html('<div class="'+(flashMessage[1]=='true'?'bad':'good')+'"><div class="text">'+flashMessage[0]+'</div></div>').show();
            setTimeout('hideFlashMessage()', 5000);
        }
    }

});
;/**
 * Giving game dev a possibility to communicate with the game page.
 * The game calls SWFtoJS with a parameter, the parameter must be a CallObject
 * @author V.A. Perez SPILGAMES SPILGAMES © 2009
 * @version 1.0
 * @param {CallObject} p_oCallObject
 */
function SWFtoJS(p_oCallObject){
	//all call functions
	this.m_oCallFuntions = new Object();
	//debug mode, default false
	this.m_bDebug = false;

	if(p_oCallObject != null){
		SWFtoJS.instance().parse(p_oCallObject);
	}
}

/**
 * @var {SWFtoJS} instance
 */
SWFtoJS.m_oSWFtoJS = null;

/**
 * instance of SWFtoJS
 * @param {Boolean} p_bDebugOn set debug on, default of
 */
SWFtoJS.instance = function(p_bDebugOn){
    if(SWFtoJS.m_oSWFtoJS == null){
		SWFtoJS.m_oSWFtoJS = new SWFtoJS();
		if(p_bDebugOn){
			SWFtoJS.m_oSWFtoJS.m_bDebug = true;
		}
	}
	return SWFtoJS.m_oSWFtoJS;
};

/**
 * add a function to a call
 * @param {String} p_sName the name of the call
 * @param {Function} p_fFunction the function to run
 */
SWFtoJS.prototype.addCallFunction = function(p_sName, p_fFunction){
    if(typeof p_fFunction == 'function'){
		this.m_oCallFuntions[p_sName] = p_fFunction;
	}
};

/**
 * Parse the CallObject and call the function.
 * @param {CallObject} p_oCallObject
 */
SWFtoJS.prototype.parse = function(p_oCallObject){
    try {
        if (p_oCallObject.call) {
            switch (p_oCallObject.call) {
				//parse multie
                case 'MULTI':{
                    for(i = 0; i < p_oData.calls.length; i++){
                        SWFtoJS(p_oCallObject.calls[i]);
                    }
                }
                break;

				//parse data
                default:{
					//check call exists
                    if(this.m_oCallFuntions[p_oCallObject.call]){
						//create empty params if no params exists
						if(!p_oCallObject.params){
							p_oCallObject.params = {};
						}
						//call function
						this.m_oCallFuntions[p_oCallObject.call](p_oCallObject.params);
					}else{
						throw "call: " + p_oCallObject.call +" not found in call functions!";
					}
                }
                break;
            }
        }else{
			throw "call attribute not found in CallObject!";
		}
    }catch(sError){
		//debug mode on
        if(this.m_bDebug){
			alert(sError);
		}
    }
};
;;(function() {
jQuery.fn.cookieBoxHide = function(settings) {

    var settings = $.extend({
        'name': null,
        'time': 365,
        'click': null,
        'path': '/'
    }, settings);
    var self = this;
    
    return this.each(function(i, val){
        if( settings.name != null ) {
            var container = this;
            if( ($.cookie(''+settings.name)||'0') == '0' ) {
                $(this).show();
            } else {
                $(this).hide();
            }
            if( settings.click != null && settings.click.length>0 ) {
                $(settings.click).click(function(){
                    $.cookie(''+settings.name, '1', {path: settings.path, expires: settings.time} );
                    $(container).hide();
                });
            }
        }
            //if(($.cookie('_SPI_agskiphead')||'0')=='0'){$('div#awardgames div.chicks_container').show();}
            //$('div#awardgames div.chicks_container div.skip a').click(function(){ $.cookie('_SPI_agskiphead', '1',{path: '/', expires: 365}); $('div#awardgames div.chicks_container').hide(); });
    });
}
})(jQuery);

;/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 3/9/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.1
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height';

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[Dim.toLowerCase()]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

			// Max scrolling position, works on quirks mode
			// It only fails (not too badly) on IE, quirks mode.
			function max( Dim ){
				var scroll = 'scroll'+Dim;
				
				if( !win )
					return elem[scroll];
				
				var size = 'client' + Dim,
					html = elem.ownerDocument.documentElement,
					body = elem.ownerDocument.body;

				return Math.max( html[scroll], body[scroll] ) 
					 - Math.min( html[size]  , body[size]   );
					
			};

		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
;/**
 * jQuery.LocalScroll
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 6/3/2008
 *
 * @projectDescription Animated scrolling navigation, using anchors.
 * http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html
 * @author Ariel Flesler
 * @version 1.2.6
 *
 * @id jQuery.fn.localScroll
 * @param {Object} settings Hash of settings, it is passed in to jQuery.ScrollTo, none is required.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example $('ul.links').localScroll();
 *
 * @example $('ul.links').localScroll({ filter:'.animated', duration:400, axis:'x' });
 *
 * @example $.localScroll({ target:'#pane', axis:'xy', queue:true, event:'mouseover' });
 *
 * Notes:
 *	- The plugin requires jQuery.ScrollTo.
 *	- The hash of settings, is passed to jQuery.ScrollTo, so the settings are valid for that plugin as well.
 *	- jQuery.localScroll can be used if the desired links, are all over the document, it accepts the same settings.
 *  - If the setting 'lazy' is set to true, then the binding will still work for later added anchors.
 *  - The setting 'speed' is deprecated, use 'duration' instead.
 *	- If onBefore returns false, the event is ignored.
 **/
;(function( $ ){
	var URI = location.href.replace(/#.*/,'');//local url without hash

	var $localScroll = $.localScroll = function( settings ){
		$('body').localScroll( settings );
	};

	//Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
	//@see http://www.freewebs.com/flesler/jQuery.ScrollTo/
	$localScroll.defaults = {//the defaults are public and can be overriden.
		duration:1000, //how long to animate.
		axis:'y',//which of top and left should be modified.
		event:'click',//on which event to react.
		stop:true//avoid queuing animations 
		/*
		lock:false,//ignore events if already animating
		lazy:false,//if true, links can be added later, and will still work.
		target:null, //what to scroll (selector or element). Keep it null if want to scroll the whole window.
		filter:null, //filter some anchors out of the matched elements.
		hash: false//if true, the hash of the selected link, will appear on the address bar.
		*/
	};

	//if the URL contains a hash, it will scroll to the pointed element
	$localScroll.hash = function( settings ){
		settings = $.extend( {}, $localScroll.defaults, settings );
		settings.hash = false;//can't be true
		if( location.hash )
			setTimeout(function(){ scroll( 0, location, settings ); }, 0 );//better wrapped with a setTimeout
	};

	$.fn.localScroll = function( settings ){
		settings = $.extend( {}, $localScroll.defaults, settings );

		return ( settings.persistent || settings.lazy ) 
				? this.bind( settings.event, function( e ){//use event delegation, more links can be added later.
					var a = $([e.target, e.target.parentNode]).filter(filter)[0];//if a valid link was clicked.
					a && scroll( e, a, settings );//do scroll.
				})
				: this.find('a,area')//bind concretely, to each matching link
						.filter( filter ).bind( settings.event, function(e){
							scroll( e, this, settings );
						}).end()
					.end();

		function filter(){//is this a link that points to an anchor and passes a possible filter ? href is checked to avoid a bug in FF.
			return !!this.href && !!this.hash && this.href.replace(this.hash,'') == URI && (!settings.filter || $(this).is( settings.filter ));
		};
	};

	function scroll( e, link, settings ){
		var id = link.hash.slice(1),
			elem = document.getElementById(id) || document.getElementsByName(id)[0];
		if ( elem ){
			e && e.preventDefault();
			var $target = $( settings.target || $.scrollTo.window() );//if none specified, then the window.

			if( settings.lock && $target.is(':animated') ||
			settings.onBefore && settings.onBefore.call(link, e, elem, $target) === false ) return;

			if( settings.stop )
				$target.queue('fx',[]).stop();//remove all its animations
			$target
				.scrollTo( elem, settings )//do scroll
				.trigger('notify.serialScroll',[elem]);//notify serialScroll about this change
			if( settings.hash )
				$target.queue(function(){
					location = link.hash;
					// make sure this function is released
					$(this).dequeue();
				});
		}
	};

})( jQuery );
;;
//validation functions
validateBasic = function(data){
	validInfo1 = validateBasicGivenname(data);
	validInfo2 = validateBasicSurname(data);
  if (validInfo1 && validInfo2){
    return {valid:true};
  }else{
    toReturn = {valid:false,invalidFields:[],validFields:[]};
    if(!validInfo1) toReturn.invalidFields.push('givenname');else toReturn.validFields.push('givenname');
    if(!validInfo2) toReturn.invalidFields.push('surname');else toReturn.validFields.push('surname');
    return toReturn;
  };
};

validateBasicGivenname = function(data){
	data.oldgivenname = $.profilar.get('givenname');
	if (typeof(data.oldgivenname) != 'undefined' && data.oldgivenname != '' && typeof(data.givenname) != 'undefined' && data.givenname != '') return true;
	if (typeof(data.oldgivenname) != 'undefined' && data.oldgivenname == '' && typeof(data.givenname) != 'undefined' && data.givenname == '') return true;
	if (typeof(data.oldgivenname) != 'undefined' && data.oldgivenname == '' && typeof(data.givenname) != 'undefined' && data.givenname != '') return true;
	return false
};
livecheckGivenname = function(data){
	if(!validateBasicGivenname(data)){
		$('.error_givenname').show();
		$('.correct_givenname').hide();
	}else{
		$('.error_givenname').hide();
		$('.correct_givenname').show();
	};
	return false;
};
validateBasicSurname = function(data){
	data.oldsurname = $.profilar.get('surname');
	if (typeof(data.oldsurname) != 'undefined' && data.oldsurname != '' && typeof(data.surname) != 'undefined' && data.surname != '') return true;
	if (typeof(data.oldsurname) != 'undefined' && data.oldsurname == '' && typeof(data.surname) != 'undefined' && data.surname == '') return true;
	if (typeof(data.oldsurname) != 'undefined' && data.oldsurname == '' && typeof(data.surname) != 'undefined' && data.surname != '') return true;
	return false
};
livecheckSurname = function(data){
	if(!validateBasicSurname(data)){
		$('.error_surname').show();
		$('.correct_surname').hide();
	}else{
		$('.error_surname').hide();
		$('.correct_surname').show();
	};
	return false;
};

livecheckOld = function(pass){
	$('.error_oldpass').hide();
	if(!validateConfirm(pass)){
		$('.correct_old').hide();
		$('.error_old').show();
	}else{
		$('.correct_old').show();
		$('.error_old').hide();
	};
	return false;
};
livecheckRepeat = function(pass){
	if(validateConfirm(pass) && pass==$('#f_password').val()){
		$('.correct_same').show();
		$('.error_same').hide();
	}else{
		$('.correct_same').hide();
		$('.error_same').show();
	};
	return false;
};

livecheckPassword = function(pass){
	if(!validateConfirm(pass)){
		$('.correct_password').hide();
		$('.error_password').show();
	}else{
		$('.correct_password').show();
		$('.error_password').hide();
	};
	return false;
};


validateConfirm = function(pass){
  if (typeof(pass) != 'undefined' && pass.length > 5) return true;
  return false;
}
validatePass = function(data){
  toReturn = {valid:true,invalid:[],isvalid:[]};
  if (typeof(data.old) != 'undefined' && data.old.length <6){
    toReturn.valid = false;
    toReturn.invalid.push('old');
  }else{
    toReturn.isvalid.push('old');
  };
  if (typeof(data.password) != 'undefined' && data.password.length <6){
    toReturn.valid = false;
    toReturn.invalid.push('password');
  }else{
    toReturn.isvalid.push('password');
  };
  if (typeof(data.password) != 'undefined' && typeof(data.repeat) != 'undefined' && data.password == data.repeat){
	    toReturn.isvalid.push('same');
	  }else{
	    toReturn.valid = false;
	    toReturn.invalid.push('same');
	  };
	  
  if (typeof(data.repeat) != 'undefined' && data.repeat.length <6){
    toReturn.valid = false;
    toReturn.invalid.push('password_repeat');
  }else{
    toReturn.isvalid.push('password_repeat');
  };
 
  return toReturn;
};

var validateEmail = function(value) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
	return {valid:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)};
};

$(function(){
	$.profilar.addInitHandler(function(logged) {
        if( !logged ) { 
            return; 
        }
        $('div#change_profile .settingsBox').show();
        $.profilar.load(function(errors) {
           if (errors) {
           } else {
               var uname = $.profilar.get('username') || '';
               $('input[name=password]').val('');
               $('#basic span#f_username').html( uname );
               $('#basic input[name=username]').val( uname );
               $('#basic input[name=givenname]').val($.profilar.get('givenname'));
               $('#basic input#f_old_givenname').val($.profilar.get('givenname'));
               $('#basic input[name=surname]').val($.profilar.get('surname'));
               $('#basic input#f_old_surname').val($.profilar.get('surname'));
               $('#email span#f_email_current').html($.profilar.get('email'));
               var dob = $.profilar.get('dob').split('-');
               dobstr = SPI._langStrings.myprofile.months[dob[1]-1]+' '+dob[2]+', '+dob[0];
               $('#basic span#f_dob').html(dobstr);
               $('#basic input[name=gender][value='+$.profilar.get('gender')+']').attr('checked','checked');
           }
        },['dob', 'gender', 'email', 'givenname', 'surname']);

        $("#basic input[name=givenname]").trigger('focus');        

        // BASIC SAVE
        var saveBasicConfirm = function(){
          $('#saveBasicConfirm .loginIndicator').css('display','inline');
          $('#changeprofileconfirm .error_pass').hide();
          if(validateConfirm($('div#changeprofileconfirm input:first').val())){
              var olds = {'givenname': $.profilar.get('givenname'),'surname':   $.profilar.get('surname')};
              $.profilar.set('givenname', $('#basic input[name=givenname]').val());
              $.profilar.set('surname', $('#basic input[name=surname]').val());
              $.profilar.set('gender', $('input[name=gender]:checked').val());
              $('div#saveBasic span').unbind('click');
              $.profilar.submit($('div#changeprofileconfirm input:first').val(), function(errors) {
                   if (errors) {
                	   	$('#changeprofileconfirm .error_pass').show();
                        $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
                        $('#saveBasicConfirm .loginIndicator').css('display','none');
                   } else {
                	   $('#saveBasicConfirm .loginIndicator').css('display','none');
                       SPI.flashMessage.set( SPI._langStrings.myprofile.profile_saved );
                       SPI.reloadSite( SPI._settings.myprofile.pageurl );
                   }
                }, ['givenname', 'surname', 'gender'] );
          }else{
        	  $('#changeprofileconfirm .error_pass').show();
        	  $('#saveBasicConfirm .loginIndicator').css('display','none');
          };
        };
        
        var saveBasic = function(realSave,gn,sn) {
            $('div#saveBasic span').unbind('click');
            validationInfo = validateBasic({givenname:gn, oldgivenname:$.profilar.get('givenname'), surname:sn, oldsurname:$.profilar.get('surname')});
            if(validationInfo.valid){
               $('.correct_givenname').show();
               $('.correct_surname').show();
               $('.error_givenname').hide();
               $('.error_surname').hide();
            }else{
              $(validationInfo.invalidFields).each(function(){
                $('.error_'+this).show();
                $('.correct_'+this).hide();
              });
              $(validationInfo.validFields).each(function(){
                $('.error_'+this).hide();
                $('.correct_'+this).show();
              });
            }
            $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
            
            if(realSave == true && validationInfo.valid == true){
              $('form#basic,form#email,form#pass').hide();
              $('div#changeprofileconfirm').show();
              $('div#changeprofileconfirm input:first').focus();
              $('#saveBasicConfirm span').click(function(){
                saveBasicConfirm();  
              });
            }
            return false;
        };
        
        $('#f_givenname').focus(function(){
          $('.error_givenname').hide();
          $('.correct_givenname').hide();    
        }).blur(function(){
        	livecheckGivenname({'givenname':$('#f_givenname').val()});  
        });
        
        $('#f_surname').focus(function(){
          $('.error_surname').hide();
          $('.correct_surname').hide();  
        }).blur(function(){
        	livecheckSurname({'surname':$('#f_surname').val()});  
        });
        
        
        $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
        
        // EMAIL SAVE
        var saveEmailConfirm = function(){
        	$('#saveEmailConfirm .loginIndicator').css('display','inline');
        	if(validateConfirm($('div#changeemailconfirm input:first').val())){
        		oldEmail = $.profilar.get('email');
                $.profilar.set('email', $('input#f_email').val());
                $('div#saveBasic span').unbind('click');
                $.profilar.submit($('div#changeemailconfirm input:first').val(), function(errors) {
                     if (errors) {
                          $('#changeemailconfirm .error_pass').show();
                          $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
                          $('#saveEmailConfirm .loginIndicator').css('display','none');
                     } else {
                    	 $('#changeemailconfirm .error_pass').hide();
                    	 $.profilar.triggerEvent({
                             cheetah_sub: {aid: ''+SPI._settings.myprofile.profilar_newsletter_sub_aid, email: oldEmail, newemail: $.profilar.get('email')},
                             email: $.profilar.get('email')
                         }, function(eventId, errors) {                        
                        	 $('#saveEmailConfirm .loginIndicator').css('display','none');
                             SPI.flashMessage.set( SPI._langStrings.myprofile.email_saved );
                             SPI.reloadSite( SPI._settings.myprofile.pageurl );
                         });
                     }
                  }, ['email'] );
            }else{
              $('#changeemailconfirm .error_pass').show();
              $('#saveEmailConfirm .loginIndicator').css('display','none');
            };
          };
          
          
        var saveEmail = function(realSave){
          $('div#saveEmail span').unbind('click');
          emailtoTest = $('#f_email').val();
          validationInfo = validateEmail(emailtoTest);
          if(validationInfo.valid){
            $.profilar.isEmailAvailable( emailtoTest, function(available){
                if (available) {
                    $('.error_email_taken').hide();
                    $('.error_email').hide();
                    $('.correct_email').show();
                    if(realSave == true){
                    	$('form#basic,form#email,form#pass').hide();
                        $('div#changeemailconfirm').show();
                        $('div#changeemailconfirm input:first').focus();
                        $('#saveEmailConfirm span').click(function(){
                        	saveEmailConfirm();  
                        });
                    };
                } else {
                    $('.error_email_taken').show();
                    $('.error_email').hide();
                    $('img.error_email').show();
                    $('.correct_email').hide();
                }
            });
          }else{
            $('.error_email').show();
            $('.correct_email').hide();
          };
          $('div#saveEmail span').click(function(){saveEmail(true)});
          return false;
        };
        
        $('#f_email').focus(function(){
          $('.error_email').hide();  
        }).blur(function(){
          saveEmail(false);  
        });
        
        $('div#saveEmail span').click(function(){saveEmail(true)});
        
        var savePass = function(){
        	$('#pass .loginIndicator').css('display','inline');
        	$('div#savePass span').unbind('click');
        	passToTest = {old:$('#f_old_password').val(),password:$('#f_password').val(),repeat:$('#f_password_repeat').val()};
        	validationInfo = validatePass(passToTest)
        	if(validationInfo.valid){
        		$(validationInfo.isvalid).each(function(){
        			$('.correct_'+this).show();
        			$('.error_'+this).hide();
        		});
        		$.profilar.set('password', $('#f_password').val());
        		$.profilar.submit($('#f_old_password').val(), function(errors) {
	                if (errors) {
	                	$('#pass .loginIndicator').css('display','none');
	                	$('#f_old_password').unbind('focus',function(){
	                		$('#f_old_password').focus()
	                		$('.correct_old').hide()
	                	}).unbind('blur').focus();
	                    $('img.error_old').show(1,function(){
	                    	$('.error_oldpass').show();
	                    	$('#f_old_password').focus(function(){
	                            $('.error_old').hide();
	                            $('.correct_old').hide();
	                            $('.error_oldpass').hide();
	                          }).blur(function(){
	                        	  livecheckOld( $('#f_old_password').val()); 
	                          });
	                    	
	                    });
	                    $('div#savePass span').click(savePass);
	                } else {
	                	$('#pass .loginIndicator').css('display','none');
	                	SPI.flashMessage.set( SPI._langStrings.myprofile.password_saved);
	                    SPI.reloadSite( SPI._settings.myprofile.pageurl );
	                };
        		},['password']);
        	}else{
        		$(validationInfo.isvalid).each(function(){
                  $('.correct_'+this).show();
                  $('.error_'+this).hide();
                });
        		$(validationInfo.invalid).each(function(){
        			$('.correct_'+this).hide();
        			$('.error_'+this).show();
        			if (this == 'password_repeat'){
        				$('img.correct_same').hide();
        				$('img.error_same').show();  
        			};
        		});
        		$('div#savePass span').click(savePass);
        		$('#pass .loginIndicator').css('display','none');
        	};
        	return false;
        };
        $('div#savePass span').click(savePass);
        
        
        $('#f_old_password').focus(function(){
            $('.error_old').hide();
            $('.correct_old').hide();
          }).blur(function(){
        	  livecheckOld( $('#f_old_password').val()); 
          });
        
        $('#f_password').focus(function(){
            $('.error_password').hide();
            $('.correct_password').hide();
          }).blur(function(){
        	  livecheckPassword( $('#f_password').val()); 
        	  livecheckRepeat( $('#f_password_repeat').val()); 
          });
        
        $('#f_password_repeat').focus(function(){
            $('.error_password_repeat').hide();
            $('.correct_password_repeat').hide();
            $('.error_same').hide();
            $('.correct_same').hide();
          }).blur(function(){
        	  livecheckRepeat( $('#f_password_repeat').val()); 
          });
    
    // ENTER KEY LAUNCH
    $('input, select', $('#basic')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_basic').trigger('click'); }
    });
    $('input, select', $('#basic_confirmation')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_basic_confirmation').trigger('click'); }
        if(e.keyCode == 27) { $('a#cancel_basic_confirmation').trigger('click'); }
    });    
    $('input, select', $('#email')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_email').trigger('click'); }
    });
    $('input, select', $('#email_confirmation')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_email_confirmation').trigger('click'); }
        if(e.keyCode == 27) { $('a#cancel_email_confirmation').trigger('click'); }
    });
    $('input, select', $('#password')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_password').trigger('click'); }
    });

});
});

;/* rewritten COMPLETELY for girls by macic */

(function($) {
	$.prettyPhoto = {version: '2.5.3'};

	$.fn.prettyPhoto = function(settings) {
        var isIE6 = $.browser.msie && ($.browser.version.substr(0,1)<7);

		settings = jQuery.extend({
			animationSpeed: 'fast', /* fast/slow/normal */
			padding: 30, /* padding for each side of the picture */
			opacity: 0.8, /* Value between 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
            timeout: 7000,
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square */
			hideflash: true, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			modal: false, /* If set to true, only the close button will close the window */
			changepicturecallback: function(){
                /**************/
                // REPORT BUTTON
                /*************/
                if($("#ruser").text()== $.profilar.forService().username) {
                    $('.report').hide();
                } else {
                    $('.report').show();
                }
                /**************/
                // COMMENTS
                /**************/
                var text = $("#pp_full_res img").attr('src');
                var regexp = /^.*\//gi;
                var itemid = text.replace(regexp, "");
                $.ajax({
                    cache: true,
                    url: SPI.sprintf(settings.comments_url, settings.site_id, itemid),
                    data: {
                       authenticated: '1',
                       pagesize: 1,
                       reported_limit: 100,
                       outputtype: 'json'
                    },
                    dataType: 'json',
                    global: false,
                    timeout: settings.timeout,
                    type: 'GET',
                    error: function(data){console.log('Cant fetch commments for that item.',data);},
                    success: function(data){
                        $(".gp_comments").text(sprintf($(".gp_comments").text(), data.commentar.total));
                        /**************/
                        // RATING
                        /**************/
                        var temprat = $("#pic_rating_"+itemid).text();
                        var ratingValue = (parseInt(temprat)) * 14;
                        $("a#pic-rating-display span.hearts3").css('background-position','right -'+(ratingValue)+'px');
                        $("#pic-rating").pRating({
                            siteid: settings.site_id,
                            gameid: parseInt(itemid),
                            itemtype: 10, // 10 = UGC
                            visibility: 1, // hide with css visibility not css display
                            buttonLike: '#i-like-this-pic',
                            buttonDontLike: '#i-dont-like-this-pic',
                            buttonRatingHearts: '#pic-rating-display',
                            buttonThanks: '#pic-rating',
                            langstrings: {
                                ilikeit: settings.inclusion_ilikepic,
                                ihateit: settings.inclusion_idontlikepic,
                                thanks: settings.inclusion_rating_thanks
                            }
                    }).css('visibility','visible');
                    }
                });
            }, /* Called everytime an item is shown/changed */
			callback: function(){}, /* Called when prettyPhoto is closed */
            inclusion_closebutton: 'Close',
            inclusion_byauthor: 'By',
            inclusion_your_rating: 'Your rating?',
            inclusion_ilikepic: 'I like this pic!',
            inclusion_idontlikepic: "I dont like this pic!",
            inclusion_areyousure: "Are you sure you want to report this?",
            inclusion_comments: '%s comments',
            channel_id: 4
		}, settings);

		// Fallback to a supported theme for IE6
		if($.browser.msie && $.browser.version == 6){
			settings.theme = "light_square";
		}

		if($('.pp_overlay').size() == 0) {
			_buildOverlay(); // If the overlay is not there, inject it!
		}else{
			// Set my global selectors
			$pp_pic_holder = $('.pp_pic_holder');
			$ppt = $('.ppt');
		}

		// Global variables accessible only by prettyPhoto
		var doresize = true, percentBased = false, correctSizes,

		// Cached selectors
		$pp_pic_holder, $ppt, settings,

		// prettyPhoto container specific
		pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth, pp_type = 'image',

		//Gallery specific
		setPosition = 0,

		// Global elements
		$scrollPos = _getScroll();

		// Window/Keyboard events
		$(window).scroll(function(){ $scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay();});

        if (!isIE6) {
            //on IE6 it causes infinity loop
            $(window).resize(function(){ _centerOverlay(); _resizeOverlay(); });
        }

		$(document).keydown(function(e){
			if($pp_pic_holder.is(':visible'))
			switch(e.keyCode){
				/*case 37:
					$.prettyPhoto.changePage('previous');
					break;
				case 39:
					$.prettyPhoto.changePage('next');
					break;*/
				case 27:
					if(!settings.modal)
					$.prettyPhoto.close();
					break;
			};
	    });

		// Bind the code to each links
		$(this).each(function(){
			$(this).bind('click',function(){

				link = this; // Fix scoping

				// Find out if the picture is part of a set
				theRel = $(this).attr('rel');
				galleryRegExp = /\[(?:.*)\]/;
				theGallery = galleryRegExp.exec(theRel);

				// Build the gallery array
				// @TODO @FIXME macic - THIS SHITE NEEDS TO BE AN TEMPLATE FFS
				var images = new Array(), titles = new Array(), descriptions = new Array();
				if(theGallery){
					$('a[rel*='+theGallery+']').each(function(i){
						if($(this)[0] === $(link)[0]) setPosition = i; // Get the position in the set
						images.push($(this).attr('href'));
						titles.push($(this).find('img').attr('alt'));
                        if(!settings.onlyTitle) {
                            var addText =
                            $(this).parents().filter('li').find('.tooltipTitle').text()
                            + '<br/>'
                            + SPI.sprintf(settings.inclusion_byauthor, ' <a id="ruser" href="' + settings.userprofilelink +'?username=' + $(this).parents().filter('li').find('.tooltipUsername').text() + '">' + $(this).parents().filter('li').find('.tooltipUsername').text() + '</a>')
                            + ' <img class="report" alt="" src="/img/userprofile/ico_report.png"/><br/>'
                            + '<span class="gp_comments">'+ settings.inclusion_nrofcomments + '</span>'
                            + '<div id="pic-rating" style="margin: 0 auto; text-align: center; width: 340px;">'
                            + '<span class="middle yourrat"><strong>' + settings.inclusion_your_rating + '</strong></span>'
                            + '<div class="pic-button-space-left">'
                            + '<a href="#" id="i-like-this-pic">'
                            + '<span class="right"/>'
                            + '<span class="middle">' + settings.inclusion_ilikepic +'<span class="minwidth"/></span>'
                            + '<span class="left"/>'
                            + '</a>'
                            + '</div>'
                            + '<div class="pic-button-space-right">'
                            + '<a href="#" id="i-dont-like-this-pic">'
                            + '<span class="left"/>'
                            + '<span class="middle">' + settings.inclusion_idontlikepic +'<span class="minwidth"/></span>'
                            + '<span class="right"/>'
                            + '</a>'
                            + '</div>'
                            + '<a id="pic-rating-display" class="pic-rating-hidden" href="#">'
                            + '<span class="dtooltipRating" style="padding-top: 7px;"><span class="hearts3 heartsgamepage" style="background-position: right -0px; width: 150px !important;">'+ settings.inclusion_average_rating +':</span></span>'
                            + '</a>'

                            + '</div>';
                        } else {
                            var addText=settings.onlyTitleValue;
                        }
						descriptions.push(
                            addText
                        );
					});
				}else{
					images = $(this).attr('href');
					titles = ($(this).find('img').attr('alt')) ?  $(this).find('img').attr('alt') : '';
					descriptions = ($(this).attr('title')) ?  $(this).attr('title') : '';
				}

				$.prettyPhoto.open(images,titles,descriptions);
				return false;
			});
		});


		/**
		* Opens the prettyPhoto modal box.
		* @param image {String,Array} Full path to the image to be open, can also be an array containing full images paths.
		* @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
		* @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions.
		*/
		$.prettyPhoto.open = function(gallery_images,gallery_titles,gallery_descriptions) {
			// To fix the bug with IE select boxes
			if($.browser.msie && $.browser.version == 6){
				$('select').css('visibility','hidden');
			};

			// Hide the flash
			if(settings.hideflash) $('object,embed').css('visibility','hidden');

			// Convert everything to an array in the case it's a single item
			images = $.makeArray(gallery_images);
			titles = $.makeArray(gallery_titles);
			descriptions = $.makeArray(gallery_descriptions);

			if($('.pp_overlay').size() == 0) {
				_buildOverlay(); // If the overlay is not there, inject it!
			}else{
				// Set my global selectors
				$pp_pic_holder = $('.pp_pic_holder');
				$ppt = $('.ppt');
			}

			$pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme

			isSet = ($(images).size() > 0) ?  true : false; // Find out if it's a set
			_getFileType(images[setPosition]); // Set the proper file type

			_centerOverlay(); // Center it

			// Hide the next/previous links if on first or last images.
			_checkPosition($(images).size());

			$('.pp_loaderIcon').show(); // Do I need to explain?

			// Fade the content in
			$('div.pp_overlay').show().fadeTo(settings.animationSpeed,settings.opacity, function(){
				$pp_pic_holder.fadeIn(settings.animationSpeed,function(){
					// Display the current position
					$pp_pic_holder.find('p.currentTextHolder').text((setPosition+1) + settings.counter_separator_label + $(images).size());

					// Set the description
					if(descriptions[setPosition]){
						$pp_pic_holder.find('.pp_description').show().html(unescape(descriptions[setPosition]));
					}else{
						$pp_pic_holder.find('.pp_description').hide().text('');
					};

					// Set the title
					if(titles[setPosition] && settings.showTitle){
						hasTitle = true;
						$ppt.html(unescape(titles[setPosition]));
					}else{
						hasTitle = false;
					};

					// Inject the proper content
					if(pp_type == 'image'){
						// Set the new image
						imgPreloader = new Image();

						// Preload the neighbour images
						nextImage = new Image();
						if(isSet && setPosition > $(images).size()) nextImage.src = images[setPosition + 1];
						prevImage = new Image();
						if(isSet && images[setPosition - 1]) prevImage.src = images[setPosition - 1];

						pp_typeMarkup = '<img id="fullResImage" src="" />';
						$pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;

						$pp_pic_holder.find('.pp_content').css('overflow','hidden');
						$pp_pic_holder.find('#fullResImage').attr('src',images[setPosition]);

						imgPreloader.onload = function(){
							// Fit item to viewport
							correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);

							_showContent();
						};

						imgPreloader.src = images[setPosition];
					}else{
						// Get the dimensions
						movie_width = ( parseFloat(grab_param('width',images[setPosition])) ) ? grab_param('width',images[setPosition]) : "425";
						movie_height = ( parseFloat(grab_param('height',images[setPosition])) ) ? grab_param('height',images[setPosition]) : "344";

						// If the size is % based, calculate according to window dimensions
						if(movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1){
							movie_height = ($(window).height() * parseFloat(movie_height) / 100) - 100;
							movie_width = ($(window).width() * parseFloat(movie_width) / 100) - 100;
							percentBased = true;
						}

						movie_height = parseFloat(movie_height);
						movie_width = parseFloat(movie_width);

						if(pp_type == 'quicktime') movie_height+=15; // Add space for the control bar

						// Fit item to viewport
						correctSizes = _fitToViewport(movie_width,movie_height);

						if(pp_type == 'youtube'){
							pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.youtube.com/v/'+grab_param('v',images[setPosition])+'" /><embed src="http://www.youtube.com/v/'+grab_param('v',images[setPosition])+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
						}else if(pp_type == 'quicktime'){
							pp_typeMarkup = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'"><param name="src" value="'+images[setPosition]+'"><param name="autoplay" value="true"><param name="type" value="video/quicktime"><embed src="'+images[setPosition]+'" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'" autoplay="true" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>';
						}else if(pp_type == 'flash'){
							flash_vars = images[setPosition];
							flash_vars = flash_vars.substring(images[setPosition].indexOf('flashvars') + 10,images[setPosition].length);

							filename = images[setPosition];
							filename = filename.substring(0,filename.indexOf('?'));

							pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+filename+'?'+flash_vars+'" /><embed src="'+filename+'?'+flash_vars+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
						}else if(pp_type == 'iframe'){
							movie_url = images[setPosition];
							movie_url = movie_url.substr(0,movie_url.indexOf('iframe')-1);

							pp_typeMarkup = '<iframe src ="'+movie_url+'" width="'+(correctSizes['width']-10)+'" height="'+(correctSizes['height']-10)+'" frameborder="no"></iframe>';
						}

						// Show content
						_showContent();
					}
				});
			});
		};

		/**
		* Change page in the prettyPhoto modal box
		* @param direction {String} Direction of the paging, previous or next.
		*/
		$.prettyPhoto.changePage = function(direction){
			if(direction == 'previous') {
				setPosition--;
				if (setPosition < 0){
					setPosition = 0;
					return;
				}
			}else{
				if($('.pp_arrow_next').is('.disabled')) return;
				setPosition++;
			};

			// Allow the resizing of the images
			if(!doresize) doresize = true;

			_hideContent();
			$('a.pp_expand,a.pp_contract').fadeOut(settings.animationSpeed,function(){
				$(this).removeClass('pp_contract').addClass('pp_expand');
				$.prettyPhoto.open(images,titles,descriptions);
			});
		};

		/**
		* Closes the prettyPhoto modal box.
		*/
		$.prettyPhoto.close = function(){
			$pp_pic_holder.find('object,embed').css('visibility','hidden');

			$('div.pp_pic_holder,div.ppt').fadeOut(settings.animationSpeed);

			$('div.pp_overlay').fadeOut(settings.animationSpeed, function(){
				$('div.pp_overlay,div.pp_pic_holder,div.ppt').remove();

				// To fix the bug with IE select boxes
				if($.browser.msie && $.browser.version == 6){
					$('select').css('visibility','visible');
				};

				// Show the flash
				if(settings.hideflash) $('object,embed').css('visibility','visible');

				setPosition = 0;

				settings.callback();
			});

			doresize = true;
		};

		/**
		* Set the proper sizes on the containers and animate the content in.
		*/
		_showContent = function(){
			$('.pp_loaderIcon').hide();

			if($.browser.opera) {
				windowHeight = window.innerHeight;
				windowWidth = window.innerWidth;
			}else{
				windowHeight = $(window).height();
				windowWidth = $(window).width();
			};

			// Calculate the opened top position of the pic holder
			projectedTop = $scrollPos['scrollTop'] + ((windowHeight/2) - (correctSizes['containerHeight']/2));
			if(projectedTop < 0) projectedTop = 0 + $pp_pic_holder.find('.ppt').height();

			// Resize the content holder
			$pp_pic_holder.find('.pp_content').animate({'height':correctSizes['contentHeight']},settings.animationSpeed);

			// Resize picture the holder
			$pp_pic_holder.animate({
				'top': projectedTop,
				'left': ((windowWidth/2) - (correctSizes['containerWidth']/2)),
				'width': correctSizes['containerWidth']
			},settings.animationSpeed,function(){
				$pp_pic_holder.width(correctSizes['containerWidth']);
				/*$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']);*/
                $pp_pic_holder.find('#fullResImage').height(correctSizes['height']).width(correctSizes['width']);
                $pp_pic_holder.find('.pp_hoverContainer').height(correctSizes['height']).width(Math.max(336,correctSizes['width']));
				// Fade the new image
				$pp_pic_holder.find('#pp_full_res').fadeIn(settings.animationSpeed);

				// Show the nav
				if(isSet && pp_type=="image") { $pp_pic_holder.find('.pp_hoverContainer').fadeIn(settings.animationSpeed); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }
				$pp_pic_holder.find('.pp_details').fadeIn(settings.animationSpeed);

				// Show the title
				if(settings.showTitle && hasTitle){
					$ppt.css({
						'top' : $pp_pic_holder.offset().top - 20,
						'left' : $pp_pic_holder.offset().left + (settings.padding/2),
						'display' : 'none'
					});

					$ppt.fadeIn(settings.animationSpeed);
				};

				// Fade the resizing link if the image is resized
				if(correctSizes['resized']) $('a.pp_expand,a.pp_contract').fadeIn(settings.animationSpeed);

				// Once everything is done, inject the content if it's now a photo
				if(pp_type != 'image') $pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;

				// Callback!
				settings.changepicturecallback();
			});
		};

		/**
		* Hide the content...DUH!
		*/
		function _hideContent(){
			// Fade out the current picture
			$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
			$pp_pic_holder.find('.pp_hoverContainer,.pp_details').fadeOut(settings.animationSpeed);
			$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
				$('.pp_loaderIcon').show();
			});

			// Hide the title
			$ppt.fadeOut(settings.animationSpeed);
		}

		/**
		* Check the item position in the gallery array, hide or show the navigation links
		* @param setCount {integer} The total number of items in the set
		*/
		function _checkPosition(setCount){
			// If at the end, hide the next link
			if(setPosition == setCount-1) {
				$pp_pic_holder.find('a.pp_next').css('visibility','hidden');
				$pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
			}else{
				$pp_pic_holder.find('a.pp_next').css('visibility','visible');
				$pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',function(){
					$.prettyPhoto.changePage('next');
					return false;
				});
			};

			// If at the beginning, hide the previous link
			if(setPosition == 0) {
				$pp_pic_holder.find('a.pp_previous').css('visibility','hidden');
				$pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
			}else{
				$pp_pic_holder.find('a.pp_previous').css('visibility','visible');
				$pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',function(){
					$.prettyPhoto.changePage('previous');
					return false;
				});
			};

			// Hide the bottom nav if it's not a set.
			if(setCount > 1) {
				$('.pp_nav').show();
			}else{
				$('.pp_nav').hide();
			}
		};

		/**
		* Resize the item dimensions if it's bigger than the viewport
		* @param width {integer} Width of the item to be opened
		* @param height {integer} Height of the item to be opened
		* @return An array containin the "fitted" dimensions
		*/
		function _fitToViewport(width,height){
			hasBeenResized = false;

			_getDimensions(width,height);

			// Define them in case there's no resize needed
			imageWidth = width;
			imageHeight = height;

			windowHeight = $(window).height();
			windowWidth = $(window).width();

			if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
				hasBeenResized = true;
				notFitting = true;

				while (notFitting){
					if((pp_containerWidth > windowWidth)){
						imageWidth = (windowWidth - 200);
						imageHeight = (height/width) * imageWidth;
					}else if((pp_containerHeight > windowHeight)){
						imageHeight = (windowHeight - 200);
						imageWidth = (width/height) * imageHeight;
					}else{
						notFitting = false;
					};

					pp_containerHeight = imageHeight;
					pp_containerWidth = imageWidth;
				};

				_getDimensions(imageWidth,imageHeight);
			};

			return {
				width:imageWidth,
				height:imageHeight,
				containerHeight:pp_containerHeight,
				containerWidth:Math.max(346,pp_containerWidth),
				contentHeight:pp_contentHeight,
				contentWidth:pp_contentWidth,
				resized:hasBeenResized
			};
		};

		/**
		* Get the containers dimensions according to the item size
		* @param width {integer} Width of the item to be opened
		* @param height {integer} Height of the item to be opened
		*/
		function _getDimensions(width,height){
			$pp_pic_holder.find('.pp_details').width(Math.max(346,width)).find('.pp_description').width(Math.max(346,width)); /* To have the correct height */
			// Get the container size, to resize the holder to the right dimensions
			pp_contentHeight = height + $pp_pic_holder.find('.pp_details').height() + parseFloat($pp_pic_holder.find('.pp_details').css('marginTop')) + parseFloat($pp_pic_holder.find('.pp_details').css('marginBottom'));
			pp_contentWidth = width;
			pp_containerHeight = pp_contentHeight + $pp_pic_holder.find('.ppt').height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
			pp_containerWidth = width + settings.padding;
		}

		function _getFileType(itemSrc){
			if (itemSrc.match(/youtube\.com\/watch/i)) {
				pp_type = 'youtube';
			}else if(itemSrc.indexOf('.mov') != -1){
				pp_type = 'quicktime';
			}else if(itemSrc.indexOf('.swf') != -1){
				pp_type = 'flash';
			}else if(itemSrc.indexOf('iframe') != -1){
				pp_type = 'iframe'
			}else{
				pp_type = 'image';
			};
		};

		function _centerOverlay(){
			if($.browser.opera) {
				windowHeight = window.innerHeight;
				windowWidth = window.innerWidth;
			}else{
				windowHeight = $(window).height();
				windowWidth = $(window).width();
			};

			if(doresize) {
				$pHeight = $pp_pic_holder.height();
				$pWidth = $pp_pic_holder.width();
				$tHeight = $ppt.height();

				projectedTop = (windowHeight/2) + $scrollPos['scrollTop'] - ($pHeight/2);
				if(projectedTop < 0) projectedTop = 0 + $tHeight;

				$pp_pic_holder.css({
					'top': projectedTop,
					'left': (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2)
				});

				$ppt.css({
					'top' : projectedTop - $tHeight,
					'left' : (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2) + (settings.padding/2)
				});
			};
		};

		function _getScroll(){
			if (self.pageYOffset) {
				scrollTop = self.pageYOffset;
				scrollLeft = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
				scrollTop = document.documentElement.scrollTop;
				scrollLeft = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				scrollTop = document.body.scrollTop;
				scrollLeft = document.body.scrollLeft;
			}

			return {scrollTop:scrollTop,scrollLeft:scrollLeft};
		};

		function _resizeOverlay() {
			$('div.pp_overlay').css({
				'height':$(document).height(),
				'width':$(window).width()
			});
		};

		function _buildOverlay(){
			toInject = "";

			// Build the background overlay div
			toInject += "<div class='pp_overlay'></div>";

			// Basic HTML for the picture holder
			toInject += '<div class="pp_pic_holder"><a href="#" class="new_close">'+settings.inclusion_closebutton+'</a><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content"><a href="#" class="pp_expand" title="Expand the image">Expand</a><div class="pp_loaderIcon"></div><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res"></div><div class="pp_details clearfix"><p class="pp_description"></p></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div>';

			// Basic html for the title holder
			toInject += '<div class="ppt"></div>';

			$('body').append(toInject);

			// So it fades nicely
			$('div.pp_overlay').css('opacity',0);

			// Set my global selectors
			$pp_pic_holder = $('.pp_pic_holder');
			$ppt = $('.ppt');

			$('div.pp_overlay').css('height',$(document).height()).hide().bind('click',function(){
				if(!settings.modal)
				$.prettyPhoto.close();
			});

			$('a.new_close').bind('click',function(){ $.prettyPhoto.close(); return false; });

            // report picture
            $('img.report').live('mouseover', function(){
                    $(this).attr('src','/img/userprofile/ico_report_hover.png');
                }).live('mouseout', function(){
                    $(this).attr('src','/img/userprofile/ico_report.png');
                }).live('click', function(){
                    var confirmed = window.confirm(settings.inclusion_areyousure);
                    if(confirmed) {
                        var text = $("#pp_full_res img").attr('src');
                        var regexp = /^.*\//gi;
                        var itemid = text.replace(regexp, "");
                        var reporteduser = $("#ruser").text();

                        var postData = {
                            username: '',
                            hash: '',
                            outputtype: 'json',
                            reporttype: 'ugc',
                            reporteduser: reporteduser
                        };

                        if ($.profilar.loggedIn()) {
                            postData.username = $.profilar.forService().username;
                            postData.hash = $.profilar.forService().hash;
                        }

                        var what_to_report=SPI.sprintf(settings.reportar_url, settings.site_id, itemid);
                        $.ajax({
                            url: what_to_report,
                            data: postData,
                            global: false,
                            timeout: settings.timeout,
                            type: 'POST',
                            success: function(data) {
                                alert(settings.inclusion_reportar_success);
                            },
                            error: function(data) {
                            }
                        });
                }
           });

			$('a.pp_expand').bind('click',function(){
				$this = $(this); // Fix scoping

				// Expand the image
				if($this.hasClass('pp_expand')){
					$this.removeClass('pp_expand').addClass('pp_contract');
					doresize = false;
				}else{
					$this.removeClass('pp_contract').addClass('pp_expand');
					doresize = true;
				};

				_hideContent();

				$pp_pic_holder.find('.pp_hoverContainer, .pp_details').fadeOut(settings.animationSpeed);
				$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
					$.prettyPhoto.open(images,titles,descriptions);
				});

				return false;
			});

			$pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click',function(){
				$.prettyPhoto.changePage('previous');
				return false;
			});

			$pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click',function(){
				$.prettyPhoto.changePage('next');
				return false;
			});

			$pp_pic_holder.find('.pp_hoverContainer').css({
				'margin-left': settings.padding/2
			});
		};
	};

	function grab_param(name,url){
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
})(jQuery);

;                                                               /* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 88 2009-12-31 16:24:03Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *								topCapHeight	-	The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *								bottomCapHeight	-	The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 *								observeHash		-	Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			var paneEle = this;
			var currentScrollPosition = 0;
			var paneWidth;
			var paneHeight;
			var trackHeight;
			var trackOffset = settings.topCapHeight;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				paneWidth = $c.innerWidth();
				paneHeight = $c.outerHeight();
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
				$this.css({'top':0});
			} else {
				$this.data('originalStyleTag', $this.attr('style'));
				// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
				$this.css('overflow', 'hidden');
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				paneWidth = $this.innerWidth();
				paneHeight = $this.innerHeight();
				var $container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				$this.wrap($container);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			trackHeight = paneHeight;
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					),
					$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowUp', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'top':settings.topCapHeight + 'px'
									}
								)
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowDown', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'bottom':settings.bottomCapHeight + 'px'
									}
								)
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
				}
				
				if (settings.arrowSize) {
					trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
					trackOffset += settings.arrowSize;
				} else if ($upArrow) {
					var topArrowHeight = $upArrow.height();
					settings.arrowSize = topArrowHeight;
					trackHeight = paneHeight - topArrowHeight - $downArrow.height();
					trackOffset += topArrowHeight;
				}
				trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
				$track.css({'height': trackHeight+'px', top:trackOffset+'px'})
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					$container.scrollTop(0);
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						$container.scrollTop(0);
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (settings.observeHash) {
					if (location.hash && location.hash.length > 1) {
						setTimeout(function(){
							scrollTo(location.hash);
						}, $.browser.safari ? 100 : 0);
					}
					
					// use event delegation to listen for all clicks on links and hijack them if they are links to
					// anchors within our content...
					$(document).bind('click', function(e){
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function(){
									scrollTo(h, !settings.animateToInternalLinks);
								}, $.browser.safari ? 100 : 0);
							}
						}
					});
				}
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$this.attr('style', $this.data('originalStyleTag'));
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	topCapHeight: 0,
	bottomCapHeight: 0,
	observeHash: true
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);
;/*
 * jQuery UI Effects 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/Effects/
 */
jQuery.effects||(function(d){d.effects={version:"1.7.2",save:function(g,h){for(var f=0;f<h.length;f++){if(h[f]!==null){g.data("ec.storage."+h[f],g[0].style[h[f]])}}},restore:function(g,h){for(var f=0;f<h.length;f++){if(h[f]!==null){g.css(h[f],g.data("ec.storage."+h[f]))}}},setMode:function(f,g){if(g=="toggle"){g=f.is(":hidden")?"show":"hide"}return g},getBaseline:function(g,h){var i,f;switch(g[0]){case"top":i=0;break;case"middle":i=0.5;break;case"bottom":i=1;break;default:i=g[0]/h.height}switch(g[1]){case"left":f=0;break;case"center":f=0.5;break;case"right":f=1;break;default:f=g[1]/h.width}return{x:f,y:i}},createWrapper:function(f){if(f.parent().is(".ui-effects-wrapper")){return f.parent()}var g={width:f.outerWidth(true),height:f.outerHeight(true),"float":f.css("float")};f.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');var j=f.parent();if(f.css("position")=="static"){j.css({position:"relative"});f.css({position:"relative"})}else{var i=f.css("top");if(isNaN(parseInt(i,10))){i="auto"}var h=f.css("left");if(isNaN(parseInt(h,10))){h="auto"}j.css({position:f.css("position"),top:i,left:h,zIndex:f.css("z-index")}).show();f.css({position:"relative",top:0,left:0})}j.css(g);return j},removeWrapper:function(f){if(f.parent().is(".ui-effects-wrapper")){return f.parent().replaceWith(f)}return f},setTransition:function(g,i,f,h){h=h||{};d.each(i,function(k,j){unit=g.cssUnit(j);if(unit[0]>0){h[j]=unit[0]*f+unit[1]}});return h},animateClass:function(h,i,k,j){var f=(typeof k=="function"?k:(j?j:null));var g=(typeof k=="string"?k:null);return this.each(function(){var q={};var o=d(this);var p=o.attr("style")||"";if(typeof p=="object"){p=p.cssText}if(h.toggle){o.hasClass(h.toggle)?h.remove=h.toggle:h.add=h.toggle}var l=d.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(h.add){o.addClass(h.add)}if(h.remove){o.removeClass(h.remove)}var m=d.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(h.add){o.removeClass(h.add)}if(h.remove){o.addClass(h.remove)}for(var r in m){if(typeof m[r]!="function"&&m[r]&&r.indexOf("Moz")==-1&&r.indexOf("length")==-1&&m[r]!=l[r]&&(r.match(/color/i)||(!r.match(/color/i)&&!isNaN(parseInt(m[r],10))))&&(l.position!="static"||(l.position=="static"&&!r.match(/left|top|bottom|right/)))){q[r]=m[r]}}o.animate(q,i,g,function(){if(typeof d(this).attr("style")=="object"){d(this).attr("style")["cssText"]="";d(this).attr("style")["cssText"]=p}else{d(this).attr("style",p)}if(h.add){d(this).addClass(h.add)}if(h.remove){d(this).removeClass(h.remove)}if(f){f.apply(this,arguments)}})})}};function c(g,f){var i=g[1]&&g[1].constructor==Object?g[1]:{};if(f){i.mode=f}var h=g[1]&&g[1].constructor!=Object?g[1]:(i.duration?i.duration:g[2]);h=d.fx.off?0:typeof h==="number"?h:d.fx.speeds[h]||d.fx.speeds._default;var j=i.callback||(d.isFunction(g[1])&&g[1])||(d.isFunction(g[2])&&g[2])||(d.isFunction(g[3])&&g[3]);return[g[0],i,h,j]}d.fn.extend({_show:d.fn.show,_hide:d.fn.hide,__toggle:d.fn.toggle,_addClass:d.fn.addClass,_removeClass:d.fn.removeClass,_toggleClass:d.fn.toggleClass,effect:function(g,f,h,i){return d.effects[g]?d.effects[g].call(this,{method:g,options:f||{},duration:h,callback:i}):null},show:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))){return this._show.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"show"))}},hide:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))){return this._hide.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"hide"))}},toggle:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))||(d.isFunction(arguments[0])||typeof arguments[0]=="boolean")){return this.__toggle.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"toggle"))}},addClass:function(g,f,i,h){return f?d.effects.animateClass.apply(this,[{add:g},f,i,h]):this._addClass(g)},removeClass:function(g,f,i,h){return f?d.effects.animateClass.apply(this,[{remove:g},f,i,h]):this._removeClass(g)},toggleClass:function(g,f,i,h){return((typeof f!=="boolean")&&f)?d.effects.animateClass.apply(this,[{toggle:g},f,i,h]):this._toggleClass(g,f)},morph:function(f,h,g,j,i){return d.effects.animateClass.apply(this,[{add:h,remove:f},g,j,i])},switchClass:function(){return this.morph.apply(this,arguments)},cssUnit:function(f){var g=this.css(f),h=[];d.each(["em","px","%","pt"],function(j,k){if(g.indexOf(k)>0){h=[parseFloat(g),k]}});return h}});d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(g,f){d.fx.step[f]=function(h){if(h.state==0){h.start=e(h.elem,f);h.end=b(h.end)}h.elem.style[f]="rgb("+[Math.max(Math.min(parseInt((h.pos*(h.end[0]-h.start[0]))+h.start[0],10),255),0),Math.max(Math.min(parseInt((h.pos*(h.end[1]-h.start[1]))+h.start[1],10),255),0),Math.max(Math.min(parseInt((h.pos*(h.end[2]-h.start[2]))+h.start[2],10),255),0)].join(",")+")"}});function b(g){var f;if(g&&g.constructor==Array&&g.length==3){return g}if(f=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(g)){return[parseInt(f[1],10),parseInt(f[2],10),parseInt(f[3],10)]}if(f=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(g)){return[parseFloat(f[1])*2.55,parseFloat(f[2])*2.55,parseFloat(f[3])*2.55]}if(f=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(g)){return[parseInt(f[1],16),parseInt(f[2],16),parseInt(f[3],16)]}if(f=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(g)){return[parseInt(f[1]+f[1],16),parseInt(f[2]+f[2],16),parseInt(f[3]+f[3],16)]}if(f=/rgba\(0, 0, 0, 0\)/.exec(g)){return a.transparent}return a[d.trim(g).toLowerCase()]}function e(h,f){var g;do{g=d.curCSS(h,f);if(g!=""&&g!="transparent"||d.nodeName(h,"body")){break}f="backgroundColor"}while(h=h.parentNode);return b(g)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};d.easing.jswing=d.easing.swing;d.extend(d.easing,{def:"easeOutQuad",swing:function(g,h,f,j,i){return d.easing[d.easing.def](g,h,f,j,i)},easeInQuad:function(g,h,f,j,i){return j*(h/=i)*h+f},easeOutQuad:function(g,h,f,j,i){return -j*(h/=i)*(h-2)+f},easeInOutQuad:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h+f}return -j/2*((--h)*(h-2)-1)+f},easeInCubic:function(g,h,f,j,i){return j*(h/=i)*h*h+f},easeOutCubic:function(g,h,f,j,i){return j*((h=h/i-1)*h*h+1)+f},easeInOutCubic:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h+f}return j/2*((h-=2)*h*h+2)+f},easeInQuart:function(g,h,f,j,i){return j*(h/=i)*h*h*h+f},easeOutQuart:function(g,h,f,j,i){return -j*((h=h/i-1)*h*h*h-1)+f},easeInOutQuart:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h*h+f}return -j/2*((h-=2)*h*h*h-2)+f},easeInQuint:function(g,h,f,j,i){return j*(h/=i)*h*h*h*h+f},easeOutQuint:function(g,h,f,j,i){return j*((h=h/i-1)*h*h*h*h+1)+f},easeInOutQuint:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h*h*h+f}return j/2*((h-=2)*h*h*h*h+2)+f},easeInSine:function(g,h,f,j,i){return -j*Math.cos(h/i*(Math.PI/2))+j+f},easeOutSine:function(g,h,f,j,i){return j*Math.sin(h/i*(Math.PI/2))+f},easeInOutSine:function(g,h,f,j,i){return -j/2*(Math.cos(Math.PI*h/i)-1)+f},easeInExpo:function(g,h,f,j,i){return(h==0)?f:j*Math.pow(2,10*(h/i-1))+f},easeOutExpo:function(g,h,f,j,i){return(h==i)?f+j:j*(-Math.pow(2,-10*h/i)+1)+f},easeInOutExpo:function(g,h,f,j,i){if(h==0){return f}if(h==i){return f+j}if((h/=i/2)<1){return j/2*Math.pow(2,10*(h-1))+f}return j/2*(-Math.pow(2,-10*--h)+2)+f},easeInCirc:function(g,h,f,j,i){return -j*(Math.sqrt(1-(h/=i)*h)-1)+f},easeOutCirc:function(g,h,f,j,i){return j*Math.sqrt(1-(h=h/i-1)*h)+f},easeInOutCirc:function(g,h,f,j,i){if((h/=i/2)<1){return -j/2*(Math.sqrt(1-h*h)-1)+f}return j/2*(Math.sqrt(1-(h-=2)*h)+1)+f},easeInElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l)==1){return f+m}if(!k){k=l*0.3}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}return -(h*Math.pow(2,10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k))+f},easeOutElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l)==1){return f+m}if(!k){k=l*0.3}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}return h*Math.pow(2,-10*i)*Math.sin((i*l-j)*(2*Math.PI)/k)+m+f},easeInOutElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l/2)==2){return f+m}if(!k){k=l*(0.3*1.5)}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}if(i<1){return -0.5*(h*Math.pow(2,10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k))+f}return h*Math.pow(2,-10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k)*0.5+m+f},easeInBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}return k*(h/=j)*h*((i+1)*h-i)+f},easeOutBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}return k*((h=h/j-1)*h*((i+1)*h+i)+1)+f},easeInOutBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}if((h/=j/2)<1){return k/2*(h*h*(((i*=(1.525))+1)*h-i))+f}return k/2*((h-=2)*h*(((i*=(1.525))+1)*h+i)+2)+f},easeInBounce:function(g,h,f,j,i){return j-d.easing.easeOutBounce(g,i-h,0,j,i)+f},easeOutBounce:function(g,h,f,j,i){if((h/=i)<(1/2.75)){return j*(7.5625*h*h)+f}else{if(h<(2/2.75)){return j*(7.5625*(h-=(1.5/2.75))*h+0.75)+f}else{if(h<(2.5/2.75)){return j*(7.5625*(h-=(2.25/2.75))*h+0.9375)+f}else{return j*(7.5625*(h-=(2.625/2.75))*h+0.984375)+f}}}},easeInOutBounce:function(g,h,f,j,i){if(h<i/2){return d.easing.easeInBounce(g,h*2,0,j,i)*0.5+f}return d.easing.easeOutBounce(g,h*2-i,0,j,i)*0.5+j*0.5+f}})})(jQuery);;/*
 * jQuery UI Effects Pulsate 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/Effects/Pulsate
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.pulsate=function(b){return this.queue(function(){var d=a(this);var g=a.effects.setMode(d,b.options.mode||"show");var f=b.options.times||5;var e=b.duration?b.duration/2:a.fx.speeds._default/2;if(g=="hide"){f--}if(d.is(":hidden")){d.css("opacity",0);d.show();d.animate({opacity:1},e,b.options.easing);f=f-2}for(var c=0;c<f;c++){d.animate({opacity:0},e,b.options.easing).animate({opacity:1},e,b.options.easing)}if(g=="hide"){d.animate({opacity:0},e,b.options.easing,function(){d.hide();if(b.callback){b.callback.apply(this,arguments)}})}else{d.animate({opacity:0},e,b.options.easing).animate({opacity:1},e,b.options.easing,function(){if(b.callback){b.callback.apply(this,arguments)}})}d.queue("fx",function(){d.dequeue()});d.dequeue()})}})(jQuery);;
;/*
* jQuery RTE plugin 0.5.1 - create a rich text form for Mozilla, Opera, Safari and Internet Explorer
*
* Copyright (c) 2009 Batiste Bieler
* Distributed under the GPL Licenses.
* Distributed under the MIT License.
*/
// define the rte light plugin
(function ($) {
    if (typeof $.fn.rte === "undefined") {
        var defaults = {
            content_css_url: "/css/rte.css",
            max_height: 350,
            ignored_keycode: [9, 16, 17, 18, 20, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 37, 39, 92, 144, 188],
            smileys: {},
            counter: 0
        };
        $.fn.rte = function (options) {
            $.fn.rte.html = function (iframe) {
                return iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
            };
            var amImsie = $.browser.msie;
            var amIopera = $.browser.opera;
            var amIff = $.browser.mozilla;
            var amIsafari = $.browser.safari;
            var position = 0;
            smi_escape = function (str) {
                var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
                return str.replace(specials, "\\$&");
            };



                var smi_indexOf = function (string, obj) {
                    for (var i = 0; i < string.length; i++) {
                        if (string.substr(i,obj.length) == obj) {
                            return i;
                        }
                    }
                    return -1;
                }

            // build main options before element iteration
            var opts = $.extend(defaults, options);

            var str = '';
            for (var i in opts.smileys) {
                str += smi_escape(i) + "|";
            }
            str += '\n';
            /*var rxp = {
                regexp: new RegExp(str, 'i')
            };*/
            opts.regexp = new RegExp(str, 'i');
            //var opts = $.extend(opts, rxp);
            // iterate and construct the RTEs
            return this.each(function () {
                var textarea = $(this);
                var iframe;
                var element_id = textarea.attr("id");
                // enable design mode


                function enableDesignMode() {
                    var content = textarea.val();
                    // Mozilla needs this to display caret
                    if (amIff && $.trim(content) == '') {
                        content = '<br />';
                    } else if (amIsafari && $.trim(content) == '') {
                        content = '<div>';
                    }

                    // already created? show/hide
                    if (iframe) {
                        textarea.hide();
                        $(iframe).contents().find("body").html(content);
                        $(iframe).show();
                        $("#toolbar-" + element_id).remove();
                        textarea.before(toolbar());
                        return true;
                    }
                    // for compatibility reasons, need to be created this way

	               if (opts.iconlist_div !== false) {
		                var div;
		                div = document.createElement("div");
		                div.id = opts.iconlist_div;
		                    var divcontent = '<ul>';
		                    var iconsrc = opts.smileys_path;
		                    for (var i in opts.smileys) {
                                if(opts.smileys[i].display == '1') {
                                    divcontent += '<li><a href="#" onclick = "insert_smiley_from_list(\''+i+'\'); return false;"><img src="' + iconsrc + opts.smileys[i]['url'] + '" alt = "' + i + '" title = "'+opts.smileys[i]['desc']+'" /></a></li>' + "\n";
                                }
		                    }
		                divcontent += '</ul>';
		                $(div).html(divcontent);
		            };



					iframe = document.createElement("iframe");
                    iframe.frameBorder = 0;
                    iframe.frameMargin = 0;
                    iframe.framePadding = 0;
                    iframe.height = 200;
                    if (textarea.attr('class')) iframe.className = textarea.attr('class');
                    if (textarea.attr('id')) iframe.id = element_id;
                    if (textarea.attr('name')) iframe.title = textarea.attr('name');
                    textarea.after(iframe);
                    //console.log(iframe);
					$(iframe).after(div);
                    var css = "";
                    if (opts.content_css_url) {
                        css = "<link type='text/css' rel='stylesheet' href='" + opts.content_css_url + "' />";
                    }
                    var doc = "<html><head>" + css + "</head><body class='frameBody'>" + content + "</body></html>";
                    tryEnableDesignMode(doc, function () {
                        $("#toolbar-" + element_id).remove();
                        textarea.before(toolbar());
                        // hide textarea
                        textarea.hide();
                    });
                }
                var get_content = function get_content(node) {
                    if (node == null) return '';
                    if (node.lastChild == null) return '';
                    var scontent = '';
                    var nodelen = node.childNodes.length;
                    if (node.lastChild.nodeName.toLowerCase() == 'br') {
                        nodelen = nodelen - 1;
                    }
                    for (var i = 0; i < nodelen; i++) {
                        if (node.childNodes[i].nodeType == 3) {
                            scontent += node.childNodes[i].nodeValue;
                        } else {
                            switch (node.childNodes[i].nodeName.toLowerCase()) {
                            case 'meta':
                                scontent += '';
                                break;
                            case 'p':
                                if (i == 0 && get_content(node.childNodes[i]).length == 0) {
                                    scontent = ''
                                } else if (i == nodelen - 1) {
                                    scontent += get_content(node.childNodes[i]);
                                } else {
                                    scontent += get_content(node.childNodes[i]) + "\n";
                                }
                                break;
                            case 'span':
                                if (i == 0 && get_content(node.childNodes[i]).length == 0) {
                                    scontent = ''
                                } else if (i == nodelen - 1) {
                                    scontent += get_content(node.childNodes[i]);
                                } else {
                                    scontent += get_content(node.childNodes[i]) + "\n";
                                }
                                break;
                            case 'div':
                                if (i == 0 && get_content(node.childNodes[i]).length == 0) {
                                    scontent = ''
                                } else if (i == nodelen - 1) {
                                    scontent += get_content(node.childNodes[i]);
                                } else {
                                    scontent += get_content(node.childNodes[i]) + "\n";
                                }
                                break;
                            case 'br':
                                scontent += "\n";
                                break;
                            case 'img':
                                scontent += node.childNodes[i].alt;
                                break;
                            default:
                                scontent += $(node.childNodes[i]).text() + "\n";
                            }
                        }
                    }
                    //$('#debug').html(scontent.replace(new RegExp('\\n','ig'),'<br />'));
                    textarea.val(scontent).change();
                    return scontent;
                }
                var get_content_length = function get_content_length() {
                    return get_content(iframe.contentWindow.document.body).length;
                }

                function tryEnableDesignMode(doc, callback) {
                    if (!iframe) {
                        return false;
                    }
                    try {
                        iframe.contentWindow.document.open();
                        iframe.contentWindow.document.write(doc);
                        iframe.contentWindow.document.close();
                    } catch(error) {}
                    if (document.contentEditable) {
                        iframe.contentWindow.document.designMode = "On";
                        callback();
                        return true;
                    } else if (document.designMode != null) {
                        try {
                            iframe.contentWindow.document.designMode = "on";
                            callback();
                            return true;
                        } catch(error) {}
                    }
                    setTimeout(function () {
                        tryEnableDesignMode(doc, callback)
                    },
                    500);
                    return false;
                }

                /*function disableDesignMode(submit) {
                    var content = get_content(iframe.contentWindow.document.body);
                    if ($(iframe).is(":visible")) {
                        textarea.val(content);
                    }
                    if (submit !== true) {
                        textarea.show();
                        $(iframe).hide();
                    }
                }*/
                // create toolbar and bind events to it's elements


                function toolbar() {
                    var tb = '';
                    var iframeDoc = $(iframe.contentWindow.document);
                    $(iframe).parents('form').submit(function () {
                    	$(iframe).contents().find("body").html('<br />');
                    });
                    iframeDoc.keydown(function (e) {
                        var code = e.which || e.keyCode;
						if (amIopera && ((e.ctrlKey && code == 86) || (e.shiftKey && code == 45))) {
                            paste(e);
                            return;
                        }
                        if (opts.max_content_length <= get_content_length()) {
                            if ((code == 8 || code == 37 || code == 38 || code == 39 || code == 40 || code == 46)) {
                                return;
                            }
                            return false;
                        }

                        if (code == 13) {

						}

                        /// tu wstawić <br> i abortnąć akcję :)


                    });
                    iframeDoc.click(function () {
                        if (amImsie) save_position();
                    });
                    iframeDoc.keyup(function (e, offset) {
                        var code = e.which || e.keyCode;
                        if ($.inArray(code,opts.ignored_keycode) != -1) {
							if (amImsie) save_position();
                            updateCounter();
                            return
                        }
                        insertSmiley(offset);
                        updateCounter();
                        if (get_content_length()==0) {
							if (amIsafari) iframe.contentWindow.document.createElement('div');
	                        if (amIff) iframe.contentWindow.document.createElement('br');
	                        //if (amImsie) iframe.contentWindow.document.body.pasteHTML('<p>');
						}


                        return true;
                    });
                    return tb;
                };

                function updateCounter() {
                return false;
                    $('p#counter').text(get_content_length() + '/' + opts.max_content_length);
                };

                function paste(e) {}
                var insertSmiley = function insertSmiley(offset) {
                    if (amImsie) {
                        function $for(obj, callback) {
                            var proto = obj.constructor.prototype,
                                h = obj.hasOwnProperty,
                                key;
                            for (key in obj) {
                                if ((h && h.call(obj, key)) || proto[key] !== obj[key]) callback(key, obj[key]);
                            }
                        };
                        var range = iframe.contentWindow.document.body.createTextRange();
                        range.moveToElementText(iframe.contentWindow.document.body);
                        $for(opts.smileys, function (code, data) {
                            for (var n = 0; range.findText(code, 1000000, 0); n++) {
                                range.text = '';
                                range.pasteHTML('<img src="' + opts.smileys_path + data['url'] + '" title="'+data['desc']+'" alt="' + code + '" >');
                                range.collapse(false);
                            }
                        });
                        save_position();
                    } else {
                        var selection = iframe.contentWindow.getSelection();
                        if (selection === null) {
                            return;
                        }
                        var range = selection.getRangeAt(0),
                            code = null;
                        if (range.startContainer.nodeValue && (f = find(range.startContainer.nodeValue, opts.regexp, offset || 0))) {
                            var d = range.startContainer.nodeValue.length - range.endOffset;
                            var code = f.match;
                            ssmiley = opts.smileys;
                            ssmileysrc = opts.smileys_path + ssmiley[code.toLowerCase()]['url'];
                            ssmileytitle = ssmiley[code.toLowerCase()]['desc'];
                            if (f.match == '\n') {
                                var smiley = iframe.contentWindow.document.createElement('br');
                            } else {
                                var smiley = iframe.contentWindow.document.createElement('img');
                                smiley.alt = code;
                                smiley.src = ssmileysrc;
                                smiley.title = ssmileytitle;
                            }
                            range.startContainer.nodeValue = range.startContainer.nodeValue.substring(0, f.index) + range.startContainer.nodeValue.substring(f.index + f.match.length);
                            range.setStart(selection.anchorNode, f.index);
                            range.setEnd(selection.anchorNode, f.index);
                            selection.removeAllRanges();
                            selection.addRange(range);
                            range.insertNode(smiley);
                            try {
                                range.setEnd(smiley.nextSibling, smiley.nextSibling.length - d);
                                range.setStart(smiley.nextSibling, smiley.nextSibling.length - d);
                            } catch(e) {}
                            selection.removeAllRanges();
                            selection.addRange(range);
                            insertSmiley(offset);
                        }
                    }
                	get_content_length();
                }
                if (amImsie) {
                    save_position = function () {
					try {
                        if (iframe.contentWindow.document.selection) {
                            position = -1 * iframe.contentWindow.document.selection.createRange().moveEnd("character", -100000000);
                        } } catch(e){}
                    };
                };
                insert_smiley_from_list = function (code) {
                    if (opts.max_content_length <= get_content_length() + code.length) return false;
                    var editor = iframe.contentWindow;
                    editor.focus();
                    ssmiley = opts.smileys;
                    ssmileysrc = opts.smileys_path + ssmiley[code]['url'];
                    ssmileytitle = ssmiley[code]['desc'];
                    if (amImsie) {
                        var range = editor.document.body.createTextRange();
                        range.collapse(true);
                        range.moveStart('character', position);
                        range.collapse(true);
                        range.pasteHTML('<img src="' + ssmileysrc + '" alt="' + code + '" title="'+code+'" >');
                        range.collapse(false);
                        range.select();
                        save_position();
                    } else {
                        var smiley = editor.document.createElement('img');
                        smiley.alt = code;
                        smiley.src = ssmileysrc;
                        smiley.title = code;
                        var selection = editor.getSelection();
                        selection.getRangeAt(0).insertNode(smiley);
                        var range = editor.document.createRange();
                        range.setStartAfter(smiley);
                        range.setEndAfter(smiley);
                        selection.removeAllRanges();
                        selection.addRange(range);
                    }
                    $(iframe.contentWindow).focus();
                    updateCounter();
                    get_content_length();
                };
                /*
        function formatText(command, option) {
            iframe.contentWindow.focus();
            try{

                iframe.contentWindow.document.execCommand(command, false, option);
            }catch(e){
            }
            iframe.contentWindow.focus();
            iframe.contentWindow.change();



        };*/

                function getSelectionElement() {
                    if (iframe.contentWindow.document.selection) {
                        // IE selections
                        selection = iframe.contentWindow.document.selection;
                        range = selection.createRange();
                        try {
                            node = range.parentElement();
                        }
                        catch(e) {
                            return false;
                        }
                    } else {
                        // Mozilla selections
                        try {
                            selection = iframe.contentWindow.getSelection();
                            range = selection.getRangeAt(0);
                        }
                        catch(e) {
                            return false;
                        }
                        node = range.commonAncestorContainer;
                    }
                    return node;
                };
                var find = function (text, regexp, offset) {
                    var index, subb_length = 0,
                        c = null;
                    while (true) {
                        regexp.lastIndex = 0;
                        if (c = text.match(regexp)) {
                            //index = text.indexOf(c[0], 0);
							index = smi_indexOf(text, c[0]);
                            if (index + subb_length >= offset) {
                                return {
                                    'index': index + subb_length,
                                    'match': c[0]
                                }
                            } else {
                                subb_length += index + c[0].length;
                                text = text.substr(index + c[0].length);
                            }
                        } else {
                            return null;
                        }
                    };
                };
                if (amImsie) {} else {};
                enableDesignMode();
                //console.log($('div#'+opts.iconlist_div));
                //console.log($('div#'+opts.iconlist_div));
				$('div#'+opts.iconlist_div + ' li a').click(function () {

	                    return false;
            		})
            });
        };
    }
})(jQuery);
;(function ($) {
    if (typeof $.fn.parseEmo === "undefined") {

    		var defaults = {
            smileys: {}
        };

            $.fn.parseEmo = function (options, text) {
            var opts = $.extend(defaults, options);
            var amImsie = $.browser.msie;
            var amIopera = $.browser.opera;
            var position = 0;
            smi_escape = function (str) {
                var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
                return str.replace(specials, "\\$&");
            };

			var str = '';
            for (var i in opts.smileys) {
                str += smi_escape(i)+'|';
            }
            str += '\n';
            var rxp = {
                regexp: new RegExp(str, 'i')
            };
            var opts = $.extend(opts, rxp);

			var parseText = function parseText(text){
			var c = text.match(opts.regexp);
            if (c) {
                            if (c[0] == '\n') {

							text = text.replace(new RegExp('\n','ig'),'<br />');
							} else {
							var ssmiley = '<img title = "'+opts.smileys[c[0].toLowerCase()]['desc']+'" src="'+opts.smileys_path+opts.smileys[c[0].toLowerCase()]['url']+'" />';
                            //console.log(ssmiley);
                            var repl = new RegExp(smi_escape(c[0]), 'ig');
                            text = text.replace(repl,ssmiley);
				            //console.log(text);

							}
							return parseText(text);



        } else { return text; }
		}
            //console.log(this.text());
            //console.log(opts);
            var newtext = parseText(text);
            //console.log(newtext);
            return newtext;

            };
    }


})(jQuery);
;/*global jQuery */
/* ****************************************************************************

	CJ Object Scaler jQuery Plug-In v2.0

	This library is released under the BSD license:

	Copyright (c) 2008, Doug Jones. All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	Redistributions of source code must retain the above copyright notice, this
	list of conditions and the following disclaimer. Redistributions in binary
	form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials
	provided with the distribution. Neither the name BernieCode nor
	the names of its contributors may be used to endorse or promote products
	derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
	ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
	DAMAGE.

	For more information please visit www.cjboco.com.

	Example:

	$("#myImage").cjObjectScaler({
		destObj: $("#myDiv"),	// Needs to be a jQuery object
		method: "fit",			// fit | fill (default)
		fade: 500				// 0 no fade, positive integer fade duration
	});

	CHANGELOG

		v1.0	09/10/08 -	Initial Release
		v2.0	09/22/09 -	Coverted it to a jQuery plug-in
		v2.0.1	10/14/09 -	Fixed a bug where the scaling function
								wasn't being triggered, do to the
								image already being loaded.
								(Discovered by Ben Visser)


**************************************************************************** */
(function ($) {
	$.fn.cjObjectScaler = function (options) {

		/*
			user variables (settings)
		***************************************/
		var settings = {
			// user editable settings
			destObj: null,
			// must be a jQuery object
			method: "fill",
			// fit|fill
			fade: 0 // if positive value, do hide/fadeIn
		};

		/*
			system variables
		***************************************/
		var sys = {
			// function parameters
			version: '2.0.0',
			elem: null
		};

		/*
			scale the image
		***************************************/
		function scale(self) {

			// declare some local variables
			var dest = settings.destObj,
			destW = $(dest).width(),
			destH = $(dest).height(),
			ratioX,
			ratioY,
			scale,
			newWidth,
			newHeight;

			// calculate scale ratios
			ratioX = destW / $(self).width();
			ratioY = destH / $(self).height();

			// Determine which algorithm to use
			if (!$(self).hasClass("cf_image_scaler_fill") && ($(self).hasClass("cf_image_scaler_fit") || settings.method === "fit")) {
				scale = ratioX < ratioY ? ratioX : ratioY;
			} else if (!$(self).hasClass("cf_image_scaler_fit") && ($(self).hasClass("cf_image_scaler_fill") || settings.method === "fill")) {
				scale = ratioX > ratioY ? ratioX : ratioY;
			}

			// calculate our new image dimensions
			newWidth = parseInt($(self).width() * scale, 10);
			newHeight = parseInt($(self).height() * scale, 10);

			// Set new dimensions & offset
			$(self).css({
				"width": newWidth + "px",
				"height": newHeight + "px",
				"position": "absolute",
				"top": parseInt((destH - newHeight) / 2, 10) + "px",
				"left": parseInt((destW - newWidth) / 2, 10) + "px"
			}).attr({
				"width": newWidth,
				"height": newHeight
			});

			// do our fancy fade in, if user supplied a fade amount
			if (settings.fade > 0) {
				$(self).fadeIn(settings.fade);
			}

		}

		/*
			initialize the flipBox
		***************************************/
		function init() {

			var self = $(sys.elem)[0];

			// check to make sure we have a valid destination object
			if (settings.destObj === null || typeof settings.method !== "string" || typeof $(settings.destObj)[0] !== "object") {
				return;
			} else {

				// need to make sure the user set the parent's position
				// things go bonkers, if not set.
				if ($(settings.destObj).css("position") === "static") {
					$(settings.destObj).css({
						"position": "relative"
					});
				}

				// if the user supplied a fade amount, hide our image
				if (settings.fade > 0) {
					$(self).hide();
				}

				// run our scale function. Special case for images, we need
				// to make sure the image has loaded in order to get the width & height
				if ($(self)[0].nodeName === "IMG") {
					// check to see if the image is already loaded
					if ($(self).attr("complete")) {
						scale($(self)[0]);
					} else {
						$(self).load(function () {
							scale($(self)[0]);
						});
					}
				} else {
					scale($(self)[0]);
				}

			}
		}

		/*
			set up any user passed variables
		***************************************/
		if (options) {
			$.extend(settings, options);
		}

		/*
			main
		***************************************/
		return this.each(function () {
			sys.elem = this;
			init();
		});

	};
})(jQuery);
;﻿/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});
