(function(){
/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
 * $Rev: 5685 $
 */

// Map over jQuery in case of overwrite
var _jQuery = window.jQuery,
// Map over the $ in case of overwrite
	_$ = window.$;

var 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)
var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,

// Is it a simple selector
	isSimple = /^.[^:#\[\.]*$/,

// Will speed up references to undefined, and allows munging its name.
	undefined;

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

					// Make sure an element was located
					if ( elem ){
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id != match[3] )
							return jQuery().find( selector );

						// Otherwise, we inject the element directly into the jQuery object
						return jQuery( elem );
					}
					selector = [];
				}

			// 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 )[ jQuery.fn.ready ? "ready" : "load" ]( selector );

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

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

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

	// The number of elements contained in the matched element set
	length: 0,

	// 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 ) {
		// Build a new jQuery matched element set
		var ret = jQuery( elems );

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

		// 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 ) {
		var ret = -1;

		// 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 ( name.constructor == 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
			jQuery( html, this[0].ownerDocument )
				.clone()
				.insertBefore( this[0] )
				.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, false, function(elem){
			if (this.nodeType == 1)
				this.appendChild( elem );
		});
	},

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

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

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

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

	find: function( selector ) {
		var elems = jQuery.map(this, function(elem){
			return jQuery.find( selector, elem );
		});

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

	clone: function( events ) {
		// Do the clone
		var ret = this.map(function(){
			if ( jQuery.browser.msie && !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, this ) );
	},

	not: function( selector ) {
		if ( selector.constructor == String )
			// test special case where just one selector is passed in
			if ( isSimple.test( selector ) )
				return this.pushStack( jQuery.multiFilter( selector, this, true ) );
			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 this.is( "." + selector );
	},

	val: function( value ) {
		if ( value == undefined ) {

			if ( this.length ) {
				var elem = this[0];

				// 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.browser.msie && !option.attributes.value.specified ? option.text : option.value;

							// 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
				} else
					return (this[0].value || "").replace(/\r/g, "");

			}

			return undefined;
		}

		if( value.constructor == Number )
			value += '';

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

			if ( value.constructor == Array && /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 ) );
	},

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

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

	domManip: function( args, table, reverse, callback ) {
		var clone = this.length > 1, elems;

		return this.each(function(){
			if ( !elems ) {
				elems = jQuery.clean( args, this.ownerDocument );

				if ( reverse )
					elems.reverse();
			}

			var obj = this;

			if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) )
				obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") );

			var scripts = jQuery( [] );

			jQuery.each(elems, function(){
				var elem = clone ?
					jQuery( this ).clone( true )[0] :
					this;

				// execute all scripts after the elements have been injected
				if ( jQuery.nodeName( elem, "script" ) )
					scripts = scripts.add( elem );
				else {
					// Remove any inner scripts for later evaluation
					if ( elem.nodeType == 1 )
						scripts = scripts.add( jQuery( "script", elem ).remove() );

					// Inject the elements into the document
					callback.call( obj, elem );
				}
			});

			scripts.each( evalScript );
		});
	}
};

// 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 ( target.constructor == 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" && typeof target != "function" )
		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;
};

var expando = "jQuery" + now(), uuid = 0, windowData = {},
	// exclude the following css properties to add px
	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
	// cache defaultView
	defaultView = document.defaultView || {};

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

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

	// See test/unit/core.js for details concerning this function.
	isFunction: function( fn ) {
		return !!fn && typeof fn != "string" && !fn.nodeName &&
			fn.constructor != Array && /^[\s[]?function/.test( fn + "" );
	},

	// check if an element is in a (or is an) XML document
	isXMLDoc: function( elem ) {
		return elem.documentElement && !elem.body ||
			elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
	},

	// 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.browser.msie )
				script.text = data;
			else
				script.appendChild( document.createTextNode( 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();
	},

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

	// 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 value && value.constructor == 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 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;

		// A helper method for determining if an element's values are broken
		function color( elem ) {
			if ( !jQuery.browser.safari )
				return false;

			// defaultView is cached
			var ret = defaultView.getComputedStyle( elem, null );
			return !ret || ret.getPropertyValue("color") == "";
		}

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

			return ret == "" ?
				"1" :
				ret;
		}
		// Opera sometimes will give the wrong display answer, this fixes it, see #2037
		if ( jQuery.browser.opera && name == "display" ) {
			var save = style.outline;
			style.outline = "0 solid black";
			style.outline = save;
		}

		// 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 && !color( elem ) )
				ret = computedStyle.getPropertyValue( name );

			// If the element isn't reporting its values properly in Safari
			// then some display: none elements are involved
			else {
				var swap = [], stack = [], a = elem, i = 0;

				// Locate all of the parent display: none elements
				for ( ; a && color(a); a = a.parentNode )
					stack.unshift(a);

				// Go through and make them visible, but in reverse
				// (It would be better if we knew the exact display type that they had)
				for ( ; i < stack.length; i++ )
					if ( color( stack[ i ] ) ) {
						swap[ i ] = stack[ i ].style.display;
						stack[ i ].style.display = "block";
					}

				// Since we flip the display style, we have to handle that
				// one special, otherwise get the value
				ret = name == "display" && swap[ stack.length - 1 ] != null ?
					"none" :
					( computedStyle && computedStyle.getPropertyValue( name ) ) || "";

				// Finally, revert the display styles back
				for ( i = 0; i < swap.length; i++ )
					if ( swap[ i ] != null )
						stack[ i ].style.display = swap[ i ];
			}

			// 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 ) {
		var ret = [];
		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;

		jQuery.each(elems, function(i, elem){
			if ( !elem )
				return;

			if ( elem.constructor == Number )
				elem += '';

			// 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(), div = context.createElement("div");

				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.browser.msie &&
					[ 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.browser.msie ) {

					// 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 ( /^\s/.test( elem ) )
						div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );

				}

				elem = jQuery.makeArray( div.childNodes );
			}

			if ( elem.length === 0 && (!jQuery.nodeName( elem, "form" ) && !jQuery.nodeName( elem, "select" )) )
				return;

			if ( elem[0] == undefined || jQuery.nodeName( elem, "form" ) || elem.options )
				ret.push( elem );

			else
				ret = jQuery.merge( ret, elem );

		});

		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,
			msie = jQuery.browser.msie;

		// 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" && jQuery.browser.safari )
				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;

				return elem[ name ];
			}

			if ( msie && 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 = msie && 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 ( msie && 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 || array.split || array.setInterval || array.call )
				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.browser.msie ) {
			while ( elem = second[ i++ ] )
				if ( elem.nodeType != 8 )
					first[ pos++ ] = elem;

		} else
			while ( elem = second[ i++ ] )
				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 );
	}
});

var userAgent = navigator.userAgent.toLowerCase();

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

var styleFloat = jQuery.browser.msie ?
	"styleFloat" :
	"cssFloat";

jQuery.extend({
	// Check to see if the W3C box model is being used
	boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",

	props: {
		"for": "htmlFor",
		"class": "className",
		"float": styleFloat,
		cssFloat: styleFloat,
		styleFloat: styleFloat,
		readonly: "readOnly",
		maxlength: "maxLength",
		cellspacing: "cellSpacing"
	}
});

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

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 ) {
		jQuery.className[ jQuery.className.has( this, classNames ) ? "remove" : "add" ]( this, classNames );
	},

	remove: function( selector ) {
		if ( !selector || jQuery.filter( selector, [ this ] ).r.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 );
	};
});

jQuery.each([ "Height", "Width" ], function(i, name){
	var type = name.toLowerCase();

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		return this[0] == window ?
			// Opera reports document.body.client[Width/Height] properly in both quirks and standards
			jQuery.browser.opera && document.body[ "client" + name ] ||

			// Safari reports inner[Width/Height] just fine (Mozilla and Opera include scroll bar widths)
			jQuery.browser.safari && window[ "inner" + name ] ||

			// 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(
					Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
					Math.max(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, size.constructor == String ? size : size + "px" );
	};
});

// 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 chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
		"(?:[\\w*_-]|\\\\.)" :
		"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
	quickChild = new RegExp("^>\\s*(" + chars + "+)"),
	quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
	quickClass = new RegExp("^([#.]?)(" + chars + "*)");

jQuery.extend({
	expr: {
		"": function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},
		"#": function(a,i,m){return a.getAttribute("id")==m[2];},
		":": {
			// Position Checks
			lt: function(a,i,m){return i<m[3]-0;},
			gt: function(a,i,m){return i>m[3]-0;},
			nth: function(a,i,m){return m[3]-0==i;},
			eq: function(a,i,m){return m[3]-0==i;},
			first: function(a,i){return i==0;},
			last: function(a,i,m,r){return i==r.length-1;},
			even: function(a,i){return i%2==0;},
			odd: function(a,i){return i%2;},

			// Child Checks
			"first-child": function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},
			"last-child": function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},
			"only-child": function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},

			// Parent Checks
			parent: function(a){return a.firstChild;},
			empty: function(a){return !a.firstChild;},

			// Text Check
			contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},

			// Visibility
			visible: function(a){return "hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},
			hidden: function(a){return "hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},

			// Form attributes
			enabled: function(a){return !a.disabled;},
			disabled: function(a){return a.disabled;},
			checked: function(a){return a.checked;},
			selected: function(a){return a.selected||jQuery.attr(a,"selected");},

			// Form elements
			text: function(a){return "text"==a.type;},
			radio: function(a){return "radio"==a.type;},
			checkbox: function(a){return "checkbox"==a.type;},
			file: function(a){return "file"==a.type;},
			password: function(a){return "password"==a.type;},
			submit: function(a){return "submit"==a.type;},
			image: function(a){return "image"==a.type;},
			reset: function(a){return "reset"==a.type;},
			button: function(a){return "button"==a.type||jQuery.nodeName(a,"button");},
			input: function(a){return /input|select|textarea|button/i.test(a.nodeName);},

			// :has()
			has: function(a,i,m){return jQuery.find(m[3],a).length;},

			// :header
			header: function(a){return /h\d/i.test(a.nodeName);},

			// :animated
			animated: function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}
		}
	},

	// The regular expressions that power the parsing engine
	parse: [
		// Match: [@value='test'], [@foo]
		/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,

		// Match: :contains('foo')
		/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,

		// Match: :even, :last-child, #id, .class
		new RegExp("^([:.#]*)(" + chars + "+)")
	],

	multiFilter: function( expr, elems, not ) {
		var old, cur = [];

		while ( expr && expr != old ) {
			old = expr;
			var f = jQuery.filter( expr, elems, not );
			expr = f.t.replace(/^\s*,\s*/, "" );
			cur = not ? elems = f.r : jQuery.merge( cur, f.r );
		}

		return cur;
	},

	find: function( t, context ) {
		// Quickly handle non-string expressions
		if ( typeof t != "string" )
			return [ t ];

		// check to make sure context is a DOM element or a document
		if ( context && context.nodeType != 1 && context.nodeType != 9)
			return [ ];

		// Set the correct context (if none is provided)
		context = context || document;

		// Initialize the search
		var ret = [context], done = [], last, nodeName;

		// Continue while a selector expression exists, and while
		// we're no longer looping upon ourselves
		while ( t && last != t ) {
			var r = [];
			last = t;

			t = jQuery.trim(t);

			var foundToken = false,

			// An attempt at speeding up child selectors that
			// point to a specific element tag
				re = quickChild,

				m = re.exec(t);

			if ( m ) {
				nodeName = m[1].toUpperCase();

				// Perform our own iteration and filter
				for ( var i = 0; ret[i]; i++ )
					for ( var c = ret[i].firstChild; c; c = c.nextSibling )
						if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
							r.push( c );

				ret = r;
				t = t.replace( re, "" );
				if ( t.indexOf(" ") == 0 ) continue;
				foundToken = true;
			} else {
				re = /^([>+~])\s*(\w*)/i;

				if ( (m = re.exec(t)) != null ) {
					r = [];

					var merge = {};
					nodeName = m[2].toUpperCase();
					m = m[1];

					for ( var j = 0, rl = ret.length; j < rl; j++ ) {
						var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
						for ( ; n; n = n.nextSibling )
							if ( n.nodeType == 1 ) {
								var id = jQuery.data(n);

								if ( m == "~" && merge[id] ) break;

								if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
									if ( m == "~" ) merge[id] = true;
									r.push( n );
								}

								if ( m == "+" ) break;
							}
					}

					ret = r;

					// And remove the token
					t = jQuery.trim( t.replace( re, "" ) );
					foundToken = true;
				}
			}

			// See if there's still an expression, and that we haven't already
			// matched a token
			if ( t && !foundToken ) {
				// Handle multiple expressions
				if ( !t.indexOf(",") ) {
					// Clean the result set
					if ( context == ret[0] ) ret.shift();

					// Merge the result sets
					done = jQuery.merge( done, ret );

					// Reset the context
					r = ret = [context];

					// Touch up the selector string
					t = " " + t.substr(1,t.length);

				} else {
					// Optimize for the case nodeName#idName
					var re2 = quickID;
					var m = re2.exec(t);

					// Re-organize the results, so that they're consistent
					if ( m ) {
						m = [ 0, m[2], m[3], m[1] ];

					} else {
						// Otherwise, do a traditional filter check for
						// ID, class, and element selectors
						re2 = quickClass;
						m = re2.exec(t);
					}

					m[2] = m[2].replace(/\\/g, "");

					var elem = ret[ret.length-1];

					// Try to do a global search by ID, where we can
					if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
						// Optimization for HTML document case
						var oid = elem.getElementById(m[2]);

						// Do a quick check for the existence of the actual ID attribute
						// to avoid selecting by the name attribute in IE
						// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
						if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
							oid = jQuery('[@id="'+m[2]+'"]', elem)[0];

						// Do a quick check for node name (where applicable) so
						// that div#foo searches will be really fast
						ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
					} else {
						// We need to find all descendant elements
						for ( var i = 0; ret[i]; i++ ) {
							// Grab the tag name being searched for
							var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];

							// Handle IE7 being really dumb about <object>s
							if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
								tag = "param";

							r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
						}

						// It's faster to filter by class and be done with it
						if ( m[1] == "." )
							r = jQuery.classFilter( r, m[2] );

						// Same with ID filtering
						if ( m[1] == "#" ) {
							var tmp = [];

							// Try to find the element with the ID
							for ( var i = 0; r[i]; i++ )
								if ( r[i].getAttribute("id") == m[2] ) {
									tmp = [ r[i] ];
									break;
								}

							r = tmp;
						}

						ret = r;
					}

					t = t.replace( re2, "" );
				}

			}

			// If a selector string still exists
			if ( t ) {
				// Attempt to filter it
				var val = jQuery.filter(t,r);
				ret = r = val.r;
				t = jQuery.trim(val.t);
			}
		}

		// An error occurred with the selector;
		// just return an empty set instead
		if ( t )
			ret = [];

		// Remove the root context
		if ( ret && context == ret[0] )
			ret.shift();

		// And combine the results
		done = jQuery.merge( done, ret );

		return done;
	},

	classFilter: function(r,m,not){
		m = " " + m + " ";
		var tmp = [];
		for ( var i = 0; r[i]; i++ ) {
			var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
			if ( !not && pass || not && !pass )
				tmp.push( r[i] );
		}
		return tmp;
	},

	filter: function(t,r,not) {
		var last;

		// Look for common filter expressions
		while ( t && t != last ) {
			last = t;

			var p = jQuery.parse, m;

			for ( var i = 0; p[i]; i++ ) {
				m = p[i].exec( t );

				if ( m ) {
					// Remove what we just matched
					t = t.substring( m[0].length );

					m[2] = m[2].replace(/\\/g, "");
					break;
				}
			}

			if ( !m )
				break;

			// :not() is a special case that can be optimized by
			// keeping it out of the expression list
			if ( m[1] == ":" && m[2] == "not" )
				// optimize if only one selector found (most common case)
				r = isSimple.test( m[3] ) ?
					jQuery.filter(m[3], r, true).r :
					jQuery( r ).not( m[3] );

			// We can get a big speed boost by filtering by class here
			else if ( m[1] == "." )
				r = jQuery.classFilter(r, m[2], not);

			else if ( m[1] == "[" ) {
				var tmp = [], type = m[3];

				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];

					if ( z == null || /href|src|selected/.test(m[2]) )
						z = jQuery.attr(a,m[2]) || '';

					if ( (type == "" && !!z ||
						 type == "=" && z == m[5] ||
						 type == "!=" && z != m[5] ||
						 type == "^=" && z && !z.indexOf(m[5]) ||
						 type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
						 (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
							tmp.push( a );
				}

				r = tmp;

			// We can get a speed boost by handling nth-child here
			} else if ( m[1] == ":" && m[2] == "nth-child" ) {
				var merge = {}, tmp = [],
					// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
					test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
						m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
						!/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
					// calculate the numbers (first)n+(last) including if they are negative
					first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;

				// loop through all the elements left in the jQuery object
				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);

					if ( !merge[id] ) {
						var c = 1;

						for ( var n = parentNode.firstChild; n; n = n.nextSibling )
							if ( n.nodeType == 1 )
								n.nodeIndex = c++;

						merge[id] = true;
					}

					var add = false;

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

					if ( add ^ not )
						tmp.push( node );
				}

				r = tmp;

			// Otherwise, find the expression to execute
			} else {
				var fn = jQuery.expr[ m[1] ];
				if ( typeof fn == "object" )
					fn = fn[ m[2] ];

				if ( typeof fn == "string" )
					fn = eval("false||function(a,i){return " + fn + ";}");

				// Execute it against the current filter
				r = jQuery.grep( r, function(elem, i){
					return fn(elem, i, m, r);
				}, not );
			}
		}

		// Return an array of filtered elements (r)
		// and the modified expression string (t)
		return { r: r, t: t };
	},

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

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

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

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

		return r;
	}
});
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code orignated 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 ( jQuery.browser.msie && elem.setInterval )
			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, function() {
				// Pass arguments and context to original handler
				return fn.apply(this, arguments);
			});

			// 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
				if ( typeof jQuery != "undefined" && !jQuery.event.triggered )
					return jQuery.event.handle.apply(arguments.callee.elem, arguments);
			});
		// 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 parts = type.split(".");
			type = parts[0];
			handler.type = parts[1];

			// Get the current list of functions bound to this event
			var handlers = events[type];

			// 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) === 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 parts = type.split(".");
					type = parts[0];

					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 ( handler in events[type] )
								// Handle the removal of namespaced events
								if ( !parts[1] || events[type][handler].type == parts[1] )
									delete events[type][handler];

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

	trigger: function(type, data, elem, donative, extra) {
		// Clone the incoming data, if any
		data = jQuery.makeArray(data);

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

		// Handle a global trigger
		if ( !elem ) {
			// Only trigger if we've ever bound an event for it
			if ( this.global[type] )
				jQuery("*").add([window, document]).trigger(type, data);

		// Handle triggering a single element
		} else {
			// don't do events on text and comment nodes
			if ( elem.nodeType == 3 || elem.nodeType == 8 )
				return undefined;

			var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
				// Check to see if we need to provide a fake event, or not
				event = !data[0] || !data[0].preventDefault;

			// Pass along a fake event
			if ( event ) {
				data.unshift({
					type: type,
					target: elem,
					preventDefault: function(){},
					stopPropagation: function(){},
					timeStamp: now()
				});
				data[0][expando] = true; // no need to fix fake event
			}

			// Enforce the right trigger type
			data[0].type = type;
			if ( exclusive )
				data[0].exclusive = true;

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

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

			// Extra functions don't get the custom event object
			if ( event )
				data.shift();

			// Handle triggering of extra function
			if ( extra && jQuery.isFunction( extra ) ) {
				// call the extra function and tack the current return value on the end for possible inspection
				ret = extra.apply( elem, val == null ? data : data.concat( val ) );
				// if anything is returned, give it precedence and have it overwrite the previous value
				if (ret !== undefined)
					val = ret;
			}

			// Trigger the native events (except for clicks on links)
			if ( fn && donative !== false && val !== false && !(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;
		}

		return val;
	},

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

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

		// Namespaced event handlers
		namespace = event.type.split(".");
		event.type = namespace[0];
		namespace = namespace[1];
		// Cache this now, all = true means, any handler
		all = !namespace && !event.exclusive;

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

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

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

				ret = handler.apply( this, arguments );

				if ( val !== false )
					val = ret;

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

		return val;
	},

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

		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = { originalEvent: originalEvent };
		var 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 timeStamp toElement type view wheelDelta which".split(" ");
		for ( var i=props.length; i; i-- )
			event[ props[i] ] = originalEvent[ props[i] ];

		// Mark it as fixed
		event[expando] = true;

		// add preventDefault and stopPropagation since
		// they will not work on the clone
		event.preventDefault = function() {
			// if preventDefault exists run it on the original event
			if (originalEvent.preventDefault)
				originalEvent.preventDefault();
			// otherwise set the returnValue property of the original event to false (IE)
			originalEvent.returnValue = false;
		};
		event.stopPropagation = function() {
			// if stopPropagation exists run it on the original event
			if (originalEvent.stopPropagation)
				originalEvent.stopPropagation();
			// otherwise set the cancelBubble property of the original event to true (IE)
			originalEvent.cancelBubble = true;
		};

		// Fix timeStamp
		event.timeStamp = event.timeStamp || now();

		// 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 ){
		// 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: {
			setup: function() {
				// Make sure the ready event is setup
				bindReady();
				return;
			},

			teardown: function() { return; }
		},

		mouseenter: {
			setup: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
				return true;
			},

			teardown: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
				return true;
			},

			handler: function(event) {
				// If we actually just moused on to a sub-element, ignore it
				if ( withinElement(event, this) ) return true;
				// Execute the right handlers by setting the event type to mouseenter
				event.type = "mouseenter";
				return jQuery.event.handle.apply(this, arguments);
			}
		},

		mouseleave: {
			setup: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
				return true;
			},

			teardown: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
				return true;
			},

			handler: function(event) {
				// If we actually just moused on to a sub-element, ignore it
				if ( withinElement(event, this) ) return true;
				// Execute the right handlers by setting the event type to mouseleave
				event.type = "mouseleave";
				return jQuery.event.handle.apply(this, arguments);
			}
		}
	}
};

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, fn ) {
		return this.each(function(){
			jQuery.event.trigger( type, data, this, true, fn );
		});
	},

	triggerHandler: function( type, data, fn ) {
		return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
	},

	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.bind('mouseenter', fnOver).bind('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( function() { return fn.call(this, jQuery); } );

		return this;
	}
});

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

				// 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 (see further below for it) and webkit nightlies currently support this event
	if ( document.addEventListener && !jQuery.browser.opera)
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", jQuery.ready, false );

	// If IE is used and is not in a frame
	// Continually check to see if the document is ready
	if ( jQuery.browser.msie && window == top ) (function(){
		if (jQuery.isReady) return;
		try {
			// If IE is used, use the trick by Diego Perini
			// http://javascript.nwbox.com/IEContentLoaded/
			document.documentElement.doScroll("left");
		} catch( error ) {
			setTimeout( arguments.callee, 0 );
			return;
		}
		// and execute any waiting functions
		jQuery.ready();
	})();

	if ( jQuery.browser.opera )
		document.addEventListener( "DOMContentLoaded", function () {
			if (jQuery.isReady) return;
			for (var i = 0; i < document.styleSheets.length; i++)
				if (document.styleSheets[i].disabled) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			// and execute any waiting functions
			jQuery.ready();
		}, false);

	if ( jQuery.browser.safari ) {
		var numStyles;
		(function(){
			if (jQuery.isReady) return;
			if ( document.readyState != "loaded" && document.readyState != "complete" ) {
				setTimeout( arguments.callee, 0 );
				return;
			}
			if ( numStyles === undefined )
				numStyles = jQuery("style, link[rel=stylesheet]").length;
			if ( document.styleSheets.length != numStyles ) {
				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,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);
	};
});

// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event, elem) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Traverse up the tree
	while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
	// Return true if we actually just moused on to a sub-element
	return parent == elem;
};

// 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() {
	jQuery("*").add(document).unbind();
});
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);
		}

		callback = callback || function(){};

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

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

	serialize: function() {
		return jQuery.param(this.serializeArray());
	},
	serializeArray: function() {
		return this.map(function(){
			return jQuery.nodeName(this, "form") ?
				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 :
				val.constructor == Array ?
					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",
		timeout: 0,
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		data: null,
		username: null,
		password: null,
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	},

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

	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 remote = /^(?:\w+:)?\/\/([^\/?#]+)/;

		// If we're requesting a remote document
		// and trying to load JSON or Script with a GET
		if ( s.dataType == "script" && type == "GET"
				&& remote.test(s.url) && remote.exec(s.url)[1] != 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; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
		var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

		// 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
		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
			// cleanup active request counter
			s.global && jQuery.active--;
			// 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 transfer is complete and the data is available, or the request timed out
			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.dataFilter );
					} 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();

				// 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 ) {
						// Cancel the request
						xhr.abort();

						if( !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 ||
				jQuery.browser.safari && xhr.status == undefined;
		} 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] ||
				jQuery.browser.safari && xhr.status == undefined;
		} catch(e){}
		return false;
	},

	httpData: function( xhr, type, filter ) {
		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
		if( filter )
			data = filter( data, type );

		// 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 = eval("(" + data + ")");

		return data;
	},

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

		// If an array was passed in, assume that it is an array
		// of form elements
		if ( a.constructor == Array || a.jquery )
			// Serialize the form elements
			jQuery.each( a, function(){
				s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
			});

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

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

});
jQuery.fn.extend({
	show: function(speed,callback){
		return speed ?
			this.animate({
				height: "show", width: "show", opacity: "show"
			}, speed, callback) :

			this.filter(":hidden").each(function(){
				this.style.display = this.oldblock || "";
				if ( jQuery.css(this,"display") == "none" ) {
					var elem = jQuery("<" + this.tagName + " />").appendTo("body");
					this.style.display = elem.css("display");
					// handle an edge condition where css is - div { display:none; } or similar
					if (this.style.display == "none")
						this.style.display = "block";
					elem.remove();
				}
			}).end();
	},

	hide: function(speed,callback){
		return speed ?
			this.animate({
				height: "hide", width: "hide", opacity: "hide"
			}, speed, callback) :

			this.filter(":visible").each(function(){
				this.oldblock = this.oldblock || jQuery.css(this,"display");
				this.style.display = "none";
			}).end();
	},

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

	toggle: function( fn, fn2 ){
		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle.apply( this, arguments ) :
			fn ?
				this.animate({
					height: "toggle", width: "toggle", opacity: "toggle"
				}, fn, fn2) :
				this.each(function(){
					jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
				});
	},

	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},

	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},

	slideToggle: function(speed, callback){
		return this.animate({height: "toggle"}, speed, callback);
	},

	fadeIn: function(speed, callback){
		return this.animate({opacity: "show"}, speed, callback);
	},

	fadeOut: function(speed, callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},

	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(){
			if ( this.nodeType != 1)
				return false;

			var opt = jQuery.extend({}, optall), p,
				hidden = 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" ) {
					// 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;
		});
	},

	queue: function(type, fn){
		if ( jQuery.isFunction(type) || ( type && type.constructor == Array )) {
			fn = type;
			type = "fx";
		}

		if ( !type || (typeof type == "string" && !fn) )
			return queue( this[0], type );

		return this.each(function(){
			if ( fn.constructor == Array )
				queue(this, type, fn);
			else {
				queue(this, type).push( fn );

				if ( queue(this, type).length == 1 )
					fn.call(this);
			}
		});
	},

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

});

var queue = function( elem, type, array ) {
	if ( elem ){

		type = type || "fx";

		var q = jQuery.data( elem, type + "queue" );

		if ( !q || array )
			q = jQuery.data( elem, type + "queue", jQuery.makeArray(array) );

	}
	return q;
};

jQuery.fn.dequeue = function(type){
	type = type || "fx";

	return this.each(function(){
		var q = queue(this, type);

		q.shift();

		if ( q.length )
			q[0].call( this );
	});
};

jQuery.extend({

	speed: function(speed, easing, fn) {
		var opt = speed && speed.constructor == Object ? speed : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && easing.constructor != Function && easing
		};

		opt.duration = (opt.duration && opt.duration.constructor == Number ?
			opt.duration :
			jQuery.fx.speeds[opt.duration]) || jQuery.fx.speeds.def;

		// 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: [],
	timerId: null,

	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.display = "block";
	},

	// Get the current size
	cur: function(force){
		if ( this.elem[this.prop] != null && 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;
		this.update();

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

		t.elem = this.elem;

		jQuery.timers.push(t);

		if ( jQuery.timerId == null ) {
			jQuery.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( jQuery.timerId );
					jQuery.timerId = null;
				}
			}, 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
		this.custom(0, this.cur());

		// Make sure that we start at a small width/height to avoid any
		// flash of content
		if ( this.prop == "width" || this.prop == "height" )
			this.elem.style[this.prop] = "1px";

		// 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 )
					this.elem.style.display = "none";

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

			if ( done )
				// 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
 		def: 400
	},
	step: {
		scrollLeft: function(fx){
			fx.elem.scrollLeft = fx.now;
		},

		scrollTop: function(fx){
			fx.elem.scrollTop = fx.now;
		},

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

		_default: function(fx){
			fx.elem.style[ fx.prop ] = fx.now + fx.unit;
		}
	}
});
// The Offset Method
// Originally By Brandon Aaron, part of the Dimension Plugin
// http://jquery.com/plugins/project/dimensions
jQuery.fn.offset = function() {
	var left = 0, top = 0, elem = this[0], results;

	if ( elem ) with ( jQuery.browser ) {
		var parent       = elem.parentNode,
		    offsetChild  = elem,
		    offsetParent = elem.offsetParent,
		    doc          = elem.ownerDocument,
		    safari2      = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),
		    css          = jQuery.curCSS,
		    fixed        = css(elem, "position") == "fixed";

		// Use getBoundingClientRect if available
		if ( elem.getBoundingClientRect ) {
			var box = elem.getBoundingClientRect();

			// Add the document scroll offsets
			add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
				box.top  + Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));

			// IE adds the HTML element's border, by default it is medium which is 2px
			// IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }
			// IE 7 standards mode, the border is always 2px
			// This border/offset is typically represented by the clientLeft and clientTop properties
			// However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS
			// Therefore this method will be off by 2px in IE while in quirksmode
			add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );

		// Otherwise loop through the offsetParents and parentNodes
		} else {

			// Initial element offsets
			add( elem.offsetLeft, elem.offsetTop );

			// Get parent offsets
			while ( offsetParent ) {
				// Add offsetParent offsets
				add( offsetParent.offsetLeft, offsetParent.offsetTop );

				// Mozilla and Safari > 2 does not include the border on offset parents
				// However Mozilla adds the border for table or table cells
				if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )
					border( offsetParent );

				// Add the document scroll offsets if position is fixed on any offsetParent
				if ( !fixed && css(offsetParent, "position") == "fixed" )
					fixed = true;

				// Set offsetChild to previous offsetParent unless it is the body element
				offsetChild  = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;
				// Get next offsetParent
				offsetParent = offsetParent.offsetParent;
			}

			// Get parent scroll offsets
			while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {
				// Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug
				if ( !/^inline|table.*$/i.test(css(parent, "display")) )
					// Subtract parent scroll offsets
					add( -parent.scrollLeft, -parent.scrollTop );

				// Mozilla does not add the border for a parent that has overflow != visible
				if ( mozilla && css(parent, "overflow") != "visible" )
					border( parent );

				// Get next parent
				parent = parent.parentNode;
			}

			// Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild
			// Mozilla doubles body offsets with a non-absolutely positioned offsetChild
			if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) ||
				(mozilla && css(offsetChild, "position") != "absolute") )
					add( -doc.body.offsetLeft, -doc.body.offsetTop );

			// Add the document scroll offsets if position is fixed
			if ( fixed )
				add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
					Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));
		}

		// Return an object with top and left properties
		results = { top: top, left: left };
	}

	function border(elem) {
		add( jQuery.curCSS(elem, "borderLeftWidth", true), jQuery.curCSS(elem, "borderTopWidth", true) );
	}

	function add(l, t) {
		left += parseInt(l, 10) || 0;
		top += parseInt(t, 10) || 0;
	}

	return results;
};


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

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

});})();
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
        	this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
            	i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);
/**
 * jQuery Ajax Rater Plugin
 *
 * This rater is based on the code Ritesh Agrawal did. Unfortunatly his CSS and the hover technique breaks in some browsers.
 * So i thought, why not use the best CSS star-rater known to man kind and throw it in the mix.
 * I have used the CSS and technique from Komodo Media since it is stable and tested on many, many browsers.
 *
 * This rater compared, has no cancel button. But i think we can live with that :)
 * To avoid conflicts i have changed the function name.
 *
 * Licensed under The MIT License
 *
 * @version     1.0
 * @since       03.01.2007
 * @author      Kjell Bublitz <m3nt0r.de@gmail.com
 * @link        http://www.m3nt0r.de/devel/raterDemo/ Demonstration and Documentation
 * @link        http://php.scripts.psu.edu/rja171/widgets/rating.php Based on Ritesh Agrawal Star Rating System
 * @link        http://komodomedia.com/blog/index.php/2007/01/20/css-star-rating-redux/ The Komodo Media CSS Rater Blogpost
 * @license     http://www.opensource.org/licenses/mit-license.php MIT
 * @package     jQuery Plugins
 * @subpackage  Rater
 */

/**
 * Usage: $('#rating').rater('your_servlet', {style:'basic', maxvalue:5, curvalue:0});
 *
 * @param url The address you want to post the result to.
 * @param options The style and value attributes
 *
 * Valid options:
 * ---------------------------------------
 *       style:       'basic', 'inline' OR 'small'
 *       maxvalue:    the maximum value / number of stars
 *       curvalue:    the initial value / selected stars
 */
jQuery.fn.rater = function(url, options, id)
{
	if(url == null) return;
	var settings = {
		url       : url, // post changes to
		maxvalue  : 5,   // max number of stars
		curvalue  : 3    // number of selected stars
	};

	if(options) { jQuery.extend(settings, options); };
	jQuery.extend(settings, {cancel: (settings.maxvalue > 1) ? true : false});

	var container = jQuery(this);
	jQuery.extend(container, { averageRating: settings.curvalue, url: settings.url });

	if(!settings.style || settings.style == null || settings.style == 'basic') {
		var raterwidth = settings.maxvalue * 25;
		var ratingparent = '<ul class="star-rating" style="width:'+raterwidth+'px">';
	}
	if(settings.style == 'small') {
		var raterwidth = settings.maxvalue * 10;
		var ratingparent = '<ul class="star-rating small-star" style="width:'+raterwidth+'px">';
	}
	if(settings.style == 'inline') {
		var raterwidth = settings.maxvalue * 10;
		var ratingparent = '<span class="inline-rating"><ul class="star-rating small-star" style="width:'+raterwidth+'px">';
	}
	container.append(ratingparent);

	// create rater
	var starWidth, starIndex, listitems = '';
	var curvalueWidth = Math.floor(100 / settings.maxvalue * settings.curvalue);
	for(var i = 0; i <= settings.maxvalue ; i++) {
		if (i == 0) {
			listitems+='<li class="current-rating" style="width:'+curvalueWidth+'%;">'+settings.curvalue+'/'+settings.maxvalue+'</li>';
		} else {
			starWidth = Math.floor(100 / settings.maxvalue * i);
			starIndex = (settings.maxvalue - i) + 2;
			listitems+='<li class="star"><a href="#'+i+'" title="'+i+'/'+settings.maxvalue +'" style="width:'+starWidth+'%;z-index:'+starIndex+'">'+i+'</a></li>';
		}
	}
	container.find('.star-rating').append(listitems); // i am using find here, because the span wrapped in the small style would break children()

	if(settings.maxvalue > 1) // add a container for the ajax result
	{
		container.append('<span class="star-rating-result"></span>');
	}
	var stars = jQuery(container).find('.star-rating').children('.star');
	stars.click(function()
	{
		if(settings.maxvalue == 1) // on / off
		{
			settings.curvalue = (settings.curvalue == 0) ? 1 : 0;
			jQuery(container).find('.star-rating').children('.current-rating').css({width:(settings.curvalue*100)+'%'});
			jQuery.post(container.url, { "rating": settings.curvalue, "id": id});
			return false;
		}
		else
		{

			settings.curvalue = stars.index(this) + 1;
			raterValue = jQuery(this).children('a')[0].href.split('#')[1];
			jQuery.post(container.url, { "rating": raterValue, "id": id }, function(response){
				container.children('.star-rating-result').html(response)
			});

			return false;
		}
		return true;
	});

	return this; // strict warning: anonymous function does not always return a value. fix?
}
/*
 *
 * Copyright (c) 2006-2008 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.2.3
 * Demo: http://www.texotela.co.uk/code/jquery/select/
 *
 * $LastChangedDate$
 * $Rev$
 *
 */

;(function($) {

/**
 * Adds (single/multiple) options to a select box (or series of select boxes)
 *
 * @name     addOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
 * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
 * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
 *
 */
$.fn.addOption = function()
{
	var add = function(el, v, t, sO)
	{
		var option = document.createElement("option");
		option.value = v, option.text = t;
		// get options
		var o = el.options;
		// get number of options
		var oL = o.length;
		if(!el.cache)
		{
			el.cache = {};
			// loop through existing options, adding to cache
			for(var i = 0; i < oL; i++)
			{
				el.cache[o[i].value] = i;
			}
		}
		// add to cache if it isn't already
		if(typeof el.cache[v] == "undefined") el.cache[v] = oL;
		el.options[el.cache[v]] = option;
		if(sO)
		{
			option.selected = true;
		}
	};

	var a = arguments;
	if(a.length == 0) return this;
	// select option when added? default is true
	var sO = true;
	// multiple items
	var m = false;
	// other variables
	var items, v, t;
	if(typeof(a[0]) == "object")
	{
		m = true;
		items = a[0];
	}
	if(a.length >= 2)
	{
		if(typeof(a[1]) == "boolean") sO = a[1];
		else if(typeof(a[2]) == "boolean") sO = a[2];
		if(!m)
		{
			v = a[0];
			t = a[1];
		}
	}
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			if(m)
			{
				for(var item in items)
				{
					add(this, item, items[item], sO);
				}
			}
			else
			{
				add(this, v, t, sO);
			}
		}
	);
	return this;
};

/**
 * Add options via ajax
 *
 * @name     ajaxAddOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String url      Page to get options from (must be valid JSON)
 * @param    Object params   (optional) Any parameters to send with the request
 * @param    Boolean select  (optional) Select the added options, default true
 * @param    Function fn     (optional) Call this function with the select object as param after completion
 * @param    Array args      (optional) Array with params to pass to the function afterwards
 * @example  $("#myselect").ajaxAddOption("myoptions.php");
 * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"});
 * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"}, false, sortoptions, [{"dir": "desc"}]);
 *
 */
$.fn.ajaxAddOption = function(url, params, select, fn, args)
{
	if(typeof(url) != "string") return this;
	if(typeof(params) != "object") params = {};
	if(typeof(select) != "boolean") select = true;
	this.each(
		function()
		{
			var el = this;
			$.getJSON(url,
				params,
				function(r)
				{
					$(el).addOption(r, select);
					if(typeof fn == "function")
					{
						if(typeof args == "object")
						{
							fn.apply(el, args);
						}
						else
						{
							fn.call(el);
						}
					}
				}
			);
		}
	);
	return this;
};

/**
 * Removes an option (by value or index) from a select box (or series of select boxes)
 *
 * @name     removeOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String|RegExp|Number what  Option to remove
 * @param    Boolean selectedOnly       (optional) Remove only if it has been selected (default false)
 * @example  $("#myselect").removeOption("Value"); // remove by value
 * @example  $("#myselect").removeOption(/^val/i); // remove options with a value starting with 'val'
 * @example  $("#myselect").removeOption(/./); // remove all options
 * @example  $("#myselect").removeOption(/./, true); // remove all options that have been selected
 * @example  $("#myselect").removeOption(0); // remove by index
 * @example  $("#myselect").removeOption(["myselect_1","myselect_2"]); // values contained in passed array
 *
 */
$.fn.removeOption = function()
{
	var a = arguments;
	if(a.length == 0) return this;
	var ta = typeof(a[0]);
	var v, index;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(ta == "string" || ta == "object" || ta == "function" )
	{
		v = a[0];
		// if an array, remove items
		if(v.constructor == Array)
		{
			var l = v.length;
			for(var i = 0; i<l; i++)
			{
				this.removeOption(v[i], a[1]);
			}
			return this;
		}
	}
	else if(ta == "number") index = a[0];
	else return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			// clear cache
			if(this.cache) this.cache = null;
			// does the option need to be removed?
			var remove = false;
			// get options
			var o = this.options;
			if(!!v)
			{
				// get number of options
				var oL = o.length;
				for(var i=oL-1; i>=0; i--)
				{
					if(v.constructor == RegExp)
					{
						if(o[i].value.match(v))
						{
							remove = true;
						}
					}
					else if(o[i].value == v)
					{
						remove = true;
					}
					// if the option is only to be removed if selected
					if(remove && a[1] === true) remove = o[i].selected;
					if(remove)
					{
						o[i] = null;
					}
					remove = false;
				}
			}
			else
			{
				// only remove if selected?
				if(a[1] === true)
				{
					remove = o[index].selected;
				}
				else
				{
					remove = true;
				}
				if(remove)
				{
					this.remove(index);
				}
			}
		}
	);
	return this;
};

/**
 * Sort options (ascending or descending) in a select box (or series of select boxes)
 *
 * @name     sortOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    Boolean ascending   (optional) Sort ascending (true/undefined), or descending (false)
 * @example  // ascending
 * $("#myselect").sortOptions(); // or $("#myselect").sortOptions(true);
 * @example  // descending
 * $("#myselect").sortOptions(false);
 *
 */
$.fn.sortOptions = function(ascending)
{
	var a = typeof(ascending) == "undefined" ? true : !!ascending;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			// create an array for sorting
			var sA = [];
			// loop through options, adding to sort array
			for(var i = 0; i<oL; i++)
			{
				sA[i] = {
					v: o[i].value,
					t: o[i].text
				}
			}
			// sort items in array
			sA.sort(
				function(o1, o2)
				{
					// option text is made lowercase for case insensitive sorting
					o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase();
					// if options are the same, no sorting is needed
					if(o1t == o2t) return 0;
					if(a)
					{
						return o1t < o2t ? -1 : 1;
					}
					else
					{
						return o1t > o2t ? -1 : 1;
					}
				}
			);
			// change the options to match the sort array
			for(var i = 0; i<oL; i++)
			{
				o[i].text = sA[i].t;
				o[i].value = sA[i].v;
			}
		}
	);
	return this;
};
/**
 * Selects an option by value
 *
 * @name     selectOptions
 * @author   Mathias Bank (http://www.mathias-bank.de), original function
 * @author   Sam Collett (http://www.texotela.co.uk), addition of regular expression matching
 * @type     jQuery
 * @param    String|RegExp value  Which options should be selected
 * can be a string or regular expression
 * @param    Boolean clear  Clear existing selected options, default false
 * @example  $("#myselect").selectOptions("val1"); // with the value 'val1'
 * @example  $("#myselect").selectOptions(/^val/i); // with the value starting with 'val', case insensitive
 *
 */
$.fn.selectOptions = function(value, clear)
{
	var v = value;
	var vT = typeof(value);
	var c = clear || false;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if(o[i].value.match(v))
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
				else
				{
					if(o[i].value == v)
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
			}
		}
	);
	return this;
};

/**
 * Copy options to another select
 *
 * @name     copyOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String to  Element to copy to
 * @param    String which  (optional) Specifies which options should be copied - 'all' or 'selected'. Default is 'selected'
 * @example  $("#myselect").copyOptions("#myselect2"); // copy selected options from 'myselect' to 'myselect2'
 * @example  $("#myselect").copyOptions("#myselect2","selected"); // same as above
 * @example  $("#myselect").copyOptions("#myselect2","all"); // copy all options from 'myselect' to 'myselect2'
 *
 */
$.fn.copyOptions = function(to, which)
{
	var w = which || "selected";
	if($(to).size() == 0) return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(w == "all" ||	(w == "selected" && o[i].selected))
				{
					$(to).addOption(o[i].value, o[i].text);
				}
			}
		}
	);
	return this;
};

/**
 * Checks if a select box has an option with the supplied value
 *
 * @name     containsOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Boolean|jQuery
 * @param    String|RegExp value  Which value to check for. Can be a string or regular expression
 * @param    Function fn          (optional) Function to apply if an option with the given value is found.
 * Use this if you don't want to break the chaining
 * @example  if($("#myselect").containsOption("val1")) alert("Has an option with the value 'val1'");
 * @example  if($("#myselect").containsOption(/^val/i)) alert("Has an option with the value starting with 'val'");
 * @example  $("#myselect").containsOption("val1", copyoption).doSomethingElseWithSelect(); // calls copyoption (user defined function) for any options found, chain is continued
 *
 */
$.fn.containsOption = function(value, fn)
{
	var found = false;
	var v = value;
	var vT = typeof(v);
	var fT = typeof(fn);
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return fT == "function" ? this: found;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// option already found
			if(found && fT != "function") return false;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if (o[i].value.match(v))
					{
						found = true;
						if(fT == "function") fn.call(o[i], i);
					}
				}
				else
				{
					if (o[i].value == v)
					{
						found = true;
						if(fT == "function") fn.call(o[i], i);
					}
				}
			}
		}
	);
	return fT == "function" ? this : found;
};

/**
 * Returns values which have been selected
 *
 * @name     selectedValues
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Array
 * @example  $("#myselect").selectedValues();
 *
 */
$.fn.selectedValues = function()
{
	var v = [];
	this.find("option:selected").each(
		function()
		{
			v[v.length] = this.value;
		}
	);
	return v;
};

/**
 * Returns options which have been selected
 *
 * @name     selectedOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").selectedOptions();
 *
 */
$.fn.selectedOptions = function()
{
	return this.find("option:selected");
};

})(jQuery);
(function($) {


    $.fn.ajaxMultiFileUpload = function(options) {

        return this.each(function() {

			var opt = $.extend({},$.fn.ajaxMultiFileUpload.defaults, options);
			var fopt = {
    				image: "images/btn_add_photo.gif",
    				imageheight : 30,
    				imagewidth : 96,
    				width : 268,
    				onlyButton: false
				};
        	if (opt.fileTypes.match('jpg') && !opt.fileTypes.match('jpeg')) opt.fileTypes += ',jpeg';

			// add the form to the document
         	$(this).append('<input type="hidden" name="uploadCount" id="uploadCount" value="0" />' +
							'<div id="listOfFiles"><h2 class="numFiles"></h2></div><div class="responseMsg">Odpowiedź:</div><div id="response"><ul></ul></div>'
							+ '<form action="' + opt.ajaxFile + '" method="post" enctype="multipart/form-data" id="myUploadForm" name="myUploadForm">' +
         					'<input type="hidden" name="sid" value="' + opt.sid + '" />' +
         					'<input type="hidden" name="filetypes" value="' + opt.fileTypes + '" /><div id="listOfInputs">' +
  							'<input size="1" type="file" id="img1" class="myUploadFile" name="file1"  /></div></form>');
			$(this).bind('addThumbEx', function(e, val, selected){addThumb(val, selected);});
			// delete previously uploaded file
			$("a.remove").livequery('click', function(){

				var _delete = this.id;
				var _this = $(this);

			//	UNCOMMENT THIS FUNCTION WHEN NOT BLOCKING FILES FROM STAYING ON SERVER
				$.get(opt.ajaxFile +"?delete=" + _delete + "&sid=" + opt.sid, function(returned){
					if(returned=="NONE") return;
					$('#response ul').append('<div><li>' + returned.replace(/^\s+|\s+$/g, '') + '</li></div>');
					// remove input.file by searching for input with filename as class
					$("input[@className*='"+ _delete + "']").parent().remove();
					// remove the first input.file also.  another will be added by addInput()
					deleteFileInput($("#listOfInputs input:file.myUploadFile:eq(0)"));

					_this.parent().remove();
					addInput(false);
 				});
 			//	DELETE THIS LINE WHEN NOT BLOCKING FILES FROM STAYING ON SERVER
 			//	$('#response ul').append('<div><li>Plik <span>' +_delete + '</span> został usunięty.</li></div>');
			});

			/**
			 *
			 * @access public
			 * @return void
			 **/
			function deleteFileInput(fileInput){
				$(fileInput).parent().prev().remove(); 				// remove the input
				$(fileInput).parent().remove(); 				// remove the input

			}

        	// update the file counter
			function updateCount(mode) {
				var cnt = $(".nameOfFile").size();
				$("#uploadCount").val(cnt);
				$("h2.numFiles").text( "dodanych zdjęć: " + cnt);
				if(cnt||mode)
				{
					fopt.image = "images/btn_add_photo_next.gif";
					$('#listOfFiles').show();
				}
				else
				{
					fopt.image = "images/btn_add_photo.gif";
					$('#listOfFiles').hide();
				}
			}

			// update the input to the form after submit
			function addInput(mode) {
				updateCount(mode);
				// add another input.file to the page and initialize the inputfile plugin
				$("#listOfInputs").prepend('<input size="1" type="file" class="myUploadFile" name="file" id="img" />');
				$("#listOfInputs input:file.myUploadFile:eq(0)").filestyle(fopt);
			}

			function addThumb(_img_name, selected)
			{
				_newFile = $('<div class="nameOfFile"></div>');

				// add thumb image
				//compute path
				img_ = new Image();
				$(img_).appendTo(_newFile).attr({ src:_img_name, title:_img_name });

                _newFile.append('<a href="#" class="remove" id="'+_img_name+'">Usuń zdjęcie</a>');
                _newFile.append('<br /><input type="radio" name="set_avatar" value="'+_img_name+'" '+selected+'> <span style="font-size: 15px;">Ustaw jako zdjęcie główne</span>');
				// add to dom
				$("#listOfFiles").append(_newFile);

				// update file counter
		 		updateCount(false);
			}

			// when form input changes
			//$("input.myUploadFile").livequery('change', function(){
			$("#listOfInputs input:file.myUploadFile").livequery('change', function(){

				if(this.value) {
					// check file extension for approved file types
					if (opt.fileTypes.match(this.value.toLowerCase().substr(this.value.toLowerCase().lastIndexOf('.')+1))) {
						$('form#myUploadForm').submit();	// submit the form
						deleteFileInput(this);
						//$(this).remove(); 				// remove the input
						addInput(true);										// add new input
					}
					else {
						alert('Typ ' + this.value.substr(this.value.lastIndexOf('.')+1) + ' jest niedozwolony');
						return false;
					}
				}
				else alert("Brak zdjęć do załadowania.");
			});

			var event = {

				frame : function() {
					// build iframe to receive form data, remove previous iFrame first
					$("iframe#myFrame").remove();
					$("body").append("<div><iframe src='about:blank' id='myFrame' name='myFrame'></iframe></div>");
					// onload iFrame, call loaded function
					$("iframe#myFrame").load(function(){
							event.loaded(this);
					});
					// return iFrame id for form target
					return 'myFrame';
				},

				submit : function(_form) {
					// onsubmit, reassign form target to iframe and show ajax loader
					_form.setAttribute('target', event.frame());
					$('#loader').show();
				},

				loaded : function(id) {
					// determine platform syntax
					if (id.contentDocument)
						var d = id.contentDocument;
					else if (id.contentWindow)
						var d = id.contentWindow.document;
					else
						var d = window.frames[id].document;

					// trim name of file returned to iFrame
					
					var _img_name = d.body.innerHTML.replace(/^\s+|\s+$/g, '');
					if(_img_name == '') return;
					// hide ajax loader
					$('#loader').hide();

					// check if php mime file type is approved
					if (_img_name.match('niedozwolony')) {
						$('#response ul').append(_img_name);
						return false;
					}
					else if(_img_name.match('Minimalny')) {
						$('#valErr').html(_img_name);
                        $('#valErr').show();
						jQuery(window).scrollTop(0);
                        return false;
					}
					else {
						// build file thumb display
						
						addThumb(_img_name);
                        $('#valErr').hide();
                        $('#valErr').empty();
		 			}
				}
			}
			// submit form to event variable
			$('form#myUploadForm').submit(function(){
					return event.submit(this);
			});

			// initialize the inputfile plugin for input.file
			$("input:file.myUploadFile").filestyle(fopt);

			// update the file counter
			updateCount(false);

			// add ajax loader
			$('#listOfInputs').append("<div id='loader'><img src='images/sending-bar.gif' /><div>");
      		$('#loader').hide();

        });
	};

    // plugin defaults
    $.fn.ajaxMultiFileUpload.defaults = {
        ajaxFile: "ajax-upload.html",
        fileTypes: "jpg",
        sid: 0
    };

})(jQuery);
/*##############################################################################
#    ____________________________________________________________________
#   /                                                                    \
#  |               ____  __      ___          _____  /     ___    ___     |
#  |     ____       /  \/  \  ' /   \      / /      /__   /   \  /   \    |
#  |    / _  \     /   /   / / /    /  ___/  \__   /     /____/ /    /    |
#  |   / |_  /    /   /   / / /    / /   /      \ /     /      /____/     |
#  |   \____/    /   /    \/_/    /  \__/  _____/ \__/  \___/ /           |
#  |                                                         /            |
#  |                                                                      |
#  |   Copyright (c) 2007                             MindStep SCOP SARL  |
#  |   Herve Masson                                                       |
#  |                                                                      |
#  |      www.mindstep.com                              www.mjslib.com    |
#  |   info-oss@mindstep.com                           mjslib@mjslib.com  |
#   \____________________________________________________________________/
#
#  Version: 1.0.0
#
#  (Svn version: $Id: jquery.autoimage.js 3437 2007-11-07 05:14:14Z herve $)
#
#----------[This product is distributed under a BSD license]-----------------
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#
#     2. 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.
#
#  THIS SOFTWARE IS PROVIDED BY THE MINDSTEP CORP PROJECT ``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 MINDSTEP CORP 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.
#
#  The views and conclusions contained in the software and documentation
#  are those of the authors and should not be interpreted as representing
#  official policies, either expressed or implied, of MindStep Corp.
#
################################################################################
#
#	This is a jQuery [jquery.com] plugin that implements image animations
#
#	@author: Herve Masson
#	@version: 1.0 (8/5/2007)
#	@requires jQuery v1.1.2 or later
#
#	(Partly based on the legacy mjslib.org framework)
#
#	Dependencies: you need to load jquery.printf.js before this plugin
#
##############################################################################*/

/*
**	$('#image').autoimage({ options })
**
**	Options:
**
**	mouseover:
**		When true, animation progresses when the mouse is placed over the image.
**		Otherwise, animation runs contunously over time.
**
**	href:
**		specifies a link reference that will be associated with the image. When the
**		image is clicked, this link is handled the same way we set 'href'
**		to a <a> tag.
**
**	images:
**		this gives a list of secundary images to be displayed. For a mouseover
**		image, you only need one. For an animated image, you can use as many
**		as you want.
**
**	circular:
**		enable (when true) circular animation
**
**
*/

/*
**	                 =================================
**	                 >> Some Implementation details <<
**	                 =================================
**
**
**	A full animation cycle is represented by a 'pos' float value between 0 and 1:
**	=============================================================================
**
**
**	                        +--- current position
**	                        |
**	    0                   v                        1 <-- position value
**	    |---------=====|----x----=====|---------=====|
**	    |              |    ^         |              |
**	     \_ image1      \_ image2      \_ image3      \_ image4
**	       (slide1)       (slide2)       (slide3)       (slide4)
**
**
**	"-----"		the image is shown stable during this period of time
**	"====="		represents the smooth transition between images (crossfade)
**
**
**	In circular mode (loop=="cycle"):
**	=================================
**
**	The schema takes an extra slide so that the first image can follow
**	the last one.
**
**	                        +--- current position
**	                        |
**	    0                   v                                       1
**	    |---------=====|----x----=====|---------=====|---------=====|---------=====|...
**	    |              |    ^         |              |              |
**	    |    image1    |   image2     |   image3     |   image4     |     image1
**	    |   (slide1)   |  (slide2)    |  (slide3)    |  (slide4)    |    (slide1)
**
**
**	The amount of time spent in both stable and fade period is set via
**	the 'fade' parameter. It sets, in percentage, how long the fade
**	period lasts:
**
**	 - 100% means maximum fading (fadin occurs all along the slide period)
**	 - 0% means no fading
**	 - with 50%, stable and crossfading duration are equal
**
**
**	Internal representation:
**	========================
**
**	The whole sequence is converted into a list of regions. Each region is
**	defined by:
**
**	 - a length (a value in the 0...1 position domain)
**	 - an index representing the source image
**	 - an index representing the target image
**	 - a boolean that tells if this is a crossfade transition or not
**
**	For example, a non-cyclic animation made of 3 images with a fade parameter
**	set as 50% will be converted in 4 regions:
**
**	- region 1: source=0, target=undefined, length=.25, fade=false
**	- region 2: source=0, target=1, length=.25, fade=true
**	- region 3: source=1, target=undefined, length=.25, fade=false
**	- region 4: source=1, target=2, length=.25, fade=true
**
**	    0             .25              .5             .75             1 <-- position
**	    |---------------===============|---------------===============|
**	    |    region1        region2    |    region3        region4    |
**	    |                              |                              |
**	    |                              |                              |
**	     \_ image1                      \_ image2                      \_ image3
**	       (slide1)                       (slide2)                       (slide3)
**
**
**	Note: I've done this representation so that we can specify arbitrary
**	transition durations in the future (for now, all slides have the same
**	region pattern). This will come in future revisions.
**
**
**	Looping
**	=======
**
**	By default, the image animation stops when it reaches a boundary (first or
**	last images). You can change that by giving a 'loop' parameter, which can
**	take those values:
**
**	  'none'     no looping (default)
**	  'cycle'    jump to the first image when we reach the last
**	  'bounce'   change direction when we reach the first or the last image
**
*/


(function($) {

	var TIMERINTERVAL=50;

	var LOOPMODES=
	{
		cycle:	{ cycle:true },
		bounce:	{ bounce: true }
	};

	var ISIE=jQuery.browser.msie;

	$.fn.extend(
		{
			autoimage:function(opts)
				{ return this.each(function() { return $.autoimage(this,opts); });			},

			aiButton:function(opts)
				{ return this.each(function() { return $.aiButton(this,opts); });			},

			aiApplyMarkupExtensions:function()
				{ return this.each(function() { return $.aiApplyMarkupExtensions(this); });	}
		}
	);

	$.autoimage=function(image,opts)
	{
		if(opts==undefined)
		{
			errorf("options are missing in autoimage()");
			return;
		}
		if(image.aimInfo!=undefined)
		{
			errorf("image is already assigned on element ID=%s",image.id);
			return;
		}

		var srclist=opts.images;

		/*
		** Creates a container for all images (they'll be shown one by one)
		** Note: to position images within the container, the
		** container needs to have a relative positioning (don't ask me why)
		*/

		$(image).wrap("<div></div>");
		var imcontainer=image.parentNode;
		imcontainer.style.position="relative";
		// Resizes the container to fit the image exactly
		resize(imcontainer,image.offsetWidth,image.offsetHeight);

		/*
		** Now, creates alternate image(s) and move them all in absolute positions
		** at offset 0:0 so that they all fit in the same screen space
		*/

		var imlist=[image];
		if(srclist!=undefined)
		{
			for(var i=1;i<=srclist.length;i++)
			{
				var im=document.createElement('img');
				im.src=srclist[i-1];
				imcontainer.appendChild(im);
				imlist[i]=im;
			}
		}

		for(var i=0;i<imlist.length;i++)
		{
			var im=imlist[i];
			im.style.position="absolute";
			im.style.top="0px";
			im.style.left="0px";
			im.border=0;
			if(i>0)
			{
				// Only keep the primary image visible for now
				$(im).hide;
			}
		}


		/*
		** Now deals with the href option
		*/

		if(opts.href)
		{
			$(imcontainer).wrap("<a></a>");
			var anchor=imcontainer.parentNode;
			anchor.href=opts.href;
		}

		if(imlist.length==1)
		{
			// No image animation, just a link
			return;
		}

		/*
		**	Parses options; build the AutoIMage information block,
		**	and attach it to the container
		*/

		var aim=imcontainer.aimInfo=image.aimInfo=
			{
				id:			image.id,
				images:		imlist,
				count:		imlist.length,
				fade:		opts.fade,
				speed:		opts.speed,
				bwspeed:	opts.bwspeed,
				fwspeed:	opts.fwspeed,
				mouseover:	opts.mouseover
			};

		var mode=opts.loop,val;
		if(mode!=undefined)
		{
			if((val=LOOPMODES[mode])==undefined)
			{
				errorf("unknown loop mode '%s'",mode);
			}
			else
			{
				aim.bounce=val.bounce;
				aim.cycle=val.cycle;
			}
		}

		// Computes animation speed values
		if(aim.speed==undefined)
		{
			aim.speed=$.autoimage.defaults.speed;
		}
		if(aim.fwspeed==undefined)
		{
			aim.fwspeed=aim.speed;
		}
		if(aim.bwspeed==undefined)
		{
			aim.bwspeed=aim.fwspeed;
		}
		if(aim.fwspeed>0)
		{
			aim.incfactor=1/aim.fwspeed;
		}

		if(aim.fade==undefined)
		{
			aim.fade=$.autoimage.defaults.fade;
		}
		if(aim.fade===true)
		{
			aim.fade=100;
		}

		/*
		**	Build the region map
		*/

		var nslices=(aim.cycle)?aim.count:aim.count-1;
		var regsz=1/nslices;
		var reglist=[],regidx=0

		for(var i=0;i<nslices;i++)
		{
			var next=(i+1)%aim.count;
			if(aim.fade>=100)
			{
				// Full fading mode (no stable image)
				reglist[regidx++]={ source:i, target:next, length: regsz, fade:true };
			}
			else if(aim.fade<=0)
			{
				// Non fading mode
				reglist[regidx++]={ source:i, length: regsz, fade:false };
			}
			else
			{
				var fadesz=(aim.fade*regsz)/100;
				var stsz=regsz-fadesz;
				reglist[regidx++]={ source:i, length: stsz, fade:false };
				reglist[regidx++]={ source:i, target: next, length: fadesz, fade:true };
			}
		}

		// Inserts an artificial region for the non-circular mode (last image in stable mode)
		if(!aim.cycle)
		{
			reglist[regidx++]={ source:(aim.count-1), length: 0, fade:false };
		}

		aim.regions=reglist;
		aim.regcount=reglist.length;

		/*
		**	Hook necessary event handlers
		*/

		if(opts.mouseover)
		{
			//	We want the image animation to run when the mouse is over the image
			$(imcontainer).hover(
				function(){return onMouseEnter(aim)},
				function(){return onMouseLeave(aim)}
			);
		}
		else
		{
			//	Time controls the animation
			startTimeAnim(aim);
		}

		// Starts at position 0

		setPosition(aim,0);
	}

	$.aiButton=function(image,opts)
	{
		if(opts==undefined)
		{
			errorf("options are missing in aiButton()");
			return;
		}
		if(opts.oversrc!=undefined)
		{
			opts.images=[opts.oversrc];
		}
		opts.mouseover=true;
		if(opts.fade)
		{
			opts.fwspeed=$.autoimage.defaults.buttons.fwspeed;
			opts.bwspeed=$.autoimage.defaults.buttons.bwspeed;
		}
		else
		{
			opts.speed=0;
		}
		return $.autoimage(image,opts);
	}


	/*
	**	Apply autoimage markup extensions
	**	=================================
	**
	**	Because I find writing javascript hooks overkilling for small features
	**	such as overstate images, I added this possibility to extend the HTML
	**	attributes of the image element.
	**
	**	If you want to create an overstate button with fading effect between
	**	the two state images, you would write this in your HTML:
	**
	**		<img src=image1 oversrc=image2 href="javascript:bingo()" fade="true">
	**		                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	**	This markup extensions recognize the following non-conventional attributes:
	**
	**	- href: just set it as you would do with <a>
	**	- oversrc: set an overstate image
	**	- fade: set the fade value (ex: "yes","no","true","false",50,...)
	**
	**	Note: the HTML extensions are enabled by default.
	**
	*/

	function applyImageMarkup(image)
	{
		var opts={},href,oversrc,fade,doit=false;

		if(href=$(image).attr("href"))
		{
			opts.href=href;
			doit=true;
		}
		if(oversrc=$(image).attr("oversrc"))
		{
			opts.oversrc=oversrc;
			doit=true;
			if(fade=$(image).attr("fade"))
			{
				opts.fade=parseFade(fade);
			}
		}
		if(doit)
		{
			$(image).aiButton(opts);
		}
	}

	$.aiApplyMarkupExtensions=function(from)
	{
		from=from||document.body;

		$("img").each(function()
			{
				applyImageMarkup(this);
			});
	}

	/*
	**	              ========================================
	**	              >> Private code - do not use directly <<
	**	              ========================================
	*/


	/*
	**	Progress the animation
	**	======================
	**
	**	Change the animation position backward or forward, according to
	**	the current increment factor value. Stops the timer when we
	**	reached an end.
	**
	*/

	function onTimer(aim)
	{
		var now=curtime();

		if(aim.hoverlast==undefined)
		{
			aim.hoverlast=now;
		}

		var delta=now-aim.hoverlast;
		var inc=aim.incfactor*delta;
		var newpos=aim.pos+inc;

		if(!aim.cycle)
		{
			if(aim.bounce)
			{
				if(newpos>=1)
				{
					newpos=1;
					aim.incfactor=-1/aim.bwspeed;
				}
				else if(newpos<=0)
				{
					newpos=0;
					aim.incfactor=1/aim.fwspeed;
				}
			}
			else
			{
				// Clip the value in non circular mode
				newpos=newpos>1?1:newpos;
				newpos=newpos<0?0:newpos;
			}
		}

		setPosition(aim,newpos);
		aim.hoverlast=now;

		if(aim.incfactor<0 && newpos<=0)
		{
			// Backward animation finished -> we no longer need the timer
			stopHoverTimer(aim);
		}
	}


	/*
	**	Runs the animation continously
	**	==============================
	**
	*/

	function startTimeAnim(aim)
	{
		aim.timer=setInterval(function(){onTimer(aim);},TIMERINTERVAL);
	}

	/*
	**	Runs the animation on mouseover conditions:
	**	===========================================
	**
	**	In circular mode, the animation stops when the mouse leave the area,
	**	and restarts on next mouseenter at the same position.
	**
	**	In non circular mode, the animation goes backward when the mouse leave
	**	the area, until it reaches the position 0.
	**
	*/

	function stopHoverTimer(aim)
	{
		clearInterval(aim.timer);
		aim.timer=undefined;
		aim.hoverlast=undefined;
	}

	function onMouseEnter(aim)
	{
		if(aim.fwspeed<=0)
		{
			// speed=0 means instantly
			stopHoverTimer(aim);
			setPosition(aim,1);
			return;
		}
		aim.incfactor=1/aim.fwspeed;
		if(aim.timer==undefined)
		{
			aim.timer=setInterval(function(){onTimer(aim)},TIMERINTERVAL);
		}
	}

	function onMouseLeave(aim)
	{
		if(aim.bwspeed<=0)
		{
			// speed=0 means instantly
			stopHoverTimer(aim);
			setPosition(aim,0);
			return;
		}
		aim.incfactor=-1/aim.bwspeed;
		if(aim.cycle)
		{
			// circular mode: we stop where we are
			stopHoverTimer(aim);
		}
	}


	/*
	**	Set the animation position, and update image(s) accordingly
	**	===========================================================
	**
	**	This is the heart of this module. It select an arbitrary position
	**	within the animation, from 0 (start) to 1 (end).
	**
	*/

	function setPosition(aim,pos)
	{
		// Slide "size" (how much we spend in one frame)
		var slsize=1/aim.count;

		// Current image transparency
		var transp=0;

		// Current and next image indexes
		var curim;

		// Keep for later
		aim.pos=pos;

		// Sanitize the 'pos' value
		if(aim.cycle)
		{
			// In circular mode, we do modulo
			if(pos<0)
			{
				pos=pos-int(pos)+1;
			}
			if(pos>=1)
			{
				pos=pos-int(pos);
			}
		}
		else
		{
			// In non-circular mode, we do clipping (and the value 1 is okay)
			pos=pos<0?0:pos;
			pos=pos>1?1:pos;
		}

		// See if something changed since last time
		if(pos==aim.sanepos)
		{
			// We are already there
			return;
		}

		// Saves the sanitized value
		aim.sanepos=pos;

		// Parses the region list to see where we are
		var reg,regpos=pos;
		for(var i=0;i<aim.regcount;i++)
		{
			reg=aim.regions[i];
			if(reg.length>regpos)
			{
				break;
			}
			regpos-=reg.length;
		}

		if(!reg.fade)
		{
			// No crossfading here -> show the current image and hide others
			for(var i=0;i<aim.count;i++)
			{
				if(i==reg.source)
				{
					showOpaqueImage(aim.images[i]);
				}
				else
				{
					hideImage(aim.images[i]);
				}
			}
			return;
		}

		/*
		**	This is where it gets a little trickier - cross-fading
		**
		** See where we are in the image transition (0: source image, 1: dest image)
		** (This gives the opacity factor, also between 0 and 1)
		*/

		var opac=(regpos/reg.length);
		for(var i=0;i<aim.count;i++)
		{
			var im=aim.images[i];
			if(i==reg.target)
			{
				// Makes the target image the foreground image
				im.style.zIndex=1;
				setOpacity(im,opac);
				showImage(im);
			}
			else if(i==reg.source)
			{
				// Makes the source image the background image
				im.style.zIndex=0;
				showOpaqueImage(im);
			}
			else
			{
				// We don't need this one for now
				hideImage(im);
			}
		}
	}

	/*
	**	Misc utilities
	*/

	function showImage(im)			{ im.style.visibility="visible";	}
	function showOpaqueImage(im)	{ setOpacity(im,1); showImage(im);	}
	function hideImage(im)			{ im.style.visibility="hidden";		}
	function int(val)				{ return Math.floor(val);			}
	function curtime()				{ return (new Date()).getTime();	}

	if($.verrorf)
	{
		function errorf()	{ $.verrorf(arguments);	}
		function logf()		{ $.vlogf(arguments);	}
	}
	else
	{
		function errorf()	{ }
		function logf()		{ }
	}

	function setOpacity(elem,opac)
	{
		if(opac>=1 && !elem.aimHasOpac)
		{
			// Don't apply opacity filter when we never use a value != 1 before
			// (I am not sure if that worth it, but some browser might like it)
			return;
		}
		if(ISIE)
		{
			elem.style.filter="alpha(opacity=" + opac + ")";
		}
		else
		{
			elem.style.opacity=opac;
		}
		elem.aimHasOpac=true;
	}

	function resize(el,dx,dy)
	{
		if(dx != undefined)
		{
			el.style.width=dx+"px";
		}
		if(dy != undefined)
		{
			el.style.height=dy+"px";
		}
	}

	function parseFade(prm)
	{
		if(prm.constructor!=String)
		{
			return prm;
		}
		prm=prm.toLowerCase();
		// Parses the string value
		if(prm=="true" || prm=="yes")
		{
			return true;
		}
		if(prm=="false" || prm=="no")
		{
			return false;
		}
		var ival=parseInt(prm);
		if(isNaN(prm))
		{
			errorf("'%s' is not a legal value for 'fade' parameter",prm);
			return undefined;
		}
		return ival;
	}



$.autoimage.defaults=
{
	speed:			1000,		// default speed for image animation
	fade:			0,			// default fading factor, in percent

	// Defaults for aiButton()
	buttons:
		{
			fwspeed:	100,	// speed for the normal->over transition
			bwspeed:	300		// speed for the over->normal transition
		}
};

})(jQuery);


$(function()
{
	jQuery.aiApplyMarkupExtensions();
});

/*
 * Style File - jQuery plugin for styling file input elements
 *
 * Copyright (c) 2007-2008 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Based on work by Shaun Inman
 *   http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
 *
 * Revision: $Id: jquery.filestyle.js 303 2008-01-30 13:53:24Z tuupola $
 *
 */

(function($) {

    $.fn.filestyle = function(options) {

        /* TODO: This should not override CSS. */
        var settings = {
            width : 250
        };

        if(options) {
            $.extend(settings, options);
        }

        return this.each(function() {

            var self = this;
            var wrapper = $("<div>")
                            .css({
                                "width": settings.imagewidth + "px",
                                "height": settings.imageheight + "px",
                                "background": "url(" + settings.image + ") 0 0 no-repeat",
                                "background-position": "right",
                                "display": "inline",
                                "position": "absolute",
                                "overflow": "hidden"
                            });

            var filename = $('<input class="file">')
                             .addClass($(self).attr("class"))
                             .css({
                                 "display": (settings.onlyButton?"none":"inline"),
                                 "width": settings.width + "px"
                             });

            $(self).before(filename);
            $(self).wrap(wrapper);

            $(self).css({
                        "position": "absolute",
                        "height": settings.imageheight + "px",
                        "display": "inline",
                        "cursor": "pointer",
                        "opacity": "0.0",
                        "margin" : "0",
                        "right" : "0"
                    });
/*
            if ($.browser.mozilla) {
                if (/Win/.test(navigator.platform)) {
                    $(self).css("margin-left", "-142px");
                } else {
                    $(self).css("margin-left", "-168px");
                };
            } else {
                $(self).css("margin-left", settings.imagewidth - settings.width + "px");
            };
*/
            $(self).bind("change", function() {
                filename.val($(self).val());
            });

        });


    };

})(jQuery);
/* Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || 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.
 *
 * Version: 1.0.2
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);
/*
 * jQuery Cycle Plugin for light-weight slideshows
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2008 M. Alsup
 * Version: 2.28 (06-OCT-2008)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.2.3 or later
 *
 * Based on the work of:
 *  1) Matt Oakes (http://portfolio.gizone.co.uk/applications/slideshow/)
 *  2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
 *  3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/)
 */
;(function($) {

var ver = '2.28';
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);

function log() {
    if (window.console && window.console.log)
        window.console.log('[cycle] ' + Array.prototype.join.call(arguments,''));
};

$.fn.cycle = function(options) {
	var opt2 = arguments[1];
    return this.each(function() {
        if (options === undefined || options === null)
            options = {};
        if (options.constructor == String) {
            switch(options) {
            case 'stop':
                if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
                this.cycleTimeout = 0;
                $(this).data('cycle.opts', '');
                return;
            case 'pause':
                this.cyclePause = 1;
                return;
            case 'resume':
				this.cyclePause = 0;
				if (opt2 === true) { // resume now!
		            options = $(this).data('cycle.opts');
		            if (!options) {
		                log('options not found, can not resume');
		                return;
		            }
					if (this.cycleTimeout) {
						clearTimeout(this.cycleTimeout);
						this.cycleTimeout = 0;
					}            
					go(options.elements, options, 1, 1);
				}
                return;
            default:
                options = { fx: options };
            };
        }
        else if (options.constructor == Number) {
            // go to the requested slide
            var num = options;
            options = $(this).data('cycle.opts');
            if (!options) {
                log('options not found, can not advance slide');
                return;
            }
            if (num < 0 || num >= options.elements.length) {
                log('invalid slide index: ' + num);
                return;
            }
            options.nextSlide = num;
            if (this.cycleTimeout) {
                clearTimeout(this.cycleTimeout);
                this.cycleTimeout = 0;
            }            
            go(options.elements, options, 1, num >= options.currSlide);
            return;
        }

        // stop existing slideshow for this container (if there is one)
        if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
        this.cycleTimeout = 0;
        this.cyclePause = 0;
        
        var $cont = $(this);
        var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
        var els = $slides.get();
        if (els.length < 2) {
            log('terminating; too few slides: ' + els.length);
            return; // don't bother
        }

        // support metadata plugin (v1.0 and v2.0)
        var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
        if (opts.autostop) 
            opts.countdown = opts.autostopCount || els.length;

        $cont.data('cycle.opts', opts);
        opts.container = this;

        opts.elements = els;
        opts.before = opts.before ? [opts.before] : [];
        opts.after = opts.after ? [opts.after] : [];
        opts.after.unshift(function(){ opts.busy=0; });
        if (opts.continuous)
            opts.after.push(function() { go(els,opts,0,!opts.rev); });
            
        // clearType corrections
        if (ie6 && opts.cleartype && !opts.cleartypeNoBg)
            clearTypeFix($slides);

        // allow shorthand overrides of width, height and timeout
        var cls = this.className;
        opts.width = parseInt((cls.match(/w:(\d+)/)||[])[1]) || opts.width;
        opts.height = parseInt((cls.match(/h:(\d+)/)||[])[1]) || opts.height;
        opts.timeout = parseInt((cls.match(/t:(\d+)/)||[])[1]) || opts.timeout;

        if ($cont.css('position') == 'static') 
            $cont.css('position', 'relative');
        if (opts.width) 
            $cont.width(opts.width);
        if (opts.height && opts.height != 'auto') 
            $cont.height(opts.height);

		if (opts.startingSlide) opts.startingSlide = parseInt(opts.startingSlide);	
			
        if (opts.random) {
            opts.randomMap = [];
            for (var i = 0; i < els.length; i++) 
                opts.randomMap.push(i);
            opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
            opts.randomIndex = 0;
            opts.startingSlide = opts.randomMap[0];
        }
        else if (opts.startingSlide >= els.length)
            opts.startingSlide = 0; // catch bogus input
        var first = opts.startingSlide || 0;
        $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { 
            var z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
            $(this).css('z-index', z) 
        });
        
        $(els[first]).css('opacity',1).show(); // opacity bit needed to handle reinit case
        if ($.browser.msie) els[first].style.removeAttribute('filter');

        if (opts.fit && opts.width) 
            $slides.width(opts.width);
        if (opts.fit && opts.height && opts.height != 'auto') 
            $slides.height(opts.height);
        if (opts.pause) 
            $cont.hover(function(){this.cyclePause=1;},function(){this.cyclePause=0;});

        // run transition init fn
        var init = $.fn.cycle.transitions[opts.fx];
        if ($.isFunction(init))
            init($cont, $slides, opts);
        else if (opts.fx != 'custom')
            log('unknown transition: ' + opts.fx);
        
        $slides.each(function() {
            var $el = $(this);
            this.cycleH = (opts.fit && opts.height) ? opts.height : $el.height();
            this.cycleW = (opts.fit && opts.width) ? opts.width : $el.width();
        });

        opts.cssBefore = opts.cssBefore || {};
        opts.animIn = opts.animIn || {};
        opts.animOut = opts.animOut || {};

        $slides.not(':eq('+first+')').css(opts.cssBefore);
        if (opts.cssFirst)
            $($slides[first]).css(opts.cssFirst);

        if (opts.timeout) {
			opts.timeout = parseInt(opts.timeout);
            // ensure that timeout and speed settings are sane
            if (opts.speed.constructor == String)
                opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed);
            if (!opts.sync)
                opts.speed = opts.speed / 2;
            while((opts.timeout - opts.speed) < 250)
                opts.timeout += opts.speed;
        }
        if (opts.easing) 
            opts.easeIn = opts.easeOut = opts.easing;
        if (!opts.speedIn) 
            opts.speedIn = opts.speed;
        if (!opts.speedOut) 
            opts.speedOut = opts.speed;

 		opts.slideCount = els.length;
        opts.currSlide = first;
        if (opts.random) {
            opts.nextSlide = opts.currSlide;
            if (++opts.randomIndex == els.length) 
                opts.randomIndex = 0;
            opts.nextSlide = opts.randomMap[opts.randomIndex];
        }
        else
            opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;

        // fire artificial events
        var e0 = $slides[first];
        if (opts.before.length)
            opts.before[0].apply(e0, [e0, e0, opts, true]);
        if (opts.after.length > 1)
            opts.after[1].apply(e0, [e0, e0, opts, true]);
        
        if (opts.click && !opts.next)
            opts.next = opts.click;
        if (opts.next)
            $(opts.next).bind('click', function(){return advance(els,opts,opts.rev?-1:1)});
        if (opts.prev)
            $(opts.prev).bind('click', function(){return advance(els,opts,opts.rev?1:-1)});
        if (opts.pager)
            buildPager(els,opts);

        // expose fn for adding slides after the show has started
        opts.addSlide = function(newSlide) {
            var $s = $(newSlide), s = $s[0];
            if (!opts.autostopCount)
                opts.countdown++;
            els.push(s);
            if (opts.els) 
                opts.els.push(s); // shuffle needs this
            opts.slideCount = els.length;
            
            $s.css('position','absolute').appendTo($cont);
            
            if (ie6 && opts.cleartype && !opts.cleartypeNoBg)
                clearTypeFix($s);

            if (opts.fit && opts.width) 
                $s.width(opts.width);
            if (opts.fit && opts.height && opts.height != 'auto') 
                $slides.height(opts.height);
            s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
            s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();

            $s.css(opts.cssBefore);

            if (opts.pager)
                $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);
            
            if (typeof opts.onAddSlide == 'function')
                opts.onAddSlide($s);
        };

        if (opts.timeout || opts.continuous)
            this.cycleTimeout = setTimeout(
                function(){go(els,opts,0,!opts.rev)}, 
                opts.continuous ? 10 : opts.timeout + (opts.delay||0));
    });
};

function go(els, opts, manual, fwd) {
    if (opts.busy) return;
    var p = opts.container, curr = els[opts.currSlide], next = els[opts.nextSlide];
    if (p.cycleTimeout === 0 && !manual) 
        return;

    if (!manual && !p.cyclePause && 
        ((opts.autostop && (--opts.countdown <= 0)) ||
        (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
        if (opts.end)
            opts.end(opts);
        return;
    }

    if (manual || !p.cyclePause) {
        if (opts.before.length)
            $.each(opts.before, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
        var after = function() {
            if ($.browser.msie && opts.cleartype)
                this.style.removeAttribute('filter');
            $.each(opts.after, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
        };

        if (opts.nextSlide != opts.currSlide) {
            opts.busy = 1;
            if (opts.fxFn)
                opts.fxFn(curr, next, opts, after, fwd);
            else if ($.isFunction($.fn.cycle[opts.fx]))
                $.fn.cycle[opts.fx](curr, next, opts, after);
            else
                $.fn.cycle.custom(curr, next, opts, after, manual && opts.fastOnEvent);
        }
        if (opts.random) {
            opts.currSlide = opts.nextSlide;
            if (++opts.randomIndex == els.length) 
                opts.randomIndex = 0;
            opts.nextSlide = opts.randomMap[opts.randomIndex];
        }
        else { // sequence
            var roll = (opts.nextSlide + 1) == els.length;
            opts.nextSlide = roll ? 0 : opts.nextSlide+1;
            opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
        }
        if (opts.pager)
            $.fn.cycle.updateActivePagerLink(opts.pager, opts.currSlide);
    }
    if (opts.timeout && !opts.continuous)
        p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, opts.timeout);
    else if (opts.continuous && p.cyclePause) 
        p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, 10);
};

$.fn.cycle.updateActivePagerLink = function(pager, currSlide) {
    $(pager).find('a').removeClass('activeSlide').filter('a:eq('+currSlide+')').addClass('activeSlide');
};

// advance slide forward or back
function advance(els, opts, val) {
    var p = opts.container, timeout = p.cycleTimeout;
    if (timeout) {
        clearTimeout(timeout);
        p.cycleTimeout = 0;
    }
    if (opts.random && val < 0) {
        // move back to the previously display slide
        opts.randomIndex--;
        if (--opts.randomIndex == -2)
            opts.randomIndex = els.length-2;
        else if (opts.randomIndex == -1)
            opts.randomIndex = els.length-1;
        opts.nextSlide = opts.randomMap[opts.randomIndex];
    }
    else if (opts.random) {
        if (++opts.randomIndex == els.length) 
            opts.randomIndex = 0;
        opts.nextSlide = opts.randomMap[opts.randomIndex];
    }
    else {
        opts.nextSlide = opts.currSlide + val;
        if (opts.nextSlide < 0) {
            if (opts.nowrap) return false;
            opts.nextSlide = els.length - 1;
        }
        else if (opts.nextSlide >= els.length) {
            if (opts.nowrap) return false;
            opts.nextSlide = 0;
        }
    }
    
    if (opts.prevNextClick && typeof opts.prevNextClick == 'function')
        opts.prevNextClick(val > 0, opts.nextSlide, els[opts.nextSlide]);
    go(els, opts, 1, val>=0);
    return false;
};

function buildPager(els, opts) {
    var $p = $(opts.pager);
    $.each(els, function(i,o) {
        $.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
    });
   $.fn.cycle.updateActivePagerLink(opts.pager, opts.startingSlide);
};

$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
    var $a = (typeof opts.pagerAnchorBuilder == 'function')
        ? $(opts.pagerAnchorBuilder(i,el))
        : $('<a href="#">'+(i+1)+'</a>');
    
    // don't reparent if anchor is in the dom
    if ($a.parents('body').length == 0)
        $a.appendTo($p);
        
    $a.bind(opts.pagerEvent, function() {
        opts.nextSlide = i;
        var p = opts.container, timeout = p.cycleTimeout;
        if (timeout) {
            clearTimeout(timeout);
            p.cycleTimeout = 0;
        }            
        if (typeof opts.pagerClick == 'function')
            opts.pagerClick(opts.nextSlide, els[opts.nextSlide]);
        go(els,opts,1,opts.currSlide < i);
        return false;
    });
	if (opts.pauseOnPagerHover)
		$a.hover(function() { opts.container.cyclePause = 1; }, function() { opts.container.cyclePause = 0; } );
};


// this fixes clearType problems in ie6 by setting an explicit bg color
function clearTypeFix($slides) {
    function hex(s) {
        var s = parseInt(s).toString(16);
        return s.length < 2 ? '0'+s : s;
    };
    function getBg(e) {
        for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
            var v = $.css(e,'background-color');
            if (v.indexOf('rgb') >= 0 ) { 
                var rgb = v.match(/\d+/g); 
                return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
            }
            if (v && v != 'transparent')
                return v;
        }
        return '#ffffff';
    };
    $slides.each(function() { $(this).css('background-color', getBg(this)); });
};


$.fn.cycle.custom = function(curr, next, opts, cb, immediate) {
    var $l = $(curr), $n = $(next);
    $n.css(opts.cssBefore);
    var speedIn = immediate ? 1 : opts.speedIn;
    var speedOut = immediate ? 1 : opts.speedOut;
    var easeIn = immediate ? null : opts.easeIn;
    var easeOut = immediate ? null : opts.easeOut;
    var fn = function() {$n.animate(opts.animIn, speedIn, easeIn, cb)};
    $l.animate(opts.animOut, speedOut, easeOut, function() {
        if (opts.cssAfter) $l.css(opts.cssAfter);
        if (!opts.sync) fn();
    });
    if (opts.sync) fn();
};

$.fn.cycle.transitions = {
    fade: function($cont, $slides, opts) {
        $slides.not(':eq('+opts.startingSlide+')').css('opacity',0);
        opts.before.push(function() { $(this).show() });
        opts.animIn    = { opacity: 1 };
        opts.animOut   = { opacity: 0 };
        opts.cssBefore = { opacity: 0 };
        opts.cssAfter  = { display: 'none' };
    }
};

$.fn.cycle.ver = function() { return ver; };

// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
    fx:           'fade', // one of: fade, shuffle, zoom, scrollLeft, etc
    timeout:       4000,  // milliseconds between slide transitions (0 to disable auto advance)
    continuous:    0,     // true to start next transition immediately after current one completes
    speed:         1000,  // speed of the transition (any valid fx speed value)
    speedIn:       null,  // speed of the 'in' transition
    speedOut:      null,  // speed of the 'out' transition
    next:          null,  // id of element to use as click trigger for next slide
    prev:          null,  // id of element to use as click trigger for previous slide
    prevNextClick: null,  // callback fn for prev/next clicks:  function(isNext, zeroBasedSlideIndex, slideElement)
    pager:         null,  // id of element to use as pager container
    pagerClick:    null,  // callback fn for pager clicks:  function(zeroBasedSlideIndex, slideElement)
    pagerEvent:   'click', // event which drives the pager navigation
    pagerAnchorBuilder: null, // callback fn for building anchor links
    before:        null,  // transition callback (scope set to element to be shown)
    after:         null,  // transition callback (scope set to element that was shown)
    end:           null,  // callback invoked when the slideshow terminates (use with autostop or nowrap options)
    easing:        null,  // easing method for both in and out transitions
    easeIn:        null,  // easing for "in" transition
    easeOut:       null,  // easing for "out" transition
    shuffle:       null,  // coords for shuffle animation, ex: { top:15, left: 200 }
    animIn:        null,  // properties that define how the slide animates in
    animOut:       null,  // properties that define how the slide animates out
    cssBefore:     null,  // properties that define the initial state of the slide before transitioning in
    cssAfter:      null,  // properties that defined the state of the slide after transitioning out
    fxFn:          null,  // function used to control the transition
    height:       'auto', // container height
    startingSlide: 0,     // zero-based index of the first slide to be displayed
    sync:          1,     // true if in/out transitions should occur simultaneously
    random:        0,     // true for random, false for sequence (not applicable to shuffle fx)
    fit:           0,     // force slides to fit container
    pause:         0,     // true to enable "pause on hover"
	pauseOnPagerHover: 0, // true to pause when hovering over pager link
    autostop:      0,     // true to end slideshow after X transitions (where X == slide count)
    autostopCount: 0,     // number of transitions (optionally used with autostop to define X)
    delay:         0,     // additional delay (in ms) for first transition (hint: can be negative)
    slideExpr:     null,  // expression for selecting slides (if something other than all children is required)
    cleartype:     0,     // true if clearType corrections should be applied (for IE)
    nowrap:        0,     // true to prevent slideshow from wrapping
    fastOnEvent:   0      // force immediate transition when triggered manually (via pager or prev/next)
};

})(jQuery);


/*
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2008 M. Alsup
 * Version:  2.22
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {

//
// These functions define one-time slide initialization for the named
// transitions. To save file size feel free to remove any of these that you 
// don't need.
//

// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.top = next.offsetHeight;
        opts.animOut.top = 0-curr.offsetHeight;
    });
    opts.cssFirst = { top: 0 };
    opts.animIn   = { top: 0 };
    opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.top = 0-next.offsetHeight;
        opts.animOut.top = curr.offsetHeight;
    });
    opts.cssFirst = { top: 0 };
    opts.animIn   = { top: 0 };
    opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.left = next.offsetWidth;
        opts.animOut.left = 0-curr.offsetWidth;
    });
    opts.cssFirst = { left: 0 };
    opts.animIn   = { left: 0 };
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.left = 0-next.offsetWidth;
        opts.animOut.left = curr.offsetWidth;
    });
    opts.cssFirst = { left: 0 };
    opts.animIn   = { left: 0 };
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
    $cont.css('overflow','hidden').width();
//    $slides.show();
    opts.before.push(function(curr, next, opts, fwd) {
        $(this).show();
        var currW = curr.offsetWidth, nextW = next.offsetWidth;
        opts.cssBefore = fwd ? { left: nextW } : { left: -nextW };
        opts.animIn.left = 0;
        opts.animOut.left = fwd ? -currW : currW;
        $slides.not(curr).css(opts.cssBefore);
    });
    opts.cssFirst = { left: 0 };
    opts.cssAfter = { display: 'none' }
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
//    $slides.show();
    opts.before.push(function(curr, next, opts, fwd) {
        $(this).show();
        var currH = curr.offsetHeight, nextH = next.offsetHeight;
        opts.cssBefore = fwd ? { top: -nextH } : { top: nextH };
        opts.animIn.top = 0;
        opts.animOut.top = fwd ? currH : -currH;
        $slides.not(curr).css(opts.cssBefore);
    });
    opts.cssFirst = { top: 0 };
    opts.cssAfter = { display: 'none' }
};

// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { zIndex: 2 };
    opts.animIn  = { width: 'show' };
    opts.animOut = { width: 'hide' };
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { zIndex: 2 };
    opts.animIn  = { height: 'show' };
    opts.animOut = { height: 'hide' };
};

// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
    var w = $cont.css('overflow', 'visible').width();
    $slides.css({left: 0, top: 0});
    opts.before.push(function() { $(this).show() });
    opts.speed = opts.speed / 2; // shuffle has 2 transitions        
    opts.random = 0;
    opts.shuffle = opts.shuffle || {left:-w, top:15};
    opts.els = [];
    for (var i=0; i < $slides.length; i++)
        opts.els.push($slides[i]);

    for (var i=0; i < opts.startingSlide; i++)
        opts.els.push(opts.els.shift());

    // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
    opts.fxFn = function(curr, next, opts, cb, fwd) {
        var $el = fwd ? $(curr) : $(next);
        $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
            fwd ? opts.els.push(opts.els.shift()) : opts.els.unshift(opts.els.pop());
            if (fwd) 
                for (var i=0, len=opts.els.length; i < len; i++)
                    $(opts.els[i]).css('z-index', len-i);
            else {
                var z = $(curr).css('z-index');
                $el.css('z-index', parseInt(z)+1);
            }
            $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
                $(fwd ? this : curr).hide();
                if (cb) cb();
            });
        });
    };
    opts.onAddSlide = function($s) { $s.hide(); };
};

// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.top = next.cycleH;
        opts.animIn.height = next.cycleH;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssFirst  = { top: 0 };
    opts.cssBefore = { height: 0 };
    opts.animIn    = { top: 0 };
    opts.animOut   = { height: 0 };
    opts.cssAfter  = { display: 'none' };
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.animIn.height = next.cycleH;
        opts.animOut.top   = curr.cycleH;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssFirst  = { top: 0 };
    opts.cssBefore = { top: 0, height: 0 };
    opts.animOut   = { height: 0 };
    opts.cssAfter  = { display: 'none' };
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.left = next.cycleW;
        opts.animIn.width = next.cycleW;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { width: 0 };
    opts.animIn    = { left: 0 };
    opts.animOut   = { width: 0 };
    opts.cssAfter  = { display: 'none' };
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.animIn.width = next.cycleW;
        opts.animOut.left = curr.cycleW;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { left: 0, width: 0 };
    opts.animIn    = { left: 0 };
    opts.animOut   = { width: 0 };
    opts.cssAfter  = { display: 'none' };
};

// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
    opts.cssFirst = { top:0, left: 0 }; 
    opts.cssAfter = { display: 'none' };
    
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore = { width: 0, height: 0, top: next.cycleH/2, left: next.cycleW/2 };
        opts.cssAfter  = { display: 'none' };
        opts.animIn    = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
        opts.animOut   = { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 };
        $(curr).css('zIndex',2);
        $(next).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
};

// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { width: 0, height: 0, opacity: 1, left: next.cycleW/2, top: next.cycleH/2, zIndex: 1 };
        opts.animIn    = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
    });    
    opts.animOut  = { opacity: 0 };
    opts.cssAfter = { zIndex: 0 };
};

// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
    var w = $cont.css('overflow','hidden').width();
    $slides.show();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.cssBefore = { left: w, zIndex: 2 };
    opts.cssAfter = { zIndex: 1 };
    opts.animIn = { left: 0 };
    opts.animOut  = { left: w };
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
    var h = $cont.css('overflow','hidden').height();
    $slides.show();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.cssBefore = { top: h, zIndex: 2 };
    opts.cssAfter = { zIndex: 1 };
    opts.animIn = { top: 0 };
    opts.animOut  = { top: h };
};
// blindZ
$.fn.cycle.transitions.blindZ = function($cont, $slides, opts) {
    var h = $cont.css('overflow','hidden').height();
    var w = $cont.width();
    $slides.show();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.cssBefore = { top: h, left: w, zIndex: 2 };
    opts.cssAfter = { zIndex: 1 };
    opts.animIn = { top: 0, left: 0 };
    opts.animOut  = { top: h, left: w };
};

// growX - grow horizontally from centered 0 width
$.fn.cycle.transitions.growX = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { left: this.cycleW/2, width: 0, zIndex: 2 };
        opts.animIn = { left: 0, width: this.cycleW };
        opts.animOut = { left: 0 };
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide().css('zIndex',1); };
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { top: this.cycleH/2, height: 0, zIndex: 2 };
        opts.animIn = { top: 0, height: this.cycleH };
        opts.animOut = { top: 0 };
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide().css('zIndex',1); };
};

// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { left: next.cycleW/2, width: 0, zIndex: 1, display: 'block' };
        opts.animIn = { left: 0, width: this.cycleW };
        opts.animOut = { left: curr.cycleW/2, width: 0 };
        $(curr).css('zIndex',2);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssAfter = { zIndex: 1, display: 'none' };
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { top: next.cycleH/2, height: 0, zIndex: 1, display: 'block' };
        opts.animIn = { top: 0, height: this.cycleH };
        opts.animOut = { top: curr.cycleH/2, height: 0 };
        $(curr).css('zIndex',2);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssAfter = { zIndex: 1, display: 'none' };
};

// cover - curr slide covered by next slide
$.fn.cycle.transitions.cover = function($cont, $slides, opts) {
    var d = opts.direction || 'left';
    var w = $cont.css('overflow','hidden').width();
    var h = $cont.height();
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = opts.cssBefore || {};
        opts.cssBefore.zIndex = 2;
        opts.cssBefore.display = 'block';
        
        if (d == 'right') 
            opts.cssBefore.left = -w;
        else if (d == 'up')    
            opts.cssBefore.top = h;
        else if (d == 'down')  
            opts.cssBefore.top = -h;
        else
            opts.cssBefore.left = w;
        $(curr).css('zIndex',1);
    });    
    if (!opts.animIn)  opts.animIn = { left: 0, top: 0 };
    if (!opts.animOut) opts.animOut = { left: 0, top: 0 };
    opts.cssAfter = opts.cssAfter || {};
    opts.cssAfter.zIndex = 2;
    opts.cssAfter.display = 'none';
};

// uncover - curr slide moves off next slide
$.fn.cycle.transitions.uncover = function($cont, $slides, opts) {
    var d = opts.direction || 'left';
    var w = $cont.css('overflow','hidden').width();
    var h = $cont.height();
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore.display = 'block';
        if (d == 'right') 
            opts.animOut.left = w;
        else if (d == 'up')    
            opts.animOut.top = -h;
        else if (d == 'down')  
            opts.animOut.top = h;
        else
            opts.animOut.left = -w;
        $(curr).css('zIndex',2);
        $(next).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    if (!opts.animIn)  opts.animIn = { left: 0, top: 0 };
    opts.cssBefore = opts.cssBefore || {};
    opts.cssBefore.top = 0;
    opts.cssBefore.left = 0;
    
    opts.cssAfter = opts.cssAfter || {};
    opts.cssAfter.zIndex = 1;
    opts.cssAfter.display = 'none';
};

// toss - move top slide and fade away
$.fn.cycle.transitions.toss = function($cont, $slides, opts) {
    var w = $cont.css('overflow','visible').width();
    var h = $cont.height();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',2);
        opts.cssBefore.display = 'block'; 
        // provide default toss settings if animOut not provided
        if (!opts.animOut.left && !opts.animOut.top)
            opts.animOut = { left: w*2, top: -h/2, opacity: 0 };
        else
            opts.animOut.opacity = 0;
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { left: 0, top: 0, zIndex: 1, opacity: 1 };
    opts.animIn = { left: 0 };
    opts.cssAfter = { zIndex: 2, display: 'none' };
};

// wipe - clip animation
$.fn.cycle.transitions.wipe = function($cont, $slides, opts) {
    var w = $cont.css('overflow','hidden').width();
    var h = $cont.height();
    opts.cssBefore = opts.cssBefore || {};
    var clip;
    if (opts.clip) {
        if (/l2r/.test(opts.clip))
            clip = 'rect(0px 0px '+h+'px 0px)';
        else if (/r2l/.test(opts.clip))
            clip = 'rect(0px '+w+'px '+h+'px '+w+'px)';
        else if (/t2b/.test(opts.clip))
            clip = 'rect(0px '+w+'px 0px 0px)';
        else if (/b2t/.test(opts.clip))
            clip = 'rect('+h+'px '+w+'px '+h+'px 0px)';
        else if (/zoom/.test(opts.clip)) {
            var t = parseInt(h/2);
            var l = parseInt(w/2);
            clip = 'rect('+t+'px '+l+'px '+t+'px '+l+'px)';
        }
    }
    
    opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';
    
    var d = opts.cssBefore.clip.match(/(\d+)/g);
    var t = parseInt(d[0]), r = parseInt(d[1]), b = parseInt(d[2]), l = parseInt(d[3]);
    
    opts.before.push(function(curr, next, opts) {
        if (curr == next) return;
        var $curr = $(curr).css('zIndex',2);
        var $next = $(next).css({
            zIndex:  3,
            display: 'block'
        });
        
        var step = 1, count = parseInt((opts.speedIn / 13)) - 1;
        function f() {
            var tt = t ? t - parseInt(step * (t/count)) : 0;
            var ll = l ? l - parseInt(step * (l/count)) : 0;
            var bb = b < h ? b + parseInt(step * ((h-b)/count || 1)) : h;
            var rr = r < w ? r + parseInt(step * ((w-r)/count || 1)) : w;
            $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' });
            (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
        }
        f();
    });    
    opts.cssAfter  = { };
    opts.animIn    = { left: 0 };
    opts.animOut   = { left: 0 };
};

})(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-06-20 03:23:36 +0200 (Mi, 20 Jun 2007) $
 * $Rev: 2110 $
 *
 * Version 2.1
 */

(function($){

/**
 * The bgiframe is chainable and applies the iframe hack to get
 * around zIndex issues in IE6. It will only apply itself in IE
 * and adds a class to the iframe called 'bgiframe'. The iframe
 * is appeneded as the first child of the matched element(s)
 * with a tabIndex and zIndex of -1.
 *
 * By default the plugin will take borders, sized with pixel units,
 * into account. If a different unit is used for the border's width,
 * then you will need to use the top and left settings as explained below.
 *
 * NOTICE: This plugin has been reported to cause perfromance problems
 * when used on elements that change properties (like width, height and
 * opacity) a lot in IE6. Most of these problems have been caused by
 * the expressions used to calculate the elements width, height and
 * borders. Some have reported it is due to the opacity filter. All
 * these settings can be changed if needed as explained below.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @param Map settings Optional settings to configure the iframe.
 * @option String|Number top The iframe must be offset to the top
 * 		by the width of the top border. This should be a negative
 *      number representing the border-top-width. If a number is
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used.
 * 		By default the value is "auto" which will use an expression
 * 		to get the border-top-width if it is in pixels.
 * @option String|Number left The iframe must be offset to the left
 * 		by the width of the left border. This should be a negative
 *      number representing the border-left-width. If a number is
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used.
 * 		By default the value is "auto" which will use an expression
 * 		to get the border-left-width if it is in pixels.
 * @option String|Number width This is the width of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetWidth.
 * @option String|Number height This is the height of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetHeight.
 * @option Boolean opacity This is a boolean representing whether or not
 * 		to use opacity. If set to true, the opacity of 0 is applied. If
 *		set to false, the opacity filter is not applied. Default: true.
 * @option String src This setting is provided so that one could change
 *		the src of the iframe to whatever they need.
 *		Default: "javascript:false;"
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			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;
};

// Add browser.version if it doesn't exist
if (!$.browser.version)
	$.browser.version = navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)[1];

})(jQuery);
$.fn.jForms = 
function(options)
{
	var lastKeypress = 0;
    var keyBuffer = '';
    var self = this;
    var defaults = {
	imagePath : '/niceforms/default/',
	listSize:20
	}	
	if($.browser.safari){return false;}

	var opts = $.extend(defaults, options);
	var imagePath = opts.imagePath	
	
	//preload images
	var images = [imagePath + "button_left_xon.gif", imagePath + "button_right_xon.gif", 
	imagePath + "input_left_xon.gif", imagePath + "input_right_xon.gif",
	imagePath + "txtarea_bl_xon.gif", imagePath + "txtarea_br_xon.gif", 
	imagePath + "txtarea_cntr_xon.gif", imagePath + "txtarea_l_xon.gif", imagePath + "txtarea_tl_xon.gif", imagePath + "txtarea_tr_xon.gif"]
	var imgs = new Array();
	for(var i = 0; i<images.length; i++)
	{
		imgs[i] = $("<img>").attr("src", images[i]);
	}

	$(self).attr('autocomplete','off').addClass('niceforms');
	
	//text and passwords
	$(':text,:password',self).each(function()
	{
		$(this).addClass('textinput').before('<img src = "'+imagePath+'input_left.gif" class="inputCorner" />').after('<img src="'+imagePath+'input_right.gif" class="inputCorner" />').focus(function()
		{
			$(this).css('background-position','bottom').prev().attr('src',imagePath+'input_left_xon.gif')
			$(this).next().attr('src',imagePath+'input_right_xon.gif');

		}).blur(function()
		{
			$(this).css('background-position','top').prev().attr('src',imagePath+'input_left.gif')
			$(this).next().attr('src',imagePath+'input_right.gif');
		});	
	});
	
			//select boxes
$('select',self).each(function ()
{
	$('body').append('<ul id = "'+this.id+'_fake_list" class="fake_list"></ul>');
	$(this).children().each(function()
	{
		$('#'+$(this).parent().attr('id')+'_fake_list').append('<li>'+$(this).text()+'</li>');
	});
	$('#'+this.id+'_fake_list').css('height',($('#'+this.id+'_fake_list li:first').height()+4)*($('#'+this.id+'_fake_list li').size()<opts.listSize?$('#'+this.id+'_fake_list li').size():opts.listSize)).css('width',$(this).width()+18).toggle();
	
	$('#'+this.id+'_fake_list > li').hover(function(){$(this).addClass('selected')},function(){$(this).removeClass('selected');}).each(function(i)
	{
		$(this).click(function(){
		var id = $(this).parent().attr('id');
		$('#'+id).toggle();
	    $('#'+id.replace('_list','')).attr('value',$(this).text());
		$('#'+id.replace('_fake_list','')).attr('selectedIndex',i).change();
		$('#'+id+' >  li').removeClass('selected');
		$(this).addClass('selected');	
	});
	});

$(this).before('<div class="selectArea" style="width:'+($(this).width()+43)+'px"><div class="left"></div><div class="right"><a class="selectButton" href="javascript:;" onclick="$(\'#'+this.id+'_fake\').focus().click()"></a></div><input type = "text" class="center" style="width:'+($(this).width())+'px;cursor:default" id="'+this.id+'_fake"  value="'+this[this.selectedIndex].text+'"  /></div>').css('position','absolute').css('left','-6000px');

	$('#'+this.id+'_fake').click(function(){
		$('#'+this.id+'_list').focus();
		$('#'+this.id+'_list').css('left',$(this).offset().left-8);
		
		if(($('#'+this.id+'_list').height()+$(this).offset().top -document.documentElement.scrollTop) > $(window).height())
		{
			$('#'+this.id+'_list').css('top',$(this).offset().top-$('#'+this.id+'_list').height()-4);
		}
		else
		{
			$('#'+this.id+'_list').css('top',$(this).offset().top+$(this).height()+4);
		}
		$('#'+this.id+'_list > li').removeClass('selected');
		$('#'+this.id+'_list > li').get($('#'+this.id.replace('_fake','')).attr('selectedIndex')).className='selected';

		
		$('.fake_list:visible:not(#'+this.id+'_list)').toggle();
		$list = $('#'+this.id+'_list');	
		$list.toggle();		
		var offSet = (($('.selected', $list).length>0? $('.selected', $list).offset().top:0)- $list.offset().top);
		$list.animate({scrollTop: offSet});
		}).css('font-size',$(this).css('font-size')).css('padding','2px 0px 2px 2px').keyup(function(e)
		{
			var pressedKey = e.charCode || e.keyCode || -1;
			var $dd = $('#'+this.id.replace('_fake',''));
			$('#'+this.id+'_list > li').removeClass('selected');
			switch(pressedKey)
			{
				//down
				case 40:						
					var curr = ($dd.attr('selectedIndex')+1>=$('option',$dd).length?0:$dd.attr('selectedIndex')+1);
				break;
				case 38:						
					var curr = ($dd.attr('selectedIndex')-1<0?$('option',$dd).length-1:$dd.attr('selectedIndex')-1);						
				break;
				case 13:
					$('#'+this.id+'_list').toggle();
					return false;
				break;
				default:
				var t = new Date();
				if(t.getTime()-lastKeypress>1000)
				{
					lastKeypress=t.getTime();
					keyBuffer ='';
				}
					keyBuffer +=String.fromCharCode(pressedKey).toLowerCase();
					curr=-1;
					$('#'+this.id+'_list > li').each(function(i)
					{
						if($(this).text().toLowerCase().indexOf(keyBuffer)==0&&curr==-1)
						{
							curr = i;
							return;
						}
					});
					break;
			}
			if(curr==-1)
			{
				curr=0;
			}
			$($('#'+this.id+'_list > li').get(curr)).addClass('selected').focus();
			$list = $('#'+this.id+'_list');
			var offSet = (($('.selected', $list).length>0? $('.selected', $list).offset().top:0)- $list.offset().top);
			$list.attr('scrollTop',offSet);
			$dd.attr('selectedIndex',curr).change();
			$(this).attr('value', $($('#'+this.id+'_list > li').get(curr)).text());
			return false;
						
		}).focus(function()
		{
			$(document).keypress(function(e)
			{
				var pressedKey = e.charCode || e.keyCode || -1;
				if(pressedKey==13)
				{
					return false;
				}
			});
		}).blur(function()
		{
			$(document).unbind('keypress').unbind('click');
		});

});

	//checkboxes
	$(':checkbox',self).each(function()
	{
		$(this).before('<div style="margin: 1px;" id="'+this.id+'_fake"></div>');
		$(this).addClass('outtaHere');
		this.checked?$('label[for='+this.id+']').addClass('chosen'):'';
		$('#'+this.id+'_fake').addClass(this.checked?'checkboxAreaChecked':'checkboxArea').click(function()
		{
			$('label[for='+this.id.replace('_fake','')+']').click();	
			$('#'+this.id.replace('_fake','')).attr('checked')?$('#'+this.id.replace('_fake','')).attr('checked',''):$('#'+this.id.replace('_fake','')).attr('checked','checked');
		});
		$('label[for='+this.id+']').click(function()
		{
			//these are backwards on purpose -click functions are called before the checkbox is selected
			$('#'+$(this).attr('for')).attr('checked')?$(this).removeClass('chosen'):$(this).addClass('chosen');
			$('#'+$(this).attr('for')+'_fake').addClass($('#'+$(this).attr('for')).attr('checked')?'checkboxArea':'checkboxAreaChecked').removeClass($('#'+$(this).attr('for')).attr('checked')?'checkboxAreaChecked':'checkboxArea');
		});
		
	});
	//radios
	$(':radio',self).each(function()
	{
		$(this).after('<div style="margin: 1px;" id="'+this.id+'_fake"></div>').addClass('outtaHere');
		this.checked?$('label[for='+this.id+']').addClass('chosen'):'';
		$('#'+this.id+'_fake').addClass(this.checked?'radioAreaChecked':'radioArea').click(function()
		{
			$(':radio[name='+$('#'+this.id.replace('_fake','')).attr('name')+']').each(function()
			{
				this.checked=false;	
			});
			$('#'+this.id.replace('_fake','')).attr('checked','checked');
			$('label[for='+this.id.replace('_fake','')+']').click();
		});	
		$('label[for='+this.id+']').click(function()
		{					
			$(':radio[name='+$('#'+$(this).attr('for')).attr('name')+']').each(function()
			{
				$('label[for='+this.id+']').removeClass('chosen');
				$('#'+this.id+'_fake').addClass('radioArea').removeClass('radioAreaChecked');
				$('label[for='+this.id.replace('_fake','')+']').removeClass('chosen');
			});
			$(this).addClass('chosen');	
			$('#'+$(this).attr('for')+'_fake').addClass('radioAreaChecked');	

		})
	});
	//text areas
	$('textarea',self).each(function()
	{
		$(this).replaceWith('<div style="width: '+($(this).width()+20)+'px; height: '+($(this).height()+20)+'px;" class="txtarea" id = "'+this.id+'_fake"><div class="tr"><img src="/niceforms/default/txtarea_tl.gif" class="txt_corner"></div><div class="cntr"><div style="height: '+($(this).height()+10)+'px;" class="cntr_l"></div></div><div class="br"><img src="'+imagePath+'txtarea_bl.gif" class="txt_corner"></div></div>');
		$('#'+this.id+'_fake .cntr').append($(this));
		
	}).focus(function()
	{
		$('#'+this.id+'_fake .tr').removeClass('tr').addClass('tr_xon');
		$('#'+this.id+'_fake .br').removeClass('br').addClass('br_xon');
		$('#'+this.id+'_fake .cntr').removeClass('cntr').addClass('cntr_xon');
		$('#'+this.id+'_fake .cntr_l').removeClass('cntr_').addClass('cntr_l_xon');
		$('#'+this.id+'_fake img:first').attr('src',imagePath+'txtarea_tl_xon.gif');
		$('#'+this.id+'_fake img:last').attr('src',imagePath+'txtarea_bl_xon.gif');
	}).blur(function()
	{
		$('#'+this.id+'_fake .tr_xon').addClass('tr').removeClass('tr_xon');
		$('#'+this.id+'_fake .br_xon').addClass('br').removeClass('br_xon');
		$('#'+this.id+'_fake .cntr_xon').addClass('cntr').removeClass('cntr_xon');
		$('#'+this.id+'_fake .cntr_l_xon').addClass('cntr_').removeClass('cntr_l_xon');
		$('#'+this.id+'_fake img:first').attr('src',imagePath+'txtarea_tl.gif');
		$('#'+this.id+'_fake img:last').attr('src',imagePath+'txtarea_bl.gif');
	});
	
	$(':button,:submit',self).each(function()
	{
		$(this).before('<img class="buttonImg" src="'+imagePath+'button_left.gif">').after('<img class="buttonImg" src="'+imagePath+'button_right.gif">').addClass('buttonSubmit').hover(function()
		{
			$(this).prev().attr('src',imagePath+'button_left_xon.gif');
			$(this).next().attr('src',imagePath+'button_right_xon.gif');
			$(this).addClass('buttonSubmitHovered').removeClass('buttonSubmit');
		},
	 function()
	 {
			$(this).prev().attr('src',imagePath+'button_left.gif');
			$(this).next().attr('src',imagePath+'button_right.gif');
			$(this).removeClass('buttonSubmitHovered').addClass('buttonSubmit');
	});
	});
	return self;
}/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
	
		// the tooltip element
	var helper = {},
		// the current tooltipped element
		current,
		// the title of the current element, used for restoring
		title,
		// timeout id for delayed tooltips
		tID,
		// IE 5.5 or 6
		IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		// flag for mouse tracking
		track = false;
	
	$.tooltip = {
		blocked: false,
		defaults: {
			delay: 200,
			fade: false,
			showURL: true,
			extraClass: "",
			top: 15,
			left: 15,
			id: "tooltip"
		},
		block: function() {
			$.tooltip.blocked = !$.tooltip.blocked;
		}
	};
	
	$.fn.extend({
		tooltip: function(settings) {
			settings = $.extend({}, $.tooltip.defaults, settings);
			createHelper(settings);
			return this.each(function() {
					$.data(this, "tooltip", settings);
					this.tOpacity = helper.parent.css("opacity");
					// copy tooltip into its own expando and remove the title
					this.tooltipText = this.title;
					$(this).removeAttr("title");
					// also remove alt attribute to prevent default tooltip in IE
					this.alt = "";
				})
				.mouseover(save)
				.mouseout(hide)
				.click(hide);
		},
		fixPNG: IE ? function() {
			return this.each(function () {
				var image = $(this).css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
					image = RegExp.$1;
					$(this).css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
					}).each(function () {
						var position = $(this).css('position');
						if (position != 'absolute' && position != 'relative')
							$(this).css('position', 'relative');
					});
				}
			});
		} : function() { return this; },
		unfixPNG: IE ? function() {
			return this.each(function () {
				$(this).css({'filter': '', backgroundImage: ''});
			});
		} : function() { return this; },
		hideWhenEmpty: function() {
			return this.each(function() {
				$(this)[ $(this).html() ? "show" : "hide" ]();
			});
		},
		url: function() {
			return this.attr('href') || this.attr('src');
		}
	});
	
	function createHelper(settings) {
		// there can be only one tooltip helper
		if( helper.parent )
			return;
		// create the helper, h3 for title, div for url
		helper.parent = $('<div id="' + settings.id + '"><div class="title"><h3></h3></div><div class="body"></div><div class="url"></div></div>')
			// add to document
			.appendTo(document.body)
			// hide it at first
			.hide();
			
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			helper.parent.bgiframe();
		
		// save references to title and url elements
		helper.title = $('h3', helper.parent);
		helper.body = $('div.body', helper.parent);
		helper.url = $('div.url', helper.parent);
	}
	
	function settings(element) {
		return $.data(element, "tooltip");
	}
	
	// main event handler to start showing tooltips
	function handle(event) {
		// show helper, either with timeout or on instant
		if( settings(this).delay )
			tID = setTimeout(show, settings(this).delay);
		else
			show();
		
		// if selected, update the helper position when the mouse moves
		track = !!settings(this).track;
		$(document.body).bind('mousemove', update);
			
		// update at least once
		update(event);
	}
	
	// save elements title before the tooltip is displayed
	function save() {
		// if this is the current source, or it has no title (occurs with click event), stop
		if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
			return;

		// save current
		current = this;
		title = this.tooltipText;
		
		if ( settings(this).bodyHandler ) {
			helper.title.hide();
			var bodyContent = settings(this).bodyHandler.call(this);
			if (bodyContent.nodeType || bodyContent.jquery) {
				helper.body.empty().append(bodyContent)
			} else {
				helper.body.html( bodyContent );
			}
			helper.body.show();
		} else if ( settings(this).showBody ) {
			var parts = title.split(settings(this).showBody);
			helper.title.html(parts.shift()).show();
			helper.body.empty();
			for(var i = 0, part; (part = parts[i]); i++) {
				if(i > 0)
					helper.body.append("<br/>");
				part = part.replace(/%{%/g, "<");
				part = part.replace(/%}%/g, ">");
				helper.body.append(part);
			}
			helper.body.hideWhenEmpty();
		} else {
			helper.title.html(title).show();
			helper.body.hide();
		}
		
		// if element has href or src, add and show it, otherwise hide it
		if( settings(this).showURL && $(this).url() )
			helper.url.html( $(this).url().replace('http://', '') ).show();
		else 
			helper.url.hide();
		
		// add an optional class for this tip
		helper.parent.addClass(settings(this).extraClass);

		// fix PNG background for IE
		if (settings(this).fixPNG )
			helper.parent.fixPNG();
			
		handle.apply(this, arguments);
	}
	
	// delete timeout and show helper
	function show() {
		tID = null;
		if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
			if (helper.parent.is(":animated"))
				helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
			else
				helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
		} else {
			helper.parent.show();
		}
		update();
	}
	
	/**
	 * callback for mousemove
	 * updates the helper position
	 * removes itself when no current element
	 */
	function update(event)	{
		if($.tooltip.blocked)
			return;
		
		if (event && event.target.tagName == "OPTION") {
			return;
		}
		
		// stop updating when tracking is disabled and the tooltip is visible
		if ( !track && helper.parent.is(":visible")) {
			$(document.body).unbind('mousemove', update)
		}
		
		// if no current element is available, remove this listener
		if( current == null ) {
			$(document.body).unbind('mousemove', update);
			return;	
		}
		
		// remove position helper classes
		helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
		
		var left = helper.parent[0].offsetLeft;
		var top = helper.parent[0].offsetTop;
		if (event) {
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = event.pageX + settings(current).left;
			top = event.pageY + settings(current).top;
			var right='auto';
			if (settings(current).positionLeft) {
				right = $(window).width() - left;
				left = 'auto';
			}
			helper.parent.css({
				left: left,
				right: right,
				top: top
			});
		}
		
		var v = viewport(),
			h = helper.parent[0];
		// check horizontal position
		if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
			left -= h.offsetWidth + 20 + settings(current).left;
			helper.parent.css({left: left + 'px'}).addClass("viewport-right");
		}
		// check vertical position
		if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
			top -= h.offsetHeight + 20 + settings(current).top;
			helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
		}
	}
	
	function viewport() {
		return {
			x: $(window).scrollLeft(),
			y: $(window).scrollTop(),
			cx: $(window).width(),
			cy: $(window).height()
		};
	}
	
	// hide helper and restore added classes and the title
	function hide(event) {
		if($.tooltip.blocked)
			return;
		// clear timeout if possible
		if(tID)
			clearTimeout(tID);
		// no more current element
		current = null;
		
		var tsettings = settings(this);
		function complete() {
			helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
		}
		if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
			if (helper.parent.is(':animated'))
				helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
			else
				helper.parent.stop().fadeOut(tsettings.fade, complete);
		} else
			complete();
		
		if( settings(this).fixPNG )
			helper.parent.unfixPNG();
	}
	
})(jQuery);

(function($){var options={};var returnHash=[];$.fn.RSV=function(params){options=$.extend({},$.fn.RSV.defaults,params);return this.each(function(){$(this).bind('submit',{currForm:this,options:options},$(this).RSV.validate);});};$.fn.RSV.defaults={rules:[],displayType:"alert-all",errorFieldClass:null,errorTextIntro:"Please fix the following error(s) and resubmit:",errorJSItemBullet:"* ",errorHTMLItemBullet:"&bull; ",errorTargetElementId:"rsvErrors",customErrorHandler:null,onCompleteHandler:null};$.fn.RSV.validate=function(event)
{options=event.data.options;var form=event.data.currForm;var rules=options.rules;returnHash=[];for(var i=0;i<rules.length;i++)
{var row=rules[i].replace(/\\,/ig,"%%C%%");row=row.split("#");var satisfiesIfConditions=true;while(row[0].match("^if:"))
{var cond=row[0];cond=cond.replace("if:","");var comparison="equal";var parts=[];if(cond.search("!=")!=-1)
{parts=cond.split("!=");comparison="not_equal";}
else
parts=cond.split("=");var fieldToCheck=parts[0];var valueToCheck=parts[1];var fieldnameValue="";if(form[fieldToCheck].type==undefined)
{for(var j=0;j<form[fieldToCheck].length;j++)
{if(form[fieldToCheck][j].checked)
fieldnameValue=form[fieldToCheck][j].value;}}
else if(form[fieldToCheck].type=="checkbox")
{fieldnameValue=(form[fieldToCheck].checked)?1:0;//form[parts[0]].value;
}
else
fieldnameValue=form[parts[0]].value;//alert(fieldToCheck+'['+fieldnameValue+']'+((fieldnameValue==valueToCheck)?'T':'F')+'('+valueToCheck+')');
if(comparison=="equal"&&fieldnameValue!=valueToCheck)
{satisfiesIfConditions=false;break;}
else if(comparison=="not_equal"&&fieldnameValue==valueToCheck)
{satisfiesIfConditions=false;break;}
else
row.shift();}
if(!satisfiesIfConditions)
continue;var requirement=row[0];var fieldName=row[1];var fieldName2,fieldName3,errorMessage,lengthRequirements,date_flag;if(requirement!="function"&&form[fieldName]==undefined)
{alert("RSV Error: the field \""+fieldName+"\" doesn't exist! Please check your form and settings.");return false;}
if(requirement!="function"&&options.errorFieldClass)
{if(form[fieldName].type==undefined)
{for(var j=0;j<form[fieldName].length;j++)
{if($(form[fieldName][j]).hasClass(options.errorFieldClass))
$(form[fieldName][j]).removeClass(options.errorFieldClass);}}
else
{if($(form[fieldName]).hasClass(options.errorFieldClass))
$(form[fieldName]).removeClass(options.errorFieldClass);}}
if(row.length==6)
{fieldName2=row[2];fieldName3=row[3];date_flag=row[4];errorMessage=row[5];}
else if(row.length==5)
{fieldName2=row[2];fieldName3=row[3];errorMessage=row[4];}
else if(row.length==4)
{fieldName2=row[2];errorMessage=row[3];}
else
errorMessage=row[2];if(requirement.match("^length"))
{lengthRequirements=requirement;requirement="length";}
if(requirement.match("^range"))
{rangeRequirements=requirement;requirement="range";}
switch(requirement)
{case"required":if(form[fieldName].type==undefined)
{var oneIsChecked=false;for(var j=0;j<form[fieldName].length;j++)
{if(form[fieldName][j].checked)
oneIsChecked=true;}
if(!oneIsChecked)
{if(!processError(form[fieldName],errorMessage))
return false;}}
else if(form[fieldName].type=="select-multiple")
{var oneIsSelected=false;for(var k=0;k<form[fieldName].length;k++)
{if(form[fieldName][k].selected)
oneIsSelected=true;}
if(!oneIsSelected||form[fieldName].length==0)
{if(!processError(form[fieldName],errorMessage))
return false;}}
else if(form[fieldName].type=="checkbox")
{if(!form[fieldName].checked)
{if(!processError(form[fieldName],errorMessage))
return false;}}
else if(!form[fieldName].value)
{if(!processError(form[fieldName],errorMessage))
return false;}
else if((form[fieldName].value=="0")||(form[fieldName].value=="-"))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"digits_only":if(form[fieldName].value&&form[fieldName].value.match(/\D/))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"letters_only":if(form[fieldName].value&&form[fieldName].value.match(/[^a-zA-Z]/))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"is_alpha":if(form[fieldName].value&&form[fieldName].value.match(/\W/))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"custom_alpha":var conversion={"L":"[A-Z]","V":"[AEIOU]","l":"[a-z]","v":"[aeiou]","D":"[a-zA-Z]","F":"[aeiouAEIOU]","C":"[BCDFGHJKLMNPQRSTVWXYZ]","x":"[0-9]","c":"[bcdfghjklmnpqrstvwxyz]","X":"[1-9]","E":"[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]"};var reg_exp_str="";for(var j=0;j<fieldName2.length;j++)
{if(conversion[fieldName2.charAt(j)])
reg_exp_str+=conversion[fieldName2.charAt(j)];else
reg_exp_str+=fieldName2.charAt(j);}
var reg_exp=new RegExp(reg_exp_str);if(form[fieldName].value&&reg_exp.exec(form[fieldName].value)==null)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"reg_exp":var reg_exp_str=fieldName2;if(row.length==5)
var reg_exp=new RegExp(reg_exp_str,fieldName3);else
var reg_exp=new RegExp(reg_exp_str);if(form[fieldName].value&&reg_exp.exec(form[fieldName].value)==null)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"length":comparison_rule="";rule_string="";if(lengthRequirements.match(/length=/))
{comparison_rule="equal";rule_string=lengthRequirements.replace("length=","");}
else if(lengthRequirements.match(/length>=/))
{comparison_rule="greater_than_or_equal";rule_string=lengthRequirements.replace("length>=","");}
else if(lengthRequirements.match(/length>/))
{comparison_rule="greater_than";rule_string=lengthRequirements.replace("length>","");}
else if(lengthRequirements.match(/length<=/))
{comparison_rule="less_than_or_equal";rule_string=lengthRequirements.replace("length<=","");}
else if(lengthRequirements.match(/length</))
{comparison_rule="less_than";rule_string=lengthRequirements.replace("length<","");}
switch(comparison_rule)
{case"greater_than_or_equal":if(!(form[fieldName].value.length>=parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"greater_than":if(!(form[fieldName].value.length>parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than_or_equal":if(!(form[fieldName].value.length<=parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than":if(!(form[fieldName].value.length<parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"equal":var range_or_exact_number=rule_string.match(/[^_]+/);var fieldCount=range_or_exact_number[0].split("-");if(fieldCount.length==2)
{if(form[fieldName].value.length<fieldCount[0]||form[fieldName].value.length>fieldCount[1])
{if(!processError(form[fieldName],errorMessage))
return false;}}
else
{if(form[fieldName].value.length!=fieldCount[0])
{if(!processError(form[fieldName],errorMessage))
return false;}}
break;}
break;case"valid_email":if(form[fieldName].value&&!isValidEmail(form[fieldName].value))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"valid_date":var isLaterDate=false;if(date_flag=="later_date")
isLaterDate=true;else if(date_flag=="any_date")
isLaterDate=false;if(!isValidDate(form[fieldName].value,form[fieldName2].value,form[fieldName3].value,isLaterDate))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"same_as":if(form[fieldName].value!=form[fieldName2].value)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"range":comparison_rule="";rule_string="";if(rangeRequirements.match(/range=/))
{comparison_rule="equal";rule_string=rangeRequirements.replace("range=","");}
else if(rangeRequirements.match(/range>=/))
{comparison_rule="greater_than_or_equal";rule_string=rangeRequirements.replace("range>=","");}
else if(rangeRequirements.match(/range>/))
{comparison_rule="greater_than";rule_string=rangeRequirements.replace("range>","");}
else if(rangeRequirements.match(/range<=/))
{comparison_rule="less_than_or_equal";rule_string=rangeRequirements.replace("range<=","");}
else if(rangeRequirements.match(/range</))
{comparison_rule="less_than";rule_string=rangeRequirements.replace("range<","");}
switch(comparison_rule)
{case"greater_than_or_equal":if(!(form[fieldName].value>=Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"greater_than":if(!(form[fieldName].value>Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than_or_equal":if(!(form[fieldName].value<=Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than":if(!(form[fieldName].value<Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"equal":var rangeValues=rule_string.split("-");if((form[fieldName].value<Number(rangeValues[0]))||(form[fieldName].value>Number(rangeValues[1])))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;}
break;case"function":custom_function=fieldName;eval("var result = "+custom_function+"()");if(result.constructor.toString().indexOf("Array")!=-1)
{for(var j=0;j<result.length;j++)
{if(!processError(result[j][0],result[j][1]))
return false;}}
break;default:alert("Unknown requirement flag in validateFields(): "+requirement);return false;}}
if(typeof options.customErrorHandler=='function')
return options.customErrorHandler(form,returnHash);else if(options.displayType=="alert-all")
{var errorStr=options.errorTextIntro+"\n\n";for(var i=0;i<returnHash.length;i++)
{errorStr+=options.errorJSItemBullet+returnHash[i][1]+"\n";styleField(returnHash[i][0],i==0);}
if(returnHash.length>0)
{alert(errorStr);return false;}}
else if(options.displayType=="display-html")
{var success=displayHTMLErrors(form,returnHash);if(!success)
return false;}
if(typeof options.onCompleteHandler=='function')
return options.onCompleteHandler();else
return true;}
function processError(obj,message)
{message=message.replace(/%%C%%/ig,",");var continueProcessing=true;switch(options.displayType)
{case"alert-one":alert(message);styleField(obj,true);continueProcessing=false;break;case"alert-all":case"display-html":returnHash.push([obj,message]);break;}
return continueProcessing;}
function displayHTMLErrors(f,errorInfo)
{var errorHTML=options.errorTextIntro+"<br /><br />";for(var i=0;i<errorInfo.length;i++)
{errorHTML+=options.errorHTMLItemBullet+errorInfo[i][1]+"<br />";styleField(errorInfo[i][0],i==0);}
if(errorInfo.length>0)
{$("#"+options.errorTargetElementId).css("display","block");$("#"+options.errorTargetElementId).html(errorHTML);$.scrollTo("#"+options.errorTargetElementId);return false;}
return true;}
function styleField(field,focus)
{focus=false;
if(field.type==undefined)
{if(focus)
field[0].focus();for(var i=0;i<field.length;i++)
{if(!$(field[i]).hasClass(options.errorFieldClass))
$(field[i]).addClass(options.errorFieldClass);}}
else
{if(options.errorFieldClass)
$(field).addClass(options.errorFieldClass);if(focus)
field.focus();}}
function isValidEmail(str)
{var s=$.trim(str);var at="@";var dot=".";var lat=s.indexOf(at);var lstr=s.length;var ldot=s.indexOf(dot);if(s.indexOf(at)==-1||(s.indexOf(at)==-1||s.indexOf(at)==0||s.indexOf(at)==lstr)||(s.indexOf(dot)==-1||s.indexOf(dot)==0||s.indexOf(dot)==lstr)||(s.indexOf(at,(lat+1))!=-1)||(s.substring(lat-1,lat)==dot||s.substring(lat+1,lat+2)==dot)||(s.indexOf(dot,(lat+2))==-1)||(s.indexOf(" ")!=-1))
{return false;}
return true;}
function isValidDate(month,day,year,isLaterDate)
{var daysInMonth;if((year%4==0)&&((year%100!=0)||(year%400==0)))
daysInMonth=[31,29,31,30,31,30,31,31,30,31,30,31];else
daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];if(!month||!day||!year)return false;if(1>month||month>12)return false;if(year<0)return false;if(1>day||day>daysInMonth[month-1])return false;if(isLaterDate)
{var today=new Date();var currMonth=today.getMonth()+1;var currDay=today.getDate();var currYear=today.getFullYear();if(String(currMonth).length==1)currMonth="0"+currMonth;if(String(currDay).length==1)currDay="0"+currDay;var currDate=String(currYear)+String(currMonth)+String(currDay);if(String(month).length==1)month="0"+month;if(String(day).length==1)day="0"+day;incomingDate=String(year)+String(month)+String(day);if(Number(currDate)>Number(incomingDate))
return false;}
return true;}})(jQuery);
(function($) {$.fn.textCounting = function(parameters) {var opts = $.extend({}, $.fn.textCounting.defaults, parameters);if (opts.maxLengthSource== "list")
{
if (opts.maxLengthList != "")
{
var maxLengthArray= opts.maxLengthList.split(",");
var lengthsCounter= 0;
}
else
{
denoteError("The maxLengthSource parameter of the jQuery textCounting plugin was set to 'list', but the maxLengthList parameter is blank.");
return false;
}
}   return this.each(function() {var $box= $(this);
var options = $.metadata ? $.extend({}, opts, $box.metadata()) : opts;var proceed= true;
if (options.excludeIds != "")
{
proceed= isObjectIncluded($box.attr("id"),options.excludeIds);
}if (proceed)
{
switch (options.maxLengthSource)
{
case "list":
var maxCount= maxLengthArray[lengthsCounter];
lengthsCounter++;
break;
case "attribute":
if (options.maxLengthAttribute != "")
{
var maxCount= $box.attr(options.maxLengthAttribute);
}
else
{
denoteError("The maxLengthSource parameter of the jQuery textCounting plugin was set to 'attribute', but the maxLengthAttribute parameter is blank.");
return false;
}
break;
case "metadata":
if (options.maxLengthAttribute != "")
{
var maxCount= $box.metadata()[options.maxLengthAttribute];
if(maxCount== undefined)
{
denoteError("The maxLengthAttribute specified was not found in the metadata of element " + $box.attr("id"));
return false;
}
}
else
{
denoteError("The maxLengthSource parameter of the jQuery textCounting plugin was set to 'metadata', but the maxLengthAttribute parameter is blank.");
return false;
}
break;
}var directionArray= options.countDirection.split(",");
var targetArray= options.targetModifier.split(",");for (var setting=0;setting < directionArray.length;setting++)
{
var currentDirection= directionArray[setting];
var textCount= $.fn.textCounting.calculateCount($box,options.countWhat,currentDirection,maxCount);var currentTarget= targetArray[setting];$.fn.textCounting.displayResult($box,options.targetModifierType,currentTarget,textCount,maxCount,currentDirection,options.lengthExceededClass);}$box.keydown(function (e) {
var c = true;
for (var setting=0;setting < directionArray.length;setting++)
{
var currentDirection= directionArray[setting];
var textCount= $.fn.textCounting.calculateCount($box,options.countWhat,currentDirection,maxCount);var currentTarget= targetArray[setting];
if(textCount<=0) c=false;
if(!c && ((e.keyCode==8) || (e.keyCode==16) || ((e.keyCode>=35) && (e.keyCode<=40)) || (e.keyCode==46) || ((e.keyCode>=63232) && (e.keyCode<=63235)))) c = true;
}
return c;
});
$box.keyup(function(){
for (var setting=0;setting < directionArray.length;setting++)
{
var currentDirection= directionArray[setting];
var textCount= $.fn.textCounting.calculateCount($box,options.countWhat,currentDirection,maxCount);var currentTarget= targetArray[setting];
if(textCount<0) c=false;
$.fn.textCounting.displayResult($box,options.targetModifierType,currentTarget,textCount,maxCount,currentDirection,options.lengthExceededClass);
}
});}    });
};  
$.fn.textCounting.defaults = {
   maxLengthSource: "attribute",
   maxLengthList: "",
   maxLengthAttribute: "maxLength",
   countWhat: "characters",
   countDirection: "down",
   targetModifierType: "suffix",
   targetModifier: "Down",
   lengthExceededClass: "",
   excludeIds: ""
  };
$.fn.textCounting.calculateCount = function(obj,countWhat,direction,maxCount) {if (countWhat== "characters")
{
if (direction== "down")
{
var textCount= maxCount-obj.val().length;
}
else
{
var textCount= obj.val().length;
}
}
else if (countWhat== "words")
{
var boxText= jQuery.trim(obj.val());
if(boxText != "")
{
var wordArray= boxText.split(/\s+/);
if (direction== "down")
{
var textCount= maxCount-wordArray.length;
}
else
{
var textCount= wordArray.length;
}
}
else
{
if (direction== "down")
{
var textCount= maxCount;
}
else
{
var textCount= 0;
}
}
}
return textCount;};  
$.fn.textCounting.displayResult= function(obj,modifierType,target,textCount,maxCount,direction,lengthExceededClass) {
switch (modifierType) {
case "id":
var $targetElement= $("#" +  target);
break;
case "prefix":
var $targetElement= $("#" +  target + obj.attr("id"));
break;
case "suffix":
var $targetElement= $("#" + obj.attr("id") + target);
break;
} $targetElement.text(textCount);
if (lengthExceededClass != "")
{
if((direction== 'down' && textCount < 0) || (direction== 'up' && textCount > maxCount))
{
$targetElement.addClass(lengthExceededClass);
}
else
{
$targetElement.removeClass(lengthExceededClass);
}
}};  function isObjectIncluded(objId,excluded) {
var outcome= true;
var exclusionArray= excluded.split(",");
for (var c= 0;c < exclusionArray.length;c++)
{
if (objId== exclusionArray[c])
{
outcome= false;
}
}
return outcome;
}; function denoteError(msg) {
if(window.console)
{
     console.debug(msg);
  }
else
{
     alert(msg);
  }
};})(jQuery);
/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Tested with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.2/5 and Safari 3. on Windows.
 *
 * @author Ariel Flesler
 * @version 1.4
 *
 * @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:'y',
		duration: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(){
			// Just store it, we might need it
			var win = this.parentWindow || this.defaultView,
				// If it's a document, get its iframe or the window if it's THE document
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				// Get the corresponding document
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };

		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+(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',
					dim = Dim.toLowerCase();

				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]() * 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);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;

				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
/*
 * FancyBox - simple jQuery plugin for fancy image zooming
 * Examples and documentation at: http://fancy.klade.lv/
 * Version: 1.0.0 (29/04/2008)
 * Copyright (c) 2008 Janis Skarnelis
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Requires: jQuery v1.2.1 or later
*/
(function($) {
	var opts = {},
		imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'],
		loadingTimer, loadingFrame = 1;

   $.fn.fancybox = function(settings) {
		opts.settings = $.extend({}, $.fn.fancybox.defaults, settings);

		$.fn.fancybox.init();

		return this.each(function() {
			var $this = $(this);
			var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings;

			$this.unbind('click').click(function() {
				$.fn.fancybox.start(this, o); return false;
			});
		});
	};

	$.fn.fancybox.start = function(el, o) {
		if (opts.animating) return false;

		if (o.overlayShow) {
			$("#fancy_wrap").prepend('<div id="fancy_overlay"></div>');
			$("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity});

			if ($.browser.msie) {
				$("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>');
				$("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
			}

			$("#fancy_overlay").click($.fn.fancybox.close);
		}

		opts.itemArray	= [];
		opts.itemNum	= 0;

		if (jQuery.isFunction(o.itemLoadCallback)) {
		   o.itemLoadCallback.apply(this, [opts]);

			var c	= $(el).children("img:first").length ? $(el).children("img:first") : $(el);
			var tmp	= {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}

		   for (var i = 0; i < opts.itemArray.length; i++) {
				opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o);

				if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
					opts.itemArray[i].orig = tmp;
				}
		   }

		} else {
			if (!el.rel || el.rel == '') {
				var item = {url: el.href, title: el.title, o: o};

				if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
					var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
					item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
				}

				opts.itemArray.push(item);

			} else {
				var arr	= $("a[@rel=" + el.rel + "]").get();

				for (var i = 0; i < arr.length; i++) {
					var tmp		= $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o;
   					var item	= {url: arr[i].href, title: arr[i].title, o: tmp};

   					if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
						var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el);

						item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
					}

					if (arr[i].href == el.href) opts.itemNum = i;

					opts.itemArray.push(item);
				}
			}
		}

		$.fn.fancybox.changeItem(opts.itemNum);
	};

	$.fn.fancybox.changeItem = function(n) {
		$.fn.fancybox.showLoading();

		opts.itemNum = n;

		$("#fancy_nav").empty();
		$("#fancy_outer").stop();
		$("#fancy_title").hide();
		$(document).unbind("keydown");

		imgRegExp = imgTypes.join('|');
    	imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i');

		var url = opts.itemArray[n].url;

		if (url.match(/#/)) {
			var target = window.location.href.split('#')[0]; target = url.replace(target,'');

	        $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>');

	        $("#fancy_loading").hide();

		} else if (url.match(imgRegExp)) {
			$(imgPreloader).unbind('load').bind('load', function() {
				$("#fancy_loading").hide();

				opts.itemArray[n].o.frameWidth	= imgPreloader.width;
				opts.itemArray[n].o.frameHeight	= imgPreloader.height;

				$.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />');

			}).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) );

		} else {
			$.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>');
		}
	};

	$.fn.fancybox.showIframe = function() {
		$("#fancy_loading").hide();
		$("#fancy_frame").show();
	};

	$.fn.fancybox.showItem = function(val) {
		$.fn.fancybox.preloadNeighborImages();

		var viewportPos	= $.fn.fancybox.getViewport();
		var itemSize	= $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight);

		var itemLeft	= viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20;
		var itemTop		= viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40;

		var itemOpts = {
			'left':		itemLeft,
			'top':		itemTop,
			'width':	itemSize[0] + 'px',
			'height':	itemSize[1] + 'px'
		}

		if (opts.active) {
			$('#fancy_content').fadeOut("normal", function() {
				$("#fancy_content").empty();

				$("#fancy_outer").animate(itemOpts, "normal", function() {
					$("#fancy_content").append($(val)).fadeIn("normal");
					$.fn.fancybox.updateDetails();
				});
			});

		} else {
			opts.active = true;

			$("#fancy_content").empty();

			if ($("#fancy_content").is(":animated")) {
				console.info('animated!');
			}

			if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) {
				opts.animating		= true;
				itemOpts.opacity	= "show";

				$("#fancy_outer").css({
					'top':		opts.itemArray[opts.itemNum].orig.pos.top - 18,
					'left':		opts.itemArray[opts.itemNum].orig.pos.left - 18,
					'height':	opts.itemArray[opts.itemNum].orig.height,
					'width':	opts.itemArray[opts.itemNum].orig.width
				});

				$("#fancy_content").append($(val)).show();

				$("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() {
					opts.animating = false;
					$.fn.fancybox.updateDetails();
				});

			} else {
				$("#fancy_content").append($(val)).show();
				$("#fancy_outer").css(itemOpts).show();
				$.fn.fancybox.updateDetails();
			}
		 }
	};

	$.fn.fancybox.updateDetails = function() {
		$("#fancy_bg,#fancy_close").show();

		if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') {
			$('#fancy_title div').html(opts.itemArray[opts.itemNum].title);
			$('#fancy_title').show();
		}

		if (opts.itemArray[opts.itemNum].o.hideOnContentClick) {
			$("#fancy_content").click($.fn.fancybox.close);
		} else {
			$("#fancy_content").unbind('click');
		}

		if (opts.itemNum != 0) {
			$("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>');

			$('#fancy_left').click(function() {
				$.fn.fancybox.changeItem(opts.itemNum - 1); return false;
			});
		}

		if (opts.itemNum != (opts.itemArray.length - 1)) {
			$("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>');

			$('#fancy_right').click(function(){
				$.fn.fancybox.changeItem(opts.itemNum + 1); return false;
			});
		}

		$(document).keydown(function(event) {
			if (event.keyCode == 27) {
            	$.fn.fancybox.close();

			} else if(event.keyCode == 37 && opts.itemNum != 0) {
            	$.fn.fancybox.changeItem(opts.itemNum - 1);

			} else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) {
            	$.fn.fancybox.changeItem(opts.itemNum + 1);
			}
		});
	};

	$.fn.fancybox.preloadNeighborImages = function() {
		if ((opts.itemArray.length - 1) > opts.itemNum) {
			preloadNextImage = new Image();
			preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url;
		}

		if (opts.itemNum > 0) {
			preloadPrevImage = new Image();
			preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url;
		}
	};

	$.fn.fancybox.close = function() {
		if (opts.animating) return false;

		$(imgPreloader).unbind('load');
		$(document).unbind("keydown");

		$("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide();

		$("#fancy_nav").empty();

		opts.active	= false;

		if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) {
			var itemOpts = {
				'top':		opts.itemArray[opts.itemNum].orig.pos.top - 18,
				'left':		opts.itemArray[opts.itemNum].orig.pos.left - 18,
				'height':	opts.itemArray[opts.itemNum].orig.height,
				'width':	opts.itemArray[opts.itemNum].orig.width,
				'opacity':	'hide'
			};

			opts.animating = true;

			$("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() {
				$("#fancy_content").hide().empty();
				$("#fancy_overlay,#fancy_bigIframe").remove();
				opts.animating = false;
			});

		} else {
			$("#fancy_outer").hide();
			$("#fancy_content").hide().empty();
			$("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove();
		}
	};

	$.fn.fancybox.showLoading = function() {
		clearInterval(loadingTimer);

		var pos = $.fn.fancybox.getViewport();

		$("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();
		$("#fancy_loading").bind('click', $.fn.fancybox.close);

		loadingTimer = setInterval($.fn.fancybox.animateLoading, 66);
	};

	$.fn.fancybox.animateLoading = function(el, o) {
		if (!$("#fancy_loading").is(':visible')){
			clearInterval(loadingTimer);
			return;
		}

		$("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px');

		loadingFrame = (loadingFrame + 1) % 12;
	};

	$.fn.fancybox.init = function() {
		if (!$('#fancy_wrap').length) {
			$('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body");
			$('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner");

			$('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title');
		}

		if ($.browser.msie) {
			$("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>');
		}

		if (jQuery.fn.pngFix) $(document).pngFix();

    	$("#fancy_close").click($.fn.fancybox.close);
	};

	$.fn.fancybox.getPosition = function(el) {
		var pos = el.offset();

		pos.top	+= $.fn.fancybox.num(el, 'paddingTop');
		pos.top	+= $.fn.fancybox.num(el, 'borderTopWidth');

 		pos.left += $.fn.fancybox.num(el, 'paddingLeft');
		pos.left += $.fn.fancybox.num(el, 'borderLeftWidth');

		return pos;
	};

	$.fn.fancybox.num = function (el, prop) {
		return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
	};

	$.fn.fancybox.getPageScroll = function() {
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}

		return [xScroll, yScroll];
	};

	$.fn.fancybox.getViewport = function() {
		var scroll = $.fn.fancybox.getPageScroll();

		return [$(window).width(), $(window).height(), scroll[0], scroll[1]];
	};

	$.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) {
		var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight);

		return [Math.round(r * imageWidth), Math.round(r * imageHeight)];
	};

	$.fn.fancybox.defaults = {
		hideOnContentClick:	false,
		zoomSpeedIn:		500,
		zoomSpeedOut:		500,
		frameWidth:			600,
		frameHeight:		400,
		overlayShow:		false,
		overlayOpacity:		0.4,
		itemLoadCallback:	null
	};
})(jQuery);/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�Ürn Zaefferer, Paul McLanahan
 *
 * 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.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName ) return;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[@src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[@src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);
/**
 * jQuery Plugin colorBlend v1.6.0
 * Requires jQuery 1.2.6+ (Not tested with earlier versions).
 * Based on the Fade plugin http://plugins.jquery.com/project/fade
 * Code losely based on the Cycle plugin http://plugins.jquery.com/project/cycle It was a great resource in creating this one)
 * Copyright (c) 2007-2008 Aaron E. [jquery at happinessinmycheeks dot com]
 *
 *	@param: Object Array. Arguments need to be in object notation.
 *	Returns: jQuery.
 *	Options:
 *		param:		What css color option you wish to fade.
 *					Such as "background-color", "color", "boarder-color", "scrollbar-face-color" etc.
 *					(default: "background-color).
 *		fps:		Frames per second (default: 30).
 *		cycles:		How many times you want the object to fade. 0 = Infinite. (default: 0).
 *		random:		Will transition from a random color to a random color. (default: false).
 *					Note: Will change isFade to false.
 *		isFade:		Will fade from the original color and back to the original color. (default: true).
 *					Note: Cannont set to true if random is set to true.
 *		fromColor:	*DEPRECIATED* Starting color. accepts RGB, Hex, Name values.
 *					Will be overwritten if random is set to true. Also accepts "random" as an option.
 *		toColor:	*DEPRECIATED* Ending color. Same as above.
 *		colorList:	Now accepts an array of color strings! colorList can accept 3 or 6 digit hex colors (#000000, #000) it can also accept rgb and color names.
 *		alpha:		Opacity of element! accepts numerical array and old comma seperated string. (Default: [100, 100]).
 *		isQueue:	Will queue up color aniimations for a paramater.
 *	Examples:
 *		$("body").colorBlend([{fromColor:"black", toColor:"white", param:"color"}]);
 *		var myColors = [
 *			{param:'color', colorList["white", "black"]},
 *			{param:'background-color', random: true, alpha:[20,75]},
 *			{param:'border-left-color', colorList: ["random", "black"]},
 *			{param:'border-right-color', fromColor:"white", "black"]},
 *			{param:'border-top-color', colorList: ["white", "black", "pink"]},
 *			{param:'border-bottom-color', colorList: ["white", "tomato", "lime"]}
 *		];
 *		$("tr").colorBlend(myColors);
 *
 *	Known issues:
 *			* If used on a lot of objects it can cause major browser slowdown and it will eat a lot of cpu.
 *			* Still one flickering bug when it comes to opacity. Trying to track it down.
 *
 *	Additions:
 *		1.0.2
 *			* Added "parent" as a valid color value. Will check parents until valid color is found.
 *				defaults to white if there are no parents with color.
 *		1.0.3
 *			* Added Alpha/Opacity blending! Add alpha:"0,100" to list of parameters.
 *				Note: Will change the opacity of element only, not the property!
 *				If you only want text to appear and dissapear, you'll have to put it in it's own element, otherise the whole
 *				element will fade, not just your text.
 *		1.0.4
 *			* Alpha will now take just one argument alpha:"30" if you want to just change the alpha and not have it animate.
 *			* Current is now the default fromColor value. The current value will get the current color of the element. If current is transparent, it will get the parent color.
 *			* Opposite is now the default toColor value.
 *
 *		1.3.0
 *			* Added Queueing ability, so an animation will take arguments and process them once they are available.
 *			* Added Action parameter available arguments are stop, pause, and resume. Resume continues a paused animation. Where stop lets you assign a whole new animation to the element.
 *			* Added isQueue as an option allows you to decide if you want an option to be queued or not
 *
 *		1.4.0
 *			* Added pause all, stop all, resume all.
 *			* Have objects stored in an non-named array for traversing.
 *		1.6.0
 *			* Changed some internals for smaller quicker code.
 *			* Added colorList. fromColor and toColor still work, but they are just converted into a colorList.
 *			* Changed alpha to an array as well, can use more than 2 params. Still works with older string based param.
 *	Bugs fixed:
 *		1.0.1
 *			* Undesired flickering effect if colorBlend was called multiple times on the same css parameter.
 *		1.0.2
 *			* Noticed element would keep color attributes in certain circumstances.
 *		1.0.4
 *			* Fixed bug where under certain conditions the color would flicker.
 *		1.0.5
 *			* Great find by cratchit and he supplied the fix. Can now call colorBlend without any options.
 *		1.2.0
 *			* Flicker fix in 1.0.4 caused other issues. Fixed for good.
 *			* Found that if you try to get current color from scroll bar, it blows up. Added check for undefined as a color. Defaults to white.
 *		1.3.0
 *			* Found MORE flickering issues, and fixed them. I guess it's not over until the fat lady sings. Didn't see any more flicking, but I don't hear a fat lady.
 *		1.5.0
 *			* In my ignorance I noticed that alpha is taken care of quite nicely by jquery itself. No need to fix what isn't broke. Removed the custom stuff I had placed in.
 *			* Found an issue where if pausing and resuming something repeatitivly it might not sync up and cause weird flashing effects. Added isPOrS variable to check if paused or stopped. Seems to work.
 *		1.6.1
 *			* Found that in my last release I had accidentally hosed the "current", "random", "parent" and "opposite" options for the color list.
 */

(function($) {
	var ver = '1.6.1';
	var gObj = [];
	var q = 0;
	var tfps = [];
	var cnt = 0;
	var cid = 0;

	$.fn.colorBlend = function(opts) {
		if(!opts) { opts = [{}]; }

		var arrySelected = [];
		this.each(function() {
			arrySelected[arrySelected.length] = $.data($(this).get(0));
		});

		return this.each(function() {
			var $cont = $(this);
			var uId = $.data($cont.get(0));
			var isFlagAll = false;

			if(udf(gObj[uId])) {
				gObj[uId] = [];
			}

			$.each(opts, function(i, v){
				var isFound = false;
				opts[i] = $.extend({}, $.fn.colorBlend.defaults, opts[i]);
				opts[i].queue = [];
				opts[i].internals = $.extend({}, $.fn.colorBlend.internals);
				opts[i].parent = $cont;

				if(opts[i].param == "all") {
					isFlagAll = FlagAll(opts[i].action);
				}

				$.each(gObj[uId], function(j, w) {
					if(gObj[uId][j].param.toLowerCase() == opts[i].param.toLowerCase()
					|| opts[i].param.toLowerCase() == 'all') {
						if(!gObj[uId][j].internals.animating) {
							gObj[uId].splice(j, 1, setOptions(opts[i]));
						}
						isFound = true;
						return false;
					}
				});

				if(!isFound) {
					gObj[uId].push(setOptions(opts[i]));
				}
			});

			if(!isFlagAll) {
				$.each(gObj[uId], function(i, v){
					var ani = gObj[uId][i].internals.animating;
					var pausedOrStopped = gObj[uId][i].internals.isPOrS;

					$.each(opts, function(j, w) {
						if(gObj[uId][i].param.toLowerCase() != opts[j].param.toLowerCase()) {
							return true;
						}

						switch(opts[j].action) {
							case "stop":
							case "pause":
								clearTimeout(gObj[uId][i].internals.tId);
								gObj[uId][i].internals.isPOrS = true;
								pausedOrStopped = true;
								if(opts[j].action == "stop") {
									gObj[uId][i].internals.animating = false;
								}
							break;
							case "resume":
								ani = true;
								pausedOrStopped = false;
								gObj[uId][i].internals.isPOrS = false;
								go(gObj[uId][i]);
							break;
							default:
								if(ani) {
									if(gObj[uId][i].isQueue && gObj[uId][i].cycles > 0) {
										gObj[uId][i].queue.push(setOptions(opts[j]));
									}
								}
							break;
						}
					});

					if(!ani && !pausedOrStopped) {
						go(gObj[uId][i]);
					}
				});
			}
		});

		function FlagAll(action) {
			var res = false;
			$.each(arrySelected, function(i, v) {
				var curObj = gObj[v];
				$.each(curObj, function(j, w) {
					switch(action) {
						case "stop":
						case "pause":
							res = true;
							clearTimeout(curObj[j].internals.tId);
							curObj[j].internals.isPOrS = true;
							if(action == "stop") {
								curObj[j].internals.animating = false;
							}
						break;
						case "resume":
							res = true;
							curObj[j].internals.isPOrS = false;
							go(curObj[j]);
						break;
					}
				});
			});

			return res;
		};
	};

	$.fn.colorBlend.defaults = {
		fps:30,
		duration:1000,
		param:"background-color",
		cycles:0,
		random:false,
		isFade:true,
		fromColor:"",
		toColor:"",
		colorList: ["current", "opposite"],
		alpha:["100", "100"],
		action:"",
		isQueue:true
	};

	$.fn.colorBlend.internals = {
		aniArray:  [],
		alphaArry: [],
		pos: 0,
		currentCycle: 0,
		direction: 1,
		frames: 0,
		delay: 0,
		fromRand: false,
		toRand: false,
		animating: false,
		tId: 0,
		isPOrS: false
	};

	function setOptions(Opts) {
		if(!Opts.internals.animating) {
			var alphaParam = typeof(Opts.alpha) == "string" ? Opts.alpha.split(",") : Opts.alpha;

			if(Opts.fromColor != "" && Opts.toColor != "") {
				switch(Opts.fromColor.toLowerCase()) {
					case "current":
						Opts.fromColor = Opts.parent.css(Opts.param);
						break;
					case "parent":
					case "transparent":
						Opts.fromColor = checkParentColor(Opts.parent, Opts.param);
						break;
					case "opposite":
						Opts.fromColor = OppositeColor(Opts.toColor);
						break;
					case "random":
						Opts.fromColor = rndColor();
						Opts.internals.fromRand = true;
						break;
				}

				switch(Opts.toColor.toLowerCase()) {
					case "current":
						Opts.toColor = Opts.parent.css(Opts.param);
						break;
					case "parent":
					case "transparent":
						Opts.toColor = checkParentColor(Opts.parent, Opts.param);
						break;
					case "opposite":
						Opts.toColor = OppositeColor(Opts.fromColor);
						break;
					case "random":
						Opts.toColor = rndColor();
						Opts.internals.toRand = true;
						break;
				}

				Opts.colorList = [Opts.fromColor, Opts.toColor];
			}

			if(Opts.colorList.length == 1) {
				if(Opts.colorList[0].toLowerCase() == "random") {
					Opts.internals.toRand = true;
					Opts.colorList[0] = rndColor();
				}
			}

			$.each(Opts.colorList, function(i, v) {
				switch(v.toLowerCase()) {
					case "current":
						Opts.colorList[i] = Opts.parent.css(Opts.param) == "transparent" ? checkParentColor(Opts.parent, Opts.param) : Opts.parent.css(Opts.param);
						break;
					case "parent":
					case "transparent":
						Opts.colorList[i] = checkParentColor(Opts.parent, Opts.param);
						break;
					case "opposite":
						Opts.colorList[i] = OppositeColor(toHexColor(checkParentColor(Opts.parent, Opts.param)));
						break;
					case "random":
						Opts.colorList[i] = rndColor();
						break;
				}
			});

			Opts.internals.currentCycle = Opts.cycles > 0 ? Opts.cycles : 0;
			Opts.internals.frames = Math.floor(Opts.fps * (Opts.duration / 1000));
			Opts.internals.delay = Math.floor(Opts.duration / ((Opts.internals.frames+1)*Opts.colorList.length));

			if(Opts.random) {
				Opts.isFade = false;
				Opts.colorList = [rndColor(), rndColor()];
			}

			if(Opts.isFade) {
				Opts.internals.currentCycle = Opts.internals.currentCycle * 2;
				Opts.internals.delay = Math.floor(Opts.internals.delay / 2);
				Opts.internals.frames = Math.floor(Opts.internals.frames / 2);
			}

			Opts.internals.alphaArry = buildAlphaAni(alphaParam, Opts.internals.frames);
			Opts.internals.aniArray = buildAnimation(Opts.colorList, Opts.internals.frames);
			return Opts;
		}
	}

	function go(Opts) {
		if(!Opts.internals.isPOrS) {
			var sendStop = false;

			Opts.internals.animating = true;

			Opts.parent.css(Opts.param, Opts.internals.aniArray[Opts.internals.pos]);
			setAlpha(Opts.parent, Opts.internals.alphaArry[Opts.internals.pos]);

			Opts.internals.pos += Opts.internals.direction;

			if(Opts.internals.pos < 0 || Opts.internals.pos >= Opts.internals.aniArray.length) {
				Opts.internals.currentCycle -= Opts.internals.currentCycle != 0 ? 1 : 0;
				Opts.internals.direction = Opts.internals.direction * -1;
				Opts.internals.pos += Opts.internals.direction;

				if(Opts.random) {
					Opts.colorList = [Opts.colorList[Opts.colorList.length-1], rndColor()];
					Opts.internals.aniArray = buildAnimation(Opts.colorList, Opts.internals.frames);
				}

				if(!Opts.isFade) {
					Opts.internals.direction = 1;
					Opts.internals.pos = 0;
				}

				if(Opts.internals.currentCycle == 0 && Opts.cycles > 0) {
					sendStop = true;
				}
			}

			if(!sendStop) {
				Opts.internals.tId = setTimeout(function(){go(Opts);}, Opts.internals.delay);
			} else {
				clearTimeout(Opts.internals.tId);
				Opts.internals.tId = 0;
				if(Opts.isQueue && Opts.queue.length > 0) {
					var tmp = Opts.queue.concat();
					tmp.splice(0,1);
					Opts = $.extend(Opts, Opts.queue.shift());
					Opts.queue = tmp.concat();
					Opts.internals.tId = setTimeout(function(){go(Opts);}, Opts.internals.delay);
				} else {
					Opts.internals.animating = false;
					Opts.internals.isPOrS = true;
				}
			}
		}
	}

	function setAlpha(elm, opacity) {
		elm.css("opacity", parseFloat(opacity / 100));
	}

	function buildAlphaAni(alphaList, frames) {
		var frame = 0;
		var res = [];
		var h = 0;

		for(var i = 0;i < alphaList.length-1;i++) {
			var startOpacity = alphaList[i];
			var endOpacity = alphaList[i+1];
			for(frame = 0;frame<=frames;frame++) {
				h = Math.floor(startOpacity * ((frames-frame)/frames) + endOpacity * (frame/frames));
				res[res.length] = h
			}
		}

		if(h != alphaList[alphaList.length-1]) {
			res[res.length] = parseInt(alphaList[alphaList.length-1]);
		}

		return res;
	}

	function buildAnimation(colorList, frames) {
		var frame = 0;
		var r,g,b,h;
		var res = [];
		for(var i = 0;i < colorList.length-1;i++) {
			var fc = getRGB(colorList[i]);
			var tc = getRGB(colorList[i+1]);

			for(frame = 0;frame<=frames;frame++) {
				r = Math.floor(fc[0] * ((frames-frame)/frames) + tc[0] * (frame/frames));
				g = Math.floor(fc[1] * ((frames-frame)/frames) + tc[1] * (frame/frames));
				b = Math.floor(fc[2] * ((frames-frame)/frames) + tc[2] * (frame/frames));
				h = ColorDecToHex(r, g, b);
				res[res.length] = h;
			}
		}


		if(h.toLowerCase() != toHexColor(colorList[colorList.length-1])) {
			res[res.length] = toHexColor(colorList[colorList.length-1]);
		}

		return res;
	}

	var colors = {
		aliceblue:"F0F8FF", antiquewhite:"FAEBD7", aqua:"00FFFF", aquamarine:"7FFFD4",
		azure:"F0FFFF", beige:"F5F5DC", bisque:"FFE4C4", black:"000000",
		blanchedalmond:"FFEBCD", blue:"0000FF", blueviolet:"8A2BE2", brown:"A52A2A",
		burlywood:"DEB887", cadetblue:"5F9EA0", chartreuse:"7FFF00", chocolate:"D2691E",
		coral:"FF7F50", cornflowerblue:"6495ED", cornsilk:"FFF8DC", crimson:"DC143C",
		cyan:"00FFFF", darkblue:"00008B", darkcyan:"008B8B", darkgoldenrod:"B8860B",
		darkgray:"A9A9A9", darkgreen:"006400", darkkhaki:"BDB76B", darkmagenta:"8B008B",
		darkolivegreen:"556B2F", darkorange:"FF8C00", darkorchid:"9932CC", darkred:"8B0000",
		darksalmon:"E9967A", darkseagreen:"8FBC8F", darkslateblue:"483D8B", darkslategray:"2F4F4F",
		darkturquoise:"00CED1", darkviolet:"9400D3", deeppink:"FF1493", deepskyblue:"00BFFF",
		dimgray:"696969", dodgerblue:"1E90FF", firebrick:"B22222", floralwhite:"FFFAF0",
		forestgreen:"228B22", fuchsia:"FF00FF", gainsboro:"DCDCDC", ghostwhite:"F8F8FF",
		gold:"FFD700", goldenrod:"DAA520", gray:"808080", grey:"808080", green:"008000",
		greenyellow:"ADFF2F", honeydew:"F0FFF0", hotpink:"FF69B4", indianred:"CD5C5C",
		indigo:"4B0082", ivory:"FFFFF0", khaki:"F0E68C", lavender:"E6E6FA",
		lavenderblush:"FFF0F5", lawngreen:"7CFC00", lemonchiffon:"FFFACD", lightblue:"ADD8E6",
		lightcoral:"F08080", lightcyan:"E0FFFF", lightgoldenrodyellow:"FAFAD2", lightgreen:"90EE90",
		lightgrey:"D3D3D3", lightpink:"FFB6C1", lightsalmon:"FFA07A", lightseagreen:"20B2AA",
		lightskyblue:"87CEFA", lightslategray:"778899", lightsteelblue:"B0C4DE", lightyellow:"FFFFE0",
		lime:"00FF00", limegreen:"32CD32", linen:"FAF0E6", magenta:"FF00FF",
		maroon:"800000", mediumaquamarine:"66CDAA", mediumblue:"0000CD", mediumorchid:"BA55D3",
		mediumpurple:"9370DB", mediumseagreen:"3CB371", mediumslateblue:"7B68EE", mediumspringgreen:"00FA9A",
		mediumturquoise:"48D1CC", mediumvioletred:"C71585", midnightblue:"191970", mintcream:"F5FFFA",
		mistyrose:"FFE4E1", moccasin:"FFE4B5", navajowhite:"FFDEAD", navy:"000080",
		oldlace:"FDF5E6", olive:"808000", olivedrab:"6B8E23", orange:"FFA500",
		orangered:"FF4500", orchid:"DA70D6", palegoldenrod:"EEE8AA", palegreen:"98FB98",
		paleturquoise:"AFEEEE", palevioletred:"DB7093", papayawhip:"FFEFD5", peachpuff:"FFDAB9",
		peru:"CD853F", pink:"FFC0CB", plum:"DDA0DD", powderblue:"B0E0E6",
		purple:"800080", red:"FF0000", rosybrown:"BC8F8F", royalblue:"4169E1",
		saddlebrown:"8B4513", salmon:"FA8072", sandybrown:"F4A460", seagreen:"2E8B57",
		seashell:"FFF5EE", sienna:"A0522D", silver:"C0C0C0", skyblue:"87CEEB",
		slateblue:"6A5ACD", slategray:"708090", snow:"FFFAFA", springgreen:"00FF7F",
		steelblue:"4682B4", tan:"D2B48C", teal:"008080", thistle:"D8BFD8",
		tomato:"FF6347", turquoise:"40E0D0", violet:"EE82EE", wheat:"F5DEB3",
		white:"FFFFFF", whitesmoke:"F5F5F5", yellow:"FFFF00", yellowgreen:"9ACD32"
	};

	function OppositeColor(value) {
		value = toHexColor(value).split("#").join('').split('');
		var hexVals = "0123456789abcdef";
		var revHexs = hexVals.split('').reverse().join('');
		var currentPos;
		for(var i = 0;i < value.length;i++) {
			currentPos = hexVals.indexOf(value[i]);
			value[i] = revHexs.substring(currentPos,currentPos+1);
		}

		return "#" + value.join('');
	}

	function ColorDecToHex(r,g,b) {
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	}

	function ColorHexToDec(value) {
		var res = [];
		value = value.replace("#", "");
		for(var i = 0;i < 3;i++) {
			res[res.length] = parseInt(value.substr(i * 2, 2), 16);
		}
		return res.join(',');
	}

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/
	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return ColorHexToDec(colors[jQuery.trim(color).toLowerCase()]).split(',');
	}

	function toHexColor(value) {
		var rgb = getRGB(value);
		return ColorDecToHex(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]));
	}

	function checkParentColor(elm, param) {
		/*White is chosen as default to eliminate issues between IE and FF*/
		var pColr = "#ffffff";

		$(elm).parents().each(function(){
			var result = $(this).css(param);
			if(result != 'transparent' && result != '') {
				pColr = result;
				return false;
			}
		});

		return pColr;
	}

	function rndColor() {
		var res = [];
		var cm;
		for(var i = 0;i < 3;i++) {
			cm = randRange(0, 255).toString(16);
			if (cm.length == 1) cm = '0' + cm;
			res[res.length] = cm;
		}
		return "#" + res.join('');
	}

	function randRange(lowVal, highVal) {
		 return Math.floor(Math.random()*(highVal-lowVal+1))+lowVal;
	}

	function udf(val) {
		return typeof(val) == 'undefined' ? true : false;
	}
})(jQuery);
/*
 * jQuery validation plug-in post1.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 5968 2008-12-18 10:45:22Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

$.extend($.fn, {
	// http://docs.jquery.com/Plugins/Validation/validate
	validate: function( options ) {
		
		// if nothing is selected, return nothing; can't chain anyway
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nic nie zaznaczono, nie mogę przeprowadzić walidacji." );
			return;
		}
		
		// check if a validator for this form was already created
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}
		
		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator); 
		
		if ( validator.settings.onsubmit ) {
		
			// allow suppresing validation by adding a cancel class to the submit button
			this.find("input, button").filter(".cancel").click(function() {
				validator.cancelSubmit = true;
			});
		
			// validate the form on submit
			this.submit( function( event ) {
				if ( validator.settings.debug )
					// prevent form submit to be able to see console output
					event.preventDefault();
					
				function handle() {
					if ( validator.settings.submitHandler ) {
						validator.settings.submitHandler.call( validator, validator.currentForm );
						return false;
					}
					return true;
				}
					
				// prevent submit for invalid forms or custom submit handlers
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}
		
		return validator;
	},
	// http://docs.jquery.com/Plugins/Validation/valid
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = false;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid |= validator.element(this);
            });
            return valid;
        }
    },
	// attributes: space seperated list of attributes to retrieve and remove
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function() {
			result[this] = $element.attr(this);
			$element.removeAttr(this);
		});
		return result;
	},
	// http://docs.jquery.com/Plugins/Validation/rules
	rules: function(command, argument) {
		var element = this[0];
		
		if (command) {
			var settings = $.data(element.form, 'validator').settings;
			var staticRules = settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				if (argument.messages)
					settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}
		
		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);
		
		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}
		
		return data;
	},
	// destructive add
	push: function( t ) {
		return this.setArray( this.add(t).get() );
	}
});

// Custom selectors
$.extend($.expr[":"], {
	// http://docs.jquery.com/Plugins/Validation/blank
	blank: function(a) {return !$.trim(a.value);},
	// http://docs.jquery.com/Plugins/Validation/filled
	filled: function(a) {return !!$.trim(a.value);},
	// http://docs.jquery.com/Plugins/Validation/unchecked
	unchecked: function(a) {return !a.checked;}
});


$.format = function(source, params) {
	if ( arguments.length == 1 ) 
		return function() {
			var args = $.makeArray(arguments);
			args.unshift(source);
			return $.format.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = $.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	$.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};

// constructor for validator
$.validator = function( options, form ) {
	this.settings = $.extend( {}, $.validator.defaults, options );
	this.currentForm = form;
	this.init();
};

$.extend($.validator, {

	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: [],
		ignoreTitle: false,
		onfocusin: function(element) {
			this.lastActive = element;
				
			// hide error label and remove error class on focus if enabled
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass );
				this.errorsFor(element).hide();
			}
		},
		onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element) {
			if ( element.name in this.submitted )
				this.element(element);
		},
		highlight: function( element, errorClass ) {
			$( element ).addClass( errorClass );
		},
		unhighlight: function( element, errorClass ) {
			$( element ).removeClass( errorClass );
		}
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
	setDefaults: function(settings) {
		$.extend( $.validator.defaults, settings );
	},

	messages: {
		required: "To pole jest wymagane.",
		remote: "Proszę poprawić to pole.",
		email: "Proszę wpisać poprawny adres email.",
		url: "Prosze wpisać poprawny adres URL.",
		lettersonly: "To pole może zawierać wyłącznie litery.",
		date: "Proszę wpisać poprawną datę.",
		dateISO: "Proszę wpisać poprawną datę (ISO).",
		dateDE: "Bitte geben Sie ein gültiges Datum ein.",
		number: "Please enter a valid number.",
		numberDE: "Bitte geben Sie eine Nummer ein.",
		digits: "Please enter only digits",
		creditcard: "Please enter a valid credit card number.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.format("Please enter no more than {0} characters."),
		minlength: $.format("Please enter at least {0} characters."),
		rangelength: $.format("Please enter a value between {0} and {1} characters long."),
		range: $.format("Please enter a value between {0} and {1}."),
		max: $.format("Please enter a value less than or equal to {0}."),
		min: $.format("Please enter a value greater than or equal to {0}.")
	},
	
	autoCreateRanges: false,
	
	prototype: {
		
		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();
			
			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});
			
			function delegate(event) {
				var validator = $.data(this[0].form, "validator");
				validator.settings["on" + event.type] && validator.settings["on" + event.type].call(validator, this[0] );
			}
			$(this.currentForm)
				.delegate("focusin focusout keyup", ":text, :password, :file, select, textarea", delegate)
				.delegate("click", ":radio, :checkbox", delegate);

			if (this.settings.invalidHandler)
				$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/form
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			this.showErrors();
			return this.valid();
		},
		
		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid(); 
		},
		
		// http://docs.jquery.com/Plugins/Validation/Validator/element
		element: function( element ) {
			element = this.clean( element );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				// Hide error containers on last error
				this.toHide.push( this.containers );
			}
			this.showErrors();
			return result;
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/showErrors
		showErrors: function(errors) {
			if(errors) {
				// add items to error list and map
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				// remove items from success list
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},
		
		// http://docs.jquery.com/Plugins/Validation/Validator/resetForm
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},
		
		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},
		
		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},
		
		hideErrors: function() {
			this.addWrapper( this.toHide ).hide();
		},
		
		valid: function() {
			return this.size() == 0;
		},
		
		size: function() {
			return this.errorList.length;
		},
		
		focusInvalid: function() {
			if( this.settings.focusInvalid ) {
				try {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus();
				} catch(e) {
					// ignore IE throwing errors when focusing hidden elements
				}
			}
		},
		
		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},
		
		elements: function() {
			var validator = this,
				rulesCache = {};
			
			// select all valid inputs inside the form (no submit or reset buttons)
			// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
			return $([]).add(this.currentForm.elements)
			.filter(":input")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);
			
				// select only the first element for each name, and only those with rules specified
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;
				
				rulesCache[this.name] = true;
				return true;
			});
		},
		
		clean: function( selector ) {
			return $( selector )[0];
		},
		
		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},
		
		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.formSubmitted = false;
			this.currentElements = $([]);
		},
		
		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().push( this.containers );
		},
		
		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},
	
		check: function( element ) {
			element = this.clean( element );
			
			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name )[0];
			}
			
			var rules = $(element).rules();
			var dependencyMismatch = false;
			for( method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, element.value, element, rule.parameters );
					
					// if a method indicates that the field is optional and therefore valid,
					// don't mark it as valid when there are no other rules
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;
					
					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}
					
					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method");
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},
		
		// return the custom message for the given element and validation method
		// specified in the element's "messages" metadata
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;
			
			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();
			
			return meta && meta.messages && meta.messages[method];
		},
		
		// return the custom message for the given element name and validation method
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},
		
		// return the first defined argument, allowing empty strings
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},
		
		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				// title is never undefined, so handle empty string as undefined
				!this.settings.ignoreTitle && element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},
		
		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method );
			if ( typeof message == "function" ) 
				message = message.call(this, rule.parameters, element);
			this.errorList.push({
				message: message,
				element: element
			});
			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},
		
		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle.push( toToggle.parents( this.settings.wrapper ) );
			return toToggle;
		},
		
		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow.push( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
		},
		
		validElements: function() {
			return this.currentElements.not(this.invalidElements());
		},
		
		invalidElements: function() {
			return $(this.errorList).map(function() {
				return this.element;
			});
		},
		
		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				// refresh error/success class
				label.removeClass().addClass( this.settings.errorClass );
			
				// check if we have a generated label, replace the message then
				label.attr("generated") && label.html(message);
			} else {
				// create label
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					// make sure the element is visible, even in IE
					// actually showing the wrapped element is handled elsewhere
					label = label.hide().show().wrap("<" + this.settings.wrapper + ">").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow.push(label);
		},
		
		errorsFor: function(element) {
			return this.errors().filter("[@for='" + this.idOrName(element) + "']");
		},
		
		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},
		
		findByName: function( name ) {
			// select by name and filter by form for performance over form.find("[name=...]")
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},
		
		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},
	
		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},
	
		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},
		
		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},
		
		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},
		
		stopRequest: function(element, valid) {
			this.pendingRequest--;
			// sometimes synchronization fails, make sure pendingRequest is never < 0
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			}
		},
		
		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", previous = {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}
		
	},
	
	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},
	
	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},
	
	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},
	
	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);
		
		for (method in $.validator.methods) {
			var value = $element.attr(method);
			if (value) {
				rules[method] = value;
			}
		}
		
		// maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}
		
		return rules;
	},
	
	metadataRules: function(element) {
		if (!$.metadata) return {};
		
		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},
	
	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},
	
	normalizeRules: function(rules, element) {
		// handle dependency check
		$.each(rules, function(prop, val) {
			// ignore rule when param is explicitly false, eg. required:false
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});
		
		// evaluate parameters
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});
		
		// clean number parameters
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});
		
		if ($.validator.autoCreateRanges) {
			// auto-create ranges
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}
		
		// To support custom messages in metadata ignore rule methods titled "messages"
		if (rules.messages) {
			delete rules.messages
		}
		
		return rules;
	},
	
	// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},
	
	// http://docs.jquery.com/Plugins/Validation/Validator/addMethod
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message;
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},

	methods: {

		// http://docs.jquery.com/Plugins/Validation/Methods/required
		required: function(value, element, param) {
			// check if dependency is met
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				var options = $("option:selected", element);
				return options.length > 0 && ( element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return $.trim(value).length > 0;
			}
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/remote
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			
			var previous = this.previousValue(element);
			
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			
			param = typeof param == "string" && {url:param} || param; 
			
			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					data: data,
					success: function(response) {
						if ( response ) {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						} else {
							var errors = {};
							errors[element.name] =  response || validator.defaultMessage( element, "remote" );
							validator.showErrors(errors);
						}
						previous.valid = response;
						validator.stopRequest(element, response);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/minlength
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) >= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/maxlength
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) <= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/rangelength
		rangelength: function(value, element, param) {
			var length = this.getLength($.trim(value), element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/min
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/max
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/range
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/email
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([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);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([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])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
		},
        
		// http://docs.jquery.com/Plugins/Validation/Methods/date
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},
        
		lettersonly: function(value, element) {
			return this.optional(element) || /^[A-za-zĄĘŚĆŹŻŃÓŁąęśćźżółń\-\.\, ]+$/i.test(value);
		},
        
		address: function(value, element) {
			return this.optional(element) || /^[A-za-zĄĘŚĆŹŻŃÓŁąęśćźżółń0-9\/., -]+\s[A-Za-z0-9]+(\/[A-Za-z0-9]+)*\s*$/i.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/dateDE
		dateDE: function(value, element) {
			return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/number
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/numberDE
		numberDE: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/digits
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/creditcard
		// based on http://en.wikipedia.org/wiki/Luhn
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/accept
		accept: function(value, element, param) {
			param = typeof param == "string" ? param : "png|jpe?g|gif";
			return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); 
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/equalTo
		equalTo: function(value, element, param) {
			return value == $(param).val();
		}
		
	}
	
});

})(jQuery);

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() 
;(function($) {
	var ajax = $.ajax;
	var pendingRequests = {};
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
		var port = settings.port;
		if (settings.mode == "abort") {
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return (pendingRequests[port] = ajax.apply(this, arguments));
		}
		return ajax.apply(this, arguments);
	};
})(jQuery);

// provides cross-browser focusin and focusout events
// IE has native support, in other browsers, use event caputuring (neither bubbles)

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target 

// provides triggerEvent(type: String, target: Element) to trigger delegated events
;(function($) {
	$.each({
		focus: 'focusin',
		blur: 'focusout'	
	}, function( original, fix ){
		$.event.special[fix] = {
			setup:function() {
				if ( $.browser.msie ) return false;
				this.addEventListener( original, $.event.special[fix].handler, true );
			},
			teardown:function() {
				if ( $.browser.msie ) return false;
				this.removeEventListener( original,
				$.event.special[fix].handler, true );
			},
			handler: function(e) {
				arguments[0] = $.event.fix(e);
				arguments[0].type = fix;
				return $.event.handle.apply(this, arguments);
			}
		};
	});
	$.extend($.fn, {
		delegate: function(type, delegate, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		},
		triggerEvent: function(type, target) {
			return this.triggerHandler(type, [$.event.fix({ type: type, target: target })]);
		}
	})
})(jQuery);
/*
 * jQuery FlyOut
 * author: Jolyon Terwilliger - Nixbox Web Designs
 * website: http://nixboxdesigns.com/jquery.flyout.php
 */

$.fn.extend({flyout : function(options) {
	
		var shown=false;
		var animating=false;
		var $holder;
		var $thumb;
		var tloc;
		var th;
		var tw;
		var bigimg = new Image();
		var subType = 'img';
		var offset;
        var id = this.id;
		
		this.click(function() {
			if (animating == true) { return false; }
	
			if (shown) { putAway(this); }
			else { flyOut(this); }
	
			return false;
		});

		jQuery(document).click(function() {
			if (animating == true) { return false; }
			if (shown) { putAway(id); return false;}
		});
		
		var o = jQuery.extend({
			outSpeed : 1000,
			inSpeed : 500,
			outEase : 'swing',
			inEase : 'swing',
			loadingSrc: null,
			loader: 'loaderMini',
			loaderZIndex: 500,
			widthMargin: 40,
			heightMargin: 40,
			loadingText : "Ładowanie...",
			closeTip : " - Kliknij w obrazek aby go ukryć",
			destPadding: 20,
			startOffsetX: 0,
			startOffsetY: 0,
			startHeight: 0,
			startWidth: 0,
			flyOutStart: function() {},
			flyOutFinish: function() {},
			putAwayStart: function() {},
			putAwayFinish: function() {},
			shownClass: 'shown'
		}, options);
	
		function flyOut(it) {
			animating = true;
			
			$holder = $(it);
			$thumb = $('img',it);
			bigimg = new Image(); 
			sL = $(window).scrollLeft();
			sT = $(window).scrollTop();
			tloc = $thumb.offset();
			tloc.left += o.startOffsetX;
			tloc.top += o.startOffsetY;
			th = (o.startHeight > 0 ? o.startHeight : $thumb.height());
			tw = (o.startWidth > 0 ? o.startWidth : $thumb.width());
			
			$('<div></div>').attr('id',o.loader)
							.appendTo('body')
							.css({'position':'absolute',
								'top':tloc.top,
								'left':tloc.left,
								'height':th,
								'width':tw,
								'opacity':.5,
								'display':'block',
								'z-index':o.loaderZIndex});

			if (o.loadingSrc) {
				$('#'+o.loader).append($('<img/>')
								.load(function() {
										$(this)
											.css({'position':'relative',
												 'top':th/2-(this.height/2),
												 'left':tw/2-(this.width/2)})
											.attr('alt',o.loadingText);
										})
									.attr('src',o.loadingSrc)
								);
			}
			else {
				$('#'+o.loader).css('background-color','#000')
								.append($('<span></span>')
										  	.text(o.loadingText)
											.css({'position':'relative',
												 'top':'2px',
												 'left':'2px',
												 'color':'#FFF',
												 'font-size':'9px'})
									 	);
			}

			$(bigimg).load(function() {
				imgtag = $('<img/>').attr('src',$holder.attr('href')).attr('title',$thumb.attr('title')+o.closeTip).attr('alt',$thumb.attr('alt')+o.closeTip).height(th).width(tw);

				o.flyOutStart.call(it);

				if (o.destElement) {
					var $dest = $(o.destElement);
					max_x = $dest.innerWidth() - (o.destPadding*2);
					max_y = $dest.innerHeight() - (o.destPadding*2);
				}
				else {
					max_x = $(window).width()-o.widthMargin;
					if ($.browser.opera) 
						wh = document.getElementsByTagName('html')[0].clientHeight;
					else 
						wh = $(window).height();
					max_y = wh-o.heightMargin;
				}

				width = bigimg.width;
				height = bigimg.height;
	
				x_dim = max_x / width;
				y_dim = max_y / height;
	
				if (x_dim <=y_dim) {
					y_dim = x_dim;
				} else {
					x_dim = y_dim;
				}
				
				dw = Math.round(width  * x_dim);
				dh = Math.round(height * y_dim);
				if (dw>width) {dw = width}
				if (dh>height) {dh = height}
				
				if (o.destElement) {
					dPos = $dest.offset();
					dl = Math.round(($dest.outerWidth()/2)-(dw/2)+dPos.left);
					dt = Math.round(($dest.outerHeight()/2)-(dh/2)+dPos.top);
				}
				else {
					dl = Math.round(($(window).width()/2)-(dw/2)+sL);
					if ($.browser.opera) 
						wh = document.getElementsByTagName('html')[0].clientHeight;
					else 
						wh = $(window).height();
					dt = Math.round((wh/2)-(dh/2)+sT);
				}
				
				$('#'+o.loader).empty().css('opacity',1).append(imgtag).width('auto').height('auto').animate({top:dt, left:dl},{duration:o.outSpeed, queue:false, easing:o.outEase});
				$('#'+o.loader+' '+subType).animate({height:dh, width:dw}, o.outSpeed, o.outEase,
				function() {
					o.flyOutFinish.call(it);
					shown = it;
					$holder.addClass(o.shownClass);
					animating=false;
					$('#'+o.loader+' '+subType).click(function(){putAway(null)})
				});
			});
			bigimg.src = $holder.attr('href');
		}
	
	
		function putAway(next) {
			// for future development:
			if (animating == true || shown == false) {return false;}
			o.putAwayStart.call(shown);
			
			animating = true;
			
			// check $thumb loc again, in case it moved...
			tloc = $thumb.offset();
			tloc.left += o.startOffsetX;
			tloc.top += o.startOffsetY;

			$('#'+o.loader).animate({top:tloc.top, left:tloc.left},{duration:o.inSpeed, queue:false, easing:o.inEase});
			$('#'+o.loader+' '+subType).animate({height:th, width:tw}, 
				o.inSpeed, o.inEase, 
				function() {
					$('#'+o.loader).css('display','none').remove(); 
					o.putAwayFinish.call(shown);
					animating=false;
					bigimg=null;			
					if (next && next != shown) {
						shown = false;
						flyOut(next);
					}
					shown = false;
					$holder.removeClass(o.shownClass);
				});
		}
		
		return this;	// never break the chain
		
	}
});
/**
 * jQuery.Preload
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/12/2008
 *
 * @projectDescription Multifunctional preloader
 * @author Ariel Flesler
 * @version 1.0.7
 *
 * @id jQuery.preload
 * @param {String, jQuery, Array< String, <a>, <link>, <img> >} original Collection of sources to preload
 * @param {Object} settings Hash of settings.
 *
 * @id jQuery.fn.preload
 * @param {Object} settings Hash of settings.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example Link Mode:
 *	$.preload( '#images a' );
 *
 * @example Rollover Mode:
 *	$.preload( '#images img', {
 *		find:/\.(gif|jpg)/,
 *		replace:'_over.$1'
 *	});
 *
 * @example Src Mode:
 *	$.preload( [ 'red', 'blue', 'yellow' ], {
 *		base:'images/colors/',
 *		ext:'.jpg'
 *	});
 *
 * @example Placeholder Mode:
 *	$.preload( '#images img', {
 *		placeholder:'placeholder.jpg',
 *		notFound:'notfound.jpg'
 *	});
 *
 * @example Placeholder+Rollover Mode(High res):
 *	$.preload( '#images img', {
 *		placeholder:true,
 *		find:/\.(gif|jpg)/,
 *		replace:'_high.$1'
 *	});
 */
;(function( $ ){

	var $preload = $.preload = function( original, settings ){
		if( original.split )//selector
			original = $(original);

		settings = $.extend( {}, $preload.defaults, settings );
		var sources = $.map( original, function( source ){
			if( !source ) 
				return;//skip
			if( source.split )//URL Mode
				return settings.base + source + settings.ext;
			var url = source.src || source.href;//save the original source
			if( typeof settings.placeholder == 'string' && source.src )//Placeholder Mode, if it's an image, set it.
				source.src = settings.placeholder;
			if( url && settings.find )//Rollover mode
				url = url.replace( settings.find, settings.replace );
			return url || null;//skip if empty string
		});

		var data = {
			loaded:0,//how many were loaded successfully
			failed:0,//how many urls failed
			next:0,//which one's the next image to load (index)
			done:0,//how many urls were tried
			//found:false,//whether the last one was successful
			total:sources.length//how many images are being preloaded overall
		};
		
		if( !data.total )//nothing to preload
			return finish();
		
		var imgs = '<img/>',//ensure one
			thres = settings.threshold;//save a copy
		
		while( --thres > 0 )//it could be oddly negative
			imgs += '<img/>';
		imgs = $(imgs).load(handler).error(handler).bind('abort',handler).each(fetch);
		
		function handler( e ){
			data.found = e.type == 'load';
			data.image = this.src;
			var orig = data.original = original[this.index];
			data[data.found?'loaded':'failed']++;
			data.done++;
			if( settings.placeholder && orig.src )//special case when on placeholder mode
				orig.src = data.found ? data.image : settings.notFound || orig.src;
			if( settings.onComplete )
				settings.onComplete( data );
			if( data.done < data.total )//let's continue
				fetch( 0, this );
			else{//we are finished
				if( imgs.unbind )//sometimes IE gets here before finishing line 84
					imgs.unbind('load').unbind('error').unbind('abort');//cleanup
				imgs = null;
				finish();
			}
		};
		function fetch( i, img, retry ){
			if( $.browser.msie && data.next && data.next % $preload.gap == 0 && !retry ){//IE problem, can't preload more than 15
				setTimeout(function(){ fetch( i, img, true ); }, 0);
				return false;
			}
			if( data.next == data.total ) return false;//no more to fetch
			img.index = data.next;//save it, we'll need it.
			img.src = sources[data.next++];
			if( settings.onRequest ){
				data.image = img.src;
				data.original = original[data.next-1];
				settings.onRequest( data );
			}
		};
		function finish(){
			if( settings.onFinish )
				settings.onFinish( data );
		};
	};

	// each time we load this amount and it's IE, we must rest for a while, make it lower if you get stack overflow.
	$preload.gap = 14; 

	$preload.defaults = {
		threshold:2,//how many images to load simultaneously
		base:'',//URL mode: a base url can be specified, it is prepended to all string urls
		ext:'',//URL mode:same as base, but it's appended after the original url.
		replace:''//Rollover mode: replacement (can be left empty)
		/*
		find:null,//Rollover mode: a string or regex for the replacement
		notFound:''//Placeholder Mode: Optional url of an image to use when the original wasn't found
		placeholder:'',//Placeholder Mode: url of an image to set while loading
		onRequest:function( data ){ ... },//callback called every time a new url is requested
		onComplete:function( data ){ ... },//callback called every time a response is received(successful or not)
		onFinish:function( data ){ ... }//callback called after all the images were loaded(or failed)
		*/
	};

	$.fn.preload = function( settings ){
		$preload( this, settings );
		return this;
	};

})( jQuery );/*
 * jQuery Form Plugin
 * version: 2.25 (08-APR-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
    Usage Note:
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });

    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    // clean url (don't include hash vaue)
    var url = this.attr('action') || window.location.href;
    url = (url.match(/^([^#]+)/)||[])[1];
    url = url || '';

    options = $.extend({
        url:  url,
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } );
          }
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) {
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if (options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];

        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }

        var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" src="about:blank" />');
        var io = $io[0];

        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() {
                this.aborted = 1;
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
        }
        if (xhr.aborted)
            return;

        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);

                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
                t ? form.setAttribute('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        var nullCheckFlag = 0;

        function cb() {
            if (cbInvoked++) return;

            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

                if ((doc.body == null || doc.body.innerHTML == '') && !nullCheckFlag) {
                    // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when
                    // the onload callback fires, so we give them a 2nd chance
                    nullCheckFlag = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }

                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
                	v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
    if (b == undefined) b = true;
    return this.each(function() {
        this.disabled = !b;
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);
$(document).ready(JT_init);
$(document).bind('click', function(e) {
		var $clicked=$(e.target);
		if(!$clicked.is('INPUT[rel=\"jtip\"]') )
		{
			$('#JT').remove();
		} });function JT_init(){
	       $("INPUT[rel=\"jtip\"]")
           .click(function(){$('#JT').remove();JT_show(this.alt,this.id,this.title)});
}function JT_show(content,linkId,title){
	var title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) - 3; 
	
	var queryString = content.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 200};
	if(params['link'] !== undefined){
	$('#' + linkId).bind('click',function(){window.location = params['link']});
	$('#' + linkId).css('cursor','pointer');
	}
	
	if(hasArea>((params['width']*1)+75)){
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='JT_copy'><div class='JT_loader'><div></div></div>");
		var arrowOffset = getElementWidth(linkId) + 11;
		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; 
	}else{
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_copy'><div class='JT_loader'><div></div></div>");
		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); 
	}
	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$('#JT').show();
	$('#JT_copy').append(content); }function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}function getAbsoluteLeft(objectId) {
	
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            
	while(o.offsetParent!=null) {   
		oParent = o.offsetParent    
		oLeft += oParent.offsetLeft 
		o = oParent
	}
	return oLeft
}function getAbsoluteTop(objectId) {
	
	o = document.getElementById(objectId)
	oTop = o.offsetTop            
	while(o.offsetParent!=null) { 
		oParent = o.offsetParent  
		oTop += oParent.offsetTop 
		o = oParent
	}
	return oTop
}function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; 
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}(function($) {
	var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
	var iPhone = (window.orientation != undefined);

	$.mask = {
		
		definitions: {
			'9': "[0-9]",
			'a': "[A-Za-z]",
			'*': "[A-Za-z0-9]"
		}
	};

	$.fn.extend({
		
		caret: function(begin, end) {
			if (this.length == 0) return;
			if (typeof begin == 'number') {
				end = (typeof end == 'number') ? end : begin;
				return this.each(function() {
					if (this.setSelectionRange) {
						this.focus();
						this.setSelectionRange(begin, end);
					} else if (this.createTextRange) {
						var range = this.createTextRange();
						range.collapse(true);
						range.moveEnd('character', end);
						range.moveStart('character', begin);
						range.select();
					}
				});
			} else {
				if (this[0].setSelectionRange) {
					begin = this[0].selectionStart;
					end = this[0].selectionEnd;
				} else if (document.selection && document.selection.createRange) {
					var range = document.selection.createRange();
					begin = 0 - range.duplicate().moveStart('character', -100000);
					end = begin + range.text.length;
				}
				return { begin: begin, end: end };
			}
		},
		unmask: function() { return this.trigger("unmask"); },
		mask: function(mask, settings) {
			if (!mask && this.length > 0) {
				var input = $(this[0]);
				var tests = input.data("tests");
				return $.map(input.data("buffer"), function(c, i) {
					return tests[i] ? c : null;
				}).join('');
			}
			settings = $.extend({
				placeholder: "_",
				completed: null
			}, settings);

			var defs = $.mask.definitions;
			var tests = [];
			var partialPosition = mask.length;
			var firstNonMaskPos = null;
			var len = mask.length;

			$.each(mask.split(""), function(i, c) {
				if (c == '?') {
					len--;
					partialPosition = i;
				} else if (defs[c]) {
					tests.push(new RegExp(defs[c]));
					if(firstNonMaskPos==null)
						firstNonMaskPos =  tests.length - 1;
				} else {
					tests.push(null);
				}
			});

			return this.each(function() {
				var input = $(this);
				var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
				var ignore = false;  			
				var focusText = input.val();

				input.data("buffer", buffer).data("tests", tests);

				function seekNext(pos) {
					while (++pos <= len && !tests[pos]);
					return pos;
				};

				function shiftL(pos) {
					while (!tests[pos] && --pos >= 0);
					for (var i = pos; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							var j = seekNext(i);
							if (j < len && tests[i].test(buffer[j])) {
								buffer[i] = buffer[j];
							} else
								break;
						}
					}
					writeBuffer();
					input.caret(Math.max(firstNonMaskPos, pos));
				};

				function shiftR(pos) {
					for (var i = pos, c = settings.placeholder; i < len; i++) {
						if (tests[i]) {
							var j = seekNext(i);
							var t = buffer[i];
							buffer[i] = c;
							if (j < len && tests[j].test(t))
								c = t;
							else
								break;
						}
					}
				};

				function keydownEvent(e) {
					var pos = $(this).caret();
					var k = e.keyCode;
					ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

					
					if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46))
						clearBuffer(pos.begin, pos.end);

					
					if (k == 8 || k == 46 || (iPhone && k == 127)) {
						shiftL(pos.begin + (k == 46 ? 0 : -1));
						return false;
					} else if (k == 27) {
						input.val(focusText);
						input.caret(0, checkVal());
						return false;
					}
				};

				function keypressEvent(e) {
					if (ignore) {
						ignore = false;
						
						return (e.keyCode == 8) ? false : null;
					}
					e = e || window.event;
					var k = e.charCode || e.keyCode || e.which;
					var pos = $(this).caret();

					if (e.ctrlKey || e.altKey || e.metaKey) {
						return true;
					} else if ((k >= 32 && k <= 125) || k > 186) {
						var p = seekNext(pos.begin - 1);
						if (p < len) {
							var c = String.fromCharCode(k);
							if (tests[p].test(c)) {
								shiftR(p);
								buffer[p] = c;
								writeBuffer();
								var next = seekNext(p);
								$(this).caret(next);
								if (settings.completed && next == len)
									settings.completed.call(input);
							}
						}
					}
					return false;
				};

				function clearBuffer(start, end) {
					for (var i = start; i < end && i < len; i++) {
						if (tests[i])
							buffer[i] = settings.placeholder;
					}
				};

				function writeBuffer() { return input.val(buffer.join('')).val(); };

				function checkVal(allow) {
					
					var test = input.val();
					var lastMatch = -1;
					for (var i = 0, pos = 0; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							while (pos++ < test.length) {
								var c = test.charAt(pos - 1);
								if (tests[i].test(c)) {
									buffer[i] = c;
									lastMatch = i;
									break;
								}
							}
							if (pos > test.length)
								break;
						} else if (buffer[i] == test[pos] && i!=partialPosition) {
							pos++;
							lastMatch = i;
						} 
					}
					if (!allow && lastMatch + 1 < partialPosition) {
						input.val("");
						clearBuffer(0, len);
					} else if (allow || lastMatch + 1 >= partialPosition) {
						writeBuffer();
						if (!allow) input.val(input.val().substring(0, lastMatch + 1));
					}
					return (partialPosition ? i : firstNonMaskPos);
				};

				if (!input.attr("readonly"))
					input
					.one("unmask", function() {
						input
							.unbind(".mask")
							.removeData("buffer")
							.removeData("tests");
					})
					.bind("focus.mask", function() {
						focusText = input.val();
						var pos = checkVal();
						writeBuffer();
						setTimeout(function() {
							if (pos == mask.length)
								input.caret(0, pos);
							else
								input.caret(pos);
						}, 0);
					})
					.bind("blur.mask", function() {
						checkVal();
						if (input.val() != focusText)
							input.change();
					})
					.bind("keydown.mask", keydownEvent)
					.bind("keypress.mask", keypressEvent)
					.bind(pasteEventName, function() {
						setTimeout(function() { input.caret(checkVal(true)); }, 0);
					});

				checkVal(); 
			});
		}
	});
})(jQuery);jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){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 = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		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();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	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;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};
/**
* jAlert v.1.0.0
* Copyright (c) 2008 Julian Castaneda
* http://www.smooka.com/blog/
* Requires: jQuery 1.2+
*/

(function($) {
    $.fn.jAlert = function (msg, type, uid, alert_box_width, yoffset)
    {
        var tmpobj = this;
		var overlay = 0;
				
		if (uid == undefined)
		{	//generate an unique ID
			var d = new Date();
			var uid = d.getMonth()+""+d.getDate()+""+d.getHours()+""+d.getMinutes()+""+d.getSeconds();
		}

		if ($('#jalert_box_cont_'+uid).css('display') == 'block')
		{
			return;
		}
		
        if (!type) {
            // set type to a default warning
            type = 'warning';
        }

        if (!alert_box_width) {
            //set default width of alert box
            alert_box_width = 350;
        }

        if (!yoffset) {
            //set default y offset of alert box
            yoffset = 0;
        }
		
		if (overlay==1) {
			$('<div id="jalert_overlay_'+uid+'"></div>').prependTo('body');
				var overlayWidth = $(window).width();
				var overlayHeight = $(document).height();
				var winHeight =  $(window).height();
				$("#jalert_overlay_"+uid).css({
											  top: 0, 
											  left: 0, 
											  width: overlayWidth, 
											  height: winHeight, 
											  position: "fixed",
											  display: "block",
											  background: "#000",
											  zIndex: "1000"
										  });
				$("#jalert_overlay_"+uid).css("opacity", 0.7);
		}
		

        //create a prepend the alert box to the container
        $('<div class="msg-box-cont msg-'+type+'" id="jalert_box_cont_'+uid+'"><table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td><div class="msg-text"><div class="msg-icon msg-icon-'+type+'"></div>'+msg+'</div></td><td width="21" valign="top"><div class="msg-btn close-'+type+'"></div></td></tr></table></div>').appendTo('body');

        $("#jalert_box_cont_"+uid).width(alert_box_width);

		alignCenter();
		
        //get the y (top) position of the container
		//var top=this.y() + yoffset;

        //$("#jalert_box_cont_"+uid).css("top",top+"px");
		
		$("#jalert_box_cont_"+uid).fadeIn(500);
        $("#jalert_box_cont_"+uid).fadeOut(5000);
 
		if(overlay==1){
			$(document).click(function() {
				$("#jalert_overlay_"+uid).fadeOut(100);
				$("#jalert_overlay_"+uid).remove();
			});
		}
	
		$('.msg-btn').click(function() {
			if (overlay==1) {
				$("#jalert_overlay_"+uid).fadeOut(100);
				$("#jalert_overlay_"+uid).remove();
			}
			$("#jalert_box_cont_"+uid).fadeOut(100);
			$("#jalert_box_cont_"+uid).empty();
			$("#jalert_box_cont_"+uid).remove();
			$(window).unbind("resize");
		});
		
		
        //always center
        $(window).resize(function() {alignCenter();});
				
		function alignCenter() {
			var ibox = $("#jalert_box_cont_"+uid);
			var alert_box_width = ibox.width();
			var alert_box_height = ibox.height();
			yOffset = 0;
			if(ibox.css('position')=='absolute'){
				yOffset = document.body.scrollTop;
			}
            /*
			//get the width of the container
            var container_width = tmpobj.innerWidth();
            // get the x position of the container
            var container_left = tmpobj.x();
            //get the center position of the alert box within the container
            var actual_left = ((container_width-alert_box_width)/2)+container_left;
			*/
            //get the y (top) position of the container
            $("#jalert_box_cont_"+uid).css({"margin-left" : "-"+(alert_box_width/2)+"px", 'margin-top' : (yOffset-(alert_box_height/2))+'px'});
			
		}

    };

    //vertical positioning
    $.fn.y = function(n) {
        var result = null;
        this.each(function() {
            var o = this;
            if (n === undefined) {
                var y = 0;
                if (o.offsetParent) {
                    while (o.offsetParent) {
                        y += o.offsetTop;
                        o = o.offsetParent;
                    }
                }
                if (result === null) {
                    result = y;
                } else {
                    result = Math.min(result, y);
                }
            } else {
                o.style.top = n + 'px';
            }
        });
        return result;
    };
    
    //horizontal positioning
    $.fn.x = function(n) {
        var result = null;
        this.each(function() {
            var o = this;
            if (n === undefined) {
                var x = 0;
                if (o.offsetParent) {
                    while (o.offsetParent) {
                        x += o.offsetLeft;
                        o = o.offsetParent;
                    }
                }
                if (result === null) {
                    result = x;
                } else {
                    result = Math.min(result, x);
                }
            } else {
                o.style.left = n + 'px';
            }
        });
        return result;
    };
})(jQuery);/*
 * Another In Place Editor - a jQuery edit in place plugin
 *
 * Copyright (c) 2009 Dave Hauenstein
 *
 * License:
 * This source file is subject to the BSD license bundled with this package.
 * Available online: {@link http://www.opensource.org/licenses/bsd-license.php}
 * If you did not receive a copy of the license, and are unable to obtain it,
 * email davehauenstein@gmail.com,
 * and I will send you a copy.
 *
 * Project home:
 * http://code.google.com/p/jquery-in-place-editor/
 *
 */

/*
 * Version 1.0.1
 *
 * bg_out (string) default: transparent hex code of background color on restore from hover
 * bg_over (string) default: #ffc hex code of background color on hover
 * callback (function) default: null function to be called when editing is complete; cancels ajax submission to the url param
 * cancel_button (string) default: <input type=”submit” class=”inplace_cancel” value=”Cancel”/> image button tag to use as “Cancel” button
 * default_text (string) default: “(Click here to add text)” text to show up if the element that has this functionality is empty
 * element_id (string) default: element_id name of parameter holding element_id
 * error (function) this function gets called if server responds with an error
 * field_type (string) “text”, “textarea”, or “select”; default: “text” The type of form field that will appear on instantiation
 * on_blur (string) “save” or null; default: “save” what to do on blur; will be overridden if $param show_buttons is true
 * original_html (string) default: original_html name of parameter holding original_html
 * params (string) example: first_name=dave&last_name=hauenstein paramters sent via the post request to the server
 * save_button (string) default: <input type=”submit” class=”inplace_save” value=”Save”/> image button tag to use as “Save” button
 * saving_image (string) default: uses saving text specify an image location instead of text while server is saving
 * saving_text (string) default: “Saving…” text to be used when server is saving information
 * select_options (string) comma delimited list of options if field_type is set to select
 * select_text (string)default text to show up in select box
 * show_buttons (boolean) default: false will show the buttons: cancel or save; will automatically cancel out the onBlur functionality
 * success (function) default: null this function gets called if server responds with a success
 * textarea_cols (integer) default: 25 set cols attribute of textarea, if field_type is set to textarea
 * textarea_rows (integer) default: 10 set rows attribute of textarea, if field_type is set to textarea
 * update_value (string) default: update_value name of parameter holding update_value
 * url (string) POST URL to send edited content
 * value_required (string) default: false if set to true, the element will not be saved unless a value is entered
 *
 */

jQuery.fn.editInPlace = function(options) {

	/* DEFINE THE DEFAULT SETTINGS, SWITCH THEM WITH THE OPTIONS USER PROVIDES */
	var settings = {
		url:				"",
		params:				"",
		field_type:			"text",
		select_options:		"",
		textarea_cols:		"25",
		textarea_rows:		"10",
		bg_over:			"#ffc",
		bg_out:				"transparent",
		saving_text:		"Zapisuję...",
		saving_image:		"",
		default_text:		"(kliknij, aby włączyć edycję)",
		select_text:		"Wybierz",
		value_required:		null,
		element_id:			"element_id",
		update_value:		"update_value",
		original_html:		"original_html",
		save_button:		'<button class="inplace_save">Zapisz</button>',
		cancel_button:		'<button class="inplace_cancel">Anuluj</button>',
		show_buttons:		false,
		on_blur:			"save",
		callback:			null,
		success:			null,
		error:				function(request){
                                alert("Błąd przy zapisywaniu: " + request.responseText || 'Nieokreślony błąd');
                            }
	};

	if(options) {
		jQuery.extend(settings, options);
	}

	/* preload the loading icon if it exists */
	if(settings.saving_image != ""){
		var loading_image = new Image();
		loading_image.src = settings.saving_image;
	}

	/* THIS FUNCTION WILL TRIM WHITESPACE FROM BEFORE/AFTER A STRING */
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '')
							 .replace(/\s+$/, '');
	};

	/* THIS FUNCTION WILL ESCAPE ANY HTML ENTITIES SO "Quoted Values" work */
	String.prototype.escape_html = function() {
		return this.replace(/&/g, "&amp;")
							 .replace(/</g, "&lt;")
							 .replace(/>/g, "&gt;")
							 .replace(/"/g, "&quot;");
  };

	/* CREATE THE INPLACE EDITOR */
	return this.each(function(){

		if(jQuery(this).html() == "") jQuery(this).html(settings.default_text);

		var editing = false;

		//save the original element - for change of scope
		var original_element = jQuery(this);

		var click_count = 0;

		jQuery(this)

		.mouseover(function(){
			jQuery(this).css("background", settings.bg_over);
		})

		.mouseout(function(){
			jQuery(this).css("background", settings.bg_out);
		})

		.click(function(){
			click_count++;

			if(!editing)
			{
				editing = true;

				//save original text - for cancellation functionality
				var original_html = jQuery(this).html();
				var buttons_code  = (settings.show_buttons) ? settings.save_button + ' ' + settings.cancel_button : '';

				//if html is our default text, clear it out to prevent saving accidentally
				if (original_html == settings.default_text) jQuery(this).html('');

				if (settings.field_type == "textarea")
				{
					var use_field_type = '<textarea name="inplace_value" class="inplace_field" rows="' + settings.textarea_rows + '" cols="' + settings.textarea_cols + '">' + jQuery(this).text().trim().escape_html() + '</textarea>';
				}
				else if(settings.field_type == "text")
				{
					var use_field_type = '<input type="text" name="inplace_value" class="inplace_field" value="' +
											jQuery(this).text().trim().escape_html() + '" />';
				}
				else if(settings.field_type == "select")
				{
					var optionsArray = settings.select_options.split(',');
					var use_field_type = '<select name="inplace_value" class="inplace_field"><option value="">' + settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';
				}

				/* insert the new in place form after the element they click, then empty out the original element */
				jQuery(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' + use_field_type + ' ' + buttons_code + '</form>');

			}/* END- if(!editing) -END */

			if(click_count == 1)
			{
				function cancelAction()
				{
					editing = false;
					click_count = 0;

					/* put the original background color in */
					original_element.css("background", settings.bg_out);

					/* put back the original text */
					original_element.html(original_html);

					return false;
				}

				function saveAction()
				{
					/* put the original background color in */
					original_element.css("background", settings.bg_out);

                    var this_elem = jQuery(this);

					var new_html = (this_elem.is('form')) ? this_elem.children(0).val() : this_elem.parent().children(0).val();

					/* set saving message */
					if(settings.saving_image != ""){
						var saving_message = '<img src="' + settings.saving_image + '" alt="Saving..." />';
					} else {
						var saving_message = settings.saving_text;
					}

					/* place the saving text/image in the original element */
					original_element.html(saving_message);

					if(settings.params != ""){
						settings.params = "&" + settings.params;
					}

					if(settings.callback) {
						html = settings.callback(original_element.attr("id"), new_html, original_html, settings.params);
						editing = false;
						click_count = 0;
						if (html) {
							/* put the newly updated info into the original element */
							original_element.html(html || new_html);
						} else {
							/* failure; put original back */
							alert("Failed to save value: " + new_html);
							original_element.html(original_html);
						}
					} else if (settings.value_required && (new_html == "" || new_html == undefined)) {
						editing = false;
						click_count = 0;
						original_element.html(original_html);
						alert("Error: You must enter a value to save this field");
					} else {
						jQuery.ajax({
							url: settings.url,
							type: "POST",
							data: settings.update_value + '=' + new_html + '&' + settings.element_id + '=' + original_element.attr("id") + settings.params + '&' + settings.original_html + '=' + original_html,
							dataType: "html",
							complete: function(request){
								editing = false;
								click_count = 0;
							},
							success: function(html){
								/* if the text returned by the server is empty, */
   								/* put a marker as text in the original element */
								var new_text = html || settings.default_text;

								/* put the newly updated info into the original element */
								original_element.html(new_text);
								if (settings.success) settings.success(html, original_element);
							},
							error: function(request) {
								original_element.html(original_html);
								if (settings.error) settings.error(request, original_element);
							}
						});
					}

					return false;
				}

				/* set the focus to the new input element */
				original_element.children("form").children(".inplace_field").focus().select();

				/* CLICK CANCEL BUTTON functionality */
				original_element.children("form").children(".inplace_cancel").click(cancelAction);

				/* CLICK SAVE BUTTON functionality */
				original_element.children("form").children(".inplace_save").click(saveAction);

                /* if cancel/save buttons should be shown, cancel blur functionality */
                if(!settings.show_buttons){
                    /* if on_blur is set to save, set the save funcion */
    				if(settings.on_blur == "save")
    					original_element.children("form").children(".inplace_field").blur(saveAction);
    				/* if on_blur is set to cancel, set the cancel funcion */
    				else
    					original_element.children("form").children(".inplace_field").blur(cancelAction);
                }

				/* hit esc key */
				$(document).keyup(function(event){
				    if (event.keyCode == 27) {
						cancelAction();
				    }
				});

                original_element.children("form").submit(saveAction);

			}/* END- if(click_count == 1) -END */
		});
	});
};;(function($) {
$.ui = {
plugin: {
add: function(module, option, set) {
var proto = $.ui[module].prototype;
for(var i in set) {
proto.plugins[i] = proto.plugins[i] || [];
proto.plugins[i].push([option, set[i]]);
}
},
call: function(instance, name, args) {
var set = instance.plugins[name];
if(!set) { return; }for (var i = 0; i < set.length; i++) {
if (instance.options[set[i][0]]) {
set[i][1].apply(instance.element, args);
}
}
}
},
cssCache: {},
css: function(name) {
if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');
$.ui.cssCache[name] = !!(
(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || 
!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
);
try { $('body').get(0).removeChild(tmp.get(0));} catch(e){}
return $.ui.cssCache[name];
},
disableSelection: function(el) {
$(el).attr('unselectable', 'on').css('MozUserSelect', 'none');
},
enableSelection: function(el) {
$(el).attr('unselectable', 'off').css('MozUserSelect', '');
},
hasScroll: function(e, a) {
var scroll = /top/.test(a||"top") ? 'scrollTop' : 'scrollLeft', has = false;
if (e[scroll] > 0) return true; e[scroll] = 1;
has = e[scroll] > 0 ? true : false; e[scroll] = 0;
return has;
}
};
var _remove = $.fn.remove;
$.fn.remove = function() {
$("*", this).add(this).triggerHandler("remove");
return _remove.apply(this, arguments );
};
function getter(namespace, plugin, method) {
var methods = $[namespace][plugin].getter || [];
methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
return ($.inArray(method, methods) != -1);
}$.widget = function(name, prototype) {
var namespace = name.split(".")[0];
name = name.split(".")[1];
$.fn[name] = function(options) {
var isMethodCall = (typeof options == 'string'),
args = Array.prototype.slice.call(arguments, 1);if (isMethodCall && getter(namespace, name, options)) {
var instance = $.data(this[0], name);
return (instance ? instance[options].apply(instance, args)
: undefined);
}return this.each(function() {
var instance = $.data(this, name);
if (isMethodCall && instance && $.isFunction(instance[options])) {
instance[options].apply(instance, args);
} else if (!isMethodCall) {
$.data(this, name, new $[namespace][name](this, options));
}
});
};
$[namespace][name] = function(element, options) {
var self = this;this.widgetName = name;
this.widgetBaseClass = namespace + '-' + name;this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, options);
this.element = $(element)
.bind('setData.' + name, function(e, key, value) {
return self.setData(key, value);
})
.bind('getData.' + name, function(e, key) {
return self.getData(key);
})
.bind('remove', function() {
return self.destroy();
});
this.init();
};
$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};$.widget.prototype = {
init: function() {},
destroy: function() {
this.element.removeData(this.widgetName);
},getData: function(key) {
return this.options[key];
},
setData: function(key, value) {
this.options[key] = value;if (key == 'disabled') {
this.element[value ? 'addClass' : 'removeClass'](
this.widgetBaseClass + '-disabled');
}
},enable: function() {
this.setData('disabled', false);
},
disable: function() {
this.setData('disabled', true);
}
};$.widget.defaults = {
disabled: false
};$.ui.mouse = {
mouseInit: function() {
var self = this;this.element.bind('mousedown.'+this.widgetName, function(e) {
return self.mouseDown(e);
});
if ($.browser.msie) {
this._mouseUnselectable = this.element.attr('unselectable');
this.element.attr('unselectable', 'on');
}this.started = false;
},mouseDestroy: function() {
this.element.unbind('.'+this.widgetName);
($.browser.msie
&& this.element.attr('unselectable', this._mouseUnselectable));
},mouseDown: function(e) {(this._mouseStarted && this.mouseUp(e));this._mouseDownEvent = e;var self = this,
btnIsLeft = (e.which == 1),
elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this.mouseCapture(e)) {
return true;
}this._mouseDelayMet = !this.options.delay;
if (!this._mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
self._mouseDelayMet = true;
}, this.options.delay);
}if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
this._mouseStarted = (this.mouseStart(e) !== false);
if (!this._mouseStarted) {
e.preventDefault();
return true;
}
}
this._mouseMoveDelegate = function(e) {
return self.mouseMove(e);
};
this._mouseUpDelegate = function(e) {
return self.mouseUp(e);
};
$(document)
.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);return false;
},mouseMove: function(e) {if ($.browser.msie && !e.button) {
return this.mouseUp(e);
}if (this._mouseStarted) {
this.mouseDrag(e);
return false;
}if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
this._mouseStarted =
(this.mouseStart(this._mouseDownEvent, e) !== false);
(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
}return !this._mouseStarted;
},mouseUp: function(e) {
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);if (this._mouseStarted) {
this._mouseStarted = false;
this.mouseStop(e);
}return false;
},mouseDistanceMet: function(e) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - e.pageX),
Math.abs(this._mouseDownEvent.pageY - e.pageY)
) >= this.options.distance
);
},mouseDelayMet: function(e) {
return this._mouseDelayMet;
},
mouseStart: function(e) {},
mouseDrag: function(e) {},
mouseStop: function(e) {},
mouseCapture: function(e) { return true; }
};$.ui.mouse.defaults = {
cancel: null,
distance: 1,
delay: 0
};})(jQuery);
(function($) {

$.widget("ui.tabs", {
init: function() {
this.options.event += '.tabs'; this.tabify(true);
},
setData: function(key, value) {
if ((/^selected/).test(key))
this.select(value);
else {
this.options[key] = value;
this.tabify();
}
},
length: function() {
return this.$tabs.length;
},
tabId: function(a) {
return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '')
|| this.options.idPrefix + $.data(a);
},
ui: function(tab, panel) {
return {
options: this.options,
tab: tab,
panel: panel,
index: this.$tabs.index(tab)
};
},
tabify: function(init) {

this.$lis = $('li:has(a[href])', this.element);
this.$tabs = this.$lis.map(function() { return $('a', this)[0]; });
this.$panels = $([]);

var self = this, o = this.options;

this.$tabs.each(function(i, a) {

if (a.hash && a.hash.replace('#', '')) 
self.$panels = self.$panels.add(a.hash);

else if ($(a).attr('href') != '#') { 
$.data(a, 'href.tabs', a.href); 
$.data(a, 'load.tabs', a.href); 
var id = self.tabId(a);
a.href = '#' + id;
var $panel = $('#' + id);
if (!$panel.length) {
$panel = $(o.panelTemplate).attr('id', id).addClass(o.panelClass)
.insertAfter( self.$panels[i - 1] || self.element );
$panel.data('destroy.tabs', true);
}
self.$panels = self.$panels.add( $panel );
}

else
o.disabled.push(i + 1);
});

if (init) {this.element.addClass(o.navClass);
this.$panels.each(function() {
var $this = $(this);
$this.addClass(o.panelClass);
});
if (o.selected === undefined) {
if (location.hash) {
this.$tabs.each(function(i, a) {
if (a.hash == location.hash) {
o.selected = i;

if ($.browser.msie || $.browser.opera) { 
var $toShow = $(location.hash), toShowId = $toShow.attr('id');
$toShow.attr('id', '');
setTimeout(function() {
$toShow.attr('id', toShowId); 
}, 500);
}
scrollTo(0, 0);
return false; 
}
});
}
else if (o.cookie) {
var index = parseInt($.cookie('ui-tabs' + $.data(self.element)),10);
if (index && self.$tabs[index])
o.selected = index;
}
else if (self.$lis.filter('.' + o.selectedClass).length)
o.selected = self.$lis.index( self.$lis.filter('.' + o.selectedClass)[0] );
}
o.selected = o.selected === null || o.selected !== undefined ? o.selected : 0; 

o.disabled = $.unique(o.disabled.concat(
$.map(this.$lis.filter('.' + o.disabledClass),
function(n, i) { return self.$lis.index(n); } )
)).sort();
if ($.inArray(o.selected, o.disabled) != -1)
o.disabled.splice($.inArray(o.selected, o.disabled), 1);this.$panels.addClass(o.hideClass);
this.$lis.removeClass(o.selectedClass);
if (o.selected !== null) {
this.$panels.eq(o.selected).show().removeClass(o.hideClass); 
this.$lis.eq(o.selected).addClass(o.selectedClass);var onShow = function() {
$(self.element).triggerHandler('tabsshow',
[self.fakeEvent('tabsshow'), self.ui(self.$tabs[o.selected], self.$panels[o.selected])], o.show);
}; if ($.data(this.$tabs[o.selected], 'load.tabs'))
this.load(o.selected, onShow);

else
onShow();

}$(window).bind('unload', function() {
self.$tabs.unbind('.tabs');
self.$lis = self.$tabs = self.$panels = null;
});

}for (var i = 0, li; li = this.$lis[i]; i++)
$(li)[$.inArray(i, o.disabled) != -1 && !$(li).hasClass(o.selectedClass) ? 'addClass' : 'removeClass'](o.disabledClass);if (o.cache === false)
this.$tabs.removeData('cache.tabs');var hideFx, showFx, baseFx = { 'min-width': 0, duration: 1 }, baseDuration = 'normal';
if (o.fx && o.fx.constructor == Array)
hideFx = o.fx[0] || baseFx, showFx = o.fx[1] || baseFx;
else
hideFx = showFx = o.fx || baseFx;var resetCSS = { display: '', overflow: '', height: '' };
if (!$.browser.msie) 
resetCSS.opacity = '';
function hideTab(clicked, $hide, $show) {
$hide.animate(hideFx, hideFx.duration || baseDuration, function() { 
$hide.addClass(o.hideClass).css(resetCSS); 
if ($.browser.msie && hideFx.opacity)
$hide[0].style.filter = '';
if ($show)
showTab(clicked, $show, $hide);
});
}
function showTab(clicked, $show, $hide) {
if (showFx === baseFx)
$show.css('display', 'block'); 
$show.animate(showFx, showFx.duration || baseDuration, function() {
$show.removeClass(o.hideClass).css(resetCSS); 
if ($.browser.msie && showFx.opacity)
$show[0].style.filter = '';$(self.element).triggerHandler('tabsshow',
[self.fakeEvent('tabsshow'), self.ui(clicked, $show[0])], o.show);

});
}function switchTab(clicked, $li, $hide, $show) {
$li.addClass(o.selectedClass)
.siblings().removeClass(o.selectedClass);
hideTab(clicked, $hide, $show);
}this.$tabs.unbind('.tabs').bind(o.event, function() {var $li = $(this).parents('li:eq(0)'),
$hide = self.$panels.filter(':visible'),
$show = $(this.hash);if (($li.hasClass(o.selectedClass) && !o.unselect)
|| $li.hasClass(o.disabledClass) 
|| $(this).hasClass(o.loadingClass)
|| $(self.element).triggerHandler('tabsselect', [self.fakeEvent('tabsselect'), self.ui(this, $show[0])], o.select) === false
) {
this.blur();
return false;
}

self.options.selected = self.$tabs.index(this);if (o.unselect) {
if ($li.hasClass(o.selectedClass)) {
self.options.selected = null;
$li.removeClass(o.selectedClass);
self.$panels.stop();
hideTab(this, $hide);
this.blur();
return false;
} else if (!$hide.length) {
self.$panels.stop();
var a = this;
self.load(self.$tabs.index(this), function() {
$li.addClass(o.selectedClass).addClass(o.unselectClass);
showTab(a, $show);
});
this.blur();
return false;
}
}

if (o.cookie)
$.cookie('ui-tabs' + $.data(self.element), self.options.selected, o.cookie);self.$panels.stop();if ($show.length) {
var a = this;
self.load(self.$tabs.index(this), $hide.length ? 
function() {
switchTab(a, $li, $hide, $show);
} :
function() {
$li.addClass(o.selectedClass);
showTab(a, $show);
}
);

} else
throw 'jQuery UI Tabs: Mismatching fragment identifier.';

if ($.browser.msie)
this.blur();return false;

});if (!(/^click/).test(o.event))
this.$tabs.bind('click.tabs', function() { return false; });

},
add: function(url, label, index) {
if (index == undefined) 
index = this.$tabs.length; 

var o = this.options;
var $li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label));
$li.data('destroy.tabs', true);

var id = url.indexOf('#') == 0 ? url.replace('#', '') : this.tabId( $('a:first-child', $li)[0] );var $panel = $('#' + id);
if (!$panel.length) {
$panel = $(o.panelTemplate).attr('id', id)
.addClass(o.hideClass)
.data('destroy.tabs', true);
}
$panel.addClass(o.panelClass);
if (index >= this.$lis.length) {
$li.appendTo(this.element);
$panel.appendTo(this.element[0].parentNode);
} else {
$li.insertBefore(this.$lis[index]);
$panel.insertBefore(this.$panels[index]);
}

o.disabled = $.map(o.disabled,
function(n, i) { return n >= index ? ++n : n });

this.tabify();

if (this.$tabs.length == 1) {
$li.addClass(o.selectedClass);
$panel.removeClass(o.hideClass);
var href = $.data(this.$tabs[0], 'load.tabs');
if (href)
this.load(index, href);
}this.element.triggerHandler('tabsadd',
[this.fakeEvent('tabsadd'), this.ui(this.$tabs[index], this.$panels[index])], o.add
);
},
remove: function(index) {
var o = this.options, $li = this.$lis.eq(index).remove(),
$panel = this.$panels.eq(index).remove();
if ($li.hasClass(o.selectedClass) && this.$tabs.length > 1)
this.select(index + (index + 1 < this.$tabs.length ? 1 : -1));

o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }),
function(n, i) { return n >= index ? --n : n });

this.tabify();this.element.triggerHandler('tabsremove',
[this.fakeEvent('tabsremove'), this.ui($li.find('a')[0], $panel[0])], o.remove
);
},
enable: function(index) {
var o = this.options;
if ($.inArray(index, o.disabled) == -1)
return;

var $li = this.$lis.eq(index).removeClass(o.disabledClass);
if ($.browser.safari) { 
$li.css('display', 'inline-block');
setTimeout(function() {
$li.css('display', 'block');
}, 0);
}

o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });this.element.triggerHandler('tabsenable',
[this.fakeEvent('tabsenable'), this.ui(this.$tabs[index], this.$panels[index])], o.enable
);

},
disable: function(index) {
var self = this, o = this.options;
if (index != o.selected) { 
this.$lis.eq(index).addClass(o.disabledClass);

o.disabled.push(index);
o.disabled.sort();this.element.triggerHandler('tabsdisable',
[this.fakeEvent('tabsdisable'), this.ui(this.$tabs[index], this.$panels[index])], o.disable
);
}
},
select: function(index) {
if (typeof index == 'string')
index = this.$tabs.index( this.$tabs.filter('[href$=' + index + ']')[0] );
this.$tabs.eq(index).trigger(this.options.event);
},
load: function(index, callback) { 

var self = this, o = this.options, $a = this.$tabs.eq(index), a = $a[0],
bypassCache = callback == undefined || callback === false, url = $a.data('load.tabs');

callback = callback || function() {};if (!url || !bypassCache && $.data(a, 'cache.tabs')) {
callback();
return;
}
var inner = function(parent) {
var $parent = $(parent), $inner = $parent.find('*:last');
return $inner.length && $inner.is(':not(img)') && $inner || $parent;
};
var cleanup = function() {
self.$tabs.filter('.' + o.loadingClass).removeClass(o.loadingClass)
.each(function() {
if (o.spinner)
inner(this).parent().html(inner(this).data('label.tabs'));
});
self.xhr = null;
};

if (o.spinner) {
var label = inner(a).html();
inner(a).wrapInner('<em></em>')
.find('em').data('label.tabs', label).html(o.spinner);
}

var ajaxOptions = $.extend({}, o.ajaxOptions, {
url: url,
success: function(r, s) {
$(a.hash).html(r);
cleanup();

if (o.cache)
$.data(a, 'cache.tabs', true); $(self.element).triggerHandler('tabsload',
[self.fakeEvent('tabsload'), self.ui(self.$tabs[index], self.$panels[index])], o.load
);
o.ajaxOptions.success && o.ajaxOptions.success(r, s);

callback();
}
});
if (this.xhr) {

this.xhr.abort();
cleanup();
}
$a.addClass(o.loadingClass);
setTimeout(function() { 
self.xhr = $.ajax(ajaxOptions);
}, 0);

},
url: function(index, url) {
this.$tabs.eq(index).removeData('cache.tabs').data('load.tabs', url);
},
destroy: function() {
var o = this.options;
this.element.unbind('.tabs')
.removeClass(o.navClass).removeData('tabs');
this.$tabs.each(function() {
var href = $.data(this, 'href.tabs');
if (href)
this.href = href;
var $this = $(this).unbind('.tabs');
$.each(['href', 'load', 'cache'], function(i, prefix) {
$this.removeData(prefix + '.tabs');
});
});
this.$lis.add(this.$panels).each(function() {
if ($.data(this, 'destroy.tabs'))
$(this).remove();
else
$(this).removeClass([o.selectedClass, o.unselectClass,
o.disabledClass, o.panelClass, o.hideClass].join(' '));
});
},
fakeEvent: function(type) {
return $.event.fix({
type: type,
target: this.element[0]
});
}
});

$.ui.tabs.defaults = {

unselect: false,
event: 'click',
disabled: [],
cookie: null, 
spinner: 'Loading&#8230;',
cache: false,
idPrefix: 'ui-tabs-',
ajaxOptions: {},fx: null, tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>',
panelTemplate: '<div></div>',navClass: 'ui-tabs-nav',
selectedClass: 'ui-tabs-selected',
unselectClass: 'ui-tabs-unselect',
disabledClass: 'ui-tabs-disabled',
panelClass: 'ui-tabs-panel',
hideClass: 'ui-tabs-hide',
loadingClass: 'ui-tabs-loading'
};

$.ui.tabs.getter = "length";
$.extend($.ui.tabs.prototype, {
rotation: null,
rotate: function(ms, continuing) {

continuing = continuing || false;

var self = this, t = this.options.selected;

function start() {
self.rotation = setInterval(function() {
t = ++t < self.$tabs.length ? t : 0;
self.select(t);
}, ms); 
}

function stop(e) {
if (!e || e.clientX) { 
clearInterval(self.rotation);
}
}if (ms) {
start();
if (!continuing)
this.$tabs.bind(this.options.event, stop);
else
this.$tabs.bind(this.options.event, function() {
stop();
t = self.options.selected;
start();
});
}

else {
stop();
this.$tabs.unbind(this.options.event, stop);
}
}
});

})(jQuery);
function advAJAX(){var obj=new Object();obj.url=window.location.href;obj.method="GET";obj.parameters=new Object();obj.jsonParameters=new Object();obj.headers=new Object();obj.async=true;obj.mimeType="text/xml";obj.username=null;obj.password=null;obj.form=null;obj.disableForm=true;obj.unique=true;obj.uniqueParameter="_uniqid";obj.requestDone=false;obj.queryString="";obj.responseText=null;obj.responseXML=null;obj.status=null;obj.statusText=null;obj.aborted=false;obj.timeout=0;obj.retryCount=0;obj.retryDelay=1000;obj.tag=null;obj.group=null;obj.progressTimerInterval=50;obj.xmlHttpRequest=null;obj.onInitialization=null;obj.onFinalization=null;obj.onReadyStateChange=null;obj.onLoading=null;obj.onLoaded=null;obj.onInteractive=null;obj.onComplete=null;obj.onProgress=null;obj.onSuccess=null;obj.onFatalError=null;obj.onError=null;obj.onTimeout=null;obj.onRetryDelay=null;obj.onRetry=null;obj.onGroupEnter=null;obj.onGroupLeave=null;obj.createXmlHttpRequest=function(){if(typeof XMLHttpRequest!="undefined"){return new XMLHttpRequest();}var xhrVersion=["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];for(var i=0;i<xhrVersion.length;i++){try{var xhrObj=new ActiveXObject(xhrVersion[i]);return xhrObj;}catch(e){}}obj.raiseEvent("FatalError");return null;};obj._oldResponseLength=null;obj._progressTimer=null;obj._progressStarted=navigator.userAgent.indexOf("Opera")==-1;obj._onProgress=function(){if(typeof obj.onProgress=="function"&&typeof obj.xmlHttpRequest.getResponseHeader=="function"){var contentLength=obj.xmlHttpRequest.getResponseHeader("Content-length");if(contentLength!=null&&contentLength!=""){var responseLength=obj.xmlHttpRequest.responseText.length;if(responseLength!=obj._oldResponseLength){obj.raiseEvent("Progress",obj,responseLength,contentLength);obj._oldResponseLength=obj.xmlHttpRequest.responseText.length;}}}if(obj._progressStarted){return ;}obj._progressStarted=true;var _obj=this;this.__onProgress=function(){obj._onProgress();obj._progressTimer=window.setTimeout(_obj.__onProgress,obj.progressTimerInterval);};_obj.__onProgress();};obj._onInitializationHandled=false;obj._initObject=function(){if(obj.xmlHttpRequest!=null){delete obj.xmlHttpRequest.onreadystatechange;obj.xmlHttpRequest=null;}if((obj.xmlHttpRequest=obj.createXmlHttpRequest())==null){return null;}if(typeof obj.xmlHttpRequest.overrideMimeType!="undefined"){obj.xmlHttpRequest.overrideMimeType(obj.mimeType);}obj.xmlHttpRequest.onreadystatechange=function(){if(obj==null||obj.xmlHttpRequest==null){return ;}obj.raiseEvent("ReadyStateChange",obj,obj.xmlHttpRequest.readyState);obj._onProgress();switch(obj.xmlHttpRequest.readyState){case 1:obj._onLoading();break;case 2:obj._onLoaded();break;case 3:obj._onInteractive();break;case 4:obj._onComplete();break;}};obj._onLoadingHandled=obj._onLoadedHandled=obj._onInteractiveHandled=obj._onCompleteHandled=false;};obj._onLoading=function(){if(obj._onLoadingHandled){return ;}if(!obj._retry&&obj.group!=null){if(typeof advAJAX._groupData[obj.group]=="undefined"){advAJAX._groupData[obj.group]=0;}advAJAX._groupData[obj.group]++;if(typeof obj.onGroupEnter=="function"&&advAJAX._groupData[obj.group]==1){obj.onGroupEnter(obj);}}obj.raiseEvent("Loading",obj);obj._onLoadingHandled=true;};obj._onLoaded=function(){if(obj._onLoadedHandled){return ;}obj.raiseEvent("Loaded",obj);obj._onLoadedHandled=true;};obj._onInteractive=function(){if(obj._onInteractiveHandled){return ;}obj.raiseEvent("Interactive",obj);obj._onInteractiveHandled=true;if(!obj._progressStarted){obj._onProgress();}};obj._onComplete=function(){if(obj._onCompleteHandled||obj.aborted){return ;}if(obj._progressStarted){window.clearInterval(obj._progressTimer);obj._progressStarted=false;}obj.requestDone=true;with(obj.xmlHttpRequest){obj.responseText=responseText;obj.responseXML=responseXML;if(typeof status!="undefined"){obj.status=status;}if(typeof statusText!="undefined"){obj.statusText=statusText;}}obj.raiseEvent("Complete",obj);obj._onCompleteHandled=true;if(obj.status==200){obj.raiseEvent("Success",obj);}else{obj.raiseEvent("Error",obj);}delete obj.xmlHttpRequest.onreadystatechange;obj.xmlHttpRequest=null;if(obj.disableForm){obj.switchForm(true);}obj._groupLeave();obj.raiseEvent("Finalization",obj);};obj._groupLeave=function(){if(obj.group!=null){advAJAX._groupData[obj.group]--;if(advAJAX._groupData[obj.group]==0){obj.raiseEvent("GroupLeave",obj);}}};obj._retry=false;obj._retryNo=0;obj._onTimeout=function(){if(obj==null||obj.xmlHttpRequest==null||obj._onCompleteHandled){return ;}obj.aborted=true;obj.xmlHttpRequest.abort();obj.raiseEvent("Timeout",obj);obj._retry=true;if(obj._retryNo!=obj.retryCount){obj._initObject();if(obj.retryDelay>0){obj.raiseEvent("RetryDelay",obj);startTime=new Date().getTime();while(new Date().getTime()-startTime<obj.retryDelay){}}obj._retryNo++;obj.raiseEvent("Retry",obj,obj._retryNo);obj.run();}else{delete obj.xmlHttpRequest.onreadystatechange;obj.xmlHttpRequest=null;if(obj.disableForm){obj.switchForm(true);}obj._groupLeave();obj.raiseEvent("Finalization",obj);}};obj.run=function(){obj._initObject();if(obj.xmlHttpRequest==null){return false;}obj.aborted=false;if(!obj._onInitializationHandled){obj.raiseEvent("Initialization",obj);obj._onInitializationHandled=true;}if(obj.method=="GET"&&obj.unique){obj.parameters[encodeURIComponent(obj.uniqueParameter)]=new Date().getTime().toString().substr(5)+Math.floor(Math.random()*100).toString();}if(!obj._retry){for(var a in obj.parameters){if(obj.queryString.length>0){obj.queryString+="&";}if(typeof obj.parameters[a]!="object"){obj.queryString+=encodeURIComponent(a)+"="+encodeURIComponent(obj.parameters[a]);}else{for(var i=0;i<obj.parameters[a].length;i++){obj.queryString+=encodeURIComponent(a)+"="+encodeURIComponent(obj.parameters[a][i])+"&";}obj.queryString=obj.queryString.slice(0,-1);}}for(var a in obj.jsonParameters){var useJson=typeof [].toJSONString=="function";if(obj.queryString.length>0){obj.queryString+="&";}obj.queryString+=encodeURIComponent(a)+"=";if(useJson){obj.queryString+=encodeURIComponent(obj.jsonParameters[a].toJSONString());}else{obj.queryString+=encodeURIComponent(obj.jsonParameters[a]);}}if(obj.method=="GET"&&obj.queryString.length>0){obj.url+=(obj.url.indexOf("?")!=-1?"&":"?")+obj.queryString;}}if(obj.disableForm){obj.switchForm(false);}try{obj.xmlHttpRequest.open(obj.method,obj.url,obj.async,obj.username||"",obj.password||"");}catch(e){obj.raiseEvent("FatalError",obj,e);return ;}if(obj.timeout>0){setTimeout(obj._onTimeout,obj.timeout);}if(typeof obj.xmlHttpRequest.setRequestHeader!="undefined"){for(var a in obj.headers){obj.xmlHttpRequest.setRequestHeader(encodeURIComponent(a),encodeURIComponent(obj.headers[a]));}}if(obj.method=="POST"&&typeof obj.xmlHttpRequest.setRequestHeader!="undefined"){obj.xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");obj.xmlHttpRequest.send(obj.queryString);}else{if(obj.method=="GET"){obj.xmlHttpRequest.send("");}}};obj.handleArguments=function(args){if(typeof args.form=="object"&&args.form!=null){obj.form=args.form;obj.appendForm();}for(a in args){if(typeof obj[a]=="undefined"){obj.parameters[a]=args[a];}else{if(a!="parameters"&&a!="headers"){obj[a]=args[a];}else{for(b in args[a]){obj[a][b]=args[a][b];}}}}obj.method=obj.method.toUpperCase();};obj.switchForm=function(enable){if(typeof obj.form!="object"||obj.form==null){return ;}with(obj.form){for(var nr=0;nr<elements.length;nr++){if(!enable){if(elements[nr]["disabled"]){elements[nr]["_disabled"]=true;}else{elements[nr]["disabled"]="disabled";}}else{if(typeof elements[nr]["_disabled"]=="undefined"){elements[nr].removeAttribute("disabled");}}}}};obj.appendForm=function(){with(obj.form){obj.method=getAttribute("method").toUpperCase();obj.url=getAttribute("action");for(var nr=0;nr<elements.length;nr++){var e=elements[nr];if(e.disabled){continue;}switch(e.type){case"text":case"password":case"hidden":case"textarea":obj.addParameter(e.name,e.value);break;case"select-one":if(e.selectedIndex>=0){obj.addParameter(e.name,e.options[e.selectedIndex].value);}break;case"select-multiple":for(var nr2=0;nr2<e.options.length;nr2++){if(e.options[nr2].selected){obj.addParameter(e.name,e.options[nr2].value);}}break;case"checkbox":case"radio":if(e.checked){obj.addParameter(e.name,e.value);}break;}}}};obj.addParameter=function(name,value){if(typeof obj.parameters[name]=="undefined"){obj.parameters[name]=value;}else{if(typeof obj.parameters[name]!="object"){obj.parameters[name]=[obj.parameters[name],value];}else{obj.parameters[name][obj.parameters[name].length]=value;}}};obj.delParameter=function(name){delete obj.parameters[name];};obj.raiseEvent=function(name){var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}if(typeof obj["on"+name]=="function"){obj["on"+name].apply(null,args);}if(name=="FatalError"){obj.raiseEvent("Finalization",obj);}};if(typeof advAJAX._defaultParameters!="undefined"){obj.handleArguments(advAJAX._defaultParameters);}return obj;}advAJAX.get=function(A){return advAJAX.handleRequest("GET",A);};advAJAX.post=function(A){return advAJAX.handleRequest("POST",A);};advAJAX.head=function(A){return advAJAX.handleRequest("HEAD",A);};advAJAX.submit=function(C,A){if(typeof A=="undefined"||A==null){return -1;}if(typeof C!="object"||C==null){return -2;}var B=new advAJAX();A.form=C;B.handleArguments(A);return B.run();};advAJAX.assign=function(B,A){if(typeof A=="undefined"||A==null){return -1;}if(typeof B!="object"||B==null){return -2;}if(typeof B.onsubmit=="function"){B._onsubmit=B.onsubmit;}B.advajax_args=A;B.onsubmit=function(){if(typeof this["_onsubmit"]!="undefined"&&this["_onsubmit"]()===false){return false;}if(advAJAX.submit(this,this["advajax_args"])==false){return true;}return false;};return true;};advAJAX.download=function(B,A){if(typeof B=="string"){B=document.getElementById(B);}if(!B){return -1;}advAJAX.get({url:A,onSuccess:function(C){B.innerHTML=C.responseText;}});};advAJAX.scan=function(){var D=document.getElementsByTagName("a");for(var B=0;B<D.length;){if(D[B].getAttribute("rel")=="advancedajax"&&D[B].getAttribute("href")!==null){var A=D[B].getAttribute("href");var E=document.createElement("div");E.innerHTML=D[B].innerHTML;E.className=D[B].className;var C=D[B].parentNode;C.insertBefore(E,D[B]);C.removeChild(D[B]);advAJAX.download(E,A);}else{B++;}}};advAJAX.handleRequest=function(A,B){if(typeof B=="undefined"||B==null){return -1;}var C=new advAJAX();window.advajax_obj=C;C.method=A;C.handleArguments(B);return C.run();};advAJAX._defaultParameters=new Object();advAJAX.setDefaultParameters=function(A){advAJAX._defaultParameters=new Object();for(a in A){advAJAX._defaultParameters[a]=A[a];}};advAJAX._groupData=new Object();
Array.prototype.removeDuplicates=function(){for(var A=1;A<this.length;A++){if(this[A][0]==this[A-1][0]){this.splice(A,1)}}};Array.prototype.empty=function(){for(var A=0;A<=this.length;A++){this.shift()}};String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")};function LyteBox(){this.theme="grey";this.hideFlash=true;this.outerBorder=true;this.resizeSpeed=8;this.maxOpacity=80;this.navType=1;this.autoResize=true;this.doAnimations=true;this.borderSize=12;this.slideInterval=4000;this.showNavigation=true;this.showClose=true;this.showDetails=true;this.showPlayPause=true;this.autoEnd=true;this.pauseOnNextClick=false;this.pauseOnPrevClick=true;if(this.resizeSpeed>10){this.resizeSpeed=10}if(this.resizeSpeed<1){resizeSpeed=1}this.resizeDuration=(11-this.resizeSpeed)*0.15;this.resizeWTimerArray=new Array();this.resizeWTimerCount=0;this.resizeHTimerArray=new Array();this.resizeHTimerCount=0;this.showContentTimerArray=new Array();this.showContentTimerCount=0;this.overlayTimerArray=new Array();this.overlayTimerCount=0;this.imageTimerArray=new Array();this.imageTimerCount=0;this.timerIDArray=new Array();this.timerIDCount=0;this.slideshowIDArray=new Array();this.slideshowIDCount=0;this.imageArray=new Array();this.activeImage=null;this.slideArray=new Array();this.activeSlide=null;this.frameArray=new Array();this.activeFrame=null;this.checkFrame();this.isSlideshow=false;this.isLyteframe=false;}
if (!this.JSON) {
JSON = {};
}
(function () {

function f(n) {
return n < 10 ? '0' + n : n;
}

if (typeof Date.prototype.toJSON !== 'function') {

Date.prototype.toJSON = function (key) {

return this.getUTCFullYear()   + '-' +
 f(this.getUTCMonth() + 1) + '-' +
 f(this.getUTCDate())  + 'T' +
 f(this.getUTCHours()) + ':' +
 f(this.getUTCMinutes())   + ':' +
 f(this.getUTCSeconds())   + 'Z';
};

String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}

var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { 
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;function quote(string) {
escapeable.lastIndex = 0;
return escapeable.test(string) ?
'"' + string.replace(escapeable, function (a) {
var c = meta[a];
if (typeof c === 'string') {
return c;
}
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}function str(key, holder) {
var i,
k, 
v, 
length,
mind = gap,
partial,
value = holder[key];
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}

if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
switch (typeof value) {
case 'string':
return quote(value);

case 'number':
return isFinite(value) ? String(value) : 'null';

case 'boolean':
case 'null':

return String(value);
case 'object':

if (!value) {
return 'null';
}gap += indent;
partial = [];if (typeof value.length === 'number' &&
!value.propertyIsEnumerable('length')) {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
  '[' + partial.join(',') + ']';
gap = mind;
return v;
}if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {var i;
gap = '';
indent = '';
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}} else if (typeof space === 'string') {
indent = space;
}
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
 typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
return str('', {'': value});
};
}
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
var j;

function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {j = eval('(' + text + ')');
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}throw new SyntaxError('JSON.parse');
};
}
})();
/* related to jcarousel logic */

/**
 *
 * @access public
 * @return void
 **/
function filterLogic(f){
	var url = new Array();
	$('input:hidden', f).each(function()
	{
		url.push($(this).val());
	});
	var last = '*';
	do
	{
		last = url.pop();
	}
	while(last=='*');
	url.push(last);
	url.push('');
	return url;
}

function cc_getPos(name, params){
	first = readCookie(name+':'+JSON.stringify(params));
	if(first==null) return 1;
	return parseInt(first);
}

function cc_move(carousel, item, position, state){
	if(state=='prev' || state=='next')
	createCookie(carousel.options.name + ':' + JSON.stringify(carousel.options.params), position);
}

function cc_getItems(carousel)
{
}

function get_cc_submit()
{
	return function(){
		return cc_submit.apply(this, arguments);
	}
}
function cc_submit(e)
{
	$('#filter').unbind('submit', e.data.options.submitFn).bind('submit', cc_prevent);
	e.data.reset();
	return false;
}

function cc_prevent(e)
{
	return false;
}
/**
 *
 * @access public
 * @return void
 **/
function cc_special(val){
	return val == 'dla_chlopca' || val == 'dla_dziewczynki';
}
function shuffle( inputArr ) {
    inputArr.sort(function() {return 0.5 - Math.random();});
    return true;
}
function cc_init(carousel, state)
{
	if((state=='reset') || (state=='init'))
	{
		var flt = $('#filter');
		var opt = {};
		$('input:hidden', flt).each(function()
		{
			_th = $(this);
			opt[_th.attr('name')] = _th.val();
		});
		if(carousel.options.special == 'collection')
		{
			carousel.options.params.cat0 = (cc_special(opt.f.toString()))?6:1;
			//carousel.options.params.cat1 = (cc_special(opt.f.toString()))?5:1;
			$('div.autoflowCont:first', $(carousel.container).parents('div.wieszak')).text((cc_special(opt.f.toString()))?'Pokoik dziecięcy':'Dzieci');
		}
		$.extend(carousel.options.params,opt);
		$.getJSON("/carousel-" + carousel.options.name + ".html", carousel.options.params, function(result){


			if(result=='{}') result='[]';
			carousel.options.cloths = eval(result);
			if(carousel.options.special == 'sponsor') { shuffle(carousel.options.cloths); }
			carousel.options.size = carousel.options.cloths.length;
			carousel.scroll(cc_getPos(carousel.options.name, carousel.options.params),false);
			cc_load(carousel, 'ajax');
		});
		jQuery('.wieszak_delete', carousel.container).livequery('click', function(e){
			deleteFav(this, $(this).attr('id'), carousel);
			e.preventDefault();
			e.stopPropagation();
			return false;
		});
		$('#filter').unbind('submit', cc_prevent).bind('submit', carousel, carousel.options.submitFn);
	}
	return true;
};


function cc_load(carousel, state)
{
	if(state=='init') return true;
	if(carousel.options.cloths.length > 0)
	{
	    for (var i = carousel.first; i <= carousel.last; i++) {
            carousel.add(i, carousel.options.cloths[i-1]);
	    }
	}
	return true;
};

function deleteFav(btn, cid, carousel){
	$.get('/favDel-cloth.html',{id: cid}, function(data){
		if(data=='1')
		{
			carousel.reset();
			msgBox('Przedmiot został usunięty z ulubionych', 1);
		}
		else
		{
			msgBox('Przedmiot nie został usunięty z ulubionych', 0);
		}
	}, 'text');
}// mode : 0 - error, 1 - ok
$(document).ready(function(){
	var sz_menu = new SDMenu("szafa_cat_menu");
	if(sz_menu.menu!=null)
	{
		sz_menu.init();
	}
			$("a.wiadomoscbox, a.ofertabox").fancybox({
				'zoomSpeedIn':	0,
				'zoomSpeedOut':	0,
				'hideOnContentClick': false,
				'overlayShow':	true,
				'frameWidth': 290,
				'frameHeight': 370
			});

	   //modyfikacja ustawien, to by chyba trzeba gdzies wyjebac razem z tym co jest wyzej
      var toggleMinus = 'Nie zmieniaj hasła';
      var togglePlus = 'Zmiana hasła';
      var $LinkC = $('#ajax_hasla > a');
      var toggleSrc = togglePlus;
      var imgAv = $('div#aboutMeAvatar a.bigAvatar');
	  imgAv.preload();
	  imgAv.flyout();
	  $('a.imgShow').livequery(function(){ $(this).flyout();});

      $('#ajax_hasla > a').click(function() {

      if ( toggleSrc == toggleMinus ) {
      $LinkC.text(togglePlus);
      toggleSrc=togglePlus;
      $('#ajax_hasla_p1').fadeOut('slow');
      $('#ajax_hasla_p2').fadeOut('slow');
      $('#ajax_hasla_p3').fadeOut('slow');

      } else{
      $LinkC.text(toggleMinus);
      toggleSrc=toggleMinus;
      $('#ajax_hasla_p1').fadeIn('slow');
      $('#ajax_hasla_p2').fadeIn('slow');
      $('#ajax_hasla_p3').fadeIn('slow');
      };
    });
    $('.nodef').click(function(e){
    	e.preventDefault();
    });
    $('.stopProp').click(function(e){
    	e.stopPropagation();
    });
	$('.ajaxGet').click(function(e){
		e.preventDefault();
		var it = $(this);
		var q = it.attr('title'); 
		if(q!=undefined){
			if(!confirm(q)) return false;
		}
		jQuery.get(it.attr('href'), {}, function(data, textStatus){
			if(data=='1') it.parents('tr').remove();
		}, 'text');
		return false;
	});
    $('#abuse_btn').click(function(e){
    	reportAbuse($('#c_abuse_form').attr('action'), $('#abuse_type').val(), $('#abuse_id').val(), $('#abuse_reason').val(), '#abuse_div')
        return false;
    });
    jQuery('#showWidgetPreview').click(function(e){
        if(jQuery('#widgetPreview').toggle().is(':visible'))
            {
                jQuery('#showWidgetPreview').html('Ukryj banner');
            }
        else
            {
                jQuery('#showWidgetPreview').html('Podgląd bannera');
            }
        return false;
    });


	var mb = jQuery('#messageBox');
	mb.fadeOut();
});

function acceptVerification(id){
	if(confirm("Ar Ju Wsiur?")){
		 $.get("ajax-AdminAcceptVerify.html",
	       {uid:id, status: 3},
	       function(returned_data)
	         {
				//alert(returned_data);
				if(returned_data=='Status został zmieniony :-)'){
				    
				}else{
				    alert(returned_data);
				}
	         });
			document.getElementById('id_'+id).style.display='none';
			return true;
	}else{
		return false;
	}
}

function acceptVerification2(id, mode){
	if(confirm("Ar Ju Wsiur?")){
		 $.get("ajax-AdminAcceptVerify.html",
	       {uid:id, status:mode},
	       function(returned_data)
	         {
				//alert(returned_data);
				if(returned_data=='Status został zmieniony :-)'){
				}else{
				    alert(returned_data);
				}
	         });
			 document.getElementById('ww_id_'+id).style.display='none';
			return true;
	}else{
		return false;
	}
}

function closeMailer(){
	jQuery('#fancy_close').click();
}

function msgBox(message, mode, url, where){
	//var mb = 
	jQuery(where==undefined?'body':where).jAlert(message, mode?'success':'fatal');
	if(url!=undefined && url!='')
	{
		setTimeout("document.location = '" + url + "';", 2000);
	}
}

function usun_przedmiot(id){
	if(confirm('Czy napewno chcesz usunąć ten przedmiot?'))
	{
		jQuery.get('/usun_przedmiot,'+id+'.html',function(data){
			if(data=='1')
			{
				msgBox('Przedmiot został usunięty',1, '/profil.html');
			}
			else
			{
				msgBox('Przedmiot nie został usunięty',0);
			}
		});
	}
	return false;
}
function przenies_przedmiot(id){
	if(confirm('Czy napewno chcesz przenieść ten przedmiot?'))
	{
		jQuery.get('/ajax-functions.html?action=move_cloth&id='+id,function(data){
			if(data=='1')
			{
				msgBox('Przedmiot został przeniesiony',1, '/profil.html');
			}
			else
			{
				msgBox('Przedmiot nie został przeniesiony',0);
			}
		});
	}
	return false;
}


function reportAbuse(type,id){
	if(confirm('Czy napewno chcesz zgłosić nieprawidłowość?'))
	{
		jQuery.get('/ajax/abuse,'+type+','+id+'.html',function(data){
			if(data=='1')
			{
				msgBox('Nieprawidłowość została zgłoszona, dziękujemy.',1);
			}
			else
			{
				msgBox('Wystąpił błąd przy zgłaszaniu nieprawidłowości.',0);
			}
		});
	}
	return false;
}

function generateCWidget(type,id,bbcodeDiv){
		jQuery.get('/ajax/createWidget.php?type='+type+'&cid='+id,function(data){
			if(data=='0')
			{
				msgBox('Wystąpił problem podczas generownia kodu',1);
			}
			else
			{
				jQuery('#genBBCodeWidget').hide();
                jQuery('#'+bbcodeDiv+'In').val(data);
                jQuery('#'+bbcodeDiv).show();
			}
		});
	return false;
}

// Obsługa boxa z powiadomieniami
function show_prompt_box(name, text, fnc, args){
	isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	isIE = /msie|MSIE/.test(navigator.userAgent);
	$("#prompt_box2 .container .prompt_name").text(name);
	$("#prompt_box2 .container .prompt_text").html(text);
	var hide = $("#prompt_hide");
	if(fnc!=undefined){
		hide.css('display: block');
		hide.unbind('click');
		hide.click(function(){fnc.apply({}, args)});
	} else {
		hide.css('display: none');
	}
	if(isIE){
		$("#prompt_box2").fadeIn("slow");
	}else{
		$("#prompt_box2").fadeIn("slow");
	}
}



function softdel(id, uid, redirect, toHide){
	if(redirect==undefined) redirect='/index.html';
	var form = '<div style="line-height: 200%;"><input type="checkbox" id="powod1" name="powod1" value="Zła kategoria przedmiotu"/> Zła kategoria przedmiotu<br/><input type="checkbox" id="powod2" name="powod2" value="Niedozwolona forma sprzedaży - licytacja"/> Niedozwolona forma sprzedaży - licytacja<br/><input type="checkbox" id="powod3" name="powod3" value="Niedozwolona sprzedaż - konto niezweryfikowane"/> Niedozwolona sprzedaż - konto niezweryfikowane<br/><input type="checkbox" id="powod4" name="powod4" value="Przedmiot niezgodny z tematyką serwisu"/> Przedmiot niezgodny z tematyką serwisu<br/><input type="checkbox" id="powod5" name="powod5" value="Przedmiot narusza Regulamin Szafka.pl"/> Przedmiot narusza Regulamin Szafka.pl  (np. podróbki)<br/>Inny powód <input type="text" id="powod6" name="powod6" value=""/></div>';
	show_prompt_box("Pytanie", form, softdelhelper, [id, uid, redirect, toHide]);
	return false;
}

function softdelhelper(id, uid, redirect, toHide){
	var powod1 = $("#powod1");
	var powod2 = $("#powod2");
	var powod3 = $("#powod3");
	var powod4 = $("#powod4");
	var powod5 = $("#powod5");
	var powod6 = $("#powod6");
	if(powod1.attr("checked") || powod2.attr("checked") || powod3.attr("checked") || powod4.attr("checked") || powod5.attr("checked") || powod6.val()!="")
	{	
		powody = new Array();
		if(powod1.attr("checked")){
			powody[0] = powod1.val();
		}else{
			powody[0] = '';
		}
		if(powod2.attr("checked")){
			powody[1] = powod2.val();
		}else{
			powody[1] = '';
		}
		if(powod3.attr("checked")){
			powody[2] = powod3.val();
		}else{
			powody[2] = '';
		}
		if(powod4.attr("checked")){
			powody[3] = powod4.val();
		}else{
			powody[3] = '';
		}
		if(powod5.attr("checked")){
			powody[4] = powod5.val();
		}else{
			powody[4] = '';
		}
		if(powod6.val()!=""){
			powody[5] = powod6.val();
		}else{
			powody[5] = '';
		}
		
	
		$('#prompt_box2').fadeOut('slow');
		jQuery.post('/softdel,'+id+','+uid+'.html', { 'powody[]': [powody[0],powody[1],powody[2],powody[3],powody[4],powody[5]] }, function(data){
			if(data=='1')
			{
				if(redirect==undefined) redirect = '/index.html';
				msgBox('Przedmiot został ukryty',1, redirect);
				if(toHide!=undefined) jQuery(toHide).hide();
			}
			else
			{
				msgBox('Przedmiot nie został ukryty',0);
			}
		});
	}else{
		alert("Musisz wybrać przynajmniej jeden powód");
	}
}

function doActAdm(link, question, back){
	if(confirm(question)){
		jQuery.get(link, function(data){
			if(data=='1'){
				msgBox('OK', 1, back);
			} else {
				msgBox('Wystąpił błąd!',0);
			}
		});
	}
	return false;
}

function sendMiniMail() {
	return true;
	advAJAX.assign(document.getElementById("miniMailform2"), {
	  onSuccess : function(obj) {

		  document.getElementById('miniMailForm').style.display = "none";

		  if (obj.responseText == "1"){
				msgBox('Wiadomość została wysłana!', 1);
			}else{
				msgBox('Wiadomość NIE została wysłana!', 0);
			}
	  }
	});
}

function usunKomentarz(id, pole, who){
   var adres = "/ajax/delCom.php?id="+id+"&who="+who;
   advAJAX.get({
   url: adres,
      onLoading:function(obj) {document.getElementById(pole).innerHTML='<div align="center">Trwa usuwanie...</div>'; },
       onSuccess:function(obj) { document.getElementById(pole).innerHTML=''; 	initLytebox(); },
      onError:function(obj) {alert(obj.responseText); }
   });
}

function backSell(id, status){
   var adres = "/ajax/back_sell.php?back_id="+id+"&status="+status;
   jQuery.ajax({
   url: adres,
    success:function(obj) { jQuery('#bbacksell').html('Wysłano wiadomość'); if(obj=='2') setTimeout(document.location="wiadomosci/moje-oferty.html", 2000);},
    error:function(obj) {alert("Wystąpił błąd"); }
   });
   return false;
}

function sprawdzWiadomosc(){
	var radios = jQuery(':radio');
	if(radios.size()==3){
		if(!radios.is(':checked'))
		{
			alert('Wybierz Typ komentarza');
			return false;
		}
	}
	if(document.miniMailform2.wiadomosc.value==""){
		alert("Proszę uzupełnić treść.");
		return false;
	}
}

function openClose(id)
{
    $('#'+id).toggle();
}

function showMailForm(offer)
{
	var frm = $('#miniMailform2');
	$('#forCId', frm).remove();
	if($('#miniMailForm').toggle().is(':visible'))
	{
		$('input[name=temat]', frm).val('');
		$('textarea', frm).val('');
	}
    if(!offer)
    {
    	$('input[name=temat]', frm).removeAttr('readonly').val('');
    }
    else
    {
    	var bck = $('#mMF_bck');
    	$('input[name=temat]', frm).removeAttr('readonly').val($('span', bck).text());
    	frm.append($('input', bck).clone());
    }
}

function reportAbuse(url, type, id, reason, result_id)
{
   $.ajax({
   type: "POST",
   url: url,
   data: "type="+type+"&id="+id+"&abuse_reason="+reason,
   success: function(msg){
     $(result_id).html('<p style="margin-left:5px; color: #B990A1; font-weight:bold">Zgłoszenie zostało wysłane</p>');
   }
 });
 return false;
}

function dodOpis(id){
		document.getElementById('ukryty_opis1').style.display = (document.getElementById('ukryty_opis1').style.display == "none") ? "block" : "none";
}
function dodOpis2(id){
	if(id==1){
		document.getElementById('ukryty_opis3').style.display = "block";
		document.getElementById('ukryty_opis2').style.display = "none";
	}else{
		document.getElementById('ukryty_opis2').style.display = "block";
		document.getElementById('ukryty_opis3').style.display = "none";
	}
	//document.getElementById('ukryty_opis2').style.display = (document.getElementById('ukryty_opis2').style.display == "none") ? "block" : "none";
	//document.getElementById('ukryty_opis3').style.display = (document.getElementById('ukryty_opis3').style.display == "none") ? "block" : "none";
}

function doAction(id,akcja,fid)
{
	$('#miniMailForm').hide();
	if(akcja=='cloth_fav'){
		var par = {'fid':fid, 'type':'cloth'};
		$.get("/ajax-addToFav.html", par, function(result) {
			if(result=='1')
			{
				msgBox('Przedmiot został dodany do ulubionych',1);
			}
			else
			{
				msgBox('Masz już to w ulubionych',0);
			}
		}, 'text');

	}
	if(akcja=='user_fav'){
		var par = {'fid':fid, 'type':'user'};
		$.get("/ajax-addToFav.html", par, function(result) {
			if(result=='1')
			{
				msgBox('Użytkowniczka została dodana do obserwowanych.',1);
			}
			else
			{
				msgBox('Już obserwujesz tę użytkowniczkę',0);
			}
		}, 'text');
	}
}

function sprawdzUstawienia(){

	if(document.ustawienia_form.apassword.value!="" && document.ustawienia_form.apassword.value!="" && document.ustawienia_form.apassword.value!=""){

		if(document.ustawienia_form.apassword.value==""){
			alert("Proszę uzupełnić pole oznaczone jako aktualne hasło.");
			return false;
		}
		if(document.ustawienia_form.apassword.value==document.ustawienia_form.npassword1.value){
			alert("Nowe i aktualne hasło nie mogą być takie same!");
			return false;
		}
		if(document.ustawienia_form.npassword1.value!=document.ustawienia_form.npassword2.value){
			alert("Nowe hasło z obu pól musi być takie samo!");
			return false;
		}

	}
	if(document.ustawienia_form.email.value==""){
		alert("Proszę uzupełnić pole oznaczone jako e-mail.");
		return false;
	}

	if(document.ustawienia_form.email.value!=document.ustawienia_form.old_email.value){
		return confirm('Zmieniłaś adres email i musisz dokonać jego aktywacji.\n\nJeśli jesteś pewna jego poprawności kliknij OK - zostaniesz wylogowana i na podany adres '+document.ustawienia_form.email.value+' otrzymasz e-mail z linkiem aktywacyjnym.\n\n W przeciwnym wypadku kliknij Anuluj i podaj poprawny email');

	}

	if(document.ustawienia_form.avatar.value!=""){

		var ext = document.ustawienia_form.avatar.value;
		ext = ext.substring(ext.length-3,ext.length);
		ext = ext.toLowerCase();
		if(ext != 'jpg') {
			alert('Avatar musi być plikiem JPG');
			return false;
		}else{
			return true;
		}
	}

	return true;
}

function sprawdzKontakt(){

var dobryEmail=/^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$/i;

	if(document.kontakt_form.temat.value==""){
		alert("Proszę wybrac temat wiadomości.");
		return false;
	}
	if(document.kontakt_form.email.value==""){
		alert("Proszę wpisać swój adres email.");
		return false;
	}
	if(document.kontakt_form.wiadomosc.value==""){
		alert("Proszę wpisać treść wiadomości.");
		return false;
	}
	if (!dobryEmail.test(document.kontakt_form.email.value)){
	alert("Niepoprawny adres email!");
	return false;
	}

	return true;
}

function rozwinFiltr(){
	document.getElementById('filtr_lewa_rozw').style.display='none';
	document.getElementById('filtr_lewa_content').style.display='';
	document.getElementById('filtr_lewa_zwin').style.display='';
	createCookie('filter',1);
}
function zwinFiltr(){
	document.getElementById('filtr_lewa_zwin').style.display='none';
	document.getElementById('filtr_lewa_content').style.display='none';
	document.getElementById('filtr_lewa_rozw').style.display='';
	createCookie('filter',0);
}


function sprawdzKomentarz(){

	if(document.komentarz.clothID.value==""){
		alert("Wystąpił nieokreślony błąd.");
		return false;
	}
	if(document.komentarz.komentarz.value==""){
		alert("Proszę wpisać komentarz.");
		return false;
	}
	return true;

}

/*wysylanie zaproszen mailem*/
function dodaj_nowe_pole_mail()
{
	var frm = $('#zaproszeniaMail');
	var wyslanie = $('input[name=wyslij_zaproszenie]');
	$(wyslanie, frm).before("<input name=\"mail[]\" onBlur=\"checkemail(this)\" type=\"text\" class=\"zaproszenia_mail_pole\" />");
	$(".zaproszenia_mail_pole:last").one("click", dodaj_nowe_pole_mail)
	/*$("#btn_dodaj_pole").remove().insertBefore(wyslanie); */
}

function accountIBAN(){
	var f=jQuery('input[name=rachunek]');
	account = f.val();
	account = account.replace(/[^0-9]/,'');
	if (length(account) != 26) return [[f, 'Numer konta musi się składać z 26 cyfr']];
	vno = account.substring(2) + '2521' + account.substring(0, 2);
    v = 0;
    for(i = 0; i < 30; ++i) {
    	v = (v + (vno[i] + 0) * w[i]) % 97;
	}
	return v == 1?true:[[f, 'Niepoprawny numer konta']];
}
function szafa_analytics(iurl){
    jQuery.get('/ajax-functions.html', {action:'analytics', url:iurl});
}function onlyPlain(event,f)
{
	if (event.srcElement) {kc = event.keyCode;} else {kc = event.which;}
	if ((kc < 48 || kc > 57) && (kc < 65 || kc > 90) && (kc < 97 || kc > 122) && kc != 45 && kc != 46 && kc != 95 && kc != 8 && kc != 0) return false;
	return true;
}function disallowedCharacters(event,f)
{
	if (event.srcElement) {kc = event.keyCode;} else {kc = event.which;}
	if ((kc < 34 || kc > 39) && (kc < 91 || kc > 96) && kc != 64 && (kc < 60 || kc > 62) && (kc < 123 || kc > 126) && kc != 42 && kc != 45 && kc == 0) return true;
	return false;
}function onlyPlainLogin(event,f)
{
	if (event.srcElement) {kc = event.keyCode;} else {kc = event.which;}
	if ((kc < 48 || kc > 57) && (kc < 65 || kc > 90) && (kc < 97 || kc > 122) && kc != 45 && kc != 95 && kc != 8 && kc != 0 && kc != 127) return false;
	return true;
}function openClose(id)
{
    $('#'+id).toggle();
}
function pokazFormularzLogowania(){	document.getElementById('btn_rejestracja').style.display='none';
	document.getElementById('btn_zaloguj_sie').style.display='none';
	document.getElementById('formularzLogowania').style.display='inline';}
function ukryjFormularzLogowania(){	document.getElementById('btn_rejestracja').style.display='inline';
	document.getElementById('btn_zaloguj_sie').style.display='inline';
	document.getElementById('formularzLogowania').style.display='none';
}function sprawdzLogowanie(){	if(document.logowanie.login.value==""){
		alert("Proszę uzupełnić pole oznaczone jako login.");
		return false;
	}
	if(document.logowanie.password.value==""){
		alert("Proszę uzupełnić pole oznaczone jako hasło.");
		return false;
	}
	return true;}function sprawdzLogowanie2(){	if(document.logowanie2.login.value==""){
		alert("Proszę uzupełnić pole oznaczone jako login.");
		return false;
	}
	if(document.logowanie2.password.value==""){
		alert("Proszę uzupełnić pole oznaczone jako hasło.");
		return false;
	}
	return true;}function sprawdzRejestracje(){var dobryEmail=/^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$/i;
var dobryLogin=/^([AZa-z0-9\-\_]+)$/i;	if(document.rejestracja.login.value==""){
		alert("Proszę uzupełnić pole oznaczone jako login.");
		return false;
	}
	if(document.rejestracja.login.value.length<4){
		alert("Twój login musi być dłuższy niż 4 znaki.");
		return false;
	}
	if (!dobryLogin.test(document.rejestracja.login.value)){
	alert("W polu login wystąpiły niedozwolone znaki!");
	return false;
	}
	if(document.rejestracja.email.value==""){
		alert("Proszę uzupełnić pole oznaczone jako email.");
		return false;
	}
	if (!dobryEmail.test(document.rejestracja.email.value)){
	alert("Niepoprawny adres email!");
	return false;
	}
	if(document.rejestracja.password.value==""){
		alert("Proszę uzupełnić pole oznaczone jako hasło.");
		return false;
	}
	if(document.rejestracja.password.value.length<4){
		alert("Hasło musi być dłuższe niż 4 znaki.");
		return false;
	}
	if(document.rejestracja.login.value==document.rejestracja.password.value){
		alert("Login i hasło nie mogą być takie same");
		return false;
	}
	if(document.rejestracja.regulamin.checked==false){
		alert("Jeśli chcesz się zarejestrować, musisz zaakceptować warunki regulaminu Szafa.pl.");
		return false;
	}
	return true;}/*cookies*/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}function eraseCookie(name) {
	createCookie(name,"",-1);
}function checkemail(inp)
{
	var str = inp.value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str))
	{
	testresults=true;
	inp.style.backgroundColor = 'white';
	$('#rej_error').css("display","none");
	}
	else{
	inp.style.backgroundColor = 'red';
	$('#rej_error').css("display","block");
	testresults=false;
	}
	return (testresults)
}function validateEx(type, el, mode){
	if(mode == undefined) mode = 1;
	var f = jQuery(el);
	if(f.val()!=''){
		jQuery.get('/ajax/dictionary.php', {'type':type, 'value':f.val()}, function(data, status){
			f.next('div').remove();
			if(mode){
			    if(data=='1') {
				    var msg = (type==3 || type==5)?'Login jest już zajęty':'Adres e-mail został już użyty';
				    f.after('<div style="color: red; text-align: right; padding-right: 40px">' + msg + '</div>');
				    f.one('keypress', function(){f.next('div').remove();});
			    }
			} else {
			    if(data=='0') {
				    var msg = (type==3 || type==5)?'Login nie istnieje':'Adres e-mail nie istnieje';
				    f.after('<div style="color: red; text-align: right; padding-right: 40px">' + msg + '</div>');
				    f.one('keypress', function(){f.next('div').remove();});
			    }
			}
		}, 'text');
	}
}function SDMenu(id) {
	this.menu = $('#'+id);
	if(this.menu == null) return false;
	this.submenus = this.menu.children('div');
	this.remember = true;
	this.speed = 600;
	this.markCurrent = false;
	this.oneSmOnly = true;
	return this;
}
SDMenu.prototype.init = function() {
	var th = this;
	this.submenus.each(function(){
		sb = $(this);
		sb.children('div').bind('click', sb, function(e){
			if(e.data.hasClass('collapsed'))
			{
				th.expandMenu(e.data);
			}
			else
			{
				th.collapseMenu(e.data);
			}
		});
	});
};
SDMenu.prototype.toggleMenu = function(submenu) {
	if (submenu.hasClass('collapsed'))
	{
		this.expandMenu(submenu);
	}
	else
	{
		this.collapseMenu(submenu);
	}
};
SDMenu.prototype.expandMenu = function(submenu) {
	var fullHeight = 0;
	submenu.children('p,div').each(function(){
		fullHeight += $(this).outerHeight();
	});
	submenu.removeClass('collapsed')
	submenu.animate({height: fullHeight + 'px'}, this.speed);
	this.collapseOthers(submenu);
};
SDMenu.prototype.collapseMenu = function(submenu) {
	var minHeight = submenu.children('div').outerHeight();
	submenu.addClass('collapsed');
	submenu.animate({height: minHeight + 'px'}, this.speed);
};
SDMenu.prototype.collapseOthers = function(submenu) {
	if (this.oneSmOnly) {
		th = this;
		submenu.siblings('div').not('collapsed').each(function(){
			th.collapseMenu($(this));
		});
	}
};
SDMenu.prototype.expandAll = function() {
	var oldOneSmOnly = this.oneSmOnly;
	this.oneSmOnly = false;
	var th = this;
	this.submenus.filter('.collapsed').each(function(){	th.expandMenu($(this)); });
	this.oneSmOnly = oldOneSmOnly;
};
SDMenu.prototype.collapseAll = function() {
	this.submenus.not('.collapsed').each(function(){th.collapseMenu($(this)); });
};var DDSPEED = 10;
var DDTIMER = 15;

// main function to handle the mouse events //
function ddMenu(id,d){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearInterval(c.timer);
  if(d == 1){
    clearTimeout(h.timer);
    if(c.maxh && c.maxh <= c.offsetHeight){return}
    else if(!c.maxh){
      c.style.display = 'block';
      c.style.height = 'auto';
      c.maxh = c.offsetHeight;
      c.style.height = '0px';
    }
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }else{
    h.timer = setTimeout(function(){ddCollapse(c)},50);
  }
}

// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}

// cancel the collapse if a user rolls over the dropdown //
function cancelHide(id){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearTimeout(h.timer);
  clearInterval(c.timer);
  if(c.offsetHeight < c.maxh){
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }
}

// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh;
  c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}
