
/*!
 * jQuery JavaScript Library v1.4.2
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sat Feb 13 22:33:48 2010 -0500
 */
(function( window, undefined ) {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context );
	},

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,

	// A central reference to the root jQuery(document)
	rootjQuery,

	// A simple way to check for HTML strings or ID strings
	// (both of which we optimize for)
	quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,

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

	// Check if a string has a non-whitespace character in it
	rnotwhite = /\S/,

	// Used for trimming whitespace
	rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,

	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,

	// Keep a UserAgent string for use with jQuery.browser
	userAgent = navigator.userAgent,

	// For matching the engine and version of the browser
	browserMatch,
	
	// Has the ready events already been bound?
	readyBound = false,
	
	// The functions to execute on DOM ready
	readyList = [],

	// The ready event handler
	DOMContentLoaded,

	// Save a reference to some core methods
	toString = Object.prototype.toString,
	hasOwnProperty = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	indexOf = Array.prototype.indexOf;

jQuery.fn = jQuery.prototype = {
	init: function( selector, context ) {
		var match, elem, ret, doc;

		// Handle $(""), $(null), or $(undefined)
		if ( !selector ) {
			return this;
		}

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;
		}
		
		// The body element only exists once, optimize finding it
		if ( selector === "body" && !context ) {
			this.context = document;
			this[0] = document.body;
			this.selector = "body";
			this.length = 1;
			return this;
		}

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			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] ) {
					doc = (context ? context.ownerDocument || context : document);

					// If a single string is passed in and it's a single tag
					// just do a createElement and skip the rest
					ret = rsingleTag.exec( selector );

					if ( ret ) {
						if ( jQuery.isPlainObject( context ) ) {
							selector = [ document.createElement( ret[1] ) ];
							jQuery.fn.attr.call( selector, context, true );

						} else {
							selector = [ doc.createElement( ret[1] ) ];
						}

					} else {
						ret = buildFragment( [ match[1] ], [ doc ] );
						selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
					}
					
					return jQuery.merge( this, selector );
					
				// HANDLE: $("#id")
				} else {
					elem = document.getElementById( match[2] );

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

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $("TAG")
			} else if ( !context && /^\w+$/.test( selector ) ) {
				this.selector = selector;
				this.context = document;
				selector = document.getElementsByTagName( selector );
				return jQuery.merge( this, selector );

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return (context || rootjQuery).find( selector );

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

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

		if (selector.selector !== undefined) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

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

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

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

	// The default length of a jQuery object is 0
	length: 0,

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

	toArray: function() {
		return slice.call( this, 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 == null ?

			// Return a 'clean' array
			this.toArray() :

			// Return just the object
			( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
	},

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

		if ( jQuery.isArray( elems ) ) {
			push.apply( ret, elems );
		
		} else {
			jQuery.merge( ret, elems );
		}

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

		ret.context = this.context;

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

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

	// 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 );
	},
	
	ready: function( fn ) {
		// Attach the listeners
		jQuery.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 if ( readyList ) {
			// Add the function to the wait list
			readyList.push( fn );
		}

		return this;
	},
	
	eq: function( i ) {
		return i === -1 ?
			this.slice( i ) :
			this.slice( i, +i + 1 );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ),
			"slice", slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},
	
	end: function() {
		return this.prevObject || jQuery(null);
	},

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

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

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

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

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

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

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

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

				// Recurse if we're merging object literal values or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
					var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
						: jQuery.isArray(copy) ? [] : {};

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

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

	// Return the modified object
	return target;
};

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

		if ( deep ) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	},
	
	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,
	
	// Handle when the DOM is ready
	ready: function() {
		// Make sure that the DOM is not already loaded
		if ( !jQuery.isReady ) {
			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
			if ( !document.body ) {
				return setTimeout( jQuery.ready, 13 );
			}

			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If there are functions bound, to execute
			if ( readyList ) {
				// Execute all of them
				var fn, i = 0;
				while ( (fn = readyList[ i++ ]) ) {
					fn.call( document, jQuery );
				}

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

			// Trigger any bound ready events
			if ( jQuery.fn.triggerHandler ) {
				jQuery( document ).triggerHandler( "ready" );
			}
		}
	},
	
	bindReady: function() {
		if ( readyBound ) {
			return;
		}

		readyBound = true;

		// Catch cases where $(document).ready() is called after the
		// browser event has already occurred.
		if ( document.readyState === "complete" ) {
			return jQuery.ready();
		}

		// Mozilla, Opera and webkit nightlies currently support this event
		if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
			
			// A fallback to window.onload, that will always work
			window.addEventListener( "load", jQuery.ready, false );

		// If IE event model is used
		} else if ( document.attachEvent ) {
			// ensure firing before onload,
			// maybe late but safe also for iframes
			document.attachEvent("onreadystatechange", DOMContentLoaded);
			
			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", jQuery.ready );

			// If IE and not a frame
			// continually check to see if the document is ready
			var toplevel = false;

			try {
				toplevel = window.frameElement == null;
			} catch(e) {}

			if ( document.documentElement.doScroll && toplevel ) {
				doScrollCheck();
			}
		}
	},

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

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

	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
			return false;
		}
		
		// Not own constructor property must be Object
		if ( obj.constructor
			&& !hasOwnProperty.call(obj, "constructor")
			&& !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
			return false;
		}
		
		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.
	
		var key;
		for ( key in obj ) {}
		
		return key === undefined || hasOwnProperty.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		for ( var name in obj ) {
			return false;
		}
		return true;
	},
	
	error: function( msg ) {
		throw msg;
	},
	
	parseJSON: function( data ) {
		if ( typeof data !== "string" || !data ) {
			return null;
		}

		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );
		
		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
			.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
			.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {

			// Try to use the native JSON parser first
			return window.JSON && window.JSON.parse ?
				window.JSON.parse( data ) :
				(new Function("return " + data))();

		} else {
			jQuery.error( "Invalid JSON: " + data );
		}
	},

	noop: function() {},

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

			script.type = "text/javascript";

			if ( jQuery.support.scriptEval ) {
				script.appendChild( document.createTextNode( data ) );
			} else {
				script.text = data;
			}

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

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

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

		if ( args ) {
			if ( isObj ) {
				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 ( isObj ) {
				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;
	},

	trim: function( text ) {
		return (text || "").replace( rtrim, "" );
	},

	// results is for internal usage only
	makeArray: function( array, results ) {
		var ret = results || [];

		if ( array != null ) {
			// The window, strings (and functions) also have 'length'
			// The extra typeof function check is to prevent crashes
			// in Safari 2 (See: #3039)
			if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
				push.call( ret, array );
			} else {
				jQuery.merge( ret, array );
			}
		}

		return ret;
	},

	inArray: function( elem, array ) {
		if ( array.indexOf ) {
			return array.indexOf( elem );
		}

		for ( var i = 0, length = array.length; i < length; i++ ) {
			if ( array[ i ] === elem ) {
				return i;
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var i = first.length, j = 0;

		if ( typeof second.length === "number" ) {
			for ( var l = second.length; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}
		
		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

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

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var ret = [], value;

		// 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++ ) {
			value = callback( elems[ i ], i, arg );

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

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

	// A global GUID counter for objects
	guid: 1,

	proxy: function( fn, proxy, thisObject ) {
		if ( arguments.length === 2 ) {
			if ( typeof proxy === "string" ) {
				thisObject = fn;
				fn = thisObject[ proxy ];
				proxy = undefined;

			} else if ( proxy && !jQuery.isFunction( proxy ) ) {
				thisObject = proxy;
				proxy = undefined;
			}
		}

		if ( !proxy && fn ) {
			proxy = function() {
				return fn.apply( thisObject || this, arguments );
			};
		}

		// Set the guid of unique handler to the same of original handler, so it can be removed
		if ( fn ) {
			proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
		}

		// So proxy can be declared as an argument
		return proxy;
	},

	// Use of jQuery.browser is frowned upon.
	// More details: http://docs.jquery.com/Utilities/jQuery.browser
	uaMatch: function( ua ) {
		ua = ua.toLowerCase();

		var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
			/(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
			/(msie) ([\w.]+)/.exec( ua ) ||
			!/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
		  	[];

		return { browser: match[1] || "", version: match[2] || "0" };
	},

	browser: {}
});

browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
	jQuery.browser[ browserMatch.browser ] = true;
	jQuery.browser.version = browserMatch.version;
}

// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
	jQuery.browser.safari = true;
}

if ( indexOf ) {
	jQuery.inArray = function( elem, array ) {
		return indexOf.call( array, elem );
	};
}

// All jQuery objects should point back to these
rootjQuery = jQuery(document);

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		jQuery.ready();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			jQuery.ready();
		}
	};
}

// The DOM ready check for Internet Explorer
function doScrollCheck() {
	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( doScrollCheck, 1 );
		return;
	}

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

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

// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
function access( elems, key, value, exec, fn, pass ) {
	var length = elems.length;
	
	// Setting many attributes
	if ( typeof key === "object" ) {
		for ( var k in key ) {
			access( elems, k, key[k], exec, fn, value );
		}
		return elems;
	}
	
	// Setting one attribute
	if ( value !== undefined ) {
		// Optionally, function values get executed if exec is true
		exec = !pass && exec && jQuery.isFunction(value);
		
		for ( var i = 0; i < length; i++ ) {
			fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
		}
		
		return elems;
	}
	
	// Getting an attribute
	return length ? fn( elems[0], key ) : undefined;
}

function now() {
	return (new Date).getTime();
}
(function() {

	jQuery.support = {};

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

	div.style.display = "none";
	div.innerHTML = "   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";

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

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

	jQuery.support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: div.firstChild.nodeType === 3,

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,

		// Get the style information from getAttribute
		// (IE uses .cssText insted)
		style: /red/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: a.getAttribute("href") === "/a",

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.55$/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: div.getElementsByTagName("input")[0].value === "on",

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected,

		parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null,

		// Will be defined later
		deleteExpando: true,
		checkClone: false,
		scriptEval: false,
		noCloneEvent: true,
		boxModel: null
	};

	script.type = "text/javascript";
	try {
		script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
	} catch(e) {}

	root.insertBefore( script, root.firstChild );

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

	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete script.test;
	
	} catch(e) {
		jQuery.support.deleteExpando = false;
	}

	root.removeChild( script );

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

	div = document.createElement("div");
	div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";

	var fragment = document.createDocumentFragment();
	fragment.appendChild( div.firstChild );

	// WebKit doesn't clone checked state correctly in fragments
	jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;

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

		document.body.appendChild( div );
		jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
		document.body.removeChild( div ).style.display = 'none';

		div = null;
	});

	// Technique from Juriy Zaytsev
	// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
	var eventSupported = function( eventName ) { 
		var el = document.createElement("div"); 
		eventName = "on" + eventName; 

		var isSupported = (eventName in el); 
		if ( !isSupported ) { 
			el.setAttribute(eventName, "return;"); 
			isSupported = typeof el[eventName] === "function"; 
		} 
		el = null; 

		return isSupported; 
	};
	
	jQuery.support.submitBubbles = eventSupported("submit");
	jQuery.support.changeBubbles = eventSupported("change");

	// release memory in IE
	root = script = div = all = a = null;
})();

jQuery.props = {
	"for": "htmlFor",
	"class": "className",
	readonly: "readOnly",
	maxlength: "maxLength",
	cellspacing: "cellSpacing",
	rowspan: "rowSpan",
	colspan: "colSpan",
	tabindex: "tabIndex",
	usemap: "useMap",
	frameborder: "frameBorder"
};
var expando = "jQuery" + now(), uuid = 0, windowData = {};

jQuery.extend({
	cache: {},
	
	expando:expando,

	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		"object": true,
		"applet": true
	},

	data: function( elem, name, data ) {
		if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
			return;
		}

		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ], cache = jQuery.cache, thisCache;

		if ( !id && typeof name === "string" && data === undefined ) {
			return null;
		}

		// Compute a unique ID for the element
		if ( !id ) { 
			id = ++uuid;
		}

		// Avoid generating a new cache unless none exists and we
		// want to manipulate it.
		if ( typeof name === "object" ) {
			elem[ expando ] = id;
			thisCache = cache[ id ] = jQuery.extend(true, {}, name);

		} else if ( !cache[ id ] ) {
			elem[ expando ] = id;
			cache[ id ] = {};
		}

		thisCache = cache[ id ];

		// Prevent overriding the named cache with undefined values
		if ( data !== undefined ) {
			thisCache[ name ] = data;
		}

		return typeof name === "string" ? thisCache[ name ] : thisCache;
	},

	removeData: function( elem, name ) {
		if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
			return;
		}

		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ];

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

				// If we've removed all the data, remove the element's cache
				if ( jQuery.isEmptyObject(thisCache) ) {
					jQuery.removeData( elem );
				}
			}

		// Otherwise, we want to remove all of the element's data
		} else {
			if ( jQuery.support.deleteExpando ) {
				delete elem[ jQuery.expando ];

			} else if ( elem.removeAttribute ) {
				elem.removeAttribute( jQuery.expando );
			}

			// Completely remove the data cache
			delete cache[ id ];
		}
	}
});

jQuery.fn.extend({
	data: function( key, value ) {
		if ( typeof key === "undefined" && this.length ) {
			return jQuery.data( this[0] );

		} else if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}

		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 );
		});
	}
});
jQuery.extend({
	queue: function( elem, type, data ) {
		if ( !elem ) {
			return;
		}

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

		// Speed up dequeue by getting out quickly if this is just a lookup
		if ( !data ) {
			return q || [];
		}

		if ( !q || jQuery.isArray(data) ) {
			q = jQuery.data( elem, type, jQuery.makeArray(data) );

		} else {
			q.push( data );
		}

		return q;
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ), fn = queue.shift();

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
		}

		if ( fn ) {
			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift("inprogress");
			}

			fn.call(elem, function() {
				jQuery.dequeue(elem, type);
			});
		}
	}
});

jQuery.fn.extend({
	queue: function( type, data ) {
		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
		}

		if ( data === undefined ) {
			return jQuery.queue( this[0], type );
		}
		return this.each(function( i, elem ) {
			var queue = jQuery.queue( this, type, data );

			if ( type === "fx" && queue[0] !== "inprogress" ) {
				jQuery.dequeue( this, type );
			}
		});
	},
	dequeue: function( type ) {
		return this.each(function() {
			jQuery.dequeue( this, type );
		});
	},

	// Based off of the plugin by Clint Helfers, with permission.
	// http://blindsignals.com/index.php/2009/07/jquery-delay/
	delay: function( time, type ) {
		time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
		type = type || "fx";

		return this.queue( type, function() {
			var elem = this;
			setTimeout(function() {
				jQuery.dequeue( elem, type );
			}, time );
		});
	},

	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	}
});
var rclass = /[\n\t]/g,
	rspace = /\s+/,
	rreturn = /\r/g,
	rspecialurl = /href|src|style/,
	rtype = /(button|input)/i,
	rfocusable = /(button|input|object|select|textarea)/i,
	rclickable = /^(a|area)$/i,
	rradiocheck = /radio|checkbox/;

jQuery.fn.extend({
	attr: function( name, value ) {
		return access( this, name, value, true, jQuery.attr );
	},

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

	addClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.addClass( value.call(this, i, self.attr("class")) );
			});
		}

		if ( value && typeof value === "string" ) {
			var classNames = (value || "").split( rspace );

			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];

				if ( elem.nodeType === 1 ) {
					if ( !elem.className ) {
						elem.className = value;

					} else {
						var className = " " + elem.className + " ", setClass = elem.className;
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
								setClass += " " + classNames[c];
							}
						}
						elem.className = jQuery.trim( setClass );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.removeClass( value.call(this, i, self.attr("class")) );
			});
		}

		if ( (value && typeof value === "string") || value === undefined ) {
			var classNames = (value || "").split(rspace);

			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];

				if ( elem.nodeType === 1 && elem.className ) {
					if ( value ) {
						var className = (" " + elem.className + " ").replace(rclass, " ");
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							className = className.replace(" " + classNames[c] + " ", " ");
						}
						elem.className = jQuery.trim( className );

					} else {
						elem.className = "";
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value, isBool = typeof stateVal === "boolean";

		if ( jQuery.isFunction( value ) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className, i = 0, self = jQuery(this),
					state = stateVal,
					classNames = value.split( rspace );

				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space seperated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}

			} else if ( type === "undefined" || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery.data( this, "__className__", this.className );
				}

				// toggle whole className
				this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ";
		for ( var i = 0, l = this.length; i < l; i++ ) {
			if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
				return true;
			}
		}

		return false;
	},

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

			if ( elem ) {
				if ( jQuery.nodeName( elem, "option" ) ) {
					return (elem.attributes.value || {}).specified ? elem.value : elem.text;
				}

				// We need to handle select boxes special
				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type === "select-one";

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

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

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

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

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

					return values;
				}

				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
					return elem.getAttribute("value") === null ? "on" : elem.value;
				}
				

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

			}

			return undefined;
		}

		var isFunction = jQuery.isFunction(value);

		return this.each(function(i) {
			var self = jQuery(this), val = value;

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

			if ( isFunction ) {
				val = value.call(this, i, self.val());
			}

			// Typecast each time if the value is a Function and the appended
			// value is therefore different each time.
			if ( typeof val === "number" ) {
				val += "";
			}

			if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
				this.checked = jQuery.inArray( self.val(), val ) >= 0;

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

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

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

			} else {
				this.value = val;
			}
		});
	}
});

jQuery.extend({
	attrFn: {
		val: true,
		css: true,
		html: true,
		text: true,
		data: true,
		width: true,
		height: true,
		offset: true
	},
		
	attr: function( elem, name, value, pass ) {
		// don't set attributes on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
			return undefined;
		}

		if ( pass && name in jQuery.attrFn ) {
			return jQuery(elem)[name](value);
		}

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

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

		// Only do all the following if this is a node (faster for style)
		if ( elem.nodeType === 1 ) {
			// These attributes require special treatment
			var special = rspecialurl.test( name );

			// Safari mis-reports the default selected property of an option
			// Accessing the parent's selectedIndex property fixes it
			if ( name === "selected" && !jQuery.support.optSelected ) {
				var parent = elem.parentNode;
				if ( parent ) {
					parent.selectedIndex;
	
					// Make sure that it also works with optgroups, see #5701
					if ( parent.parentNode ) {
						parent.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" && rtype.test( elem.nodeName ) && elem.parentNode ) {
						jQuery.error( "type property can't be changed" );
					}

					elem[ name ] = value;
				}

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

				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				if ( name === "tabIndex" ) {
					var attributeNode = elem.getAttributeNode( "tabIndex" );

					return attributeNode && attributeNode.specified ?
						attributeNode.value :
						rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
							0 :
							undefined;
				}

				return elem[ name ];
			}

			if ( !jQuery.support.style && notxml && name === "style" ) {
				if ( set ) {
					elem.style.cssText = "" + value;
				}

				return elem.style.cssText;
			}

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

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

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

		// elem is actually elem.style ... set the style
		// Using attr for specific style information is now deprecated. Use style instead.
		return jQuery.style( elem, name, value );
	}
});
var rnamespaces = /\.(.*)$/,
	fcleanup = function( nm ) {
		return nm.replace(/[^\w\s\.\|`]/g, function( ch ) {
			return "\\" + ch;
		});
	};

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

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

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

		var handleObjIn, handleObj;

		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
		}

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

		// Init the element's event structure
		var elemData = jQuery.data( elem );

		// If no elemData is found then we must be trying to bind to one of the
		// banned noData elements
		if ( !elemData ) {
			return;
		}

		var events = elemData.events = elemData.events || {},
			eventHandle = elemData.handle, eventHandle;

		if ( !eventHandle ) {
			elemData.handle = eventHandle = function() {
				// Handle the second event of a trigger and when
				// an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
					jQuery.event.handle.apply( eventHandle.elem, arguments ) :
					undefined;
			};
		}

		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native events in IE.
		eventHandle.elem = elem;

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		types = types.split(" ");

		var type, i = 0, namespaces;

		while ( (type = types[ i++ ]) ) {
			handleObj = handleObjIn ?
				jQuery.extend({}, handleObjIn) :
				{ handler: handler, data: data };

			// Namespaced event handlers
			if ( type.indexOf(".") > -1 ) {
				namespaces = type.split(".");
				type = namespaces.shift();
				handleObj.namespace = namespaces.slice(0).sort().join(".");

			} else {
				namespaces = [];
				handleObj.namespace = "";
			}

			handleObj.type = type;
			handleObj.guid = handler.guid;

			// Get the current list of functions bound to this event
			var handlers = events[ type ],
				special = jQuery.event.special[ 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 ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}
			
			if ( special.add ) { 
				special.add.call( elem, handleObj ); 

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add the function to the element's handler list
			handlers.push( handleObj );

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

	global: {},

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

		var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
			elemData = jQuery.data( elem ),
			events = elemData && elemData.events;

		if ( !elemData || !events ) {
			return;
		}

		// types is actually an event object here
		if ( types && types.type ) {
			handler = types.handler;
			types = types.type;
		}

		// Unbind all events for the element
		if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
			types = types || "";

			for ( type in events ) {
				jQuery.event.remove( elem, type + types );
			}

			return;
		}

		// Handle multiple events separated by a space
		// jQuery(...).unbind("mouseover mouseout", fn);
		types = types.split(" ");

		while ( (type = types[ i++ ]) ) {
			origType = type;
			handleObj = null;
			all = type.indexOf(".") < 0;
			namespaces = [];

			if ( !all ) {
				// Namespaced event handlers
				namespaces = type.split(".");
				type = namespaces.shift();

				namespace = new RegExp("(^|\\.)" + 
					jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)")
			}

			eventType = events[ type ];

			if ( !eventType ) {
				continue;
			}

			if ( !handler ) {
				for ( var j = 0; j < eventType.length; j++ ) {
					handleObj = eventType[ j ];

					if ( all || namespace.test( handleObj.namespace ) ) {
						jQuery.event.remove( elem, origType, handleObj.handler, j );
						eventType.splice( j--, 1 );
					}
				}

				continue;
			}

			special = jQuery.event.special[ type ] || {};

			for ( var j = pos || 0; j < eventType.length; j++ ) {
				handleObj = eventType[ j ];

				if ( handler.guid === handleObj.guid ) {
					// remove the given handler for the given type
					if ( all || namespace.test( handleObj.namespace ) ) {
						if ( pos == null ) {
							eventType.splice( j--, 1 );
						}

						if ( special.remove ) {
							special.remove.call( elem, handleObj );
						}
					}

					if ( pos != null ) {
						break;
					}
				}
			}

			// remove generic event handler if no more handlers exist
			if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
				if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
					removeEvent( elem, type, elemData.handle );
				}

				ret = null;
				delete events[ type ];
			}
		}

		// Remove the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			var handle = elemData.handle;
			if ( handle ) {
				handle.elem = null;
			}

			delete elemData.events;
			delete elemData.handle;

			if ( jQuery.isEmptyObject( elemData ) ) {
				jQuery.removeData( elem );
			}
		}
	},

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

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

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

			// Handle a global trigger
			if ( !elem ) {
				// Don't bubble custom events when global (to avoid too much overhead)
				event.stopPropagation();

				// Only trigger if we've ever bound an event for it
				if ( jQuery.event.global[ type ] ) {
					jQuery.each( jQuery.cache, function() {
						if ( this.events && this.events[type] ) {
							jQuery.event.trigger( event, data, this.handle.elem );
						}
					});
				}
			}

			// Handle triggering a single element

			// don't do events on text and comment nodes
			if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
				return undefined;
			}

			// Clean up in case it is reused
			event.result = undefined;
			event.target = elem;

			// Clone the incoming data, if any
			data = jQuery.makeArray( data );
			data.unshift( event );
		}

		event.currentTarget = elem;

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

		var parent = elem.parentNode || elem.ownerDocument;

		// Trigger an inline bound script
		try {
			if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
				if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
					event.result = false;
				}
			}

		// prevent IE from throwing an error for some elements with some event types, see #3533
		} catch (e) {}

		if ( !event.isPropagationStopped() && parent ) {
			jQuery.event.trigger( event, data, parent, true );

		} else if ( !event.isDefaultPrevented() ) {
			var target = event.target, old,
				isClick = jQuery.nodeName(target, "a") && type === "click",
				special = jQuery.event.special[ type ] || {};

			if ( (!special._default || special._default.call( elem, event ) === false) && 
				!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {

				try {
					if ( target[ type ] ) {
						// Make sure that we don't accidentally re-trigger the onFOO events
						old = target[ "on" + type ];

						if ( old ) {
							target[ "on" + type ] = null;
						}

						jQuery.event.triggered = true;
						target[ type ]();
					}

				// prevent IE from throwing an error for some elements with some event types, see #3533
				} catch (e) {}

				if ( old ) {
					target[ "on" + type ] = old;
				}

				jQuery.event.triggered = false;
			}
		}
	},

	handle: function( event ) {
		var all, handlers, namespaces, namespace, events;

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

		// Namespaced event handlers
		all = event.type.indexOf(".") < 0 && !event.exclusive;

		if ( !all ) {
			namespaces = event.type.split(".");
			event.type = namespaces.shift();
			namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)");
		}

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

		if ( events && handlers ) {
			// Clone the handlers to prevent manipulation
			handlers = handlers.slice(0);

			for ( var j = 0, l = handlers.length; j < l; j++ ) {
				var handleObj = handlers[ j ];

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

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

					if ( event.isImmediatePropagationStopped() ) {
						break;
					}
				}
			}
		}

		return event.result;
	},

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

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

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

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

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

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

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

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var doc = document.documentElement, body = document.body;
			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc && doc.clientTop  || body && body.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 !== undefined ) {
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
		}

		return event;
	},

	// Deprecated, use jQuery.guid instead
	guid: 1E8,

	// Deprecated, use jQuery.proxy instead
	proxy: jQuery.proxy,

	special: {
		ready: {
			// Make sure the ready event is setup
			setup: jQuery.bindReady,
			teardown: jQuery.noop
		},

		live: {
			add: function( handleObj ) {
				jQuery.event.add( this, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); 
			},

			remove: function( handleObj ) {
				var remove = true,
					type = handleObj.origType.replace(rnamespaces, "");
				
				jQuery.each( jQuery.data(this, "events").live || [], function() {
					if ( type === this.origType.replace(rnamespaces, "") ) {
						remove = false;
						return false;
					}
				});

				if ( remove ) {
					jQuery.event.remove( this, handleObj.origType, liveHandler );
				}
			}

		},

		beforeunload: {
			setup: function( data, namespaces, eventHandle ) {
				// We only want to do this special case on windows
				if ( this.setInterval ) {
					this.onbeforeunload = eventHandle;
				}

				return false;
			},
			teardown: function( namespaces, eventHandle ) {
				if ( this.onbeforeunload === eventHandle ) {
					this.onbeforeunload = null;
				}
			}
		}
	}
};

var removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		elem.removeEventListener( type, handle, false );
	} : 
	function( elem, type, handle ) {
		elem.detachEvent( "on" + type, handle );
	};

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

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

	// timeStamp is buggy for some events on Firefox(#3843)
	// So we won't rely on the native value
	this.timeStamp = now();

	// Mark it as fixed
	this[ expando ] = true;
};

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

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

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

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}
		// if stopPropagation exists run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};

// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;

	// Firefox sometimes assigns relatedTarget a XUL element
	// which we cannot access the parentNode property of
	try {
		// Traverse up the tree
		while ( parent && parent !== this ) {
			parent = parent.parentNode;
		}

		if ( parent !== this ) {
			// set the correct event type
			event.type = event.data;

			// handle event if we actually just moused on to a non sub-element
			jQuery.event.handle.apply( this, arguments );
		}

	// assuming we've left the element since we most likely mousedover a xul element
	} catch(e) { }
},

// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
	event.type = event.data;
	jQuery.event.handle.apply( this, arguments );
};

// Create mouseenter and mouseleave events
jQuery.each({
	mouseenter: "mouseover",
	mouseleave: "mouseout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		setup: function( data ) {
			jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
		},
		teardown: function( data ) {
			jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
		}
	};
});

// submit delegation
if ( !jQuery.support.submitBubbles ) {

	jQuery.event.special.submit = {
		setup: function( data, namespaces ) {
			if ( this.nodeName.toLowerCase() !== "form" ) {
				jQuery.event.add(this, "click.specialSubmit", function( e ) {
					var elem = e.target, type = elem.type;

					if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
						return trigger( "submit", this, arguments );
					}
				});
	 
				jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
					var elem = e.target, type = elem.type;

					if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
						return trigger( "submit", this, arguments );
					}
				});

			} else {
				return false;
			}
		},

		teardown: function( namespaces ) {
			jQuery.event.remove( this, ".specialSubmit" );
		}
	};

}

// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {

	var formElems = /textarea|input|select/i,

	changeFilters,

	getVal = function( elem ) {
		var type = elem.type, val = elem.value;

		if ( type === "radio" || type === "checkbox" ) {
			val = elem.checked;

		} else if ( type === "select-multiple" ) {
			val = elem.selectedIndex > -1 ?
				jQuery.map( elem.options, function( elem ) {
					return elem.selected;
				}).join("-") :
				"";

		} else if ( elem.nodeName.toLowerCase() === "select" ) {
			val = elem.selectedIndex;
		}

		return val;
	},

	testChange = function testChange( e ) {
		var elem = e.target, data, val;

		if ( !formElems.test( elem.nodeName ) || elem.readOnly ) {
			return;
		}

		data = jQuery.data( elem, "_change_data" );
		val = getVal(elem);

		// the current data will be also retrieved by beforeactivate
		if ( e.type !== "focusout" || elem.type !== "radio" ) {
			jQuery.data( elem, "_change_data", val );
		}
		
		if ( data === undefined || val === data ) {
			return;
		}

		if ( data != null || val ) {
			e.type = "change";
			return jQuery.event.trigger( e, arguments[1], elem );
		}
	};

	jQuery.event.special.change = {
		filters: {
			focusout: testChange, 

			click: function( e ) {
				var elem = e.target, type = elem.type;

				if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
					return testChange.call( this, e );
				}
			},

			// Change has to be called before submit
			// Keydown will be called before keypress, which is used in submit-event delegation
			keydown: function( e ) {
				var elem = e.target, type = elem.type;

				if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
					(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
					type === "select-multiple" ) {
					return testChange.call( this, e );
				}
			},

			// Beforeactivate happens also before the previous element is blurred
			// with this event you can't trigger a change event, but you can store
			// information/focus[in] is not needed anymore
			beforeactivate: function( e ) {
				var elem = e.target;
				jQuery.data( elem, "_change_data", getVal(elem) );
			}
		},

		setup: function( data, namespaces ) {
			if ( this.type === "file" ) {
				return false;
			}

			for ( var type in changeFilters ) {
				jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
			}

			return formElems.test( this.nodeName );
		},

		teardown: function( namespaces ) {
			jQuery.event.remove( this, ".specialChange" );

			return formElems.test( this.nodeName );
		}
	};

	changeFilters = jQuery.event.special.change.filters;
}

function trigger( type, elem, args ) {
	args[0].type = type;
	return jQuery.event.handle.apply( elem, args );
}

// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
		jQuery.event.special[ fix ] = {
			setup: function() {
				this.addEventListener( orig, handler, true );
			}, 
			teardown: function() { 
				this.removeEventListener( orig, handler, true );
			}
		};

		function handler( e ) { 
			e = jQuery.event.fix( e );
			e.type = fix;
			return jQuery.event.handle.call( this, e );
		}
	});
}

jQuery.each(["bind", "one"], function( i, name ) {
	jQuery.fn[ name ] = function( type, data, fn ) {
		// Handle object literals
		if ( typeof type === "object" ) {
			for ( var key in type ) {
				this[ name ](key, data, type[key], fn);
			}
			return this;
		}
		
		if ( jQuery.isFunction( data ) ) {
			fn = data;
			data = undefined;
		}

		var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
			jQuery( this ).unbind( event, handler );
			return fn.apply( this, arguments );
		}) : fn;

		if ( type === "unload" && name !== "one" ) {
			this.one( type, data, fn );

		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				jQuery.event.add( this[i], type, handler, data );
			}
		}

		return this;
	};
});

jQuery.fn.extend({
	unbind: function( type, fn ) {
		// Handle object literals
		if ( typeof type === "object" && !type.preventDefault ) {
			for ( var key in type ) {
				this.unbind(key, type[key]);
			}

		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				jQuery.event.remove( this[i], type, fn );
			}
		}

		return this;
	},
	
	delegate: function( selector, types, data, fn ) {
		return this.live( types, data, fn, selector );
	},
	
	undelegate: function( selector, types, fn ) {
		if ( arguments.length === 0 ) {
				return this.unbind( "live" );
		
		} else {
			return this.die( types, null, fn, selector );
		}
	},
	
	trigger: function( type, data ) {
		return this.each(function() {
			jQuery.event.trigger( type, data, this );
		});
	},

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

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

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

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

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

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

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

var liveMap = {
	focus: "focusin",
	blur: "focusout",
	mouseenter: "mouseover",
	mouseleave: "mouseout"
};

jQuery.each(["live", "die"], function( i, name ) {
	jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
		var type, i = 0, match, namespaces, preType,
			selector = origSelector || this.selector,
			context = origSelector ? this : jQuery( this.context );

		if ( jQuery.isFunction( data ) ) {
			fn = data;
			data = undefined;
		}

		types = (types || "").split(" ");

		while ( (type = types[ i++ ]) != null ) {
			match = rnamespaces.exec( type );
			namespaces = "";

			if ( match )  {
				namespaces = match[0];
				type = type.replace( rnamespaces, "" );
			}

			if ( type === "hover" ) {
				types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
				continue;
			}

			preType = type;

			if ( type === "focus" || type === "blur" ) {
				types.push( liveMap[ type ] + namespaces );
				type = type + namespaces;

			} else {
				type = (liveMap[ type ] || type) + namespaces;
			}

			if ( name === "live" ) {
				// bind live handler
				context.each(function(){
					jQuery.event.add( this, liveConvert( type, selector ),
						{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
				});

			} else {
				// unbind live handler
				context.unbind( liveConvert( type, selector ), fn );
			}
		}
		
		return this;
	}
});

function liveHandler( event ) {
	var stop, elems = [], selectors = [], args = arguments,
		related, match, handleObj, elem, j, i, l, data,
		events = jQuery.data( this, "events" );

	// Make sure we avoid non-left-click bubbling in Firefox (#3861)
	if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
		return;
	}

	event.liveFired = this;

	var live = events.live.slice(0);

	for ( j = 0; j < live.length; j++ ) {
		handleObj = live[j];

		if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
			selectors.push( handleObj.selector );

		} else {
			live.splice( j--, 1 );
		}
	}

	match = jQuery( event.target ).closest( selectors, event.currentTarget );

	for ( i = 0, l = match.length; i < l; i++ ) {
		for ( j = 0; j < live.length; j++ ) {
			handleObj = live[j];

			if ( match[i].selector === handleObj.selector ) {
				elem = match[i].elem;
				related = null;

				// Those two events require additional checking
				if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
					related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
				}

				if ( !related || related !== elem ) {
					elems.push({ elem: elem, handleObj: handleObj });
				}
			}
		}
	}

	for ( i = 0, l = elems.length; i < l; i++ ) {
		match = elems[i];
		event.currentTarget = match.elem;
		event.data = match.handleObj.data;
		event.handleObj = match.handleObj;

		if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) {
			stop = false;
			break;
		}
	}

	return stop;
}

function liveConvert( type, selector ) {
	return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&");
}

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

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

	if ( jQuery.attrFn ) {
		jQuery.attrFn[ name ] = true;
	}
});

// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
//  - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
	window.attachEvent("onunload", function() {
		for ( var id in jQuery.cache ) {
			if ( jQuery.cache[ id ].handle ) {
				// Try/Catch is to handle iframes being unloaded, see #4280
				try {
					jQuery.event.remove( jQuery.cache[ id ].handle.elem );
				} catch(e) {}
			}
		}
	});
}
/*!
 * Sizzle CSS Selector Engine - v1.0
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

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

// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
//   Thus far that includes Google Chrome.
[0, 0].sort(function(){
	baseHasDuplicate = false;
	return 0;
});

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

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

	var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context),
		soFar = selector;
	
	// Reset the position of the chunker regexp (start from head)
	while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) {
		soFar = m[3];
		
		parts.push( m[1] );
		
		if ( m[2] ) {
			extra = m[3];
			break;
		}
	}

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

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

				if ( Expr.relative[ selector ] ) {
					selector += parts.shift();
				}
				
				set = posProcess( selector, set );
			}
		}
	} else {
		// Take a shortcut and set the context if the root selector is an ID
		// (but not if it'll be faster if the inner selector is an ID)
		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
			var ret = Sizzle.find( parts.shift(), context, contextXML );
			context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
		}

		if ( context ) {
			var ret = seed ?
				{ expr: parts.pop(), set: makeArray(seed) } :
				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
			set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;

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

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

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

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

				Expr.relative[ cur ]( checkSet, pop, contextXML );
			}
		} else {
			checkSet = parts = [];
		}
	}

	if ( !checkSet ) {
		checkSet = set;
	}

	if ( !checkSet ) {
		Sizzle.error( cur || selector );
	}

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

	if ( extra ) {
		Sizzle( extra, origContext, results, seed );
		Sizzle.uniqueSort( results );
	}

	return results;
};

Sizzle.uniqueSort = function(results){
	if ( sortOrder ) {
		hasDuplicate = baseHasDuplicate;
		results.sort(sortOrder);

		if ( hasDuplicate ) {
			for ( var i = 1; i < results.length; i++ ) {
				if ( results[i] === results[i-1] ) {
					results.splice(i--, 1);
				}
			}
		}
	}

	return results;
};

Sizzle.matches = function(expr, set){
	return Sizzle(expr, null, null, set);
};

Sizzle.find = function(expr, context, isXML){
	var set, match;

	if ( !expr ) {
		return [];
	}

	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
		var type = Expr.order[i], match;
		
		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
			var left = match[1];
			match.splice(1,1);

			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace(/\\/g, "");
				set = Expr.find[ type ]( match, context, isXML );
				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}

	if ( !set ) {
		set = context.getElementsByTagName("*");
	}

	return {set: set, expr: expr};
};

Sizzle.filter = function(expr, set, inplace, not){
	var old = expr, result = [], curLoop = set, match, anyFound,
		isXMLFilter = set && set[0] && isXML(set[0]);

	while ( expr && set.length ) {
		for ( var type in Expr.filter ) {
			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
				var filter = Expr.filter[ type ], found, item, left = match[1];
				anyFound = false;

				match.splice(1,1);

				if ( left.substr( left.length - 1 ) === "\\" ) {
					continue;
				}

				if ( curLoop === result ) {
					result = [];
				}

				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

					if ( !match ) {
						anyFound = found = true;
					} else if ( match === true ) {
						continue;
					}
				}

				if ( match ) {
					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							var pass = not ^ !!found;

							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;
								} else {
									curLoop[i] = false;
								}
							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}

				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}

					expr = expr.replace( Expr.match[ type ], "" );

					if ( !anyFound ) {
						return [];
					}

					break;
				}
			}
		}

		// Improper expression
		if ( expr === old ) {
			if ( anyFound == null ) {
				Sizzle.error( expr );
			} else {
				break;
			}
		}

		old = expr;
	}

	return curLoop;
};

Sizzle.error = function( msg ) {
	throw "Syntax error, unrecognized expression: " + msg;
};

var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],
	match: {
		ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
	},
	leftMatch: {},
	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},
	attrHandle: {
		href: function(elem){
			return elem.getAttribute("href");
		}
	},
	relative: {
		"+": function(checkSet, part){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !/\W/.test(part),
				isPartStrNotTag = isPartStr && !isTag;

			if ( isTag ) {
				part = part.toLowerCase();
			}

			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
						elem || false :
						elem === part;
				}
			}

			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},
		">": function(checkSet, part){
			var isPartStr = typeof part === "string";

			if ( isPartStr && !/\W/.test(part) ) {
				part = part.toLowerCase();

				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
					var elem = checkSet[i];
					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
					}
				}
			} else {
				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
					var elem = checkSet[i];
					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},
		"": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck;

			if ( typeof part === "string" && !/\W/.test(part) ) {
				var nodeCheck = part = part.toLowerCase();
				checkFn = dirNodeCheck;
			}

			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
		},
		"~": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck;

			if ( typeof part === "string" && !/\W/.test(part) ) {
				var nodeCheck = part = part.toLowerCase();
				checkFn = dirNodeCheck;
			}

			checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
		}
	},
	find: {
		ID: function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? [m] : [];
			}
		},
		NAME: function(match, context){
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [], results = context.getElementsByName(match[1]);

				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}

				return ret.length === 0 ? null : ret;
			}
		},
		TAG: function(match, context){
			return context.getElementsByTagName(match[1]);
		}
	},
	preFilter: {
		CLASS: function(match, curLoop, inplace, result, not, isXML){
			match = " " + match[1].replace(/\\/g, "") + " ";

			if ( isXML ) {
				return match;
			}

			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
						if ( !inplace ) {
							result.push( elem );
						}
					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}

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

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

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

			return match;
		},
		ATTR: function(match, curLoop, inplace, result, not, isXML){
			var name = match[1].replace(/\\/g, "");
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

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

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

			if ( filter ) {
				return filter( elem, i, match, array );
			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
			} else if ( name === "not" ) {
				var not = match[3];

				for ( var i = 0, l = not.length; i < l; i++ ) {
					if ( not[i] === elem ) {
						return false;
					}
				}

				return true;
			} else {
				Sizzle.error( "Syntax error, unrecognized expression: " + name );
			}
		},
		CHILD: function(elem, match){
			var type = match[1], node = elem;
			switch (type) {
				case 'only':
				case 'first':
					while ( (node = node.previousSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}
					if ( type === "first" ) { 
						return true; 
					}
					node = elem;
				case 'last':
					while ( (node = node.nextSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}
					return true;
				case 'nth':
					var first = match[2], last = match[3];

					if ( first === 1 && last === 0 ) {
						return true;
					}
					
					var doneName = match[0],
						parent = elem.parentNode;
	
					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
						var count = 0;
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 
						parent.sizcache = doneName;
					}
					
					var diff = elem.nodeIndex - last;
					if ( first === 0 ) {
						return diff === 0;
					} else {
						return ( diff % first === 0 && diff / first >= 0 );
					}
			}
		},
		ID: function(elem, match){
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},
		TAG: function(elem, match){
			return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
		},
		CLASS: function(elem, match){
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},
		ATTR: function(elem, match){
			var name = match[1],
				result = Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];

			return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value !== check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},
		POS: function(elem, match, i, array){
			var name = match[2], filter = Expr.setFilters[ name ];

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

var origPOS = Expr.match.POS;

for ( var type in Expr.match ) {
	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){
		return "\\" + (num - 0 + 1);
	}));
}

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

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

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

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

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

		return ret;
	};
}

var sortOrder;

if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
			if ( a == b ) {
				hasDuplicate = true;
			}
			return a.compareDocumentPosition ? -1 : 1;
		}

		var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( "sourceIndex" in document.documentElement ) {
	sortOrder = function( a, b ) {
		if ( !a.sourceIndex || !b.sourceIndex ) {
			if ( a == b ) {
				hasDuplicate = true;
			}
			return a.sourceIndex ? -1 : 1;
		}

		var ret = a.sourceIndex - b.sourceIndex;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( document.createRange ) {
	sortOrder = function( a, b ) {
		if ( !a.ownerDocument || !b.ownerDocument ) {
			if ( a == b ) {
				hasDuplicate = true;
			}
			return a.ownerDocument ? -1 : 1;
		}

		var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
		aRange.setStart(a, 0);
		aRange.setEnd(a, 0);
		bRange.setStart(b, 0);
		bRange.setEnd(b, 0);
		var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
}

// Utility function for retreiving the text value of an array of DOM nodes
function getText( elems ) {
	var ret = "", elem;

	for ( var i = 0; elems[i]; i++ ) {
		elem = elems[i];

		// Get the text from text nodes and CDATA nodes
		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
			ret += elem.nodeValue;

		// Traverse everything else, except comment nodes
		} else if ( elem.nodeType !== 8 ) {
			ret += getText( elem.childNodes );
		}
	}

	return ret;
}

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

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

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

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

	root.removeChild( form );
	root = form = null; // release memory in IE
})();

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

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

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

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

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

				results = tmp;
			}

			return results;
		};
	}

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

	div = null; // release memory in IE
})();

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

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

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

		for ( var prop in oldSizzle ) {
			Sizzle[ prop ] = oldSizzle[ prop ];
		}

		div = null; // release memory in IE
	})();
}

(function(){
	var div = document.createElement("div");

	div.innerHTML = "<div class='test e'></div><div class='test'></div>";

	// Opera can't find a second classname (in 9.6)
	// Also, make sure that getElementsByClassName actually exists
	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
		return;
	}

	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";

	if ( div.getElementsByClassName("e").length === 1 ) {
		return;
	}
	
	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function(match, context, isXML) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};

	div = null; // release memory in IE
})();

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

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

				if ( elem.nodeType === 1 && !isXML ){
					elem.sizcache = doneName;
					elem.sizset = i;
				}

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

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

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

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

				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem.sizcache = doneName;
						elem.sizset = i;
					}
					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

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

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

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

var isXML = function(elem){
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833) 
	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

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

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

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

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

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

// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = getText;
jQuery.isXMLDoc = isXML;
jQuery.contains = contains;

return;

window.Sizzle = Sizzle;

})();
var runtil = /Until$/,
	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
	// Note: This RegExp should be improved, or likely pulled from Sizzle
	rmultiselector = /,/,
	slice = Array.prototype.slice;

// Implement the identical functionality for filter and not
var winnow = function( elements, qualifier, keep ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep(elements, function( elem, i ) {
			return !!qualifier.call( elem, i, elem ) === keep;
		});

	} else if ( qualifier.nodeType ) {
		return jQuery.grep(elements, function( elem, i ) {
			return (elem === qualifier) === keep;
		});

	} else if ( typeof qualifier === "string" ) {
		var filtered = jQuery.grep(elements, function( elem ) {
			return elem.nodeType === 1;
		});

		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter(qualifier, filtered, !keep);
		} else {
			qualifier = jQuery.filter( qualifier, filtered );
		}
	}

	return jQuery.grep(elements, function( elem, i ) {
		return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
	});
};

jQuery.fn.extend({
	find: function( selector ) {
		var ret = this.pushStack( "", "find", selector ), length = 0;

		for ( var i = 0, l = this.length; i < l; i++ ) {
			length = ret.length;
			jQuery.find( selector, this[i], ret );

			if ( i > 0 ) {
				// Make sure that the results are unique
				for ( var n = length; n < ret.length; n++ ) {
					for ( var r = 0; r < length; r++ ) {
						if ( ret[r] === ret[n] ) {
							ret.splice(n--, 1);
							break;
						}
					}
				}
			}
		}

		return ret;
	},

	has: function( target ) {
		var targets = jQuery( target );
		return this.filter(function() {
			for ( var i = 0, l = targets.length; i < l; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector, false), "not", selector);
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector, true), "filter", selector );
	},
	
	is: function( selector ) {
		return !!selector && jQuery.filter( selector, this ).length > 0;
	},

	closest: function( selectors, context ) {
		if ( jQuery.isArray( selectors ) ) {
			var ret = [], cur = this[0], match, matches = {}, selector;

			if ( cur && selectors.length ) {
				for ( var i = 0, l = selectors.length; i < l; i++ ) {
					selector = selectors[i];

					if ( !matches[selector] ) {
						matches[selector] = jQuery.expr.match.POS.test( selector ) ? 
							jQuery( selector, context || this.context ) :
							selector;
					}
				}

				while ( cur && cur.ownerDocument && cur !== context ) {
					for ( selector in matches ) {
						match = matches[selector];

						if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
							ret.push({ selector: selector, elem: cur });
							delete matches[selector];
						}
					}
					cur = cur.parentNode;
				}
			}

			return ret;
		}

		var pos = jQuery.expr.match.POS.test( selectors ) ? 
			jQuery( selectors, context || this.context ) : null;

		return this.map(function( i, cur ) {
			while ( cur && cur.ownerDocument && cur !== context ) {
				if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) {
					return cur;
				}
				cur = cur.parentNode;
			}
			return null;
		});
	},
	
	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		if ( !elem || typeof elem === "string" ) {
			return jQuery.inArray( this[0],
				// If it receives a string, the selector is used
				// If it receives nothing, the siblings are used
				elem ? jQuery( elem ) : this.parent().children() );
		}
		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context || this.context ) :
				jQuery.makeArray( selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
			all :
			jQuery.unique( all ) );
	},

	andSelf: function() {
		return this.add( this.prevObject );
	}
});

// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
	return !node || !node.parentNode || node.parentNode.nodeType === 11;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	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" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	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( until, selector ) {
		var ret = jQuery.map( this, fn, until );
		
		if ( !runtil.test( name ) ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		ret = this.length > 1 ? jQuery.unique( ret ) : ret;

		if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
			ret = ret.reverse();
		}

		return this.pushStack( ret, name, slice.call(arguments).join(",") );
	};
});

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

		return jQuery.find.matches(expr, elems);
	},
	
	dir: function( elem, dir, until ) {
		var matched = [], cur = elem[dir];
		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			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;
	}
});
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g,
	rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnocache = /<script|<object|<embed|<option|<style/i,
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,  // checked="checked" or checked (html5)
	fcloseTag = function( all, front, tag ) {
		return rselfClosing.test( tag ) ?
			all :
			front + "></" + tag + ">";
	},
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		area: [ 1, "<map>", "</map>" ],
		_default: [ 0, "", "" ]
	};

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
	wrapMap._default = [ 1, "div<div>", "</div>" ];
}

jQuery.fn.extend({
	text: function( text ) {
		if ( jQuery.isFunction(text) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.text( text.call(this, i, self.text()) );
			});
		}

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

		return jQuery.text( this );
	},

	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapAll( html.call(this, i) );
			});
		}

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

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

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

				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

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

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapInner( html.call(this, i) );
			});
		}

		return this.each(function() {
			var self = jQuery( this ), contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		});
	},

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

	unwrap: function() {
		return this.parent().each(function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		}).end();
	},

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

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

	before: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this );
			});
		} else if ( arguments.length ) {
			var set = jQuery(arguments[0]);
			set.push.apply( set, this.toArray() );
			return this.pushStack( set, "before", arguments );
		}
	},

	after: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			});
		} else if ( arguments.length ) {
			var set = this.pushStack( this, "after", arguments );
			set.push.apply( set, jQuery(arguments[0]).toArray() );
			return set;
		}
	},
	
	// keepData is for internal use only--do not document
	remove: function( selector, keepData ) {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
				if ( !keepData && elem.nodeType === 1 ) {
					jQuery.cleanData( elem.getElementsByTagName("*") );
					jQuery.cleanData( [ elem ] );
				}

				if ( elem.parentNode ) {
					 elem.parentNode.removeChild( elem );
				}
			}
		}
		
		return this;
	},

	empty: function() {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( elem.getElementsByTagName("*") );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}
		}
		
		return this;
	},

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

				return jQuery.clean([html.replace(rinlinejQuery, "")
					// Handle the case in IE 8 where action=/test/> self-closes a tag
					.replace(/=([^="'>\s]+\/)>/g, '="$1">')
					.replace(rleadingWhitespace, "")], ownerDocument)[0];
			} else {
				return this.cloneNode(true);
			}
		});

		// Copy the events from the original to the clone
		if ( events === true ) {
			cloneCopyEvent( this, ret );
			cloneCopyEvent( this.find("*"), ret.find("*") );
		}

		// Return the cloned set
		return ret;
	},

	html: function( value ) {
		if ( value === undefined ) {
			return this[0] && this[0].nodeType === 1 ?
				this[0].innerHTML.replace(rinlinejQuery, "") :
				null;

		// See if we can take a shortcut and just use innerHTML
		} else if ( typeof value === "string" && !rnocache.test( value ) &&
			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
			!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

			value = value.replace(rxhtmlTag, fcloseTag);

			try {
				for ( var i = 0, l = this.length; i < l; i++ ) {
					// Remove element nodes and prevent memory leaks
					if ( this[i].nodeType === 1 ) {
						jQuery.cleanData( this[i].getElementsByTagName("*") );
						this[i].innerHTML = value;
					}
				}

			// If using innerHTML throws an exception, use the fallback method
			} catch(e) {
				this.empty().append( value );
			}

		} else if ( jQuery.isFunction( value ) ) {
			this.each(function(i){
				var self = jQuery(this), old = self.html();
				self.empty().append(function(){
					return value.call( this, i, old );
				});
			});

		} else {
			this.empty().append( value );
		}

		return this;
	},

	replaceWith: function( value ) {
		if ( this[0] && this[0].parentNode ) {
			// Make sure that the elements are removed from the DOM before they are inserted
			// this can help fix replacing a parent with child elements
			if ( jQuery.isFunction( value ) ) {
				return this.each(function(i) {
					var self = jQuery(this), old = self.html();
					self.replaceWith( value.call( this, i, old ) );
				});
			}

			if ( typeof value !== "string" ) {
				value = jQuery(value).detach();
			}

			return this.each(function() {
				var next = this.nextSibling, parent = this.parentNode;

				jQuery(this).remove();

				if ( next ) {
					jQuery(next).before( value );
				} else {
					jQuery(parent).append( value );
				}
			});
		} else {
			return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
		}
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, table, callback ) {
		var results, first, value = args[0], scripts = [], fragment, parent;

		// We can't cloneNode fragments that contain checked, in WebKit
		if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
			return this.each(function() {
				jQuery(this).domManip( args, table, callback, true );
			});
		}

		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				args[0] = value.call(this, i, table ? self.html() : undefined);
				self.domManip( args, table, callback );
			});
		}

		if ( this[0] ) {
			parent = value && value.parentNode;

			// If we're in a fragment, just use that instead of building a new one
			if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
				results = { fragment: parent };

			} else {
				results = buildFragment( args, this, scripts );
			}
			
			fragment = results.fragment;
			
			if ( fragment.childNodes.length === 1 ) {
				first = fragment = fragment.firstChild;
			} else {
				first = fragment.firstChild;
			}

			if ( first ) {
				table = table && jQuery.nodeName( first, "tr" );

				for ( var i = 0, l = this.length; i < l; i++ ) {
					callback.call(
						table ?
							root(this[i], first) :
							this[i],
						i > 0 || results.cacheable || this.length > 1  ?
							fragment.cloneNode(true) :
							fragment
					);
				}
			}

			if ( scripts.length ) {
				jQuery.each( scripts, evalScript );
			}
		}

		return this;

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

function cloneCopyEvent(orig, ret) {
	var i = 0;

	ret.each(function() {
		if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
			return;
		}

		var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;

		if ( events ) {
			delete curData.handle;
			curData.events = {};

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

function buildFragment( args, nodes, scripts ) {
	var fragment, cacheable, cacheresults,
		doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);

	// Only cache "small" (1/2 KB) strings that are associated with the main document
	// Cloning options loses the selected state, so don't cache them
	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
	if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
		!rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {

		cacheable = true;
		cacheresults = jQuery.fragments[ args[0] ];
		if ( cacheresults ) {
			if ( cacheresults !== 1 ) {
				fragment = cacheresults;
			}
		}
	}

	if ( !fragment ) {
		fragment = doc.createDocumentFragment();
		jQuery.clean( args, doc, fragment, scripts );
	}

	if ( cacheable ) {
		jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
	}

	return { fragment: fragment, cacheable: cacheable };
}

jQuery.fragments = {};

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var ret = [], insert = jQuery( selector ),
			parent = this.length === 1 && this[0].parentNode;
		
		if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
			insert[ original ]( this[0] );
			return this;
			
		} else {
			for ( var i = 0, l = insert.length; i < l; i++ ) {
				var elems = (i > 0 ? this.clone(true) : this).get();
				jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
				ret = ret.concat( elems );
			}
		
			return this.pushStack( ret, name, insert.selector );
		}
	};
});

jQuery.extend({
	clean: function( elems, context, fragment, scripts ) {
		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;
		}

		var ret = [];

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( typeof elem === "number" ) {
				elem += "";
			}

			if ( !elem ) {
				continue;
			}

			// Convert html string into DOM nodes
			if ( typeof elem === "string" && !rhtml.test( elem ) ) {
				elem = context.createTextNode( elem );

			} else if ( typeof elem === "string" ) {
				// Fix "XHTML"-style tags in all browsers
				elem = elem.replace(rxhtmlTag, fcloseTag);

				// Trim whitespace, otherwise indexOf won't work as expected
				var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
					wrap = wrapMap[ tag ] || wrapMap._default,
					depth = wrap[0],
					div = context.createElement("div");

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

				// Move to the right depth
				while ( depth-- ) {
					div = div.lastChild;
				}

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

					// String was a <table>, *may* have spurious <tbody>
					var hasBody = rtbody.test(elem),
						tbody = tag === "table" && !hasBody ?
							div.firstChild && div.firstChild.childNodes :

							// String was a bare <thead> or <tfoot>
							wrap[1] === "<table>" && !hasBody ?
								div.childNodes :
								[];

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

				}

				// IE completely kills leading whitespace when innerHTML is used
				if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
					div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
				}

				elem = div.childNodes;
			}

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

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

		return ret;
	},
	
	cleanData: function( elems ) {
		var data, id, cache = jQuery.cache,
			special = jQuery.event.special,
			deleteExpando = jQuery.support.deleteExpando;
		
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			id = elem[ jQuery.expando ];
			
			if ( id ) {
				data = cache[ id ];
				
				if ( data.events ) {
					for ( var type in data.events ) {
						if ( special[ type ] ) {
							jQuery.event.remove( elem, type );

						} else {
							removeEvent( elem, type, data.handle );
						}
					}
				}
				
				if ( deleteExpando ) {
					delete elem[ jQuery.expando ];

				} else if ( elem.removeAttribute ) {
					elem.removeAttribute( jQuery.expando );
				}
				
				delete cache[ id ];
			}
		}
	}
});
// exclude the following css properties to add px
var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
	ralpha = /alpha\([^)]*\)/,
	ropacity = /opacity=([^)]*)/,
	rfloat = /float/i,
	rdashAlpha = /-([a-z])/ig,
	rupper = /([A-Z])/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,

	cssShow = { position: "absolute", visibility: "hidden", display:"block" },
	cssWidth = [ "Left", "Right" ],
	cssHeight = [ "Top", "Bottom" ],

	// cache check for defaultView.getComputedStyle
	getComputedStyle = document.defaultView && document.defaultView.getComputedStyle,
	// normalize float css property
	styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat",
	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn.css = function( name, value ) {
	return access( this, name, value, true, function( elem, name, value ) {
		if ( value === undefined ) {
			return jQuery.curCSS( elem, name );
		}
		
		if ( typeof value === "number" && !rexclude.test(name) ) {
			value += "px";
		}

		jQuery.style( elem, name, value );
	});
};

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

		// ignore negative width and height values #1599
		if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) {
			value = undefined;
		}

		var style = elem.style || elem, set = value !== undefined;

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

				// Set the alpha filter to set the opacity
				var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")";
				var filter = style.filter || jQuery.curCSS( elem, "filter" ) || "";
				style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity;
			}

			return style.filter && style.filter.indexOf("opacity=") >= 0 ?
				(parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "":
				"";
		}

		// Make sure we're using the right name for getting the float value
		if ( rfloat.test( name ) ) {
			name = styleFloat;
		}

		name = name.replace(rdashAlpha, fcamelCase);

		if ( set ) {
			style[ name ] = value;
		}

		return style[ name ];
	},

	css: function( elem, name, force, extra ) {
		if ( name === "width" || name === "height" ) {
			var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight;

			function getWH() {
				val = name === "width" ? elem.offsetWidth : elem.offsetHeight;

				if ( extra === "border" ) {
					return;
				}

				jQuery.each( which, function() {
					if ( !extra ) {
						val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
					}

					if ( extra === "margin" ) {
						val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
					} else {
						val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
					}
				});
			}

			if ( elem.offsetWidth !== 0 ) {
				getWH();
			} else {
				jQuery.swap( elem, props, getWH );
			}

			return Math.max(0, Math.round(val));
		}

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

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

		// IE uses filters for opacity
		if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) {
			ret = ropacity.test(elem.currentStyle.filter || "") ?
				(parseFloat(RegExp.$1) / 100) + "" :
				"";

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

		// Make sure we're using the right name for getting the float value
		if ( rfloat.test( name ) ) {
			name = styleFloat;
		}

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

		} else if ( getComputedStyle ) {

			// Only "float" is needed here
			if ( rfloat.test( name ) ) {
				name = "float";
			}

			name = name.replace( rupper, "-$1" ).toLowerCase();

			var defaultView = elem.ownerDocument.defaultView;

			if ( !defaultView ) {
				return null;
			}

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

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

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

		} else if ( elem.currentStyle ) {
			var camelCase = name.replace(rdashAlpha, fcamelCase);

			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 ( !rnumpx.test( ret ) && rnum.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 = camelCase === "fontSize" ? "1em" : (ret || 0);
				ret = style.pixelLeft + "px";

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

		return ret;
	},

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

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		var width = elem.offsetWidth, height = elem.offsetHeight,
			skip = elem.nodeName.toLowerCase() === "tr";

		return width === 0 && height === 0 && !skip ?
			true :
			width > 0 && height > 0 && !skip ?
				false :
				jQuery.curCSS(elem, "display") === "none";
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}
var jsc = now(),
	rscript = /<script(.|\s)*?\/script>/gi,
	rselectTextarea = /select|textarea/i,
	rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
	jsre = /=\?(&|$)/,
	rquery = /\?/,
	rts = /(\?|&)_=.*?(&|$)/,
	rurl = /^(\w+:)?\/\/([^\/?#]+)/,
	r20 = /%20/g,

	// Keep a copy of the old load method
	_load = jQuery.fn.load;

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

		// Don't do a request if no elements are being requested
		} else if ( !this.length ) {
			return this;
		}

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

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

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

			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
				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(rscript, ""))

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

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

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

		return this;
	},

	serialize: function() {
		return jQuery.param(this.serializeArray());
	},
	serializeArray: function() {
		return this.map(function() {
			return this.elements ? jQuery.makeArray(this.elements) : this;
		})
		.filter(function() {
			return this.name && !this.disabled &&
				(this.checked || rselectTextarea.test(this.nodeName) ||
					rinput.test(this.type));
		})
		.map(function( i, elem ) {
			var val = jQuery(this).val();

			return val == null ?
				null :
				jQuery.isArray(val) ?
					jQuery.map( val, function( val, i ) {
						return { name: elem.name, value: val };
					}) :
					{ name: elem.name, value: val };
		}).get();
	}
});

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

jQuery.extend({

	get: function( url, data, callback, type ) {
		// shift arguments if data argument was omited
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			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 ) {
		// shift arguments if data argument was omited
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = {};
		}

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

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

	ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		username: null,
		password: null,
		traditional: false,
		*/
		// Create the request object; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7 (can't request local files),
		// so we use the ActiveXObject when it is available
		// This function can be overriden by calling jQuery.ajaxSetup
		xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
			function() {
				return new window.XMLHttpRequest();
			} :
			function() {
				try {
					return new window.ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {}
			},
		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: {},
	etag: {},

	ajax: function( origSettings ) {
		var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
		
		var jsonp, status, data,
			callbackContext = origSettings && origSettings.context || s,
			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, s.traditional );
		}

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

		// Build temporary JSONP function
		if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
			jsonp = s.jsonpCallback || ("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 ] = 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(rts, "$1_=" + ts + "$2");

			// if nothing was replaced, add timestamp to the end
			s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
		}

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

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

		// Matches an absolute URL, and saves the domain
		var parts = rurl.exec( s.url ),
			remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);

		// If we're requesting a remote document
		// and trying to load JSON or Script with a GET
		if ( s.dataType === "script" && type === "GET" && remote ) {
			var head = document.getElementsByTagName("head")[0] || document.documentElement;
			var script = document.createElement("script");
			script.src = s.url;
			if ( s.scriptCharset ) {
				script.charset = s.scriptCharset;
			}

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

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

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;
						if ( head && script.parentNode ) {
							head.removeChild( script );
						}
					}
				};
			}

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

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

		var requestDone = false;

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

		if ( !xhr ) {
			return;
		}

		// 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 || origSettings && origSettings.contentType ) {
				xhr.setRequestHeader("Content-Type", s.contentType);
			}

			// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
			if ( s.ifModified ) {
				if ( jQuery.lastModified[s.url] ) {
					xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
				}

				if ( jQuery.etag[s.url] ) {
					xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
				}
			}

			// Set header so the called script knows that it's an XMLHttpRequest
			// Only send the header if it's not a remote XHR
			if ( !remote ) {
				xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
			}

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

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

			// close opended socket
			xhr.abort();
			return false;
		}

		if ( s.global ) {
			trigger("ajaxSend", [xhr, s]);
		}

		// Wait for a response to come back
		var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
			// The request was aborted
			if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
				// Opera doesn't call onreadystatechange before this point
				// so we simulate the call
				if ( !requestDone ) {
					complete();
				}

				requestDone = true;
				if ( xhr ) {
					xhr.onreadystatechange = jQuery.noop;
				}

			// The transfer is complete and the data is available, or the request timed out
			} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
				requestDone = true;
				xhr.onreadystatechange = jQuery.noop;

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

				var errMsg;

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

				// Make sure that the request was successful or notmodified
				if ( status === "success" || status === "notmodified" ) {
					// JSONP handles its own success callback
					if ( !jsonp ) {
						success();
					}
				} else {
					jQuery.handleError(s, xhr, status, errMsg);
				}

				// Fire the complete handlers
				complete();

				if ( isTimeout === "timeout" ) {
					xhr.abort();
				}

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

		// Override the abort handler, if we can (IE doesn't allow it, but that's OK)
		// Opera doesn't fire onreadystatechange at all on abort
		try {
			var oldAbort = xhr.abort;
			xhr.abort = function() {
				if ( xhr ) {
					oldAbort.call( xhr );
				}

				onreadystatechange( "abort" );
			};
		} catch(e) { }

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

		// Send the data
		try {
			xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
		} catch(e) {
			jQuery.handleError(s, xhr, null, e);
			// Fire the complete handlers
			complete();
		}

		// 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.call( callbackContext, data, status, xhr );
			}

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

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

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

			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active ) {
				jQuery.event.trigger( "ajaxStop" );
			}
		}
		
		function trigger(type, args) {
			(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
		}

		// 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.call( s.context || s, xhr, status, e );
		}

		// Fire the global callback
		if ( s.global ) {
			(s.context ? jQuery(s.context) : 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:" ||
				// Opera returns 0 when status is 304
				( xhr.status >= 200 && xhr.status < 300 ) ||
				xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
		} catch(e) {}

		return false;
	},

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

		if ( lastModified ) {
			jQuery.lastModified[url] = lastModified;
		}

		if ( etag ) {
			jQuery.etag[url] = etag;
		}

		// Opera returns 0 when status is 304
		return xhr.status === 304 || xhr.status === 0;
	},

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

		if ( xml && data.documentElement.nodeName === "parsererror" ) {
			jQuery.error( "parsererror" );
		}

		// Allow a pre-filtering function to sanitize the response
		// s is checked to keep backwards compatibility
		if ( s && s.dataFilter ) {
			data = s.dataFilter( data, type );
		}

		// The filter can actually parse the response
		if ( typeof data === "string" ) {
			// Get the JavaScript object, if JSON is used.
			if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
				data = jQuery.parseJSON( data );

			// If the type is "script", eval it in global context
			} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
				jQuery.globalEval( data );
			}
		}

		return data;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a, traditional ) {
		var s = [];
		
		// Set traditional to true for jQuery <= 1.3.2 behavior.
		if ( traditional === undefined ) {
			traditional = jQuery.ajaxSettings.traditional;
		}
		
		// If an array was passed in, assume that it is an array of form elements.
		if ( jQuery.isArray(a) || a.jquery ) {
			// Serialize the form elements
			jQuery.each( a, function() {
				add( this.name, this.value );
			});
			
		} else {
			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for ( var prefix in a ) {
				buildParams( prefix, a[prefix] );
			}
		}

		// Return the resulting serialization
		return s.join("&").replace(r20, "+");

		function buildParams( prefix, obj ) {
			if ( jQuery.isArray(obj) ) {
				// Serialize array item.
				jQuery.each( obj, function( i, v ) {
					if ( traditional || /\[\]$/.test( prefix ) ) {
						// Treat each array item as a scalar.
						add( prefix, v );
					} else {
						// If array item is non-scalar (array or object), encode its
						// numeric index to resolve deserialization ambiguity issues.
						// Note that rack (as of 1.0.0) can't currently deserialize
						// nested arrays properly, and attempting to do so may cause
						// a server error. Possible fixes are to modify rack's
						// deserialization algorithm or to provide an option or flag
						// to force array serialization to be shallow.
						buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
					}
				});
					
			} else if ( !traditional && obj != null && typeof obj === "object" ) {
				// Serialize object item.
				jQuery.each( obj, function( k, v ) {
					buildParams( prefix + "[" + k + "]", v );
				});
					
			} else {
				// Serialize scalar item.
				add( prefix, obj );
			}
		}

		function add( key, value ) {
			// If value is a function, invoke it and return its value
			value = jQuery.isFunction(value) ? value() : value;
			s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
		}
	}
});
var elemdisplay = {},
	rfxtypes = /toggle|show|hide/,
	rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/,
	timerId,
	fxAttrs = [
		// height animations
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		// width animations
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		// opacity animations
		[ "opacity" ]
	];

jQuery.fn.extend({
	show: function( speed, callback ) {
		if ( speed || speed === 0) {
			return this.animate( genFx("show", 3), speed, callback);

		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				var old = jQuery.data(this[i], "olddisplay");

				this[i].style.display = old || "";

				if ( jQuery.css(this[i], "display") === "none" ) {
					var nodeName = this[i].nodeName, display;

					if ( elemdisplay[ nodeName ] ) {
						display = elemdisplay[ nodeName ];

					} else {
						var elem = jQuery("<" + nodeName + " />").appendTo("body");

						display = elem.css("display");

						if ( display === "none" ) {
							display = "block";
						}

						elem.remove();

						elemdisplay[ nodeName ] = display;
					}

					jQuery.data(this[i], "olddisplay", display);
				}
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( var j = 0, k = this.length; j < k; j++ ) {
				this[j].style.display = jQuery.data(this[j], "olddisplay") || "";
			}

			return this;
		}
	},

	hide: function( speed, callback ) {
		if ( speed || speed === 0 ) {
			return this.animate( genFx("hide", 3), speed, callback);

		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				var old = jQuery.data(this[i], "olddisplay");
				if ( !old && old !== "none" ) {
					jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
				}
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( var j = 0, k = this.length; j < k; j++ ) {
				this[j].style.display = "none";
			}

			return this;
		}
	},

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

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

		if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
			this._toggle.apply( this, arguments );

		} else if ( fn == null || bool ) {
			this.each(function() {
				var state = bool ? fn : jQuery(this).is(":hidden");
				jQuery(this)[ state ? "show" : "hide" ]();
			});

		} else {
			this.animate(genFx("toggle", 3), fn, fn2);
		}

		return this;
	},

	fadeTo: function( speed, to, callback ) {
		return this.filter(":hidden").css("opacity", 0).show().end()
					.animate({opacity: to}, speed, callback);
	},

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

		if ( jQuery.isEmptyObject( prop ) ) {
			return this.each( optall.complete );
		}

		return this[ optall.queue === false ? "each" : "queue" ](function() {
			var opt = jQuery.extend({}, optall), p,
				hidden = this.nodeType === 1 && jQuery(this).is(":hidden"),
				self = this;

			for ( p in prop ) {
				var name = p.replace(rdashAlpha, fcamelCase);

				if ( p !== name ) {
					prop[ name ] = prop[ p ];
					delete prop[ p ];
					p = name;
				}

				if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
					return opt.complete.call(this);
				}

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

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

				if ( jQuery.isArray( prop[p] ) ) {
					// Create (if needed) and add to specialEasing
					(opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
					prop[p] = prop[p][0];
				}
			}

			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 ( rfxtypes.test(val) ) {
					e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );

				} else {
					var parts = rfxnum.exec(val),
						start = e.cur(true) || 0;

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

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

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

						e.custom( start, end, unit );

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

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

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

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

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

					timers.splice(i, 1);
				}
			}
		});

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

		return this;
	}

});

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

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

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

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

		return opt;
	},

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

	timers: [],

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

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

});

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

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

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

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

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

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

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

		t.elem = this.elem;

		if ( t() && jQuery.timers.push(t) && !timerId ) {
			timerId = setInterval(jQuery.fx.tick, 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.style( this.elem, this.prop );
		this.options.show = true;

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

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

	// Simple 'hide' function
	hide: function() {
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.style( this.elem, 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(), done = true;

		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;

			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
					var old = jQuery.data(this.elem, "olddisplay");
					this.elem.style.display = old ? old : this.options.display;

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

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

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

				// Execute the complete function
				this.options.complete.call( this.elem );
			}

			return false;

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

			// Perform the easing function, defaults to swing
			var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
			var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
			this.pos = jQuery.easing[specialEasing || defaultEasing](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, {
	tick: function() {
		var timers = jQuery.timers;

		for ( var i = 0; i < timers.length; i++ ) {
			if ( !timers[i]() ) {
				timers.splice(i--, 1);
			}
		}

		if ( !timers.length ) {
			jQuery.fx.stop();
		}
	},
		
	stop: function() {
		clearInterval( timerId );
		timerId = null;
	},
	
	speeds: {
		slow: 600,
 		fast: 200,
 		// Default speed
 		_default: 400
	},

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

		_default: function( fx ) {
			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
				fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
			} else {
				fx.elem[ fx.prop ] = fx.now;
			}
		}
	}
});

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.animated = function( elem ) {
		return jQuery.grep(jQuery.timers, function( fn ) {
			return elem === fn.elem;
		}).length;
	};
}

function genFx( type, num ) {
	var obj = {};

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

	return obj;
}
if ( "getBoundingClientRect" in document.documentElement ) {
	jQuery.fn.offset = function( options ) {
		var elem = this[0];

		if ( options ) { 
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}

		if ( !elem || !elem.ownerDocument ) {
			return null;
		}

		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}

		var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement,
			clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
			top  = box.top  + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop ) - clientTop,
			left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;

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

} else {
	jQuery.fn.offset = function( options ) {
		var elem = this[0];

		if ( options ) { 
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}

		if ( !elem || !elem.ownerDocument ) {
			return null;
		}

		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}

		jQuery.offset.initialize();

		var offsetParent = elem.offsetParent, prevOffsetParent = elem,
			doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
			body = doc.body, defaultView = doc.defaultView,
			prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
			top = elem.offsetTop, left = elem.offsetLeft;

		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
			if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
				break;
			}

			computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
			top  -= elem.scrollTop;
			left -= elem.scrollLeft;

			if ( elem === offsetParent ) {
				top  += elem.offsetTop;
				left += elem.offsetLeft;

				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) {
					top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
					left += parseFloat( computedStyle.borderLeftWidth ) || 0;
				}

				prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
			}

			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
				top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
				left += parseFloat( computedStyle.borderLeftWidth ) || 0;
			}

			prevComputedStyle = computedStyle;
		}

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

		if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
			top  += Math.max( docElem.scrollTop, body.scrollTop );
			left += Math.max( docElem.scrollLeft, body.scrollLeft );
		}

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

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

		jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );

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

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

		checkDiv.style.position = "fixed", checkDiv.style.top = "20px";
		// safari subtracts parent border width here which is 5px
		this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
		checkDiv.style.position = checkDiv.style.top = "";

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

		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);

		body.removeChild( container );
		body = container = innerDiv = checkDiv = table = td = null;
		jQuery.offset.initialize = jQuery.noop;
	},

	bodyOffset: function( body ) {
		var top = body.offsetTop, left = body.offsetLeft;

		jQuery.offset.initialize();

		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
			top  += parseFloat( jQuery.curCSS(body, "marginTop",  true) ) || 0;
			left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0;
		}

		return { top: top, left: left };
	},
	
	setOffset: function( elem, options, i ) {
		// set position first, in-case top/left are set even on static elem
		if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) {
			elem.style.position = "relative";
		}
		var curElem   = jQuery( elem ),
			curOffset = curElem.offset(),
			curTop    = parseInt( jQuery.curCSS( elem, "top",  true ), 10 ) || 0,
			curLeft   = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0;

		if ( jQuery.isFunction( options ) ) {
			options = options.call( elem, i, curOffset );
		}

		var props = {
			top:  (options.top  - curOffset.top)  + curTop,
			left: (options.left - curOffset.left) + curLeft
		};
		
		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};


jQuery.fn.extend({
	position: function() {
		if ( !this[0] ) {
			return null;
		}

		var elem = this[0],

		// Get *real* offsetParent
		offsetParent = this.offsetParent(),

		// Get correct offsets
		offset       = this.offset(),
		parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { 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  -= parseFloat( jQuery.curCSS(elem, "marginTop",  true) ) || 0;
		offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0;

		// Add offsetParent borders
		parentOffset.top  += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth",  true) ) || 0;
		parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0;

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

	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || document.body;
			while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent;
		});
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
	var method = "scroll" + name;

	jQuery.fn[ method ] = function(val) {
		var elem = this[0], win;
		
		if ( !elem ) {
			return null;
		}

		if ( val !== undefined ) {
			// Set the scroll offset
			return this.each(function() {
				win = getWindow( this );

				if ( win ) {
					win.scrollTo(
						!i ? val : jQuery(win).scrollLeft(),
						 i ? val : jQuery(win).scrollTop()
					);

				} else {
					this[ method ] = val;
				}
			});
		} else {
			win = getWindow( elem );

			// Return the scroll offset
			return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
				jQuery.support.boxModel && win.document.documentElement[ method ] ||
					win.document.body[ method ] :
				elem[ method ];
		}
	};
});

function getWindow( elem ) {
	return ("scrollTo" in elem && elem.document) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {

	var type = name.toLowerCase();

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

	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function( margin ) {
		return this[0] ?
			jQuery.css( this[0], type, false, margin ? "margin" : "border" ) :
			null;
	};

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		var elem = this[0];
		if ( !elem ) {
			return size == null ? null : this;
		}
		
		if ( jQuery.isFunction( size ) ) {
			return this.each(function( i ) {
				var self = jQuery( this );
				self[ type ]( size.call( this, i, self[ type ]() ) );
			});
		}

		return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window?
			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
			elem.document.body[ "client" + name ] :

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

				// Get or set width or height on the element
				size === undefined ?
					// Get width or height on the element
					jQuery.css( elem, type ) :

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

});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

})(window);




/*************************************************************************************************
	ECOMPANY - ARQUIVO TEMPOR�RIO AT� ACERTOS AJAX JCOMPANY
*************************************************************************************************/


/**
 * Arquivo geral de fun??es javascript do jCompany.
 * @author Rodrigo Magno Xy
 * @author Cl?udia Seara
 * @version 3.0
 * @since jCompany 1.0
 * @lastmodified 21/02/2006
 */

/**
* Vari?veis globais de utiliza??o geral
* @deprecated NNav Vari?vel que indica o browser como Netscape. Utilizada para
* compatibiliza??o com c?digos antigos [Boolean]
* @variable debugNav Utiliza para ligar/desligar debug de vari?veis globais [Boolean]
* @variable AgntUsr  Define qual o browser utilizado [String]
* @variable AppVer Define qual vers?o do browser utilizado [String]
* @variable DomYes Define se o browser utilizado aceita a fun??o "getElementById" [Boolean]
* @variable NavYes Define se o browser ? compat?vel com engine Mozilla [Boolean]
* @variable ExpYes Define se o browser ? compat?vel com Internet Explorer [Boolean]
* @variable Opr Define se o browser ? compat?vel com Opera[Boolean]
* @variable interval Utilizada para intervalos de tempo [Object]
*/


var NNav = ((navigator.appName == "Netscape"));
var debugNav = false;
var AgntUsr	= navigator.userAgent.toLowerCase();
var AppVer	= navigator.appVersion.toLowerCase();
var DomYes	= document.getElementById ? 1:0;
var NavYes	= AgntUsr.indexOf('mozilla') != -1 && AgntUsr.indexOf('compatible') == -1 ? 1:0;
var ExpYes	= AgntUsr.indexOf('msie') != -1 ? 1:0;
var Exp7Yes	= ""+AgntUsr.indexOf("msie 7") != -1 ? 1:0;
var Exp8Yes	= ""+AgntUsr.indexOf("msie 8") != -1 ? 1:0;
var Opr		= AgntUsr.indexOf('opera')!= -1 ? 1:0;
var interval;
if(debugNav){
	alert("Agente: "+AgntUsr+" - Versao: "+AppVer+"\n"+
	"Netscape/Mozilla: "+NavYes+"\n"+
	"Internet Explorer: "+ExpYes+"\n"+
	"Opera: "+Opr);
	var i = i;
}

var tecnologia = "Struts";

function setTecnologia(tecnologiaArg) {
	tecnologia = tecnologiaArg;
}

/**
* Construtor para objeto PlcGeral
*/
function PlcGeral(){}
/**
* @variable plcGeral Instancia do objeto PlcGeral
*/
var plcGeral = new PlcGeral();
/**
* Fun??o para permitir utiliza??o do evento onload por diversos scripts
*/
PlcGeral.prototype.eventOnLoad = function(){}
/**
* Fun??o que ser? executada ap?s devolu??o de sele??o popup
*/
PlcGeral.prototype.antesDevolveSelecaoPopup = function(listaValores,urlSelecao){ return true;};
/**
* Fun??o que ser? executada ap?s devolu??o de sele??o popup
*/
PlcGeral.prototype.aposDevolveSelecaoPopup = function(){};
/**
* Fun??o que ser? executada antes l�gicas in�cio p�gina
*/
PlcGeral.prototype.antesIniciarPagina = function(){};
/**
* Fun��o que ser� executada ap�s devolu��o de sele��o popup para montar dados do track change
*/
PlcGeral.prototype.aposDevolveSelecaoPopupInformaTrackChange = function(){};
/**
* Vari?vel que contem o contexto da aplica??o
*/
PlcGeral.prototype.contextPath = "";
/**
* Mensagem de erro para obrigat?rios
*/
PlcGeral.prototype.obrigatorioMsg = "";
/**
* Express?o regular para valores alfab?ticos (sem n?meros)
*/
PlcGeral.prototype.alfabeticoPattern = /^[^0-9]+$/;
/**
* Express?o regular para valores num?ricos
*/
PlcGeral.prototype.numericoPattern =  /\d/;
/**
* Express?o regular para valores monetarios
*/
PlcGeral.prototype.currencyPattern =  /[][,]{1}\d{2}/;

/**
* Express?o regular para data
*/
PlcGeral.prototype.dataPattern =  /\d{2}\/\d{2}\/\d{4}/;
/**
* Express?o regular para data/hora
*/
PlcGeral.prototype.datahoraPattern =  /\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}/;

//Indica se menu de sistema est? ativo para navega??o via setas
PlcGeral.prototype.MENU_ATIVO = false;

PlcGeral.prototype.formSubmit = function(action,evento){
		var form = getForm();
		form.action=plcGeral.contextPath+action+".do?evento="+evento;
		form.submit();
	}
	
PlcGeral.prototype.exportaPopup = function(contextoAplicacao,pStrutsAction){

	var campoExportaPlc 	= getCampo("exportaPlc");
	var parentForm 			= getForm();

	var win 				= janela("");
	var	conteudo  			= '<html><body> <form name="inicialForm" method="post" action="'+ contextoAplicacao +  pStrutsAction + '.do?evento=F9-Pesquisar&isExportacaoPlc=S&fmtPlc=' + campoExportaPlc.value + '">'; 
	
	for (var i = 0; i < parentForm.elements.length; i++) 
		conteudo +=  ' <input type="hidden" name="' + parentForm.elements[i].name + '" value="' + parentForm.elements[i].value +'" id="' + parentForm.elements[i].name + '" >';
		
	conteudo += '</form> </body></html>';
	
	
	win.document.write(conteudo);
	var theForm 			= win.document.forms[0]; //document.getElementById('inicialForm'); 
	theForm.style.display 	= 'none';
	theForm.submit();
	
	if(campoExportaPlc)
		campoExportaPlc.selectedIndex = 0;
	
}

PlcGeral.prototype.importaJavascript = function(caminhoArquivo){

	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = caminhoArquivo;
	document.getElementsByTagName('head')[0].appendChild(script);
};

//plcGeral.importaJavascript("/ecp/plc/javascript/DP_Debug.js");

/**
 * Fun??o para executar outras fun??es no onload da p?gina
 * @variable campoFocus Vari?vel que identifica campo a ser posicionado
 * @variable interval Utilizada para intervalos de tempo [Object]
 * @see moverFoco
 * @see testaAvisoOnline
 * @see setUpOnFocusHandlers
 * @see gravaResolucaoVideo
 * @see gerarImpressaoInteligente
 * @see executarFuncaoOnLoad
 */
function iniciarPagina()
{
	plcGeral.antesIniciarPagina();
	moverFoco(); //Move foco automaticamente
	testaAvisoOnline(); //Envia aviso online
	setUpOnFocusHandlers(); //Configura evento onfocus automaticamente
	gravaResolucaoVideo(); // Grava resolucao de video para uso no jcpmonitor.
	if(typeof getParametroUrl("impIntel") != "undefined" && 
	getParametroUrl("impIntel").toLowerCase() == "s")
		gerarImpressaoInteligente(); //Executa impressao inteligente
	executarFuncaoOnLoad(); //Executa fun??es configuradas para onload da p?gina
	mantemAbaSelecionada();
	
}

/**
* Grava resolu??o de v?deo do cliente no cookie.
* Essa informa??o ? utilizada pelo jcpmonitor.
*/
function gravaResolucaoVideo() {
	try{
	document.cookie='resolucaoPlc='+screen.width+'x'+screen.height+';';
	}catch(e){}
}

/**
 * Fun??o mover o foco automaticamente
 * @variable campoFocus Vari?vel que identifica campo a ser posicionado
 */
function moverFoco(){

	if(getCampoFocus() == "")
		setTimeout("testaCampos()",20)
	else
		setTimeout("setFocus(getCampoFocus(), getCampoFocusSelecionar())",20);
}

function setAncora(ancora){
	document.location.hash = ancora;
}

/**
 * Fun??o posicionar foco em campo espec?fico
 * @variable campoFocus Vari?vel que identifica campo a ser posicionado [String]
 * @param nomeCampo Nome do campo a ser focado [String,OB]
 */
var campoFocus = "";
var campoFocusSelecionar = false;
function setCampoFocus(nomeCampo, selecionar){
	this.campoFocus = nomeCampo;
	setCampoFocusSelecionar(selecionar);	
}

function getCampoFocus(){
	return this.campoFocus;
}
function setCampoFocusSelecionar(selecionar){
	if(selecionar && typeof selecionar != "undefined" && selecionar != "")
		this.campoFocusSelecionar = true;
}
function getCampoFocusSelecionar(){
	this.campoFocusSelecionar
}

/**
 * Fun��o que retorna o objeto window correto da janela atual, para evitar problemas com IFrame PPR.
 * Implementado por Bruno Grossi - 29/03/2007
 */
function getRootWindow() {
	return "_pprIFrame" != window.name ? window : window.parent;
}

/**
 * Fun��o que retorna o document da janela atual, para evitar problemas com IFrame PPR.
 * Implementado por Bruno Grossi - 29/03/2007
 */
function getRootDocument() {
	return getRootWindow().document;
}

/**
 * Fun??o para retornar um objeto que representa um form da p?gina
 * @param form Nome do form, caso n?o seja o form padr?o. [String,OP]
 * @see getVarGlobal
 * @return form Objeto form [Object]
 */
function getForm(form){

	var sessForm = getVarGlobal("form");
	// Se houver um opener recupera o form deste
	var parentForm = "";
	if(opener && opener != null && form != null){
		try{
			var parentForm = opener.getVarGlobal("parentForm");
			return parentForm;
		}catch(e){}
	}	
	if(form != "" && form != 0 && ""+form != "undefined" && form != null)
		form = eval("document.forms['"+form+"']");
	else if(sessForm != "" && sessForm != 0 && ""+sessForm != "undefined" && ""+sessForm != "null")
		form = eval("document.forms['"+sessForm+"']");
	else
		form = eval("document.forms[0]");
	return form;
}

/**
 * Fun??o para retornar um objeto que representa um campo da p?gina
 * @param campo Nome do campo que se quer recuperar. [String, OB]
 * @param form Nome do form, caso n?o seja o form padr?o. [String,OP]
 * @see getForm
 * @return campo Objeto campo [Object]
 */
function getCampo(campo, form)
{
	form = getForm(form);
	if(form && form.elements!=null)
		campo = form.elements[campo];
	return campo;
}

/**
 * Fun??o para envia mensagem de confirma??o para  exclus?o de registro e dispara
 * bot?o associado ? exclus?o
 * @param acao A??o que determina bot?o de exclus?o a ser disparado [String]
 * @see disparaBotaoAcao
 */
function confirmaExclusao(acao)
{
	if (confirm('Confirma a Exclus?o do Registro?'))
		disparaBotaoAcao(acao);
}

/**
 * Fun??o dispara clique em um bot?o da p?gina conforme acao passada.<b>
 * Se for passado tamb?m o par?metro id o bot?o clicado deve ter este valor declarado
 * @param acao A??o que determina bot?o de exclus?o a ser disparado [String, OB]
 * @param id Identificador do bot?o a ser disparado [String, OP]
 * @return disparou Retorna true se bot?o foi disparado ou false caso contr?rio
 */
function disparaBotaoAcao(acao, id)
{
	if (id == "" || ""+id == "undefined")
		id = "botao_menu";

	var numElements;
	var elementValue;
	var disparou = false;
	var form = getForm(form);
	var elements;

	if(form.elements[id].length)
		elements = form.elements[id];
	else
		elements = form.elements;

	if (form)
	{
		numElements = elements.length;
		if(numElements > 0)
		{
			for(i=0; i < numElements; i++)
			{
				elementValue = elements[i].value;
				if(elementValue == acao)
				{
					elements[i].click();
					i =numElements;
					disparou = true;
				}
			}
		}
	}
	else if (eval(form.elements[acao]))
		form.elements[acao].click();

	return disparou;
}

/**
 * Fun??o de alerta em janela com mensagem<br>
 * Passo 1: Colar as linha abaixo no fim da p?gina:<br><dd>
 *	<blockquote><code>&lt;!-- IN?CIO DIV DE ALERTA --&gt;<br>
 *		<blockquote>&lt;div  ID=ALERTA class="janela_msg" style="visibility='hidden'"&gt;<br>
 *  		<blockquote>&lt;table width="250" height="100%"  border="0" cellpadding="0" cellspacing="0"&gt;<br>
 * 				<blockquote>&lt;tr\&gt;<br>
 *  						&lt;td width="239" class="janelaMsgTit" ID=TITULO&gt;&nbsp;&lt;/td&gt;<br>
 *  						&lt;td width="11" align="center" valign="middle" class="janelaMsgTit"&gt;<br>
 *  						<blockquote>&lt;a href="#" onclick="showDiv('ALERTA', false); return false;"&gt;<br>
 *  									&lt;img align="ABSMIDDLE" alt="Clique para fechar esta janela" border="0" height="11" hspace="0" src="&lt;%=request.getContextPath()%&gt;/midia/g_ico_fechar.gif" vspace="0" width="11"&gt;<br>
 *  									&lt;a&gt;
 * 							</blockquote><br>
 *							&lt;/td&gt;&lt;/tr&gt;<br>
 *  						&lt;tr&gt;<br>
 *							&lt;td colspan="2" class="janelaMsgSubtit" ID=SUBTITULO&gt;&lt;/td&gt;<br>
 * 							&lt;/tr&gt;<br>
 * 							&lt;tr&gt;<br>
 *  						&lt;td colspan="2" valign="top" class="janelaMsgConteudo" ID=CONTEUDO&gt;&nbsp;&lt;/td&gt;
 * 							&lt;/tr&gt;
 * 			</blockquote>
 *			&lt;/table&gt;<br>
 *		</blockquote>
 *	&lt;/div&gt;<br>
 *	</blockquote>
 *	<blockquote>&lt;!-- FIM DIV DE ALERTA --&gt;</blockquote></code><><br>
 *  Chamada: <br><dd><code>&lt;a href="#" onClick="janelaMsg('ALERTA','MEU TITULO','MEU SUBTITULO','MEU CONTEUDO'); return false;"&gt;Link&lt;/a&gt;<code>
 *  @param div Div onde a mensagem vai ser mostrada [String]
 *  @param titulo Titulo da janela de mensagem [String]
 *  @param subtitulo Sub-Titulo da janela de mensagem [String]
 *  @param conteudo Conteudo da mensagem [String]
 *  @param evt N?o utilizado (RETIRAR)
 *  @see showDiv
 */
function janelaMsg(div, titulo, subtitulo, conteudo, evt)
{
	showDiv(div, true,evt);
	var sufix = "";
	var i = div.indexOf("_");
	if(i >= 0)
		sufix = div.substring(i,div.length);
	var tit 	= eval("TITULO"+sufix);
	var subtit 	= eval("SUBTITULO"+sufix);
	var cont 	= eval("CONTEUDO"+sufix);

	tit.innerHTML = titulo;
	subtit.innerHTML = subtitulo;
	cont.innerHTML = conteudo;
}

/**
* Comuta paineis entre visiveis e invisiveis
* @since jCompany 3.03
* @param ajuda Objeto que representa a janela de ajuda [String,OB]
* @see showFormSelect
*/
function janelaPainel(painel)
{
	if (painel.style.display!=""){
		if (painel.style.display=="block"){
			painel.style.display="none";
			hideFormSelect();
		}else{
			painel.style.display="block";
			showFormSelect();
		}
	}else if (painel.style.visibility!=""){
		if (painel.style.visibility =='hidden'){
			painel.style.visibility = 'visible';
			hideFormSelect();
		}else{
			painel.style.visibility = 'hidden';
			showFormSelect();
		}
	}
}

/**
* Fun??o para esconder / mostrar qualquer elemento da tela que contenha um id
* @param idObj Objeto para esconder / mostrar [String,OB]
* @param visibilidade Define se o objeto vai ser escondido ou mostrado [Boolean,OB] {true|false}
* @TODO Alterar para chamar getElementoStyle()
*/
function setVisible(idObj, visibilidade)
{
	var obj = eval("document.all['"+idObj+"']");
	if(obj)
		obj.style.visibility = visibilidade;
}

/**
 * Fun??o que mostra/esconde div de mensagem
 *  @param div Nome do div onde a mensagem vai ser mostrada [String,OB]
 *  @param show Vari?vel que indica define se o div ser? mostrado ou escondido [Boolean,OB] {true|false}
 */
function showDiv(div, show)
{
	var wDiv = 200; //Largura do div declarada no CSS CLASS = janelaMsg
	var hDiv = 200; //Altura do div declarada no CSS CLASS = janelaMsg
    var ie4=document.all && navigator.userAgent.indexOf("Opera")==-1;
    var ns6=document.getElementById&&!document.all;
    var ns4=document.layers;
    var eventX=ie4? event.clientX : ns6? e.clientX : e.x;
    var eventY=ie4? event.clientY : ns6? e.clientY : e.y;
	var menuobj = eval(div);
	menuobj.contentwidth = wDiv;
	menuobj.contentheight = hDiv;
	menuobj.thestyle=(ie4||ns6)? menuobj.style : menuobj;

	if(show)
	{
			menuobj.style.visibility='visible';
           //Find out how close the mouse is to the corner of the window
           var rightedge=ie4? document.body.clientWidth-eventX : window.innerWidth-eventX;
           var bottomedge=ie4? document.body.clientHeight-eventY : window.innerHeight-eventY;

           //if the horizontal distance isn't enough to accomodate the width of the context menu
           if (rightedge<menuobj.contentwidth)
           //move the horizontal position of the menu to the left by it's width
	           menuobj.thestyle.left=ie4? document.body.scrollLeft+eventX-menuobj.contentwidth : ns6? window.pageXOffset+eventX-menuobj.contentwidth : eventX-menuobj.contentwidth;
           else
           //position the horizontal position of the menu where the mouse was clicked
        	   menuobj.thestyle.left=ie4? document.body.scrollLeft+eventX : ns6? window.pageXOffset+eventX : eventX;

           //same concept with the vertical position
           if (bottomedge<menuobj.contentheight)
    	       menuobj.thestyle.top=ie4? document.body.scrollTop+eventY-menuobj.contentheight : ns6? window.pageYOffset+eventY-menuobj.contentheight : eventY-menuobj.contentheight;
           else
	           menuobj.thestyle.top=ie4? document.body.scrollTop+event.clientY : ns6? window.pageYOffset+eventY : eventY;
           menuobj.thestyle.visibility="visible";
           return false;
	}
	else{
		menuobj.style.visibility='hidden';
	}
}


/**
* Fun??o para colocar foco no primeiro campo v?lido da p?gina.
* Ap?s o onload da p?gina a fun??o procura nos campos da p?gina um campo v?lido para focar
* @see setFocus
*/
function testaCampos(){

	var numForms = document.forms.length;
	var numElements = 0;
	var primeiroCampo = "";
	var campoFocado	= null;

	if(getVarGlobal("trSelecao") != null)
		return;
	if(document.location.hash && document.location.hash != null && document.location.hash.indexOf("#") > -1)	
		return;
		
	for(i=0; i < numForms; i++)
	{
		numElements = document.forms[i].elements.length;

		for(j=0; j < numElements; j++)
		{
			if(document.forms[i].elements[j].getAttribute("inibeFoco") != 'S' &&
			   document.forms[i].elements[j].className.indexOf("inibeFoco") == -1 &&
			   (typeof document.forms[i].elements[j].getAttribute("id") != 'undefined' && 
			   (document.forms[i].elements[j].getAttribute("id") == null ||
			   document.forms[i].elements[j].getAttribute("id").indexOf(":inibeFoco") == -1))){
				if((document.forms[i].elements[j].type=="text" ||
					document.forms[i].elements[j].type=="password" ||
					document.forms[i].elements[j].type=="file" ||
					document.forms[i].elements[j].type=="textarea") &&
					document.forms[i].elements[j].type != "hidden" &&
					!document.forms[i].elements[j].readOnly &&
					!document.forms[i].elements[j].disabled){
					if(document.forms[i].elements[j].value == ""){
						try{
							primeiroCampo = "";
							setFocus(document.forms[i].elements[j].name);
							campoFocado = document.forms[i].elements[j];
						}catch (e){}
						i = numForms;
						j = numElements;
					}else if(primeiroCampo == "" && document.forms[i].elements[j].type != "hidden" &&
					!document.forms[i].elements[j].readOnly && !document.forms[i].elements[j].disabled)
						primeiroCampo = document.forms[i].elements[j];
				}
				else if(document.forms[i].elements[j].type == "radio"){
					//setFocus(document.forms[i].elements[j].name);
				}
				else if((document.forms[i].elements[j].type == "select-one" ||
					document.forms[i].elements[j].type == "select-multiple") &&
					document.forms[i].elements[j].options.length > 0 &&
					document.forms[i].elements[j].options.selectedIndex <= 0 &&
					!document.forms[i].elements[j].readOnly &&
					!document.forms[i].elements[j].disabled){
					try {
						primeiroCampo = "";
						document.forms[i].elements[j].focus();
						document.forms[i].elements[j].options[0].selected = true;
						campoFocado = document.forms[i].elements[j];
					}catch (e){}
					i = numForms;
					j = numElements;
				}else if(primeiroCampo == "" && typeof document.forms[i].elements[j].type != 'undefined' &&
					document.forms[i].elements[j].type != "button" &&
					document.forms[i].elements[j].type != "submit" &&
					document.forms[i].elements[j].type != "hidden" &&
					document.forms[i].elements[j].type != "radio" &&
					document.forms[i].elements[j].type != "checkbox" &&
					!document.forms[i].elements[j].readOnly &&
					!document.forms[i].elements[j].disabled)
						primeiroCampo = document.forms[i].elements[j];
			}
		}
	}
	if(primeiroCampo != ""){
		setFocus(primeiroCampo.name, true)
		campoFocado = primeiroCampo;
	}
	setVarGlobal("campoFocadoPlc", campoFocado);	
}

/**
* Fun??o para testar se campo permite foco
*/
function permiteFocus(nomeCampo){

	var campo = getCampo(nomeCampo);
	
	if(campo && 
		((campo.getAttribute("inibeFoco") != 'S' &&
		campo.className.indexOf("inibeFoco") < 0) ||
		(typeof campo.getAttribute("id")!= 'undefined' && campo.getAttribute("id") != null &&
		  campo.getAttribute("id").indexOf(":inibeFoco")>-1)) &&
		!campo.readOnly && !campo.disabled){
		if((campo.type=="text" ||
			campo.type=="password" ||
			campo.type=="file" ||
			campo.type=="textarea") &&
			campo.type != "hidden" &&
			campo.value == ""){
			
			return true;	
		}
		else if((campo.type == "select-one" ||
			campo.type == "select-multiple") &&
			campo.options.length > 0 &&
			campo.options.selectedIndex <= 0){

			return true;
		}
	}
	
	return false;
}

function focarCampoDetalhe(nomeDetalhe, campoFoco, numDetalhes){
	try {
		for(var d = 0; d < numDetalhes; d++){
			var campoDetalhe = campoFoco.indexOf("[0]") > -1 ? campoFoco.replace("[0]","["+d+"]") : 
								nomeDetalhe+"["+d+"]."+campoFoco;
			//alert("FOCARCAMPODETALHE - CAMPODETALHE: "+campoDetalhe)								
			if(permiteFocus(campoDetalhe)){
				setCampoFocus(campoDetalhe);
				break;
			}	
		}
	}
	catch(e) {}
}

function setFocoDetalhe(){
	//alert("SETFOCODETALHE")								
	var idPortlet 	= getVarGlobal("idPortlet");
	var campoFoco 	= getVarGlobal("campoFoco_"+idPortlet);
	//alert("SETFOCODETALHE - IDPORTLET: "+idPortlet)								
	//alert("SETFOCODETALHE - CAMPOFOCO: "+campoFoco)								
	focarCampoDetalhe(idPortlet, campoFoco,parseInt(getVarGlobal("numDetalhes_"+idPortlet)))
}

/**
* Fun??o de registro dos dados de avisos on-line
* @variable avisoArray Array que guarda dados do aviso on-line
* @param url Url da popup do aviso [String,OB]
* @param props Propriedades da popup do aviso [String]
*/

var avisoArray = new Array();
function regAvisoOnline(url, props){
	this.url	= url;
	this.props	= props;
}

/**
* Fun??o para cria??o de avisos online
* @variable avisoArray Array onde s?o guardados os dados do aviso on-line
* @param url Url da popup do aviso [String,OB]
* @param props Propriedades da popup do aviso [String]
* @see regAvisoOnline
*/
function setAvisoOnline(url, props)
{
	avisoArray[avisoArray.length] = new regAvisoOnline(url, props);
}

/**
* Fun??o para testar se existe avisos online e abrir popup do mesmo
* @variable avisoArray Array de onde s?o retiradas os dados do aviso on-line
* @see janela
*/
function testaAvisoOnline()
{
	if(avisoArray.length > 0)
		janela(avisoArray[0].url,"","",avisoArray[0].props);
}


/**
* Fun??o que altera o CLASS de um elemento
* Colar dentro do elemento: styleId="botao_menu" onmouseover="try{animar(event , \'2\')}catch(e){}"  onmouseout="try{animar(event, \'\')}catch(e){}"
* @param e Evento que originou a chamada da fun??o. [Object,OB]
* @param classe Nome da classe a ser trocada dinamicamente [String,OB]
*/
function animar(e, classe)
{
	var obj;
	if(NavYes)
		obj = e.target;
	else
		obj = e.srcElement;
	var originalClass = obj.id;
	if(originalClass){
		if(originalClass.indexOf("2") != -1)
			originalClass = originalClass.substring(0, originalClass.length-1);

		classe = originalClass+classe;
		//if (DomExp)
			obj.id = classe;
	}
}

/**
* Fun??o para abrir um janela do tipo POP-UP
* Chamada: <br><dd><code>&lt;a href='#' onclick='janela("url_janela","width","height","props"); return false;'&gt;</code>
* @param url Endere?o para abertura da janela
* @param wa Largura da janela. [String, OP]
* @param ha Altura da janela. [String, OP]
* @param props Propriedades da janela. Informar no lugar de <I>wa</I> e <I>ha</I> que devem ser informados como "" [String, OP]
* @param alvo Inst?ncia para abertura. [String]
* @param max Indica que a janela deve abrir maximizada. [String]
* @param posX posi??o x onde a janela deve ser criada. [String, OP]
* @param posY posi??o y onde a janela deve ser criada. [String, OP]
*/
function janela(url,wa,ha,props,alvo,max,posX,posY) {
	var w = 720;
	var h = 350;
	var t = "";
	var p = "";
	var win;
	
	if (arguments[1] && arguments[1] != "" && arguments[1] != "0") //Largura
		w = wa;
	if (arguments[2] && arguments[2] != "" && arguments[2] != "0") //Altura
		h = ha;
	p = "resizable=yes,scrollbars=yes,width="+w+",height="+h;
	if (arguments[3] && arguments[3] != "") //Propriedades
		p = props;
		
	if(location.pathname.indexOf(".do") >= 0)
		t = location.pathname.substring(0,location.pathname.indexOf(".do"));
	t = t.replace(/\//g,"_").replace(/\./g,"_");
	if (arguments[4] && arguments[4] != "") //Alvo
		t = alvo;

	win = window.open(url,t,p);
	if(!win){
		alertaBloqueioPopup();
		return null;
	}

	if (arguments[5] && arguments[5] != "" && arguments[5] != "N") //Redimensiona
	{
		//Retirar ap?s resolver problema de privil?gios para Mozilla
		if(!NavYes)
			redimensiona(win);
	}
	else if(url.indexOf("http") == -1 && (props == "" || ""+props == "undefined"))
	{
		var posCentro = getPosicaoCentro(w,h,posX, posY);
		win.moveTo(posCentro.moveCentroX,posCentro.moveCentroY);
	}

	return win;
}

function bloqueioPopupAtivo(){
	 var pop = janela('','','','width=1,height=1,left=-100,top=-100,scrollbars=no');
	 if(pop){
		pop.close();
	    return false;
	 }
	 else
	    return true;
}

function alertaBloqueioPopup(){
  alert('Foi detectado que o recurso de bloqueio de popup do seu browser pode estar ativo.\nPor favor desative este recurso e repita o comando anterior.');	
}
/**
* Fun??o que recupera o correto posicionamento central para uma janela popup
* @param w Largura da janela. [String, OB]
* @param h Altura da janela. [String, OB]
* @param posX posi??o x onde a janela deve ser criada. [String, OP]
* @param posY posi??o y onde a janela deve ser criada. [String, OP]
* @return posicaoCentro Objeto com os valores para posicionamento da janela [Object]
*/
function getPosicaoCentro(w,h,posX, posY){

	var moveCentroX 	= 0;
	var moveCentroY 	= 0;

	if( (posX && posX != "") || (posY && posY != "") ) {
		if(posX && posX != "")
			moveCentroX = posX;
		if(posY && posY != "")
			moveCentroY = posY;
	}
	else {
		//Centralizar janela popup
		if(NavYes)
		{
			moveCentroX 	= window.screenX + ((window.outerWidth - w) / 2);
			moveCentroY 	= window.screenY + ((window.outerHeight - h) / 2);
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
		}
		else
		{
			moveCentroX = (screen.availWidth/2);
			moveCentroX = moveCentroX - (w/2);
			moveCentroY = (screen.availHeight/2);
			moveCentroY = moveCentroY - (h/2);
		}
	}

	var posicaoCentro = new Object(moveCentroX, moveCentroY);
	posicaoCentro.moveCentroX 	= moveCentroX;
	posicaoCentro.moveCentroY 	= moveCentroY;
	return posicaoCentro;
}

/**
* Fun??o que recupera o correto posicionamento do mouse na tela
* @return posicaoCentro Objeto com os valores para posicionamento da janela [Object]
*/
//document.onmousemove = getMouseXY;
//if (!ExYes) 
//	document.captureEvents(Event.MOUSEMOVE)
function getPosicaoMouse(evt){

	var posX = 0;
	var posY = 0;
	if (ExpYes) { // grab the x-y pos.s if browser is IE
		posX = evt.clientX;// + document.body.scrollLeft - document.Show.offsetX.value;
		posY = evt.clientY;// + document.body.scrollTop - document.Show.offsetY.value;
	}
	else {  // grab the x-y pos.s if browser is NS
		posX = evt.pageX;
		posY = evt.pageY;
	}  
	var posicaoMouse = new Object(posX, posY);
	posicaoMouse.posX 	= posX;
	posicaoMouse.posY 	= posY;
	return posicaoMouse;
}

/**
 * Recupera o tamanho da janela atual
 * @variable NNav Vari?vel que identifica navegador [String,SYS]
 * @return tamWindow Objeto com tamanhos horizontal e vertical da janela
 */

function getTamanhoWindow(){

	var tamX	= 0;
	var tamY	= 0;

	//Centralizar janela popup
	if(NNav)
	{
		tamX	= window.outerWidth;
		tamY	= window.outerHeight;
	}
	else
	{
		tamX	= screen.availWidth;
		tamY	= screen.availHeight;
	}
	var tamWindow = new Object(tamX, tamY);
	tamWindow.tamX 	= tamX;
	tamWindow.tamY 	= tamY;
	return tamWindow;
}
/**
* Fun??o redimensionar janela para ocupar toda a tela do browser
* @variable win Instancia de uma janela para redimensionamento
* @variable NNav Vari?vel que identifica navegador [String,SYS]
*/
function redimensiona(win)
{
	if(NNav)
	{
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
		if (win.outerHeight < screen.availHeight || win.outerWidth < screen.availWidth)
		{
			win.outerHeight = screen.availHeight;
			win.outerWidth = screen.availWidth;
		}
	}
	else
	{
		win.resizeTo(screen.availWidth,screen.availHeight);
	}
	win.moveTo(0,0);
}

/**
* Fun??o para abrir um janela do tipo POP-UP em uma mesma instancia passada
* Chamada: <br><dd><code>&lt;a href='#' onclick='janela("url_janela","alvo"); return false;'&gt;</code>
* @param url Endere?o para abertura da janela
* @param wa Largura da janela. [String, OP]
* @param ha Altura da janela. [String, OP]
* @param props Propriedades da janela. Informar no lugar de <I>wa</I> e <I>ha</I> que devem ser informados como "" [String, OP]
*/
function janelaComAlvo(url,alvo,wa,ha,props,max) {
	return janela(url,wa,ha,props,alvo,max);
}

/**
* Fun??o para abrir um janela do tipo POP-UP redimensionada para tamanho m?ximo da resolu??o
* Chamada: <br><dd><code>&lt;a href='#' onclick='janela("url_janela","alvo","props"); return false;'&gt;</code>
* @param url Endere?o para abertura da janela [String]
* @param alvo Inst?ncia para abertura. [String]
* @param props Propriedades da janela. Informar no lugar de <I>wa</I> e <I>ha</I> que devem ser informados como "" [String, OP]
*/
function janelaMaximizada(url,w,h,alvo,props) {
	return janela(url,w,h,props,alvo!=null?alvo.replaceAll('.','_').replaceAll('@','_AT_'):alvo,"S");
}

/**
* Fun??o para abrir um janela do tipo POP-UP em modo modal
* Chamada: <br><dd><code>&lt;a href='#' onclick='janela("url_janela","alvo"); return false;'&gt;</code>
* @variable modalWin Objeto que representa instancia da janela modal
* @param url Endere?o para abertura da janela [String]
* @param alvo Inst?ncia para abertura. [String]
*/
var modalWin = new Object();
modalWin.returnValue = false;
function janelaModal(url,wa,ha,props,alvo) {

	if(modalWin.returnValue)
	{
		modalWin.returnValue = false;
		return true
	}
	else if (!modalWin.win || (modalWin.win && modalWin.win.closed))
	{
		modalWin.win = janela(url,wa,ha,props,alvo);
		modalWin.modalFocus = true;
		modalWin.win.focus();
		window.onfocus = checkModal;
		return false;
	}
	else
	{
		checkModal();
		return false;
	}
}

/**
* For?a o focus em janela model
* @variable modalWin Objeto que representa instancia da janela modal
*/
function checkModal()
{
	if(modalWin.modalFocus)
	{
		if (modalWin.win && !modalWin.win.closed)
			modalWin.win.focus();
	}else
		window.focus();
}

/**
* Configura retorno da janela modal
* @variable value Valor de retorno
*/
function setReturnValue(value)
{
	window.onfocus 		= window.focus;
	modalWin.modalFocus 	= false;
	modalWin.returnValue = value;
	modalWin.win.close();
	modalWin.win = null;
}

/**
* Fun??o para guardar dados de impress?o
* @param url Endere?o para abertura da janela de impress?o
* @param titulo T?tulo da janela. [String]
* @param nome Nome da janela. [String]
* @param html Conte?do para impress?o. [String]
*/
var objImpressao;
function objetoImpressao (url, titulo, nome, html)
{
	this.titulo 	= titulo;
	this.nome	 	= nome;
	this.url 		= url;
	this.html 		= html;
}
/**
* Fun??o de chamada da impress?o
* Chamada: <br><dd><code>&lt;a href='#' onclick='janela("url_janela","width","height","props"); return false;'&gt;</code>
* @param url Endere?o para abertura da janela de impress?o
* @param titulo T?tulo da janela. [String]
* @param nome Nome da janela. [String]
* @variable objImpressao Objeto que cont?m dados para impress?o
* @see objetoImpressao
* @see htmlImpressao
*/
function chamarImpressao(url,titulo,nome)
{
// faz na p?gina para melhorar reuso
//	titulo = "<h2>" + titulo + "</h2>";
	titulo = typeof getTituloImpressao() != "undefined" ? getTituloImpressao() : titulo; 
	objImpressao = new objetoImpressao(url, titulo, nome, hmtlImpressao(window));
	window.open(objImpressao.url,objImpressao.nome,'');
	setBotaoAcao("");
}

function getTituloImpressao(){
	return getVarGlobal("IMPRESSAO_TITULO");
}

/**
* Abrir uma janela tipo IMPRESSAO<br>
* Chamada: <code><br><dd>&lt;a href=# onClick="impressao()"; return=false;&gt;Link&lt;/a&gt;
* A fun??o retira do par?metro objeto uma parte do html entre as<br>
* tags de coment?rio e retorna este html para a p?gina que a chamou
* Chamada: <br><dd><code>&lt;a href='#' onclick='janela("url_janela","width","height","props"); return false;'&gt;</code>
* @param window Objeto Window
* @return textoImpressao Conteudo final para janela de impress?o
*/
function hmtlImpressao(window)
{
	//Objeto => par?metro que representa uma p?gina

	var html = window.document.body.innerHTML;
	var textoInicioImpressao = new String("<!-- INI -->");
	var textoTerminoImpressao = new String("<!-- FIM -->");
	var posIni = html.search(textoInicioImpressao);
	var posFim = html.search(textoTerminoImpressao);
	var posTer;
	var conteudoImpressao = "";
	if (posIni >= 0 && posFim > posIni )
	{
		posTer = posFim - posIni + textoTerminoImpressao.length;
		conteudoImpressao = html.substr(posIni, posTer);
	}
	return conteudoImpressao;
}

/**
* Fun??o que redireciona p?gina est?tica fora do projeto (abrindo em nova inst?ncia)
* Chamada: &lt;body onLoad=redireciona("URL_DA_P?GINA");&gt;
* @param url Endere?o para redirecionamento
*/
function redireciona(url){
	var win;
	win = window.open(url,"win","");
	history.back();
}


/**
* Fun??o para exibir uma mensagem de texto como alerta
* Chamada: &lt;a href='#' onclick='janela("url_janela"); return false;'&gt;
* @param texto Conte?do da mensagem
*/
function exibeMsg(texto) {
	alert(texto);
}

/**
* Fun??es para registro de bot?es que respondem a eventos
* @param nomeBotao Nome do bot?o que atender? ao evento
* @param evento Evento associado ao bot?o
* @variable botaoArray Array que cont?m dados do evento/bot?o
* @see regBotao
*/
var botaoArray = new Array();
function regBotaoEvento(nomeBotao, evento)
{
	botaoArray[botaoArray.length] = new regBotaoEvt(nomeBotao, evento);
}

/**
* Fun??es que guarda dados do evento/bot?o no array
* @param nomeBotao Nome do bot?o que atender? ao evento
* @param evento Evento associado ao bot?o
*/
function regBotaoEvt(nomeBotao, evento)
{
		this.nomeBotao	= nomeBotao;
		this.evento 	= evento;
}

/**
* Fun??es que recupera o bot?o associado ao evento
* @param nomeBotao Nome do bot?o que atender? ao evento
* @param evento Evento associado ao bot?o
* @variable botaoArray Array que cont?m dados do evento/bot?o
* @return Retorna nome do bot?o ou valor "FALSE" se bot?o n?o encontrado
*/
function getBotaoArray(evento)
{	
    plcLog.debug("evento="+evento);
	for(i = 0; i < botaoArray.length; i++)
	{
		plcLog.debug("botaoArray evento="+botaoArray[i].evento+" = "+evento);
		if(botaoArray[i].evento == evento)
			return botaoArray[i].nomeBotao;
	}
	return "FALSE";
}

/**
* Fun??es para capturar tecla pressionada e executar a??o associada ? tecla
* @param nomeBotao Nome do bot?o que atender? ao evento
* @param evento Evento associado ao bot?o
* @variable disparouBotao Indicador de bot?o disparado
* @variable disparouEnter Indicador de tecla ENTER pressionada
* @variable interval Intervalo de tempo utilizado para execu??o de a??o<br>
*			associada ? tecla ENTER
* @see testaEventoFuncoes
* @see executarAcaoFuncoes
* @see executarEventoAplicacao
* @see selBotao
* @see getBotaoArray
* @see disparaBotao
*/
var disparouBotao = false;
var disparouEnter = false;
var botaoParaDisparar;
function executarAcaoFuncoes(evt)
{
	clearInterval(interval);
	plcLog.logEscondeErros();
	
	var elementoOrigem;
	if(evt){
		if(NavYes)
			elementoOrigem = evt.target;
		else
			elementoOrigem = evt.srcElement;
	}
	if(plcAjax.AJAX_ATIVO){
		return false;
	}

	var acao = "";
	var botaoAcaoAux = botaoAcao;
	botaoAcao = "";
	if (botaoAcaoAux == "")
		acao = testaEventoFuncoes(evt);
	else
		acao = botaoAcaoAux;

	if(acao == "TAB" || acao == "ERRO" || acao == "ESCAPE")
		return true;

	if(acao == "ENTER" && botaoAcaoEnter != "")
	{
		if(elementoOrigem.type != "textarea")
		{
			botaoAcao = botaoAcaoEnter;
			if(getVarGlobal("trSelecao") == null && !plcGeral.MENU_ATIVO)
				interval = setInterval("executarAcaoFuncoes()",100);
			return false;
		}
	}

	var botao = eval(selBotao(acao));
	if(!disparouBotao)
		botaoParaDisparar = botao;
	if(!disparouBotao && !executarEventoAplicacao(acao))
		return false;
	else
		disparouBotao = false;
	if(botao != null)
	{
		disparouBotao = true;
		//disparaBotao(botao);
		disparaBotao(botaoParaDisparar);
	}else
		return true;
}

/**
* Fun??es para devolver bot?o associado a tecla pressionada
* @param evt Objeto Event
* @param evento Evento associado ao bot?o
* @see getBotaoArray
* @return getBotaoArray Retorna o resultado da chamada da fun??o
*/
function testaEventoFuncoes(evt)
{
	var key;
	var keychar;
	var keycharAtalho;
	
	key = getKeyCode(evt);
	keychar = String.fromCharCode(key);

	keycharAtalho = traduzTeclaAtalho(getAtalho(keychar));
	keycharAtalho = keycharAtalho == "" ? keychar : keycharAtalho;

	//plcLog.debug("KEY: "+key)		
	//plcLog.debug("KEYCHAR: "+keychar)		
	//plcLog.debug("KEYCHARATALHO 2: "+keycharAtalho)		
	//plcLog.debug("KEYCHARATALHO CHARCODE: "+keycharAtalho.charCodeAt(0))		
	//plcLog.debug("traduzTeclaAcao(traduzTeclaAtalho(keycharAtalho)): "+traduzTeclaAcao(traduzTeclaAtalho(keycharAtalho)))		
	
   if ((key==null) || (key==0) || (key==8) || (key==9))
		return "ERRO";
 	else if ((key==13))
		return "ENTER";
   else if ((key == 9))
		return "TAB";
   else if ((key == 27))
		return "ESCAPE";
   else if (key == 117 || key == 118 || key == 119 || key == 120 || key == 121 || key == 123)
		return getBotaoArray(traduzTeclaAcao(traduzTeclaAtalho(keycharAtalho)));
/*   else if(keycharAtalho.charCodeAt(0) == traduzTeclaAtalho(keychar).charCodeAt(0))
		return getBotaoArray(traduzTeclaAcao(traduzTeclaAtalho(keychar)));
   else if(keychar.charCodeAt(0) == traduzTeclaAtalho("F8").charCodeAt(0))
		return getBotaoArray("ABRIR");
   else if(keychar.charCodeAt(0) == traduzTeclaAtalho("F9").charCodeAt(0))
		return getBotaoArray("PESQUISAR");
   else if(keychar.charCodeAt(0) == traduzTeclaAtalho("F10").charCodeAt(0))
		return getBotaoArray("GRAVAR");
   else if(keychar.charCodeAt(0) == traduzTeclaAtalho("F12").charCodeAt(0))
		return getBotaoArray("IMPRIMIR");
   else 
		return getBotaoArray(getAtalho(traduzTeclaAtalho(keychar)));
*/		
}

function getKeyCode(evt){
	var key;
	if (ExpYes)
		key = evt.keyCode;
	else
		key = evt.which;
	return key;
}
/**
* Traduz teclas de atalho. 
* Se for informado o nome da tecla retorno caracter associado.
* Se for informado o caracter associado retorno nome da tecla
* @param tecla Nome ou caracter que representa a tecla de atalho [String,OB]
* return Tecla de atalho traduziada
*/
function traduzTeclaAtalho(tecla){
	if(tecla == "F7")
		return "v";
	else if(tecla == "F8")
		return "w";
	else if(tecla == "F9")
		return "x";
	else if(tecla == "F6")
		return "u";
	else if(tecla == "F10")
		return "y";
	else if(tecla == "F12")
		return "{";
	else if(tecla == "F2")
		return "q";
	else if(tecla == "v")
		return "F7";
	else if(tecla == "w")
		return "F8";
	else if(tecla == "x")
		return "F9";
	else if(tecla == "u")
		return "F6";
	else if(tecla == "y")
		return "F10";
	else if(tecla == "{")
		return "F12";
	else if(tecla == "q")
		return "F2";
	else
		return "";		
}

function traduzTeclaAcao(tecla){
	if(tecla == "F7")
		return "INCLUIR";
	else if(tecla == "F8")
		return "ABRIR";
	else if(tecla == "F9")
		return "PESQUISAR";
	else if(tecla == "F10")
		return "GRAVAR";
	else if(tecla == "F12")
		return "IMPRIMIR";
}

/**
* Redefine uma tecla de atalho de evento para outra tecla.
* Caso n?o haja redefini??o para a nova tecla utilizada configura mensagem
* de alerta para tecla redefinida
* @see setAtalho
* @see getAtalho
*/
function redefinirTeclaAtalho(teclaDe, teclaPara){
	setAtalho(traduzTeclaAtalho(teclaPara), teclaDe);
	if(typeof getAtalho(traduzTeclaAtalho(teclaDe)) == "undefined"){
		setAtalho(traduzTeclaAtalho(teclaDe), "REDEFINIDA#"+teclaPara);
	}
}

/**
* Define uma tecla de atalho para uma evento novo
* @param novaTecla Nome da tecla de atalho [String,OB]
* @param labelBotao Label do bot?o associado ? nova tecla de atalho [String,OB]
* @param evento Evento associado ? nova tecla. Utilizado para tecla inteligentes [String,OB]
* @see setAtalho
* @see regBotaoEvento
*/
function definirTeclaAtalho(novaTecla, labelBotao, evento){
	setAtalho(novaTecla, evento);
	regBotaoEvento(labelBotao,evento);
}

/**
* Verifica se a a??o associada a uma tecla foi redefinida para outra.
* Neste caso envia mensagem informando qual tecla utilizar
* @variable msgTeclaRedefinida Mensagem para tecla redefinida. Deve ser definida no arquivo
* de mensagens no formato:  Esta fun??o foi redefinida para a tecla {0} [String,OB]
* @param keychar Caracter associado com a tecla pressionada. [String,OB]
* @see getAtalho
* @see setAtalho
*/
/*
//RETIRAR FUTURAMENTE
var msgTeclaRedefinida = "";
function verificaTeclaRedefinida(keychar){
	keychar = getAtalho(keychar);
	if(keychar != null && typeof keychar != "undefined" && keychar.indexOf("REDEFINIDA") > -1){
		keychar		= keychar.substring(keychar.indexOf("#") + 1, keychar.length);
		//alert(msgTeclaRedefinida.replace("{0}",keychar));
		return false;
	}
	return true;
}
*/
/**
* Fun??o que seleciona o bot?o associado ? fun??o da tecla
* @param acao A??o ? qual o bot?o est? associado
* @return botao Objeto Button representando o bot?o associado ? a??o
*/
function selBotao(acao, form)
{
	var numElements;
	var form = getForm(form);
	var elementValue;
	var retorno = false;
	var botao = null;

	if (document.forms && document.forms.length > 0)
	{
		if (typeof form != "undefined" && typeof form.elements["evento"] != "undefined")
		{
			numElements = form.elements["evento"].length;
			if (typeof numElements != "undefined"){
				for(i=0; i < numElements; i++)
				{
					elementValue = form.elements["evento"][i].value;
					if(elementValue == acao && form.elements["evento"][i].id != "RECUPERACAO_AUTOMATICA")
					{
						botao = eval(form.elements["evento"][i]);
						i = numElements;
					}
				}
			}else if (typeof form.elements["evento"] != "undefined"){
				elementValue = form.elements["evento"].value;
				if(elementValue == acao && form.elements["evento"].id != "RECUPERACAO_AUTOMATICA")
					botao = eval(form.elements["evento"]);
			} 
		}
		else if (eval(form.elements[acao]))
			botao = eval(form.elements[acao]);
		// acerto para encontrar os botoes do trinidad
		else if (document.getElementById('corpo:'+acao)) 
			botao = document.getElementById('corpo:'+acao);
	}
	return botao;
}

/**
* Fun??es para simular um clique no bot?o informado
* @param botao Nome do bot?o que ser? clicado
*/
function disparaBotao(botao){
	if(botao){
		botao.click();
	}
}

function alertaProcessamento(evt){
	if(onBeforeUnloadCont++ > 0){
		return "... PROCESSAMENTO SENDO EXECUTADO ...";
	}
}

var onBeforeUnloadCont = 0;
function disparaBotaoGravar(){

//	window.onbeforeunload = alertaProcessamento;
	
//	$(window).bind("beforeunload",function(event) {
//		return "... PROCESSAMENTO EM EXECU��O ...";
//	});

	if(!plcValida.validacaoVerificarRegras())
		return false;
	else{
		setBotaoAcao(getBotaoArray('GRAVAR'));
		return true;
	}	
}
/**
* Fun??es para associar a??o a um bot?o
* @param acao A??o a ser associada ao bot?o
* @variable botaoAcao Armazena a a??o associada ao bot?o
*/
var botaoAcao = "";
function setBotaoAcao(acao)
{
	botaoAcao = acao;
}

/**
* Fun??es para associar a??o a um bot?o ao pressionar a telca ENTER
* @param acao A??o a ser associada ao bot?o
* @variable botaoAcaoEnter Armazena a a??o associada ao bot?o
*/
//FUN??O PARA SETAR A??O DO BOT?O AO PRESSIONAR ENTER
var botaoAcaoEnter = "";
function setBotaoAcaoEnter(acao)
{
	botaoAcaoEnter = acao;
}

/**
* JCompany: Devolve os valores selecionados em uma janela de sele??o popup.
* Os parametros devem ser passados para este fun??o aos pares e na seguinte ordem: nome e valor do
* atributo.
* @see recebeSelecao
* @author: Rodrigo Magno - Powerlogic 2003 (c)
*/

function devolveSelecaoPopup(listaValores)
{
	//Compatibiliza??o
	if(arguments.length > 1)
		devolveSelecao(arguments);
	else
	{
			try{ //tenta focar elemento, se n�o tiver jQuery, n�o provocar� erro.
				opener.focaElementoInformado();
			}catch(erro){};
			if(opener == null || typeof opener == "undefined"){
				opener = parent;
			}
			var urlSelecao = ""+document.location.href;
			opener.setVarGlobal("urlSelecao", urlSelecao);
			opener.recebeSelecaoPopup(listaValores);
			window.close();
	}
}

/**
 * JCompany: Devolve os valores selecionados em uma janela de sele??o popup.
 * Os par?metros devem ser passados para este fun??o aos pares e na seguinte ordem: nome e valor do
 * atributo.
 * @author: Claudia Seara - Powerlogic 2003 (c)
 */
function devolveSelecao()
{
	//Compatibiliza??o
	if(arguments.length == 1)
		devolveSelecaoPopup(arguments[0])
	else
	{
		// Verifica se o n?mero de argumentos ? par
		if ((arguments.length % 2) != 0 ) {
			alert("ERRO! \n\nFun??o: devolveSelecao(). \n\nErro: A quantidade de parametros passados para esta fun??o n?o ? um n?mero par." );
			return;
		}

		// Monta os vetores de nome e valor para os atributos selecionados
		var nome = new Array();
		var valor = new Array();
		var j = 0;

		for(var i = 0; i < arguments.length;) {
			nome[j] = arguments[i++];
			valor[j++] = arguments[i++];
		}

			window.opener.focaElementoInformado();
			// Passa os vetores para a janela que acionou a janela de sele??o
			window.opener.recebeSelecao(nome, valor);
			// Fecha a janela de sele??o
			window.close();
	}
}

function focaElementoInformado (){
	if (jQuery && jQuery.plc && jQuery.plc.componenteFoco)
		jQuery.plc.componenteFoco.focus();
}

/**
 * JCompany: Recebe os valores selecionados em uma janela de sele??o popup e procura por atributos
 * do mesmo nome no form corrente. Caso encontre, atribui o valor selecionado ao atributo do form.
 * @author: Claudia Seara - Powerlogic 2003 (c)
 */
function recebeSelecao()
{
	//Compatibiliza??o
	if(arguments.length == 1)
		recebeSelecaoPopup(arguments[0])
	else
	{
		// Recebe os vetores de nome e valor dos atributos selecionados
		var nome 	= arguments[0];
		var valor 	= arguments[1];

		// Procura no form corrente por atributos de mesmo nome. Se achar, atribui o valor passado
		// do atributo ao atributo de mesmo nome no form.
		for(var j = 0; j < nome.length; j++) {
			for(var i = 0; i < document.forms[0].length; i++) {

				if (document.forms[0].elements[i].name == nome[j]) {
					document.forms[0].elements[i].value = valor[j];
					break;
				}
			}
		}
		eval("executarEventoAplicacao('TESTAR_NIVEL')");
	}
}


function recebeSelecaoPopup(listaValores)
{
	//Compatibiliza??o
	if(arguments.length > 1)
		recebeSelecao(arguments)
	else
	{
		var campo		= "";
		var nome		= "";
		var idRetorno 	= "";
		var id 			= "";
		var separador	= "";

		var urlSelecao = getVarGlobal("urlSelecao");
		setVarGlobal("urlSelecao", "");

		if(!plcGeral.antesDevolveSelecaoPopup(listaValores,urlSelecao)){
			return;
		}

		var retornoArray= registrarCamposRetorno (listaValores , "id,valor", "#");
		var devolveArray= new Array();

		for(i = 0; i < retornoArray.length; i++)
		{
			idRetorno	= retornoArray[i].id;
			valRetorno	= unescape(retornoArray[i].valor);
			//valRetorno	= retornoArray[i].valor;
			for(j = 0; j < camposRetorno.length; j++)
			{
				nome		= unescape(camposRetorno[j].nome);
				id			= camposRetorno[j].id;
				separador	= camposRetorno[j].separador;
				if(nome == idRetorno || idRetorno == id)
				{
					if(setValorCampo(nome, valRetorno, separador)){
						devolveArray[devolveArray.length] = nome;
						//Marca flag de altera??o de dados
						setAlertaAlteracao();
						break;
					}
				}
			}
		}
		plcGeral.aposDevolveSelecaoPopup(listaValores,urlSelecao);
		plcGeral.aposDevolveSelecaoPopupInformaTrackChange(devolveArray);
		eval("executarEventoAplicacao('TESTAR_NIVEL')");
	}
}

//var bgImage = new Image();
//bgImage.src = plcGeral.contextPath+"/plc/midia/linha_exclui.gif";
var divs = new Array();
function setID(checkName, id)
{
	this.id = id;
	this.checkName = checkName;
}

function getID(chkName)
{
	for(i=0; i < divs.length; i++)
	{
		if(divs[i].checkName == chkName)
			return divs[i].id;
	}
	return "";
}

function setPortlet(idPortlet)
{
	if (document.forms[0].elements["pIdPlc"])
		document.forms[0].elements["pIdPlc"].value=idPortlet;
}

function abrirArquivo(info)
{
	var arquivo = info.substr(info.indexOf(';', 0)+1);
	var path = info.substr(0, info.indexOf(';', 0));

    var win = window.open(path, 'downloadArquivo', '');
	win.location = path + '&filename=' + '/' + arquivo;
}


function recuperaCodigo(url, msg1, msg2, campo)
{
	 var codigo = document.forms[0].elements[campo].value;
	 if (codigo == "")
	 {
		 document.forms[0].elements[campo].focus();
	 }
	 else if(isNaN(codigo))
	 {
		 document.forms[0].elements[campo].select();
	 }
	 else
		 document.location.href = url+codigo;

 }

/************************************************************************
* 			L?GICAS PARA REGISTRO E EXECU??O DE EVENTOS GEN?RICOS
*
*
* Registrar eventos da aplica??o
* FORMATO: 	regEvento ("Evento","A??o Executada","Funcao Associada ? A??o");
* AC?ES:		TESTE:		Executa alguma fun??o (deve-se informar uma fun??o para teste)
*				MENSAGEM:	Envia uma mensagem
*
* EVENTOS:  Evento podem ser padr?es (definidos pelas a??es dos bot?es de a??o) ou definidos
*				pelo programador.
* Ex.:
*		Evento 'F10-Gravar':  ocorre quando o usu?rio executa grava??o de algum registro
*		Evento 'TESTAR':  	 deve ser executado pela chamada da fun??o
*									 "executarEventoAplicacao(<evento>)"
*
************************************************************************/

//Array que guarda eventos da aplica??o
var evtArray = new Array();

//Fun??es para registro de eventos
function regEvento(evento, tipoAcao, funcao)
{
	evtArray[evtArray.length] = new regEvt(evento, tipoAcao, funcao);
}

function regEvt(evento, tipoAcao, funcao)
{
		this.evento 	= evento;
		this.tipoAcao 	= tipoAcao;
		this.funcao 	= funcao;
}

//Fun??o para teste dos eventos da aplica??o
function executarEventoAplicacao(acao)
{
	var retorno = true;
	var i = 0;
	if(acao == "")
		acao = botaoAcao;

	while(i < evtArray.length)
	{
		if(evtArray[i].evento == acao)
		{
			if(evtArray[i].tipoAcao == "MENSAGEM")
			{
				retorno = enviarMensagem(evtArray[i].evento);
				break;
			}
			else if(evtArray[i].tipoAcao == "TESTE")
			{
				if (!eval(evtArray[i].funcao))
				{
					retorno = enviarMensagem(evtArray[i].evento);
					break;
				}
			}
			else if(evtArray[i].tipoAcao == "FUNCAO")
			{
					retorno = eval(evtArray[i].funcao);
					break;
			}
		}
		i++;
	}

	return retorno;
}

/************************************************************************
* 		L?GICAS PARA REGISTRO E ENVIO DE MENSAGENS DE ALERTA GEN?RICAS
*
* Registrar mensagens alertas da aplica??o
* FORMATO: regMensagem ("Evento","Tipo Mensagem","Texto Mensagem");
* EVENTO:  Deve ser um dos eventos registrados acima
* TIPOS:	  CONFIRMACAO:	Mostra janela para confirma??o
*  		  ALERTA:		Envia mensagem de alerta. (Retorna true)
*  		  ALERTA_ERRO:	Envia mensagem de alerta. (Retorna false)
*
************************************************************************/
function regMensagem(evento, tipo, msg) {
   if (this.msgArray == null) {this.msgArray = new Object();}
   this.msgArray[evento] = new regMsg(evento, tipo, msg);
}

function regMsg(evento, tipo, msg)
{
	this.evento	= evento;
	this.tipo 	= tipo;
	this.msg	= msg;
}

function getMsgArray(evento)
{
	return this.msgArray[evento];
}

function enviarMensagem(evento)
{
	auxArray = getMsgArray(evento);
	if (auxArray != null)
	{
		if(auxArray.tipo == "CONFIRMACAO")
			return confirm(auxArray.msg);
		else if (auxArray.tipo == "ALERTA")
			alert(auxArray.msg);
		else if (auxArray.tipo == "ALERTA_ERRO")
		{
			alert(auxArray.msg);
			return false;
		}
	}
	return true;
}

/******************************************************************************
* L?GICAS PARA MONTAR ARRAY DE CAMPOS E RETORNAR VALORES NESTES CAMPOS
******************************************************************************/
//Fun??o que registra os campos de retorno no array
//Array para conter os campos para l?gicas de retorno de valores
var camposRetorno = new Array();

function getCampoRetornoById(id)
{
	for(i = 0; i < camposRetorno.length; i++)
	{
		if(camposRetorno[i].id == id)
			return camposRetorno[i].nome;
	}
	return "";
}

function registrarCamposRetorno (listaRetorno, props, separador)
{
	var termosRetorno	= listaRetorno.split(",");
	var propsCampo 		= props.split(",");
	var propsRetorno;
	var arrayRetorno 	= new Array();
	var separadorCampos = listaRetorno.indexOf("#") >= 0 ? "#" : "=";
	for( i = 0; i < termosRetorno.length; i++)
	{
		propsRetorno 	= termosRetorno[i].split(separadorCampos);
		arrayRetorno[i] = new regProps(propsCampo, propsRetorno, separador);
	}
	return arrayRetorno;
}

function regProps(propsCampo, propsRetorno, separador)
{
	for(j = 0; j < propsCampo.length; j++)
		eval("this."+propsCampo[j]+" = '"+escape(propsRetorno[j])+"'");
	this.separador = separador;
}


/*----------------------------------------------------------------*\
 			FUN??ES PARA SETAR VALOR EM CAMPO INFORMADO
\*----------------------------------------------------------------*/
function set(nomeCampo, valor, separador, form) {
    setValorCampo(nomeCampo, valor, separador, form);
}

function setValorCampo(nomeCampo, valor, separador, form)
{
	var campo = getCampo(nomeCampo,form);
	if(campo)
	{
		if(arguments[2])
			campo.value = concatenar(retornaValorCampo(nomeCampo), valor, separador);
		else
			campo.value = valor;
		return true;
	}
	return false;
}

function setValorCampoAtualizacao(nomeCampo, valorReplace, valorNovo, separador, form)
{
	atualizaValorCampo(nomeCampo, valorReplace, valorNovo, separador, form);
	setValorCampo(nomeCampo, valorNovo, separador, form);
}

function atualizaValorCampo(nomeCampo, valorReplace, valorNovo, separador, form)
{
	var campo 	= getCampo(nomeCampo,form);
	var valor 	= "";
	var exp 	= "";
	var sepAux	= "";
	if(valorNovo == "")
		sepAux = "";
	else
		sepAux = separador;
	if(campo)
	{
		valor = campo.value;
		if(valor.indexOf(separador) < 0)
		{
			try{
				exp = new RegExp(valorReplace);
				if(valor != "")
					valor = replaceString(exp, valor, valorNovo);
			}catch(e){
				plcLog.alertaExcecao(e,"Erro ao criar expressao regular para:\n"+ valorReplace);
			}
		}else
		{
			try{
				exp = new RegExp(valorReplace+"\\"+separador);
				valor = replaceString(exp, valor, valorNovo+sepAux);
			}catch(e){
				plcLog.alertaExcecao(e,"Erro ao criar expressao regular para:\n"+ valorReplace+"\\"+separador);
			}
			try{
				exp = new RegExp("\\"+separador+valorReplace);
				valor = replaceString(exp, valor, sepAux+valorNovo);
			}catch(e){
				plcLog.alertaExcecao(e,"Erro ao criar expressao regular para:\n"+ "\\"+separador+valorReplace);
			}
		}
		campo.value = valor;
		return true;
	}
	return false;
}

/************************************************************************
* 			FUN??O PARA SETAR FOCUS EM UM CAMPO INFORMADO
************************************************************************/
var botao;
function setFocus(nomeCampo, selecionar){

	campoFocus = "";
	var campo 	= getCampo(nomeCampo);

	if(campo){
		try{
			if((campo.type == "text" || campo.type=="password" || campo.type=="textarea" || campo.type=="file") &&
			campo.type != "hidden"  && !campo.readOnly && !campo.disabled){
					campo.focus();
					if(selecionar)
						selecionarCampo(campo.name);
			}
			else if((campo.type == "select-one" || campo.type == "select-multiple") &&
			campo.options.length > 0 && campo.options.selectedIndex <= 0 && !campo.disabled){

				campo.focus();
				campo.options[0].selected = true;
			}
			/*else if(campo.length && campo[0].type == "radio"){
				var checado = false;
				for(i = 0; i < campo.length; i++){
					if(campo[i].checked)
						checado = true;
					alert(campo[i].checked)
				}
				if(!checado)
					campo[0].checked = true;
			}*/
		}catch(e){}
	}
}

function selecionarCampo(nomeCampo){

	var campo 	= getCampo(nomeCampo);

	if(campo)
	{
		try{
			if((campo.type == "text" || campo.type=="password" || campo.type=="textarea" || campo.type=="file") &&
			campo.type != "hidden"  && !campo.readOnly && !campo.disabled){
					campo.select();
			}
			else if((campo.type == "select-one" || campo.type == "select-multiple") &&
			campo.options.length > 0 && campo.options.selectedIndex <= 0 && !campo.disabled)
			{
					campo.focus();
					campo.selected = true;
			}
		}catch(e){}
	}
}

/************************************************************************
* 			FUN??ES PARA TRATAMENTO DE RETORNO DE DATA DO CALEND?RIO
************************************************************************/
//Campo para retorno de data
var campoData;
//Fun??o para abertura do calend?rio
function abrirCalendario(url, nomeCampo, wa, ha, props)
{
	var w = 720;
	var h = 350;

	if (arguments[1])
		w = wa;
	if (arguments[2])
		h = ha;

	nomeCampo = nomeCampo+"=data";
	camposRetorno = registrarCamposRetorno (nomeCampo, "nome,id");

	if(props != "" && ""+props != "undefined"){
		janela(url, "","", props);
	}
	else if(isNaN(w) || isNaN(h)){
		janela(url, "","", "width=260, height=250, resizable=no");
	}
	else{
		janela(url, w,h);
	}
}

//Fun??o para retorno da data no campo indicado
function retData(data)
{
	campoData.value = data;
	campoData.focus();
}


function setFocusFim (campo) {
	if (campo.createTextRange) {
		var r = campo.createTextRange();
		r.moveStart('character', campo.value.length);
		r.collapse();
		r.select();
	}
	else
		setFocus(campo.name);
}

/**********************************************************************************
* 					FUN??O PARA RETORNAR UM VALOR EM UM CAMPO
**********************************************************************************/
function get(field, form)  {
   return retornaValorCampo(field, form);
}
function retornaValorCampo(field, form)
{
	var campo = "";
	if(form == "" || form == 0 || ""+form == "undefined"){
		if(getRootDocument().forms && getRootDocument().forms[0] && getRootDocument().forms[0].elements)
			campo = eval("getRootDocument().forms[0].elements['"+field+"']");
	}
	else {
		try{
			campo = eval("getRootDocument().forms['"+form+"'].elements['"+field+"']");
		}catch (e){
			return "";
		}
	}
	if(campo)
	{
		plcLog.debug("retornaValorCampo - nome campo: "+campo.name);
		plcLog.debug("retornaValorCampo - tipo campo: "+campo.type);
		//Acerto para resolver problemas de campos duplicados inclu?dos pela
		//gera??o via plugin
		//Alterado: 16/12/2005 - by Rodrigo Magno
		if(campo.length > 0 && campo[0]){
			if(	campo[0].type == "text" || campo[0].type == "hidden" || campo[0].type == "textarea"  ||
				campo[0].type == "file" || campo[0].type == "password")
				campo = campo[0];
		}
		if(	campo.type == "text" || campo.type == "hidden" || campo.type == "textarea" ||
			campo.type == "file" || campo.type == "password")
		{
			return campo.value;
		}
		else if (campo.type == "checkbox")
		{
			if(campo.checked)
				return campo.value;
			else{
				if(getVarGlobal("uncheck_"+campo.name))
					return getVarGlobal("uncheck_"+campo.name);
				else
					return "N";
			}
		}
		else if (campo.type == "select-one")
		{	
			try{
				return campo.options[campo.selectedIndex].value;
			}catch(e){
				//Retorna vazio caso a busca n�o encontre nenhum item
				return "";
			}
		}
		else if (campo.type == "select-multiple")
		{
			var valSelect = [];
			for(i = 0; i < campo.length; i++){
				if(campo.options[i].selected){
					valSelect[valSelect.length] = campo.options[i].value;
				}
			}
			return valSelect;
		}
		else if (campo.type == "radio")
		{
			if(campo.checked)
				return campo.value;
		}
		else //if (typeof campo.type == "undefined")
		{
			plcLog.debug("retornaValorCampo - tamanho campo: "+campo.length);
			
			plcLog.debug(campo.name+' '+campo.length);
			for(var i = 0; i < campo.length; i++){
				plcLog.debug("retornaValorCampo - valor campo: "+campo[i].value);
				plcLog.debug("retornaValorCampo - check campo: "+campo[i].checked);
				if(campo[i].checked){
					return campo[i].value;
				}
			}
		}
	}

	return "";
}

/**********************************************************************************
* 					FUN??O PARA INSERIR UM VALOR EM UM CAMPO
**********************************************************************************/
function insereValorCampo(field,value,form)
{
	var campo = "";
	if(form == "" || form == 0 || ""+form == "undefined")
		campo = eval("getRootDocument().forms[0].elements['"+field+"']");
	else
		campo = eval("getRootDocument().forms['"+form+"'].elements['"+field+"']");
	if(campo)
	{
		if(campo.type == "text" || campo.type == "hidden")
			campo.value = value;
		else if (campo.type == "select-one")
		{	for(i = 0; i < campo.options.length; i++)
			{
				if(campo.options[i].value == value)
				{
					campo.options[i].selected = true;
					i = campo.options.length;
				}
			}
		}
	}
}

/**********************************************************************************
* 					FUN??O PARA REDIRECIONAMENTO DE ENDERE?O
**********************************************************************************/
/**
* @deprecated Mantida por compatibilidade. Utilizar submeteUrl
*/
function redirect(url)
{	
	if(getVarGlobal("PREVIEW_ATIVO") != "S")
		document.location.href=url;
}

/**
 * Submete (GET) a URL informada, na mesma instancia
 */
function submeteUrl(url)
{
	redirect(url);
}

/**
* fun??o mantida para compatibilidade com antigas manuten??es
*/ 
function redirectPopup(url){

	if(getParametroUrl("modoJanelaPlc") != "")
		redirect(url+"&modoJanelaPlc=popup");
	else
		redirect(url);

}
/**********************************************************************************
* 						FUN??ES PARA AVALIA??O DE EXPRESS?ES
**********************************************************************************/

/******************AVALIA??O DE EXPRESS?ES COM REPETI??O DE CAMPOS ***************
=> Avalia a express?o passada
=> Se informado um campo para retorno este ir? receber o valor da expresss?o
avaliada.
=> Sintaxe: avaliaExpressao(expressao, campoRetorno)
=> Par?metros ( O = Obrigat?rio)
	expressao 	= express?o para ser avaliada
		Para a composi??o da express?o podem ser utilizado algarismos, operadores,
		par?nteses e campos da aplica??o.
		Quando for utilizar campos informar o nome do campo entre "#".
		Exemplo: ((10-20)*5+#campo1#)/campo2
	campoRetorno= campo para onde ser? enviado o valor da express?o avaliada
*********************************************************************************/

function avaliaExpressao(expressao, campoRetorno)
{
	var debug = false;
	//Parsing de express?o
	var expAux 		= "";
	var campo 		= "";
	var valCampo 	= 0;
	var expEval 	= "";
	var index 		= 0;
	var resultado	= 0;
	if(expressao.indexOf(" ") > -1)
	{
		alert("Express?o n?o pode conter espa?os.");
		return;
	}
	else
	{
		index 	= expressao.indexOf("#");
		while(index > -1)
		{
			expEval += expressao.substring(0,index);
			expressao = expressao.substring(index+1,expressao.length);
			index = expressao.indexOf("#");
			campo = expressao.substring(0,index);
			expressao = expressao.substring(index+1,expressao.length);
			valCampo = retornaValorCampo("",campo);
			expEval += valCampo;
			index = expressao.indexOf("#");
		}
		expEval += expressao;
		expressao = expEval;
	}
	if(eval(expressao))
	{
		resultado = eval(expressao);
		campo = eval("document.forms[0].elements['"+campoRetorno+"']");
		if(campo)
			campo.value = resultado;
		return resultado;
	}
	else
		alert("Express?o inv?lida.");
}
/**
* FUN??ES PARA TORNAR VIS?VEIS/INVIS?VEIS CAMPOS DO FORM
*/
function alteraEstadoCampo(tipo, estado)
{
  if (!document.all)
  {
    return; // only Internet Explorer is affected by the bug
  }
  var numForms 	= document.forms.length;
  var numCampos	= "";
  var numTipos		= separaListaTermos(tipo,",");
  var find 			= false;
  for (var i = 0; i < numForms; i++)
  {
    numCampos = document.forms[i].elements.length;
    for (var j = 0; j < numCampos; j++)
    {
	    for (var k = 0; k < numTipos || find; k++)
	    {
	      if (document.forms[i].elements[j].type == numTipos[k])
	      {
	        document.forms[i].elements[j].style.visibility = estado;
	        find = true;
	      }
	    }
    }
  }
}

/**********************************************************************************
* 			FUN??O PARA CONCATENAR DOIS VALORES COM O SEPARADOR INFORMADO
**********************************************************************************/
function concatenar(oldValue, newValue, separator,doisLados)
{
	var valRetorno = oldValue;
	if(newValue != "")
	{
		if(oldValue == "") {
			if (doisLados)
				valRetorno = separator+newValue+separator;
			 else
				valRetorno = newValue;
		
		}
		else if (doisLados) {
			if (oldValue.indexOf(separator+newValue+separator) == -1)
				valRetorno = oldValue + newValue+separator;
		} else if (oldValue.indexOf(newValue) == -1)
			valRetorno = oldValue + separator + newValue;
	}
	return valRetorno;
}


/**
* 			FUN??O PARA SEPARAR UM LISTA DE TERMOS EM ARRAY
*/
function separaListaTermos (str, separador)
{
	var termos = new Array();
	termos = str.split(separador);
	return termos;
}

/**********************************************************************************
* 					FUN??O PARA C?LCULO DE VALORES
**********************************************************************************/
function retornaCalculo(oper, incremento, maximo, minimo, campoRetorno)
{
	var format = "00";
	var campo = eval("document.forms[0].elements['"+campoRetorno+"']");
	var resultado;
	var val = parseFloat(campo.value);
	resultado = eval(val + oper + incremento);
	if(!isNaN(resultado) && (resultado <= maximo && resultado >= minimo))
	{
		var auxResultado = "";
		var resultado = new String(resultado);
		if(format.length > resultado.length)
		{
			var posRes = 0;
			for(i = (format.length - 1); i >= 0; i--)
			{
				if(i <= resultado.length - 1)
				{
					auxResultado += parseFloat(format.charAt(i))+parseFloat(resultado.charAt(posRes));
					posRes++;
				}
				else
					auxResultado += parseFloat(format.charAt(i));
			}
			if(campo)
				campo.value = auxResultado;
			else
				return auxResultado;
		}
		else
		{
			if(campo)
				campo.value = resultado;
			else
				return resultado;
		}
	}
}

function selecaoPopup(url, listaCampos, separador, larg, alt, posX, posY, alvo)
{
	camposRetorno = registrarCamposRetorno(listaCampos, "nome,id", separador);
	 var janelaRetornada = janela(url,larg,alt,"",alvo,"",posX, posY);
// TODO garantir foco na popup
//	 setTimeout('focoJanela('+janelaRetornada+')',500);
	 return janelaRetornada;
}

function focoJanela(janela) {
	 janela.focus();
}

/******************************************************************************
* FUN??O QUE RETORNA UMA STRING PARA USO EM URL, CONTENDO O NOME DO CAMPO+VALOR DO CAMPO,
* CONCATENANDO TODOS OS CAMPOS PASSADOS POR ARGUMENTO.
* Recebe: Nome do Form + Nomes dos Campos
* Devolve: URL no formato exemplo: campo1=<valor1>&campo2=<valor2>...
******************************************************************************/
function geraLink()
{
   var form = arguments[0];
   var link = "";
   var arrayTermos;
   for (i=1;i<arguments.length;i++) {
		if (i > 1) link+="&";

		if(arguments[i].indexOf(",") >= 0)
		{
			arrayTermos = separaListaTermos(arguments[i],",");
			link+=arrayTermos[1]+"="+retornaValorCampo(arrayTermos[0],form);
		}
        else
    		link+=arguments[i]+"="+retornaValorCampo(arguments[i],form);
   }
   return link;
}


/******************************************************************************
* FUN??O PARA DIFERENCIAR LINHA PARA EXCLUS?O EM L?GICAS TABULARES
******************************************************************************/

function marcarExclusaoDetalhe(chave, checkbox, evt){

// TODO COMPATIBILIZAR COM STRUTS (sem o corpo)
	if(!checkbox.checked){
		var campo = getCampo("corpo:indExcDetPlc");
		if(campo){
			campo.value = campo.value.replace('#'+chave+"#","#");
			if (campo.value=='#')
			{
				campo.value='';
			}
			//campo.value = campo.value.replace("#"+chave,"");
			//campo.value = campo.value.replace(chave,"");
		}
	}
	else
		set("corpo:indExcDetPlc", concatenar(get("corpo:indExcDetPlc"), chave, "#",true));
}

function marcarExclusao(checkbox, evt)
{
	// TODO Struts
	//marcarExclusaoDetalhe(checkbox.name.substring(0,checkbox.name.indexOf("[")), checkbox, evt)
	marcarExclusaoDetalhe(checkbox.name, checkbox, evt)

	checarUm(checkbox);
}

function manterMarcaExc(val, frm){
	frm 		= getForm(frm);
	if(frm)
	{
		var EL	= frm.elements;
		for (var i = 0; i < EL.length; i++)
		{
			var e = EL[i];
			if ((e.name.indexOf("indExcPlc") >= 0) && (e.type == 'checkbox'))
			{
				if(e.checked || e.value == "S")
				{	e.click(); e.click();}
				else
					setClasse(e, "TR", "");
			}
		}
	}
}


/******************************************************************************
							MARCAR TODOS CHECKBOX
******************************************************************************/

function checarTodosMarcados(CTID, CHKID, frm){
	frm  				= getForm(frm);
	var checksTotal		= jQuery("INPUT[id=" + CHKID+ "][type='checkbox']", frm).size();
	var checksTotalMarcados	= jQuery("INPUT[id=" + CHKID+ "][type='checkbox'][checked=true]", frm).size();
	jQuery("#"+CTID, frm).attr("checked", checksTotalMarcados == checksTotal);
/*
	try{
	if(checks){
		for(var i = 0; i < checks.length; i++ ){
			if(!checks[i].checked){
				chkTodos.checked = false;
				return false;
			}
		}
	}
	chkTodos.checked = true;
	}catch(e){
		return false;
	}
	return true;
*/
}

function checarTodos(CT, CBID, CTID, frm, marcarLinha){
	frm  		= getForm(frm);
	CT   		= getCheckTodos(CT, frm);
	jQuery("INPUT[id=" + CTID + "][type='checkbox']", frm).attr('checked', CT.checked);

/*
	CBID 		= getCheckExc(CBID, frm);
	nomeChk 	= getNomeChk(nomeChk);
	for (var i = 0; i < CBID.length; i++)
	{
		var e=CBID[i];
		if ((e.type=='checkbox'))
		{
			if ((e.name) && (e.name.indexOf(nomeChk) >= 0))
			{
				e.checked = CT.checked;
				if(marcarLinha != 'N'){
					testarChekbox(e);
				}
			}
		}
	}
*/
}

function checarUm(CB, CT, nomeChk, CBID, frm)
{
	frm  		= getForm(frm);
	CT	  		= getCheckTodos(CT, frm);
	CBID 		= getCheckExc(CBID, frm);
	nomeChk 	= getNomeChk(nomeChk);
	testarChekbox(CB);
	var TB = TO = 0;
	for (var i=0;i < CBID.length;i++)
	{
		var e = CBID[i];
		if ((e.name && e.name.indexOf(nomeChk) >= 0) && (e.type=='checkbox'))
		{
			TO++;
			if (e.checked)	TB++;
		}
	}
	CT.checked=(TO==TB)?true:false;
}

function testarChekbox(CHK)
{
	var tag = "TR";
	if (CHK.checked) setClasse(CHK, tag, "campoComErro");
	else setClasse(CHK, tag, "");
}

function setClasse(E, tag, classe)
{
	var Etag = E.tagName;
	while (Etag != tag)
	{
		if(ExpYes)
			E = E.parentElement;
		else
			E = E.parentNode;
		Etag = E.tagName;
	}
	E.className = classe;
	E.marcado 	= true;

}
function getCheckTodos(CT, frm){
	if(""+CT != "undefined" && CT != ""){
		return CT;
	}
	else if(frm.cbTodos){
		return frm.cbTodos;
	}else{
		return frm;
	}
}

function getCheckExc(CBID, frm)
{
	if(""+CBID != "undefined" && CBID != ""){
		if(frm.CBID)
			return frm.CBID;
	}
	return frm.elements;
}

function getNomeChk(nomeChk)
{
	if(""+nomeChk != "undefined" && nomeChk != ""){
			return nomeChk;
	}
	return "indExcPlc";
}

/* ---------------------------------------------------------------------- *\
  Function    : setVarGlobal
  Description : set a variable with a global scope
  Usage       : setVarGlobal(varName, value);
  Arguments   : varName - name of the global variable to set
                value - value of the global variable to set
\* ---------------------------------------------------------------------- */
function setVarGlobal(nome, valor) {
   if (this.cache == null) {this.cache = new Object();}
   this.cache[nome] = valor;
}
/* ---------------------------------------------------------------------- *\
  Function    : getGlobalVar
  Description : get a variable in a global scope
  Usage       : value = getGlobalVar(varName);
  Arguments   : varName - name of the global variable to get
                value - value of the global variable to get
\* ---------------------------------------------------------------------- */
function getVarGlobal(nome, valor) {
   if (this.cache == null) {
     return null;
   } else {
     return this.cache[nome];
   }
}

/* ---------------------------------------------------------------------- *\
	FUN??O PARA TRATAMENTO DE ERROS
\* ---------------------------------------------------------------------- */
function stoperror(){
var strErro = "ALERTA DE ERRO. Ocorreu um erro no javascript desta pagina.\n";
//TODO VOLTAR COM ESSE C�DIGO
alert(strErro+"Mensagem: "+arguments[0]+"\n"+arguments[1]+" [Linha: "+arguments[2]+"]");
return true;
}
//TODO Retornar apos testar em IE 7
//window.onerror=stoperror;
//if(""+AgntUsr && ""+AgntUsr.indexOf("msie 7") > -1 && getParametroUrl("erro") != "s"){
//	window.onerror = function(){
		//Alerta erro, nao fazer nada neste caso
//		return true;
//	}
//}


function hideFormSelect(){
  if (!document.all)
  {
    return; // only Internet Explorer is affected by the bug
  }
  var dfl = document.forms.length;
  for (var i = 0; i < dfl; i++)
  {
    var dfle = document.forms[i].elements.length;
    for (var j = 0; j < dfle; j++)
    {
      if (document.forms[i].elements[j].type && document.forms[i].elements[j].type.indexOf('sel') != -1)
      {
        document.forms[i].elements[j].style.visibility = 'hidden'
      }
    }
  }
}

function showFormSelect()
{
  if (!document.all)
  {
    return; // only Internet Explorer is affected by the bug
  }
  var dfl = document.forms.length;
  for (var i = 0; i < dfl; i++)
  {
    var dfle = document.forms[i].elements.length;
    for (var j = 0; j < dfle; j++)
    {
      if (document.forms[i].elements[j].type && document.forms[i].elements[j].type.indexOf('sel') != -1)
      {
        document.forms[i].elements[j].style.visibility = 'visible';
      }
    }
  }
}

function hideIframe()
{
	if(document.frames){
		for(i = 0; i < document.frames.length; i++)
		{
			try{
				var ifUrl = document.frames[i].location.href;
				setVisible(document.frames[i].name, "hidden");
			}catch(e){
				plcLog.debug("IFRAME SEM PERMISSAO DE ACESSO");
			}
		}
	}
}

function showIframe()
{
	if(document.frames){
		for(i = 0; i < document.frames.length; i++)
		{
			try{
				var ifUrl = document.frames[i].location.href;
				setVisible(document.frames[i].name, "visible")
			}catch(e){
				plcLog.debug("IFRAME SEM PERMISSAO DE ACESSO");
			}
		}
	}
}

/*
* Fecha a janela
*/
function fecharJanela()
{
	window.close();
}



/*
* Abre janela utilizando a resolu??o dispon?vel.
*/
function janelaMax(url) {
    var win;
    var w = screen.availWidth -3;
    var h = screen.availHeight -25;

    win = window.open(url,"","resizable=yes,scrollbars=yes,left=0,top=0,width="+w+",height="+h);
}



/**********************************************************
Formatar a data digitada
--------------------------------------------
Fun??o:     formataData(Campo,Prox,tammax,teclapres)
--------------------------------------------

=> Campo =  Tipo: String
        Nome do campo de data
=> prox  =  Tipo: String
        Nome do pr?ximo campo
=> tammax = Tipo: int [8]
        Tamanho m?ximo permitido
=> teclapres =  Tipo: event [event]
        O evento disparado para chamar a fun??o
        (tecla pressionada, por exemplo)

<Chamar no ONKEYPRESS do campo>

Exemplo:    formataData('fldData',event);

Obs.: A data digitada aparecer? no formato: dd/mm/aaaa

**********************************************************/


function formataData(campo,evt)
{
    if(NavYes)
        var tecla = evt.which;
    else
        var tecla = evt.keyCode;

    vr = retornaValorCampo(campo);
	//Comentado por Rodrigo Magno para utiliza??o correta em Mozilla/Firefox
    /*if(NNYes)
    {
        var ult = vr.substring(0,1);
        vr = vr.substring(1,vr.length)+ult;
        vr = filtraCampo(vr);
    }
    else {*/
      vr = vr.replace( ".", "" );
        vr = vr.replace( "/", "" );
        vr = vr.replace( "/", "" );
        vr = vr.replace( "/", "" );
    //}

    tam = vr.length +1;
    if ( tecla != 9 && tecla != 8 && tecla != 0 )
    {
		if ( tam > 2 && tam < 5 )
			vr = vr.substr( 0, 2 ) + '/' + vr.substr(2, tam );
        if ( tam >= 5 && tam <= 10 )
            vr = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 3 );
		
		setValorCampo(campo, vr);
        
        return false;
    }
}

/****************************************************************
Bloqueia digita??o de caracter n?o permitido pelo tipo
------------------------------------------------
Fun??o:		validaCaracter(campo, evt, tipo)
------------------------------------------------

=> campo  =	Tipo: String
		Nome do campo atual
=> tipo   =	Tipo: String
		Tipo do valor no campo [D=Data; V=Valor ; H=Hora]
=> evt    =	[event]
		O evento disparado para chamar a fun??o
		(tecla pressionada, por exemplo)

<Chamar no ONKEYDOWN do campo testando seu retorno>

Exemplo:	return validaCaracter('fldCPF',event, "V");

****************************************************************/
function validaCaracter(campo, evt, tipo)
{
	//Contribui??o Dionatan Almeida
   var key;
   var keychar;
	key = getKeyCode(evt);	
   /**
   * C?digos de teclas do teclado num?rico
	de 96 ? 105 =  0 - 9
        106 = *
        107 = +
        109 = -
        110 = ,
        111 = /
        194 = .
      */

   // array das setas
   var keyseta = new Array(37,39);

   // array dos numeros + setas
   var keynum = new Array(96,97,98,99,100,101,102,103,104,105,37,39);

   // array de data + numeros
   var keynumD = new Array(96,97,98,99,100,101,102,103,104,105,37,39,111);

   // array dos numeros
   var keydigit = new Array(96,97,98,99,100,101,102,103,104,105);

   // array da v�rgula (,) e ponto (.)
   var keyfloat = new Array(188,190,110,194);

   keychar = String.fromCharCode(key);

   var ehValido = false;

   if ((key==null) || (key==0) || (key==8) || (key==9)|| (key==27) ||
		(key==46))
        ehValido = true;
   else if (tipo=="V" && ((("0123456789").indexOf(keychar) > -1) ||
		validaKeyArray(key,keynum)))
   		ehValido = true;
   else if (tipo=="D" && ((("/0123456789").indexOf(keychar) > -1) ||
		validaKeyArray(key,keynumD)))
	    ehValido = true;
   else if (tipo=="DT" && (((" :/0123456789").indexOf(keychar) > -1) ||
		validaKeyArray(key,keynumD)))
	    ehValido = true;
   else if (tipo=="H" && (((":0123456789").indexOf(keychar) > -1) ||
		validaKeyArray(key,keynum)))
   		ehValido = true;
   else if (tipo=="A" && (("0123456789").indexOf(keychar) == -1 || 
   			validaKeyArray(key,keyseta)))
		ehValido = true;
   else if (tipo=="F" && (("0123456789").indexOf(keychar) > -1 || 
   			validaKeyArray(key,keynum) || validaKeyArray(key,keyfloat)))
		ehValido = true;
	
	if (!ehValido && campo != null) {
		while (campo.value.indexOf(keychar) > -1 || campo.value.indexOf(keychar.toLowerCase()) > -1){
				campo.value = campo.value.replace(keychar, "");
				campo.value = campo.value.replace(keychar.toLowerCase(), "");
		}
	}	
	
   return ehValido;
}

function validaKeyArray(keycode, keyArray){
	var achou = false;

	if(keyArray != null){
		for(var i = 0; i < keyArray.length; i++){
			//alert("keycode:"+keycode+" = keyArray["+i+"]:"+keyArray[i]);
			if(keyArray[i] == keycode){
				achou = true;
				break;
			}
		}
		return achou;
	} else {
		return true;
	}
}

/***********************************************************************************
Filtra dados do campo - Utilizado apenas pelo Netscape
***********************************************************************************/
function filtraCampo(valor){
	var s = "";
	var cp = "";
	vr = valor;
	tam = vr.length;

	for (i = 0; i < tam ; i++)
	{
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && 			vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," )
		{
		 	s = s + vr.substring(i,i + 1);
		}
	}
	return s
}

/************************************************************
Saltar para o pr?ximo campo
--------------------------------------------------------
Fun??o:		saltaCampo (campo,prox,tammax,teclapres)
--------------------------------------------------------

=> campo =	Tipo: String
		Nome do campo atual
=> prox  =	Tipo: String
		Nome do pr?ximo campo
=> tammax =	Tipo: int
		Tamanho m?ximo do campo atual
=> teclapres =	[event]
		O evento disparado para chamar a fun??o
		(tecla pressionada, por exemplo)

<Chamar no ONKEYUP do campo>

Exemplo:	saltaCampo('fldatual','fldprox',5,event);

************************************************************/

function saltaCampo (campo,prox,tammax,teclapres,form)
{
    if(NNav)
        var tecla = teclapres.which;
    else
        var tecla = teclapres.keyCode;

	var ssProx 	= getCampo(prox, form);
	var vr = retornaValorCampo(campo,form);
 	var tam = vr.length;

 	if (tecla != 0 && tecla != 9 && tecla != 16)
	{
		if(tecla == 13)
			ssProx.focus();
		else if ( tam == tammax )
		{
			ssProx.focus() ;
		}
	}
}

function setFuncaoOnLoad(decFunction) {
   if (this.cacheFunction == null) {this.cacheFunction = new Array();}
   this.cacheFunction[this.cacheFunction.length] = decFunction;
}

function executarFuncaoOnLoad()
{
	plcLog.debug("##### Entrou para executar funcoes no onload")
	plcLog.debug("FUNCOES: "+this.cacheFunction);

	if(this.cacheFunction != null)
	{
		var i = 0;
		while(i < this.cacheFunction.length){

			try{
				eval(this.cacheFunction[i]);
			}catch(e){
				plcLog.alertaExcecao(e,"Erro ao executar funcao no onload. Funcao executada: "+this.cacheFunction[i]);
			}

			i++;

		}

		/*for(i = 0; i < this.cacheFunction.length; i++){
			try{
				eval(this.cacheFunction[i]);
			}catch(e){
				plcLog.alertaExcecao(e,"Erro ao executar funcao no onload. Funcao executada: "+this.cacheFunction[i]);
	}
		}*/
		
	}
}

String.prototype.replaceAll = function(de, para){
    var str = this;
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

function replaceString(exp, str, repl){
	var strRepl = new String(str);
	strRepl = strRepl.replace(exp,repl);
	return strRepl;
}

function stringPrimeiraMaiuscula(str){
	return str.substring(0,1).toUpperCase() + str.substring(1,str.length);
}

/*-------------------------------------*\
	INICIO FUN??ES PARA TRATAMENTO URL
\*-------------------------------------*/

function limparUrl(url,str)
{
	var pos = url.indexOf(str);
	if(pos >= 0)
		return url.substring(0,pos);
	else
		return url;
}

function incluirIdSessao(url, id)
{
	var exp = new RegExp("\\.do");
	url = replaceString(exp, url, ".do;jsessionid="+id);
	return url;
}

//FIM FUN??ES PARA TRATAMENTO URL


/*----------------------------------------*\
	INICIO FUN??ES PARA TRATAMENTO IMAGENS
\*----------------------------------------*/
var images = new Array();
function regImg(nome, src, alt)
{
	this.nome = nome;
	this.src  = src;
	this.alt  = alt;
}

function getImagem(nome)
{
	for(i = 0; i < images.length; i++)
	{
		if(images[i].nome == nome)
			return images[i];
	}
	return false;
}

function getImagemById(id)
{
	return document.images[id];
}

function alteraImagem(id, src, alt)
{
	var img = getImagemById(id);
	if(img)
	{
		img.src = src;
		img.alt = alt;
	}
}

function alteraImagems(id, src, alt)
{
	if(document.images){
		for(i=0; i<document.images.length; i++)
		{
			if(document.images[i] && document.images[i].id == id) {
				if(document.images[i].src)
					document.images[i].src = src;
				if(document.images[i].alt)
					document.images[i].alt = alt;
			}
		}
	}
}

/**
 * Fun??o para retornar multiplos valores.<b>
 * adiciona o valor no campo registrado para a chave idsPlc e descPlc
 * no idsPlc ser? adicionado os valos do campo com id idsPlc da p?gina de sele??o
 * no descPlc ser? adicionado os valos do campo com id descPlc da p?gina de sele??o
 */
function retornarMultiSel()
{
	var checks 	= getCampo("indExcPlc");	//checkbox
	var idsPlc 	= getCampo("idsPlc");	// ids de todas as linhas
	var descPlc = getCampo("descPlc");	// descri??o de todas as linhas

	//se encontrou o objeto
	if(checks){
		if(!checks.length){	//se for apenas 1 check, o javascript trava n�o como array e sim como apenas umc campo
			if (checks.checked){
				opener.setValorCampo(opener.getCampoRetornoById('idsPlc'),idsPlc.value,",");
				opener.setValorCampo(opener.getCampoRetornoById('descPlc'),descPlc.value,"\n");
			}
		}

		//para cada check marcado, seta o valor nos campos. n�o adiciona valores repetidos
		for (var i = 0; i < checks.length; i++){
			var e = checks[i];
			if (e.checked){
				opener.setValorCampo(opener.getCampoRetornoById('idsPlc'),idsPlc[i].value,",");
				opener.setValorCampo(opener.getCampoRetornoById('descPlc'),descPlc[i].value,"\n");
			}
		}

		window.close();
	}
}

/*-----------------------------------------------------*\
	INICIO FUN??ES PARA TRATAMENTO CRITERIO ORDENACAO
	-------------------------------------------------
 	Utiliza??o:
 	<a href="#" onclick="setValorCampoAtualizacao('saida', 'obj.id '+getCriterioOrdenacao('id'), montaCriterioNovo('id', 'obj'), ',');
 	substituirImagem('id')">C?digo</a>
\*-----------------------------------------------------*/

function atualizaCriterio(nomeCampo, valorReplace, valorNovo, separador, form)
{
	atualizaValorCampo(nomeCampo, valorReplace, valorNovo, separador, form);
	setValorCampo(nomeCampo, valorNovo, separador, form);
	setValorCampo(nomeCampo, ordenaCriterio (nomeCampo, retornaValorCampo(nomeCampo), separador));
}

var ordem = new Array();
function ordenaCriterio (campo, listaCampos, separador)
{
	listaOrdenada = "";
	for (i = 0; i < ordem.length; i++)
	{
		if(ordem[i] != "undefined" && listaCampos.indexOf(ordem[i]+" ") >= 0)
		{
			if(listaOrdenada != "")
				listaOrdenada += separador;
			listaOrdenada += ordem[i]+" "+getCriterioOrdenacao(ordem[i]);
		}
	}
	return listaOrdenada;
}

function atualizaCriterioOrdenacao(chave)
{
	var criterio = getVarGlobal(chave);
	if(criterio == "desc")
		setVarGlobal(chave, "");
	else if(criterio == "asc")
		setVarGlobal(chave, "desc");
	else if(criterio == null || criterio == "")
	{
		setVarGlobal(chave, "asc");
		criterio = "asc";
	}
	return getVarGlobal(chave);
}

function getCriterioOrdenacao(chave)
{
	var criterio = getVarGlobal(chave);
	//Alterado porque n?o retornava sem crit?rio (branco) - by Rodrigo Magno
	//if (criterio == null || criterio == "" || ""+criterio == "undefined") {
	if (criterio == null || typeof criterio == "undefined") {
		criterio = "asc";
	}
	return criterio;
}

function setCriterioOrdenacao(chave, criterio)
{
	setVarGlobal(chave,criterio);
}

function mantemEstadoCriterio(listaCampos, chave, separador)
{
	var campos = listaCampos.split(separador);
	for (k=0; k < campos.length; k++)
	{
		var dadosCampo = campos[k].split(" ");
		if(dadosCampo[0] == chave){
			setCriterioOrdenacao(dadosCampo[0],dadosCampo[1]);
			substituirImagems(dadosCampo[0]);
			break;
		}
	}
}

function montaCriterioNovo(campo, alias)
{
	var criterio = atualizaCriterioOrdenacao(campo);
	if(criterio == null || criterio == "" || ""+criterio == "undefined")
		return "";
	else
		return campo+" "+criterio;
}

function substituirImagem(campo)
{
	var criterio = getCriterioOrdenacao(campo);
	var imgArray = getImagem(criterio);
	alteraImagem("IMAGEM_"+campo, imgArray.src, imgArray.alt);
}

function substituirImagems(campo)
{
	var criterio = getCriterioOrdenacao(campo);
	var imgArray = getImagem(criterio);
	alteraImagems("IMAGEM_"+campo, imgArray.src, imgArray.alt);
}

function getDocumento(){
	return (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body
}

function getElementoPorId(elementoID){
	var crossElemento = null;
	
	if(document.getElementById && document.getElementById(elementoID))
		crossElemento = document.getElementById(elementoID)
	else{
		if (tecnologia=="struts"){
			if(document.all && eval("document.all."+elementoID))
				crossElemento = eval("document.all."+elementoID);
			else if (eval("document."+elementoID))
				return eval("document."+elementoID);
		}else{
			if(document.all && eval("document.all['"+elementoID+"']"))
				crossElemento = eval("document.all['"+elementoID+"']");
			else if (eval("document['"+elementoID+"']"))
				return eval("document['"+elementoID+"']");
		}
	}
	return crossElemento;
}

function getPosicaoScroll(){

	var dsocleft = document.all? getDocumento().scrollLeft : pageXOffset;
	var dsoctop	=	document.all? getDocumento().scrollTop : pageYOffset;

	var posicaoScroll = new Object();
	posicaoScroll.posEsquerda 	= dsocleft;
	posicaoScroll.posTopo 			= dsoctop;
	return posicaoScroll;
}

function getElementoStyle(elementoID){

	var crossElemento = getElementoPorId(elementoID);
	var crossElementoStyle = "";
	if(crossElemento){
		if (document.all||document.getElementById)
			crossElementoStyle =  eval(crossElemento.style);
		else if (document.layers)
			crossElementoStyle =  crossElemento;
	}
	return crossElementoStyle;
}

function posicionaElemento(elementoID, posX, posY, incremental){
	var crossElementoStyle = getElementoStyle(elementoID);
	incremental = incremental != "" || typeof incremental != "undefined" ? incremental : false;
	var crossElementoStyle = getElementoStyle(elementoID);
	if(posX && posX != "" && typeof posX != "undefined")
		crossElementoStyle.top = incremental ? getVarGlobal("topo"+elementoID) + parseInt(posX) : parseInt(posX) ;
	if(posY && posY != "" && typeof posY != "undefined")
		crossElementoStyle.left = incremental ? getVarGlobal("esquerda"+elementoID) + parseInt(posY) : parseInt(posY);
}

function posicionaElementoPor(elementoID, posX, posY){
	var crossElementoStyle = getElementoStyle(elementoID);
	if(getVarGlobal("esquerda"+elementoID) == null)
		setVarGlobal("esquerda"+elementoID,parseInt(crossElementoStyle.left));
	if(getVarGlobal("topo"+elementoID) == null)
		setVarGlobal("topo"+elementoID,parseInt(crossElementoStyle.top));

	posicionaElemento(elementoID, posX, posY, true);
}

function redimensionaElemento(elementoID, wa, ha, incremental){

	incremental = incremental != "" || typeof incremental != "undefined" ? incremental : false;
	var crossElementoStyle = getElementoStyle(elementoID);
	if(wa && wa != "" && typeof wa != "undefined")
		crossElementoStyle.width = incremental ? getVarGlobal("largura"+elementoID) + wa : wa;
	if(ha && ha != "" && typeof ha != "undefined")
		crossElementoStyle.height = incremental ? getVarGlobal("altura"+elementoID) + ha : ha;
}

function redimensionaElementoPor(elementoID, wa, ha){
	var crossElementoStyle = getElementoStyle(elementoID);
	if(getVarGlobal("altura"+elementoID) == null)
		setVarGlobal("altura"+elementoID,parseInt(crossElementoStyle.height));
	if(getVarGlobal("largura"+elementoID) == null)
		setVarGlobal("largura"+elementoID,parseInt(crossElementoStyle.width));

	redimensionaElemento(elementoID, wa, ha,true);
}

/*-----------------------------------------------------*\
   INICIO FUN??ES PARA ABA ?GIL
\*-----------------------------------------------------*/

var layers    = new Array();
var layersFilhos   = new Array();
var abaAgilUsaAncora = true;
var tabSelecionada = "";
var tabFilhoSelecionada = "";
function showHideAba(aba,ancora){
	var layersAux = layers;
	var _doc = getRootDocument();
	if(aba.indexOf("->") > -1)
		layersAux = layersFilhos;	
	for( var i=0; i<layersAux.length; i++){
		try{
			if(layersAux[i] == aba){
				if(aba.indexOf("->") < 0)
			   		tabSelecionada = aba;
				_doc.getElementById(layersAux[i]).className = "ativada";
				_doc.getElementById("td_borda_"+layersAux[i]).className = "ativada";
			   	_doc.getElementById(layersAux[i]+"_corpo").className = "tabVisivel";
				if(ancora != null && ancora != "" && abaAgilUsaAncora)
				   	_doc.location.hash=ancora;
				if (tecnologia=='Struts')
				   	setValorCampo('tabCorrenteDinamicoPlc',aba);
				else
					setValorCampo('corpo:tabCorrenteDinamicoPlc',aba);
				var numAba	= tabSelecionada.substring(tabSelecionada.indexOf("_")+1);
				tabFolderFocaCampo(numAba)		
			}else{
			   	_doc.getElementById(layersAux[i]).className = "";
				_doc.getElementById("td_borda_"+layersAux[i]).className = "";
			   	_doc.getElementById(layersAux[i]+"_corpo").className = "tabOculta";
			}
		}catch(e){}
  	}
}

/*MANTEM QUAL TABFOLDER EST? SELECIONADA*/
function mantemAbaSelecionada (){
	if (tecnologia=='Struts')
		tabSelecionada = get('tabCorrenteDinamicoPlc') != "" ? get('tabCorrenteDinamicoPlc') : tabSelecionada;
	else
		tabSelecionada = get('corpo:tabCorrenteDinamicoPlc') != "" ? get('corpo:tabCorrenteDinamicoPlc') : tabSelecionada;
	if(tabSelecionada.indexOf("->") > -1){
		var tabSelecionadaAux = tabSelecionada; 
		showHideAba(tabSelecionada.substring(0,tabSelecionada.indexOf("->")));
		tabSelecionada = tabSelecionadaAux; 
		showHideAba(tabSelecionada);
	}else{
		showHideAba(tabSelecionada);
		if(tabFilhoSelecionada != "")
			showHideAba(tabFilhoSelecionada);
	}	
}

function trocaAba(index,thisId,nomeAba){
	if(getVarGlobal(index) && typeof getVarGlobal(index) != "undefined")
		set('detCorrPlc',getVarGlobal(index));
	else	
		set('detCorrPlc',"");
	showHideAba(thisId,nomeAba);
}

/******************************************************************************\
					 FUN??ES PARA MANIPULA??ES DE EVENTOS
\******************************************************************************/
function PlcEvento (){}

var plcEvento = new PlcEvento();

/*----------------------------------------------------------------------------*\
   jCompany 2.5. Guarda objeto do foco para facilitar cria??o de novos detalhes
\*----------------------------------------------------------------------------*/
 function trataOnFocus (evt) {
	// Pega nome do detalhe, se campo contiver, ou esvazia o "detCorrPlc"
	var nomeCampo = this.name;
	if (nomeCampo.indexOf(".")==-1)
	   set("detCorrPlc","");
	else {
		var nomeDet = nomeCampo.substring(0,nomeCampo.indexOf("["));
		set("detCorrPlc",nomeDet);
	}
	// Compatibiliza com evento de onfocus existente

	if (evt && this.oldOnFocus && this.oldOnFocus.name != "trataOnFocus" && 
		(this.oldOnFocus+"").indexOf("function trataOnFocus") == -1){
	      this.oldOnFocus(evt);
	}
}

PlcEvento.prototype.getEventoElemento = function(evento){

	plcLog.debug("##### Entrou em getEventoElemento")
	var elemento = null;
	if(ExpYes){
		if(evento.srcElement)
			elemento = evento.srcElement;
	}else{
		if(evento.target)
			elemento = evento.target;
	}
	return elemento
}
PlcEvento.prototype.getEventoAtual = function(evento){
	if(ExpYes && window.event)
		return window.event.type;
	else if (NavYes && evento && Event){
		if(evento.toUpperCase() == "ONCHANGE" && document.captureEvents(Event.ONCHANGE))
			return document.captureEvents(Event.ONCHANGE);
		if(evento.toUpperCase() == "ONCLICK" && document.captureEvents(Event.ONCLICK))
			return document.captureEvents(Event.ONCLICK);
		if(evento.toUpperCase() == "ONKEYDOWN" && document.captureEvents(Event.ONKEYDOWN))
			return document.captureEvents(Event.ONKEYDOWN);
	}
}
/*---------------------------------------------------------------------------------*\
  jCompany 2.5. Acrescenta evento ? fun??o onFocus para logica de registro do objeto
\*---------------------------------------------------------------------------------*/
//TODO Ver possibilidade de adequar a novo modelo de eventos - by Rodrigo Magno
 function setUpOnFocusHandlers () {
 	if(document.forms) {
	    for (var f = 0; f < document.forms.length; f++) {
 			if(document.forms[f].elements) {
		      for (var e = 0; e < document.forms[f].elements.length; e++) {
		        if (document.forms[f].elements[e] &&
		          (document.forms[f].elements[e].type == 'text'
		           || document.forms[f].elements[e].type == 'textarea'
		           || document.forms[f].elements[e].type == 'select-one'
		           || document.forms[f].elements[e].type == 'select-multiple'
		           || document.forms[f].elements[e].type == 'password'
		           || document.forms[f].elements[e].type == 'checkbox'
		           || document.forms[f].elements[e].type == 'radio'
		           || document.forms[f].elements[e].type == 'file'
		           || document.forms[f].elements[e].type == 'fileupload')) {
		          document.forms[f].elements[e].oldOnFocus =
		            document.forms[f].elements[e].onfocus;
		          document.forms[f].elements[e].onfocus = trataOnFocus;
		        }
		      }
		   }
	    }
	 }
  }

/*--------------------------------------------------------------*\
   jCompany 2.7.2 - Inibe evento onclick
\*--------------------------------------------------------------*/
 function inibeOnClick (evt) {
	return false;
 }

PlcEvento.prototype.trataEventoJcp = function (evt) {
	//plcLog.debug("trataEventoJcp")
	//Desmarca item da lista de sele??o pois foi focado campo de argumento
	desmarcaListaSelecao();
	return true;
};
/*--------------------------------------------------------------*\
   jCompany 2.7.2 - Trata evento onclick genericamente
\*--------------------------------------------------------------*/
PlcEvento.prototype.eventoTrataClick = function (evt) {return true;};
function eventoTrataonclick(evt, objeto){
	var retClick = true;
	if(typeof objeto == "undefined")
		objeto = this;
	if(plcEvento.eventoTrataClick(evt)){
		if (objeto.oldonclick)
			retClick = objeto.oldonclick(evt);
		if(retClick)
			retClick = plcEvento.trataEventoJcp(evt);
	}else
		return false;
	return retClick;
}

/*--------------------------------------------------------------*\
   jCompany 2.7.2 - Trata evento onchange genericamente
\*--------------------------------------------------------------*/
PlcEvento.prototype.eventoTrataChange = function (evt) {return true;};
function eventoTrataonchange(evt, objeto){

	plcLog.debug("eventoTrataonchange")
	if(typeof evt == "undefined")
		evt = plcEvento.getEventoAtual('ONCHANGE')
	plcLog.debug("EVENTO: "+evt)	
	var retChange = true;
	if(typeof objeto == "undefined")
		objeto = this;
	if(plcEvento.eventoTrataChange(evt)){
		if (objeto.oldonchange)
			retChange = objeto.oldonchange(evt);
		if(retChange)
			retChange = plcEvento.trataEventoJcp(evt);
	}else
		return false;
	return retChange;

}

/*--------------------------------------------------------------*\
   jCompany 3.0 - Trata evento onfocus genericamente
\*--------------------------------------------------------------*/
PlcEvento.prototype.eventoTrataFocus = function (evt) {return true;};
function eventoTrataonfocus(evt, objeto){
	var retFocus = true;
	if(typeof objeto == "undefined")
		objeto = this;
	if(plcEvento.eventoTrataFocus(evt)){
		if (objeto.oldonfocus)
			retFocus = objeto.oldonfocus(evt);
		if(retFocus)
			retFocus = plcEvento.trataEventoJcp(evt);
	}else
		return false;
	return retFocus;
}

/*--------------------------------------------------------------*\
   jCompany 3.0 - Trata evento onblur genericamente
\*--------------------------------------------------------------*/
PlcEvento.prototype.eventoTrataBlur = function (evt) {return true;};
function eventoTrataonblur(evt, objeto){
	var retBlur = true;
	if(typeof objeto == "undefined")
		objeto = this;
	if(plcEvento.eventoTrataBlur(evt)){
		if (objeto.oldonblur)
			retBlur = objeto.oldonblur(evt);
		if(retBlur)
			retBlur = plcEvento.trataEventoJcp(evt);
	}else
		return false;
	return retBlur;
}

/*--------------------------------------------------------------*\
   jCompany 2.7.2 - Verifica se h? altera??o em algum campo
\*--------------------------------------------------------------*/
var msgAlteracao;
function enviaAlertaAlteracao (evt) {
	//alert("enviaAlertaAlteracao")
	//alert("inibeAlertaAlteracaoPadrao: "+inibeAlertaAlteracaoPadrao(this))
	//alert("plcGeral.inibeAlertaAlteracao: "+plcGeral.inibeAlertaAlteracao(this))
	//alert("disparouBotao: "+disparouBotao)
 	//if (ExpYes) {
		if(!disparouBotao  && !inibeAlertaAlteracaoPadrao(this) && !plcGeral.inibeAlertaAlteracao(this)){
			if(confirm(msgAlteracao)){
				setAlertaAlteracao();
			}else
				return false;
		}
	//}
	return eventoTrataonclick(evt, this);
}

/*--------------------------------------------------------------*\
   jCompany 2.7.2 - Fun??o para sobreposi??o em caso de regras para
   inibi??o de alerta de altera??o
\*--------------------------------------------------------------*/
PlcGeral.prototype.inibeAlertaAlteracao = function (objeto) {return false;}
function inibeAlertaAlteracaoPadrao(objeto){

	//alert("getAlertaAlteracao(): "+getAlertaAlteracao())
	if(getAlertaAlteracao() != "S")
		return true;
		
	var inibeAlertaAtributo = false;
	var inibeAlertaBotao 	= false;
	try{
		inibeAlertaAtributo = (typeof objeto != "undefined" && 
								(
								(objeto.getAttribute("inibeAlertaAlteracao") != null ||
								objeto.getAttribute("inibeAlertaAlteracao"))
								 || 
								(typeof objeto.id != "undefined" &&							
								objeto.id.indexOf("INIBE_ALERTA_ALTERACAO") > -1)
								)
								);
	}catch(e){}
	
	//alert("objeto.id: "+objeto.id)
	//alert("inibeAlertaAtributo : "+inibeAlertaAtributo)
	//alert("objeto.value: "+objeto.value)
	if(getAlertaAlteracao() == "S"){
		inibeAlertaBotao = 
		(objeto.value == getBotaoArray('EXCLUIR') ||
		objeto.value == getBotaoArray('GRAVAR') || 
		objeto.value == getBotaoArray('INCLUIR_DET') || 
		objeto.value == getBotaoArray('IMPRIMIR') || 
		objeto.value == getBotaoArray('ASSISTENTE_INICIALIZA') ||
		objeto.value == getBotaoArray('ASSISTENTE_ANTERIOR') ||
		objeto.value == getBotaoArray('ASSISTENTE_CANCELA') ||
		objeto.value == getBotaoArray('ASSISTENTE_PROXIMO') ||
		objeto.value == getBotaoArray('REFRESH') ||
		objeto.value == getBotaoArray('REFRESH_CACHE') ||
		objeto.value == getBotaoArray('VIS_DOCUMENTO') ||
		objeto.value == getBotaoArray('EDT_DOCUMENTO') ||
		objeto.value == getBotaoArray('ARQ_ANEXADO') ||
		(objeto.value == getBotaoArray('INCLUIR') && get('detCorrPlc') != "")
		);
	}
	//alert("inibeAlertaBotao: "+inibeAlertaBotao)
	return inibeAlertaAtributo || inibeAlertaBotao ;
}

function setAlertaAlteracao(evt, alerta){
	plcLog.debug("setAlertaAlteracao")
	if(alerta != "")
		set("alertaAlteracaoPlc","S");
	else 	
		set("alertaAlteracaoPlc","");
	plcLog.debug("setAlertaAlteracao - evt: "+evt)
	//if(evt && evt != "")	
		return eventoTrataonchange(evt, this);
}

function getAlertaAlteracao(){
	return get("alertaAlteracaoPlc");
}

/*---------------------------------------------------------------------------*\
  jCompany 2.7.2 - Acrescenta eventos a um conjunto de tags ou a um elemento
\*---------------------------------------------------------------------------*/
function setUpOnEventoElemento (idElemento, evento, funcao) {
	setUpEventos ("", idElemento, evento, funcao,"");
}

function setUpOnEventoTag (tag, evento, funcao) {
	setUpEventos (tag, "", evento, funcao,"");
}

function setUpOnEventoTagCampoNome (tag, evento, funcao, nome) {
	setUpEventos (tag, "", evento, funcao, nome);
}

function setUpEventos (tag, idElemento, evento, funcao, nome) {

	var tags;
	var tipo = "";
	var elementos;

	//alert("Entrei setUpEventos");

	//alert("setUpEventos - Nome: "+nome);
	//alert("setUpEventos - Tag: "+tag);
	//alert("setUpEventos - Funcao: "+funcao)
	//alert("setUpEventos - Tipo: "+tipo)
	//alert("setUpEventos - Id Elemento: "+idElemento);
	
	if(typeof tag != "undefined" && tag != ""){
		var posTipo = tag.indexOf("#")
		if(posTipo >= 0){
			tags = document.getElementsByTagName(tag.substring(0,posTipo));
			tipo = tag.substring(posTipo+1)
		}else
			tags = document.getElementsByTagName(tag);
	}else if (typeof nome != "undefined" && nome != ""){
		tags = new Array();
		tags[tags.length] = getCampo(nome);
	}
	else if(typeof idElemento != "undefined" && idElemento != "")
		elementos = getElementoPorId(idElemento);

 	if(tags) {
		//alert("NUM. TAGS: "+tags.length)
	    for (var t = 0; t < tags.length; t++) {
			var umaTag = tags[t];
 			if(umaTag && ((tipo == "" || umaTag.type == tipo) && 
 			(nome == "" || umaTag.name == nome))) {
				//alert("UMATAG.NAME: "+umaTag.name)
				if(eval("umaTag."+funcao) != funcao )
					eval("umaTag.old"+evento.toLowerCase()+" = umaTag."+evento.toLowerCase());
				if(typeof funcao != "undefined" && funcao != ""){
					eval("umaTag."+funcao+"='"+funcao+"'");
					eval("umaTag."+evento.toLowerCase()+" = "+funcao);
				}
				else
					eval("umaTag."+evento.toLowerCase()+" = eventoTrata"+evento.toLowerCase());
			}
			
			//if(umaTag.name == "nome_Arg"){
				//alert("FOCUS: "+umaTag.onfocus)
				//alert("OLD FOCUS: "+umaTag.oldonfocus)
				//alert("CHANGE: "+umaTag.onchange)
				//alert("OLD CHANGE: "+umaTag.oldonchange)
				//alert("BLUR: "+umaTag.onblur)
				//alert("OLD BLUR: "+umaTag.oldonblur)
			//}
		}
	}
	if(elementos) {
	
		var elementoAnterior = elementos;
		if(!elementos.length){
			elementos = new Array();
			elementos[elementos.length] = elementoAnterior
		}
		
        if (!ExpYes && evento.substring(0,2)=="on") {
			evento = evento.substring(2);
        }
		
	    for (e = 0; e < elementos.length; e++) {
	    	var umElemento = elementos[e];
	    	if(umElemento){
				if(eval("umElemento."+funcao) != funcao )
					eval("umElemento.old"+evento.toLowerCase()+" = umElemento."+evento.toLowerCase());
				if(typeof funcao != "undefined" && funcao != ""){
					if(ExpYes)
						eval("umElemento."+evento.toLowerCase()+" = "+funcao);
					else
						eval("umElemento.addEventListener('"+evento.toLowerCase()+"',"+funcao+",false)");
				}
				else{
					if(ExpYes)
						eval("umElemento."+evento.toLowerCase()+" = eventoTrata"+evento.toLowerCase());	
					else
						eval("umElemento.addEventListener('"+evento.toLowerCase()+"','eventoTrata"+evento.toLowerCase()+",false)");
				}
	    	}
		}
	}
}

/*---------------------------------------------------------------------------*\
  jCompany 2.5.3 Altera classes dos objetos
\*---------------------------------------------------------------------------*/
 function alteraClasse () {
	if(arguments && arguments.length > 0)
	{
		this.ID 		= "";
		this.CAMPO		= "";
		this.TIPO		= "";
		this.CLASSE		= "";
		this.OBJETO		= "";
		this.INICIAL	= false;
		this.NOVACLASSE	= false;

		for(i = 0; i < arguments.length; i++)
		{
			if(arguments[i] == "ID")
				this.ID = arguments[++i];
			else if(arguments[i] == "CAMPO")
				this.CAMPO = arguments[++i];
			else if(arguments[i] == "TIPO")
				this.TIPO = arguments[++i];
			else if(arguments[i] == "CLASSE")
				this.CLASSE = arguments[++i];
			else if(arguments[i] == "OBJETO")
				this.OBJETO = arguments[++i];
			else if(arguments[i] == "NOVACLASSE")
				this.NOVACLASSE = true;
			else if(arguments[i] == "INICIAL")
				this.INICIAL = true;
		}
	}

	var elements = "";
	if(this.ID != ""){
		elements = getElementoPorId(this.ID);
	}else if (this.OBJETO != ""){
		elements = this.OBJETO;
		elements = new Array(elements);
	}else if (this.CAMPO){
		elements = document.forms[0].elements[this.CAMPO];
		elements = new Array(elements);
	}
  	if(elements) {
		for (var e = 0; e < elements.length; e++) {
			if (elements[e]) {
				if(this.NOVACLASSE)
					elements[e].className = this.CLASSE;
				else if (this.INICIAL){
					var exp = this.CLASSE;
			    	elements[e].className = elements[e].className.replace(exp,"");
				}
				else{
					elements[e].className = elements[e].className +" "+ this.CLASSE;
				}
			}
		}
	}
}

function marcaSelecao(linha, evt){
		if(evt.type == "mouseover")
			alteraClasse('OBJETO', linha, 'CLASSE', 'campoComErro');
		else
			alteraClasse('OBJETO', linha, 'CLASSE', 'campoComErro','INICIAL');
			
		if(getVarGlobal("trSelecao") != null){	
			alteraClasse('OBJETO', getVarGlobal("trSelecao"), 'CLASSE', 'campoComErro','INICIAL');
			setVarGlobal("trSelecao", null)
		}	
}

/*---------------------------------------------------------------------------*\
  jCompany 2.5.7 Fun??o: formata campo do tipo monet?rio.
  Contribui??o Est?dio de Desenvolvimento - Grupo Ultra
  EXEMPLO DE CHAMADA:
  onkeypress=" return(currencyFormat(this, event, <separador milhar>, <separador decimal>))"
	this = refer?ncia ao objeto campo [OB]
	event= evento que ocasionou a chamada da fun??o. [Fixo, OB]
	separador milhar = caracter utilizado para separar milhares. <Default: '.'> [OP]
	separador decimal= caracter utilizado para separar casas decimais <Default: ','> [OP]
  @since 03/08/2005
\*---------------------------------------------------------------------------*/
  function formataMonetario(fld, e, milSep, decSep) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	milSep = typeof milSep != "undefined" ? milSep : ".";
	decSep = typeof decSep != "undefined" ? decSep : ",";
	var whichCode = getKeyCode(e);
	if (whichCode == 13) // Tecla 'Enter'
		return true;
	if (NavYes && whichCode == 0) // Tecla 'Tab'
		return true;
		
	key = String.fromCharCode(whichCode);  			// Recupera c?digo da tecla pressionada
	if(!validaCaracter(null, e, "V"))
		return false;
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))
			break;
	aux = '';
	for(; i < len; i++){
		if (strCheck.indexOf(fld.value.charAt(i))!=-1)
			aux += fld.value.charAt(i);
	}
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
 }

/**
* Fun??o que expande retrai menu de contexto
*/
 function expandeMenu(obj){
	if(document.getElementById){
	var el = document.getElementById(obj);
	var ar = document.getElementById("masterdiv").getElementsByTagName("span");
		if(el.style.display != "block"){
			for (var i=0; i<ar.length; i++){
				if (ar[i].className=="expandeRetraiPlc")
				ar[i].style.display = "none";
			}
			el.style.display = "block";
		}else{
			el.style.display = "none";
		}
	}
}

	function alteraDisplay(idObjeto, objeto, valor){

		plcLog.debug(">>>>> Entrou alteraDisplay");	
		var estiloObjeto;
		if(!objeto || typeof objeto == "undefined" || objeto == "")
			estiloObjeto = getElementoStyle(idObjeto);
		else 	
			estiloObjeto = objeto.style;
		if(typeof valor == "undefined" || valor == "")	
			valor = "block";
		plcLog.debug("estiloObjeto: "+estiloObjeto);	
		plcLog.debug("estiloObjeto.display: "+estiloObjeto.display);	
		if(estiloObjeto){
			if(estiloObjeto.display == valor)
				estiloObjeto.display = "none";
			else
				estiloObjeto.display = valor;
		}
	}

function alteraEstilo(idObjeto){

	var estiloObjeto = getElementoStyle(idObjeto);
	if(estiloObjeto){
		for(i = 1; i < arguments.length; i++){
			//plcLog.debug("alteraEstilos: "+"estiloObjeto."+arguments[i]+" = "+arguments[++i]);
			eval("estiloObjeto."+arguments[i]+" = "+arguments[++i]);
		}
	}
}

/*---------------------------------------------------------------------------*\
  jCompany 2.5.7 Configura barra de progresso
\*---------------------------------------------------------------------------*/
// xp_progressbar
// Copyright 2004 Brian Gosselin of ScriptAsylum.com
// v1.0 - Initial release
// v1.1 - Added ability to pause the scrolling action (requires you to assign
//        the bar to a unique arbitrary variable).
//      - Added ability to specify an action to perform after a x amount of
//      - bar scrolls. This requires two added arguments.
// v1.2 - Added ability to hide/show each bar (requires you to assign the bar
//        to a unique arbitrary variable).
// var xyz = createBar(total_width,total_height,background_color,border_width,border_color,block_color,scroll_speed,block_count,scroll_count,action_to_perform_after_scrolled_n_times)
// var xyz = createBar(LARGURA,ALTURA,COR FUNDO,TAMANHO BORDA,COR BORDA,COR BLOCOS,VELOCIDADE,NUMERO BLOCOS,NUMERO VEZES,ENDERE?O PARA EXECUTAR APOS FIM, MENSAGEM)
var w3c=(document.getElementById)?true:false;
var ie=(document.all)?true:false;
var N=-1;
var barraProgressoAjax;
//var deslocWidthBar = (ie) ? 10 : 5;
//var deslocHeightBar = (ie) ? 90 : 125;
var deslocWidthBar = (ie) ? 30 : 20;
var deslocHeightBar = (ie) ? 100 : 135;
function createBar(w,h,bgc,brdW,brdC,blkC,speed,blocks,count,action,msg){
	var centroBar 	= getPosicaoCentro(w,h);
	var tamWindow	= getTamanhoWindow();
	var centroFundo = getPosicaoCentro(tamWindow.tamX, tamWindow.tamY);
	//alert((parseInt(tamWindow.tamX)) +","+ (parseInt(tamWindow.tamY)))
	//alert(window.offsetHeight);
	/**
	 * Calculo da posicao central independente do tamanho e tipo de resolucao (fullframe ou widescreen)
	 * @author Rodrigo Val�rio
	 * @since jCompany 5.0
	 */
	 var margemEsquerda = w/2;
	 var margemSuperior = h/2;
	 
	if(ie||w3c){
		var t='';
		//t+='<a href="#" onclick="barraProgresso(); return false;">Barra</a>';
		t+='<div id="fundoBar" style="background-color:lavender; z-index:200; display:none; position:absolute; top:0; left:0; width:'+(tamWindow.tamX - deslocWidthBar)+'px; height:'+(tamWindow.tamY - deslocHeightBar)+'px;'
		t+=(ie)?'filter:alpha(opacity='+50+')':'-Moz-opacity:'+(0.5);
		t+='"></div>';
		//t+='<div id="barraProgresso" style="visibility:visible; z-index:300; position:absolute; top:'+centroBar.moveCentroX+'; left:'+centroBar.moveCentroY+';">';
		t+='<div id="barraProgresso" style="visibility:visible; z-index:300; position:absolute; top:50%; left:50%; margin-left:-'+margemEsquerda+'px; margin-top:-'+margemSuperior+'px;">';
		t+='<div id="_xpbar'+(++N)+'" style="display:none; position:relative; overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';
		t+='<span id="blocks'+N+'" style="left:-'+(h*2+1)+'px; position:absolute; font-size:1px">';
		for(i=0; i<blocks; i++){
			t+='<span style="background-color:'+blkC+'; left:-'+((h*i)+i)+'px; font-size:1px; position:absolute; width:'+h+'px; height:'+h+'px; '
			t+=(ie)?'filter:alpha(opacity='+(100-i*(100/blocks))+')':'-Moz-opacity:'+((100-i*(100/blocks))/100);
			t+='"></span>';
		}
		//t+='</span><span style="vertical-align:\'middle\';"><table border="0"><tr><td style="vertical-align:\'middle\';'+estiloFonte+'; width:'+w+'px; height:'+h+'px;text-align:\'center\';"><center><b>'+msg+'</b></center></td></tr></table></span></div>';
		t+='</span><span style="font: 10px Verdana; width:'+w+'px; height:'+h+'px;text-align:\'center\';"><center><b>'+msg+'</b></center></span></div>';
		t+='</div>';
		//alert(t)
		document.write(t);
		var barraProgressoAjax=(ie)?document.all['blocks'+N]:document.getElementById('blocks'+N);
		barraProgressoAjax.fundo = new Object();
		barraProgressoAjax.fundo=(ie)?document.all['fundoBar']:document.getElementById('fundoBar');
		barraProgressoAjax.bar=(ie)?document.all['_xpbar'+N]:document.getElementById('_xpbar'+N);
		barraProgressoAjax.blocks=blocks;
		barraProgressoAjax.N=N;
		barraProgressoAjax.w=w;
		barraProgressoAjax.h=h;
		barraProgressoAjax.speed=speed;
		barraProgressoAjax.ctr=0;
		barraProgressoAjax.count=count;
		barraProgressoAjax.action=action;
		//barraProgressoAjax.togglePause=togglePause;
		barraProgressoAjax.showBar=function(){
			//this.bar.style.visibility="visible";
			this.bar.style.display="block";
			this.fundo.style.display="block";
			hideFormSelect();
			hideIframe();
		}
		barraProgressoAjax.hideBar=function(){
			//this.bar.style.visibility="hidden";
			this.bar.style.display="none";
			if (this.fundo.style)
				this.fundo.style.display="none";
			showFormSelect();
			showIframe();
		}
		barraProgressoAjax.initBar=function(){
			this.showBar()
			barraProgressoAjax.tid=setInterval('startBar('+N+')',speed);
		}
		barraProgressoAjax.stopBar=function(){
			this.hideBar()
			clearInterval(barraProgressoAjax.tid);
		}
		//this.hide();
		return barraProgressoAjax;
	}
}

var winPopupBarra;
var interval;
function iniciarBarraProgresso(winPopup){
	if (barraProgressoAjax) {
		barraProgressoAjax.initBar();
		if (winPopup) {
			winPopupBarra = winPopup;
			interval = setInterval('testePararBarra()', 1);
		}
	}
}
function testePararBarra(){
	clearInterval(interval);
	interval = setInterval('testePararBarra()',1);
	if(winPopupBarra && winPopupBarra.closed){
		clearInterval(interval);
		barraProgressoAjax.hideBar();
	}
}

/**
* Para a barra de progresso
*/
function pararBarraProgresso(){
	if(barraProgressoAjax)
		barraProgressoAjax.stopBar();
}

/**
* Inicia a barra de progresso
*/
function startBar(bn){
	var t=(ie)?document.all['blocks'+bn]:document.getElementById('blocks'+bn);
	try {
	
	  if( this.tid != 0){
		if(t.style && parseInt(t.style.left)+t.h+1-(t.blocks*t.h+t.blocks)>t.w){
			t.style.left=-(t.h*2+1)+'px';
			t.ctr++;
			if(t.ctr >= t.count){
				eval(t.action);
				clearInterval(this.tid)
				this.tid=0;
				t.ctr=0;
			}
		}else
			t.style.left=(parseInt(t.style.left)+t.h+1)+'px';
	  }
	  } catch (e) {
	    // Nao precisa tratar
	  }

		//Posiciona a barra e fundo caso haja scroll na p?gina
		var posScroll = getPosicaoScroll();
		redimensionaElementoPor("fundoBar", posScroll.posEsquerda, posScroll.posTopo);
		//posicionaElementoPor("barraProgresso", posScroll.posTopo, posScroll.posEsquerda);
}

/*---------------------------------------------------------------------------*\
  jCompany 2.5.7 - Fun??o para recuperar valor de par?metros na url
\*---------------------------------------------------------------------------*/
function getParametroUrl ( parametro, queryString) {
	queryString = (typeof queryString == "undefined" && queryString != "") ? getQueryString() : queryString;
	if(queryString.indexOf(parametro+"=") >= 0){
		queryString = queryString.lastIndexOf("#") >= 0 ? queryString.substring(0,queryString.lastIndexOf("#")) : queryString;
 		var arrayParametros	= separaListaTermos(queryString,"&");
		for(i = 0; i < arrayParametros.length; i++){
			if(arrayParametros[i].indexOf(parametro+"=") >= 0){
				return (arrayParametros[i].substring(arrayParametros[i].indexOf("=")+1,arrayParametros[i].length));
			}
		}
	}
}

/*---------------------------------------------------------------------------*\
  jCompany 2.5.7 - Fun??o para recuperar todos os par?metros da url
\*---------------------------------------------------------------------------*/
function getQueryString(){
	return document.location.search;
}

function getCamposEntrada (strTest, atributo, operador) {

	var condicao = 	(typeof strTest != "undefined" &&
					typeof atributo != "undefined" &&
					typeof operador != "undefined") ?
					operador == "indexOf" ?
					".indexOf('"+strTest+"') >= 0" :
					operador+strTest : "";
	var arrayCamposEntrada = new Array();
	var form = getForm();
	if(form){
		var formElements = form.elements;
		//plcLog.debug("formElements: "+formElements.length);
		for(e = 0; e < formElements.length; e++ ){
			//plcLog.debug("formElements[e].type: "+formElements[e].type);
	        if(condicao == "" || plcEval(formElements[e], atributo, condicao)){
	        	arrayCamposEntrada[arrayCamposEntrada.length] = formElements[e];
	        }
        }
	}
	return arrayCamposEntrada;
}

/**
* Fun??o que avalia o atributo de um elemento para uma condi??o preestabelecida
*/
function plcEval(elemento, atributo, condicao){

	if(atributo == "name"){
		return eval("\"" + elemento.name + "\"" + condicao);
	}
	return false;
}

/**
* Fun??o que inibe o clique do bot?o direito do mouse
*/
function inibeRightClick(evt){
	var valEvento = "";
	if (ExpYes)
		valEvento = event.button;
	else
		valEvento = evt.which;
	if (valEvento ==2 || valEvento == 3){
		alert("Desabilitado");
		return false;
	}
}

/**
* Fun??o que configura funcionamento para eventos do mouse associando uma
* nova fun??o ao evento
*/
function configEventosMouse(tipoEvento, funcao){
	if(typeof funcao == "undefined")
		funcao = "inibeRightClick";
	//Evento MOUSEDOWN
	if(tipoEvento.toLowerCase() == "mousedown"){
		if (NavYes)
			document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown = eval(funcao);
	}
	//Menu de contexto (bot?o direito)
	if(tipoEvento.toLowerCase() == "contextmenu"){
		document.oncontextmenu = eval(funcao);
	}
}

/*-----------------------------------------------------*\
   		FUN??ES PARA LOG JAVASCRIPT EM CONSOLE
\*-----------------------------------------------------*/
function PlcLog (){
	this.isEnabled = false;
	this.console = new Object();
}
var plcLog = new PlcLog();

PlcLog.prototype.newLogErros = function(){
	plcLog.logErros = new Object();
	plcLog.logErros["TAMANHO"] = 0;
}

PlcLog.prototype.logErros = new plcLog.newLogErros();

PlcLog.prototype.logEvent = function (evt){}

//Envia alerta de excecao
PlcLog.prototype.alertaExcecao = function (ex, msg){alert(plcLog.montaMsgExcecao(ex,msg));}

//Envia log de excecao
PlcLog.prototype.logExcecao = function (ex, msg){plcLog.debug(plcLog.montaMsgExcecao(ex,msg));}

PlcLog.prototype.logMostraErros = function (){
	plcLog.debug("LOG MOSTRA ERROS")
	var erros = plcLog.logPreparaErros()
	if(plcLog.logErros["TAMANHO"] > 0){
		getElementoStyle("MENSAGEM_TABELA_msgVermelho").display  = 'none';
		getElementoStyle("VALIDACAO_TABELA_JAVASCRIPT").display  = 'block';
		getElementoPorId("validacao_erros_javascript").innerHTML = erros;
		plcLog.debug("ERROS "+erros)
		plcLog.newLogErros();
	}
}

PlcLog.prototype.logEscondeErros = function (){
	//plcLog.debug("LOG ESCONDE ERROS")
	var tabela = getElementoStyle("VALIDACAO_TABELA_JAVASCRIPT");
	var erros = getElementoPorId("validacao_erros_javascript");
	if (tabela && erros) {
		tabela.display = "none";
	    erros.innerHTML = "";
		plcLog.newLogErros();
	}
}

PlcLog.prototype.logPreparaErros= function (){
	plcLog.debug("LOG PREPARA ERROS")
	var msgErros = "";
	var k = 0;
	var naoInformouCamposObrigatorios = false;
	for (var propErro in plcLog.logErros){
		if(propErro != "TAMANHO"){
			plcLog.debug("PROP: "+propErro);
			plcLog.debug("ERRO: "+plcLog.logErros[propErro]);
			if(plcLog.logErros[propErro] != "OBRIGATORIO"){
				msgErros += "<img align='ABSMIDDLE' alt='Erro' height='11' hspace='4' src='"+plcGeral.contextPath+"/plc/midia/msgVermelho/lin.gif' vspace='4' width='11'>";
				msgErros += plcLog.logErros[propErro] + "<br>";
			}else
				naoInformouCamposObrigatorios = true;
		//	alert('propErro='+propErro);
		  //  alert('valor='+getCampo(propErro));
		   //  alert('valor aval ='+getCampo(propErro)+ " tipo="+(typeof getCampo(propErro)));
			if ((!(getCampo(propErro)) && !(getCampo(propErro).type) &&
			     getCampo(propErro).length && getCampo(propErro).length>1)) {
			 	for (var j = 0; j<getCampo(propErro).length; j++) {
			 		alteraClasse ("OBJETO",getCampo(propErro)[j],"CLASSE","campoComErro","NOVACLASSE");
			 	}
			}  else {
					alteraClasse ("CAMPO",propErro,"CLASSE","campoComErro","NOVACLASSE");
			}
	
			if(k == 0)		
				setFocus(propErro);
			k++;	
		}
	}
	if(naoInformouCamposObrigatorios){
		msgErros += "<img align='ABSMIDDLE' alt='Erro' height='11' hspace='4' src='"+plcGeral.contextPath+"/plc/midia/msgVermelho/lin.gif' vspace='4' width='11'>";
		msgErros += plcGeral.obrigatorioMsg;
	}	
	
	return msgErros;
}

PlcLog.prototype.logAdicionaErro = function (){
	plcLog.debug("ADICIONA ERRO")
	if(arguments.length == 1){
		this.ID 	= "ERRO_"+plcLog.logErros.TAMANHO;
		this.ERRO 	= arguments[0];
	}else{
		for(var j = 0; j < arguments.length; j++)
		{
			if(arguments[j] == "ID")
				this.ID = arguments[++j];
			if(arguments[j] == "ERRO")
				this.ERRO = arguments[++j];
		}
	}
	plcLog.debug("ADD ERRO - ID: "+this.ID)
	plcLog.debug("ADD ERRO - ERRO: "+this.ERRO)
	plcLog.logErros[this.ID] = this.ERRO;
	plcLog.logErros["TAMANHO"] = plcLog.logErros.TAMANHO + 1;
}

PlcLog.prototype.logAdicionaErroCampo = function (nomeCampo, erro){
	plcLog.debug("ADICIONA ERRO CAMPO");
	plcLog.logAdicionaErro("ID", nomeCampo, "ERRO", erro);
}

PlcLog.prototype.logEnviaErro = function (erro){
	plcLog.debug("ENVIA ERRO");
	plcLog.logAdicionaErro(erro);
	plcLog.logMostraErros();
}

PlcLog.prototype.logEnviaErroCampo = function (nomeCampo, erro){
	plcLog.debug("ENVIA ERRO CAMPO");
	plcLog.logAdicionaErro("ID", nomeCampo, "ERRO", erro);
	plcLog.logMostraErros();
}

//Monta mensagem de excecao
PlcLog.prototype.montaMsgExcecao = function (ex, msg){
	var msgExPadrao = "ALERTA DE ERRO. Ocorreu um erro no javascript desta pagina.";
	var descEx = plcLog.logGetDescExcecao(ex);
	if(typeof msg != "undefined")
		msgExPadrao += "\n" + msg;
	var msgEx = msgExPadrao + "\nExcecao: "+ ex.name +".\nDescricao: "+ descEx;
	if(getVarGlobal("EXCECAO_CALLER") != null)
		msgEx += "\nStackTrace: "+ plcLog.printStackTrace(getVarGlobal("EXCECAO_CALLER"));
	return msgEx;
};

function funcname(f){
	var s = f.toString();
	//var s = f.toString().match(/function (\w*)/)[1];
	//if((s == null) || (s.length == 0))
		//return "anonymous";
 	return s
}

//Monta stack trace
PlcLog.prototype.printStackTrace = function (funcCaller){
	var stack = "";
	var fname = "";
	for(var a = funcCaller; a != null; a = a.caller){
		fname = funcname(a.callee);
		stack +=  fname + "\n";
		if(a.caller == a && fname.indexOf("montaMsgExcecao") == -1)
			break;
	}
	return stack;
};

//Recupera descri??o da exce??o
PlcLog.prototype.logGetDescExcecao = function (ex){
	return ExpYes ? ex.description : ex.message;
}

if(ExpYes)
	document.onkeydown   = function() { plcLog.logEvent(event); }
else {
	document.onkeydown   = function(evt){
		plcLog.logEvent(evt);
	}
}	

var strChave = "";
PlcLog.prototype.logEvent = function (evt){

	var ord = ""; // ascii order of key pressed

	if (ExpYes)
		ord = evt.keyCode;
	else
		ord = evt.which;
	var altKey    = evt.altKey;
	var ctrlKey   = evt.ctrlKey;
	var shiftKey  = evt.shiftKey;

	/*alert(
	"evt.type: "+evt.type+"\n"+
	"ctrlKey: "+ctrlKey+"\n"+
	"altKey: "+altKey+"\n"+
	"shiftKey: "+shiftKey+"\n"+
	"ord: "+ord+"\n"
	)*/
	//Clicando ALT + SHIFT + CTRL + C
	if (altKey && shiftKey && ctrlKey && (ord == 67) && evt.type == 'keydown') {
		alert("Utilize SHIFT + CTRL + C");
	}


	//Clicando SHIFT + CTRL + C
	if (!altKey && shiftKey && ctrlKey && (ord == 68) && evt.type == 'keydown') {     //Abrir debug javascript
		if(DP_Debug.isEnabled())
			DP_Debug.disable() 
		else
			DP_Debug.enable();
		alert("jCompany Framework Suite - Debug Javascript "+(DP_Debug.isEnabled() == true ? "Ligado" : "Desligado"));
	}
	//Clicando SHIFT + CTRL + C
	if (shiftKey && ctrlKey && (ord == 67) && evt.type == 'keydown') {     //Abrir console javascript

		evt.returnValue = false;  evt.cancelBubble = true;
		plcLog.isEnabled = !plcLog.isEnabled;
		if(DP_Debug.isEnabled())
			DP_Debug.disable() 
		else
			DP_Debug.enable();
		alert("jCompany Framework Suite - Debug/Console Javascript "+(plcLog.isEnabled == true ? "Ligado" : "Desligado"));

		if(plcLog.isEnabled){
			//plcLog.console.window = window.open("","CONSOLE");
			//plcLog.console.window.document.writeln("<input type='button' onclick='window.document.all.CONSOLE.innerHTML=\"\"' value='Limpar'>");
			//plcLog.console.window.document.write("<input type='button' onclick='window.close()' value='Fechar'>");
			//plcLog.console.window.document.writeln("<H3>CONSOLE JAVASCRIPT</H3>");
			//plcLog.console.window.document.writeln("<div id='CONSOLE'>");
			//plcLog.console.window.document.writeln("</div>");
		}else{
			//plcLog.console.window.close();
		}
	}
	//Clicando ALT + SHIFT + CTRL + SCROLL
	if (altKey && shiftKey && ctrlKey && (ord == 145) && evt.type == 'keydown') {
		alert("jCompany Framework Suite - Javascript Log \n by Rodrigo Magno\nPowerlogic S.A.");
	}

	//Clicando ALT + SHIFT + CTRL + PLC
	if (altKey && shiftKey && ctrlKey && evt.type == 'keydown' && (ord == 80 || ord == 76 || ord == 67)) {
		//alert(strChave)
		if(ord == 80 && strChave == ""){
			strChave += "P";
		}
		else if(ord == 76 && strChave == "P"){
			strChave += "L";
		}
		else if(ord == 67 && strChave == "PL"){
			strChave = "jCompany Framework Suite \n";
			strChave += "Arquivo de Javascript\n";
			strChave += "by Rodrigo Magno\n";
			strChave += "rodrigo@powerlogic.com.br\n";
			strChave += "Powerlogic S.A.";
			alert(strChave);
			strChave = "";
		}
		//else
			//strChave = "";
	}

	var retornoEvento = executarAtalho(evt);
/*
	try{
		document.focus() ;
	}catch(e){}
*/
	if(retornoEvento)
		return retornoEvento;

	return true;
}

PlcLog.prototype.debug = function (log) {
	if(plcLog.isEnabled)
	{
		//if(eval(plcLog.console.window) && !plcLog.console.window.closed)
		//{
			plcLog.logger(log,"Info");
			//plcLog.console.window.focus();
			//var htmlLog = plcLog.console.window.document.all.CONSOLE.innerHTML;
			//htmlLog += "<br>" + log;
			//plcLog.console.window.document.all.CONSOLE.innerHTML = htmlLog;
		//}
	}
};

PlcLog.prototype.logInfo = function (log) {
	plcLog.logger(log,"Info");
};

PlcLog.prototype.logWarning = function (log) {
	plcLog.logger(log,"Warning");
};

PlcLog.prototype.logError = function (log) {
	plcLog.logger(log,"Error");
};

PlcLog.prototype.logger = function (log, tipo) {

	if(plcLog.isEnabled)
	{
		if("Info" == tipo)
			DP_Debug.logInfo(log);
		else if("Warning" == tipo)
			DP_Debug.logWarning(log);
		else if("Error" == tipo)
			DP_Debug.logError(log);
	}
}

PlcLog.prototype.debugObjeto = function (objeto, label) {

	if(DP_Debug.isEnabled())
	{
		if(typeof label != "undefined" && label != "")
			DP_Debug.dump(objeto, label); 
		else
			DP_Debug.dump(objeto); 
	}
};
/*MANIPULADOR DE TECLAS DE ATALHO*/
function setAtalho(atalho, funcao){
    if (this.objetoAtalho == null) {this.objetoAtalho = new Object();}
	this.objetoAtalho[atalho.toUpperCase()] = funcao;
}

function getAtalho(atalho){
	if(this.objetoAtalho && atalho != null && typeof atalho != "undefined")
		return this.objetoAtalho[atalho.toUpperCase()];
	return null;	
}

function executarAtalho(evt){

	var ctrlKey   	= evt.ctrlKey 	? "CTRL" 	: "";
	var altKey    	= evt.altKey 	? "#ALT" 	: "";
	var shiftKey  	= evt.shiftKey 	? "#SHIFT" 	: "";
	var keyChar   	= evt.keyCode && keyCodePermitido(evt.keyCode) ? "#"+String.fromCharCode(evt.keyCode).toUpperCase() : "";    // ascii order of key pressed
	//Tratar acao enter
	if(evt.keyCode == 13){
		return eval(getAtalho("#ENTER"));
	}
	var funcao 		= "";
	var atalho = (ctrlKey+altKey+shiftKey+keyChar).toUpperCase();
	
	//alert(evt.keyCode)
	//alert(String.fromCharCode(evt.keyCode))
	//alert(keyCodePermitido(evt.keyCode))
	//alert(atalho)
	//alert(getAtalho(atalho))
	
	var cancelaEvento = false;
	try{
		//if((ctrlKey && altKey) || (ctrlKey && shiftKey) || (shiftKey && altKey))
		setVarGlobal("event", evt);
		cancelaEvento = eval(getAtalho(atalho));
		//setVarGlobal("event", null);
	}catch(e){
		plcLog.alertaExcecao(e,"Erro ao executar atalho. Funcao: "+getAtalho(atalho));
	}
	
	if(cancelaEvento){
		if( evt.stopPropagation ) 
			evt.stopPropagation(); 
		evt.cancelBubble = true;
		return false;
	}
	
}

function keyCodePermitido(keyCode){
	return keyCodeSeta(keyCode) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122);
}
function keyCodeSeta(keyCode){
	return keyCode == 40 || keyCode == 38 || keyCode == 39 || keyCode == 37;
}

/*-----------------------------------------------------*\
   	  FUN??ES PARA MANIPULA??O DE REQUEST VIA AJAX
\*-----------------------------------------------------*/
//Contrutor Ajax
function PlcAjax(){}

var plcAjax = new PlcAjax();

//Constante para que indica que o request via AJAX foi completado
PlcAjax.prototype.REQUEST_COMPLETO = 4;

//Constante para que indica que h? uma requisi??o AJAX em andamento
PlcAjax.prototype.AJAX_ATIVO = false;

//Indica se a aplica??o utiliza barra de progresso no tratamento
PlcAjax.prototype.ajaxUsaBarraProgresso = true;

//Habilita a barra de progresso. Default false
PlcAjax.prototype.ajaxEscondeBarraProgresso = function (){
	plcAjax.ajaxUsaBarraProgresso = false;
}
//Indica se a requisi??o ? para camadas diferentes da camada padr?o jCompany
PlcAjax.prototype.ajaxEspecifico = false;

//Indica se a requesi??o espec?fica utiliza barra de progresso. Default = true
PlcAjax.prototype.ajaxEspecificoBarraProgresso = true;

//Indica qual evento est? executando atualmente a requisi??o Ajax
PlcAjax.prototype.ajaxEventoAtual = "";

//Guarda objeto Event
PlcAjax.prototype.ajaxEvent;

//Indica tipo de encoding utilizado para retorno dos dados pelo Ajax
PlcAjax.prototype.ajaxCharset = "UTF-8";

//Indica que o m?todo GET deve ser executado com endere?o absoluto
PlcAjax.prototype.ajaxUrlBase = new Object();

//Indica uma ?rea espec?fica para atualiza??o
PlcAjax.prototype.ajaxCamadaEspecifica = "";

//Habilita m?todo GET com endere?o absoluto
PlcAjax.prototype.ajaxSetUrlBase = function (actionBase, urlBase){
	plcAjax.ajaxUrlBase[actionBase] = urlBase;
}


/**
* Executa chamada POST Ajax para URL espec�fica
*/
PlcAjax.prototype.ajaxPost = function (URL, especifico, usaBarra, evento, form){
	if(especifico)
		plcAjax.ajaxHabilitaEspecifico(usaBarra);	
	plcAjax.ajaxSubmit("POST", evento, URL, form);
};
/**
* Executa chamada POST Ajax para m�todo espec�fico e URL espec�fica e �rea espec�fica
*/
PlcAjax.prototype.ajaxPostEspecificoArea = function (URL, usaBarra, evento, area, form){
	plcLog.debug("#####AJAX POST AREA ESPECIFICA");
	plcAjax.ajaxCamadaEspecifica = area;
	plcAjax.ajaxPost(URL, true, usaBarra, evento, form);
};
/**
* Executa chamada GET Ajax para m�todo espec�fico e URL espec�fica e �rea espec�fica
*/
PlcAjax.prototype.ajaxGetEspecificoArea = function (URL, usaBarra, evento, area){
	plcLog.debug("#####AJAX GET AREA ESPECIFICA");
	plcAjax.ajaxCamadaEspecifica = area;
	plcAjax.ajaxGet(URL, true, usaBarra, evento);
};

/**
* Executa chamada GET Ajax para URL espec�fica
*/
PlcAjax.prototype.ajaxGet = function (URL, especifico, usaBarra, evento){
	plcLog.debug("#####AJAX GET");
	if(especifico)
		plcAjax.ajaxHabilitaEspecifico(usaBarra);	
	plcAjax.ajaxSubmit("GET", evento, URL);
};

/**
* Executa chamada Ajax para m�todo espec�fico e URL espec�fica
*/
PlcAjax.prototype.ajaxSubmitSimples = function (metodo, URL, especifico, usaBarra, evento, form){
	plcLog.debug("#####AJAX SUBMIT SIMPLES");
	if(metodo.toUpperCase() == "GET")
		plcAjax.ajaxGet(URL, especifico, usaBarra, evento, form);
	else if(metodo.toUpperCase() == "POST")
		plcAjax.ajaxPost(URL, especifico, usaBarra, evento, form);
};

/**
* Executa chamada Ajax para m�todo espec�fico e URL atual
*/
PlcAjax.prototype.ajaxSubmitDireto = function (metodo, evento, especifico, usaBarra, form){
	plcLog.debug("#####AJAX SUBMIT DIRETO");
	if(metodo.toUpperCase() == "GET")
		plcAjax.ajaxGet("", especifico, usaBarra, evento, form);
	else if(metodo.toUpperCase() == "POST")
		plcAjax.ajaxPost("", especifico, usaBarra, evento, form);
};

//Fun??o para configura??o de submit espec?fico com Ajax
PlcAjax.prototype.ajaxSubmitEspecifico = function(metodo,evento,usaBarra) {
	plcAjax.ajaxHabilitaEspecifico(usaBarra);
	plcAjax.ajaxSubmit(metodo,evento);
};

/**
 * Executa chamada Ajax para m?todo espec?fico e URL espec?fica e ?rea espec?fica
 */
PlcAjax.prototype.ajaxSubmitEspecificoCamada = function (metodo,evento,usaBarra, camada){
	plcLog.debug("#####AJAX SUBMIT CAMADA ESPECIFICA");
	plcAjax.ajaxCamadaEspecifica = camada;
	plcAjax.ajaxSubmitEspecifico(metodo, evento, usaBarra);
};


//Habilita ajax especifico. Default false
PlcAjax.prototype.ajaxHabilitaEspecifico = function (usaBarraProgresso){
	plcAjax.ajaxEspecifico 			= true;
	if(!usaBarraProgresso || usaBarraProgresso == "")
		plcAjax.ajaxEspecificoBarraProgresso 	= usaBarraProgresso;
}

//Objeto que representa camadas AJAX da aplica??o
//Caso a camada de dados n?o seja informada, assume a camadaAtualiza??o com padr?o
PlcAjax.prototype.ajaxCamada = function (camadaAtualizacao, camadaDados){
	this.camadaAtualizacao 	= camadaAtualizacao;
	if(typeof camadaDados != "undefined" && camadaDados != "")
		this.camadaDados 	= camadaDados;
	else
		this.camadaDados 	= camadaAtualizacao;
}

//Cria camadas de atualiza??o via AJAX
PlcAjax.prototype.arrayCamadaAjax;
//Camadas por ID: retorna a posi??o no arrayCamadaAjax
PlcAjax.prototype.arrayCamadaAjaxPorId;
PlcAjax.prototype.ajaxCriaCamada 	= function (camadaAtualizacao, camadaDados){
	if(plcAjax.arrayCamadaAjax == null)
		plcAjax.arrayCamadaAjax = new Array();
	if(plcAjax.arrayCamadaAjaxPorId == null)
		plcAjax.arrayCamadaAjaxPorId = new Object();
	
	if (!plcAjax.arrayCamadaAjaxPorId[camadaAtualizacao]) { //Evita criar camada que j? existe.
		var camada = new plcAjax.ajaxCamada(camadaAtualizacao,camadaDados);
		plcAjax.arrayCamadaAjaxPorId[camadaAtualizacao] = plcAjax.arrayCamadaAjax.length;
		plcAjax.arrayCamadaAjax[plcAjax.arrayCamadaAjax.length] = camada;
	}
}

PlcAjax.prototype.cacheFunctionAjax = new Array();
//Guarda fun??es para serem executadas ap?s submit Ajax
PlcAjax.prototype.setFuncaoAposAjax = function (decFunction) {
   if (this.cacheFunctionAjax == null) {this.cacheFunctionAjax = new Array();}
   this.cacheFunctionAjax[this.cacheFunctionAjax.length] = decFunction;
}

//Executa fun??es ap?s submit Ajax
PlcAjax.prototype.ajaxExecutaFuncaoAposSubmit = function ()
{
	if(this.cacheFunctionAjax != null)
	{
		for(i = 0; i < this.cacheFunctionAjax.length; i++){
			try{
				eval(this.cacheFunctionAjax[i]);
			}catch(e){
				plcLog.debug("Erro ao executar funcao apos Ajax. Funcao "+this.cacheFunctionAjax[i]+" nao declarada.")
			}	
		}	
	}
}


//Recupera objeto de request para utiliza??o AJAX
PlcAjax.prototype.ajaxGetRequest = function (){

	var ajaxhttp = false;
	//Default
	if(window.XMLHttpRequest) {
		try {
			ajaxhttp = new XMLHttpRequest();
	    } catch(e) {
	    	alert("Objeto AJAX inexistente");
			ajaxhttp = false;
	    }
	// IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
	   	try {
	    	ajaxhttp = new ActiveXObject("Msxml2.XMLHTTP");
	  	} catch(e) {
	    	try {
	      		ajaxhttp = new ActiveXObject("Microsoft.XMLHTTP");
	    	} catch(e) {
	    		alert("Erro ao utilizar Ajax. Controles ActiveX podem estar desabilitados. Habilite-os para utilizar Ajax\n"+
						"Acesse 'Tools/Internet Options/Security. Selecione 'Internet' ou 'Intranet', clique 'Custom Level'\n"+
						"Marque 'Enable' para o item 'Initialize and script ActiveX controls no marked as safe'");
	      		ajaxhttp = false;
	    	}
		}
	}
	return ajaxhttp;
}

/**
 * Realiza submit via request AJAX
 * @variable metodo M?todo utilizado no request [String,Ob] {GET,POST}
 * @variable evento Evento jCompany a ser enviado no request [String,Ob]
 * @variable url Url chamado no request [String,Ob]
 * @variable form Nome do formul?rio que cont?m os dados de entrada para request [String,Op]
 * @variable actionBase Action enviado no request. Necess?rio quando a chamada utilizar url absoluta [String,Op]
 * @see getForm
 * @see get
 * @see disparaBotao
 */
PlcAjax.prototype.ajaxSubmit = function (metodo, evento, url, nomeForm, actionBase){

	plcLog.debug("##### Entrou para submit AJAX");

	//if(!plcValida.validacaoVerificarRegras())
		//return false;

	var paramPost 	= "";
	var contentType	= "";
	var charset		= "";
	var form 		= getForm(nomeForm);

	//Cria??o do objeto xmlhttprequest
	var ajaxhttp 	= plcAjax.ajaxGetRequest();
	plcLog.debug("AJAXHTTP: "+ajaxhttp);

	//Defini??o de content type
	if(ExpYes && form)
		contentType = form.encoding;
	else
		contentType = "application/x-www-form-urlencoded";

	//Defini??o de encoding
	if(plcAjax.ajaxCharset != "")
		charset = plcAjax.ajaxCharset;

	//Defini??o de url para request
    if (form && (url == "" || typeof url == "undefined"))
    	url = form.action;
    if (url == "")
    	url = location.href;

	if(plcAjax.ajaxUrlBase[actionBase]){
		url = plcAjax.ajaxUrlBase[actionBase] + url;
	}

	if(ajaxhttp){
		//Defini??o do m?todo de request
		metodo = metodo != "" && typeof metodo != "undefined" ? metodo : "POST";

		//Testa se foi informado o argumento id_Arg para l?gica de recupera??o autom?tica via id
		var id_Arg = get("id_Arg");
		if(evento == getBotaoArray('PESQUISAR') &&
		   id_Arg != "" && typeof id_Arg != "undefined"){
			var botao = getElementoPorId("RECUPERACAO_AUTOMATICA");
			//disparaBotao(selBotao(evento));
			disparaBotao(botao);
			return;
		}

		//Defini??o de evento para request
		if(evento != ""){
			if(metodo == "GET"){
					url =+ "?evento="+escape(evento);
			}
			if(metodo == "POST"){
				//plcAjax.antesAjaxComplementaPost();
				paramPost += "evento="+escape(evento)+"&";
				//paramPost += plcAjax.ajaxMontaPost();
			}
		}
		if(metodo == "POST"){
			paramPost += plcAjax.antesAjaxComplementaPost();
			paramPost += plcAjax.ajaxMontaPost(nomeForm);
		}

		plcLog.debug("Parametros para request");
		plcLog.debug("URL: "+url);
		plcLog.debug("METODO: "+metodo);
		plcLog.debug("EVENTO: "+evento);
		plcLog.debug("CONTENT TYPE: "+contentType);
		plcLog.debug("CHARSET: "+charset);
		plcLog.debug("PARAMPOST: "+paramPost);
		plcLog.debug("ESPECIFICO BARRA: "+plcAjax.ajaxEspecificoBarraProgresso);

		plcLog.debug("EVENTO ATUAL AJAX: "+plcAjax.ajaxEventoAtual)
		//plcLog.debug("EVENTO JANELA: "+window.event.type)
		//Executa a??o antes de enviar submit
		plcLog.debug("AJAX ATIVO: "+plcAjax.AJAX_ATIVO);
		if(!plcAjax.AJAX_ATIVO && plcAjax.antesAjaxSubmit() && 
			(plcAjax.ajaxEventoAtual == "" || plcAjax.ajaxEventoAtual == window.event.type)){
			plcLog.debug("Executando request Ajax para url: "+url);

				if(ExpYes){
					try{
						plcAjax.ajaxEventoAtual = window.event.type;
					}catch(e){}	
				}	
				else{
					if(document.captureEvents(Event.ONCHANGE))
						plcAjax.ajaxEventoAtual = document.captureEvents(Event.ONCHANGE).type;
				}

			//Aborta submit anterior n?o completado
			ajaxhttp.abort()
			plcLog.debug("apos abort");
			//Abrir thread para request
			ajaxhttp.open(metodo,url,true);
			plcLog.debug("apos open");
			//Configura??o encoding do request
	   		ajaxhttp.setRequestHeader("Content-Type", contentType);
			plcLog.debug("apos setRequestHeader 1");
			//Configura??o encoding do request
			if(charset != "")
		   		ajaxhttp.setRequestHeader("charset", charset);
			plcLog.debug("apos setRequestHeader 2");
			//Definir fun??o para tratamento do retorno do request
			ajaxhttp.onreadystatechange = function(){
				if(ajaxhttp.readyState == plcAjax.REQUEST_COMPLETO){
					plcLog.debug(ajaxhttp.getAllResponseHeaders());
					plcAjax.ajaxResponse(ajaxhttp.responseText);
				}
			}
			plcLog.debug("apos onreadystatechange");

			if(plcAjax.ajaxUsaBarraProgresso && plcAjax.ajaxEspecificoBarraProgresso)
				iniciarBarraProgresso();
			plcLog.debug("apos iniciarBarraProgresso");
			plcAjax.AJAX_ATIVO = true;
			ajaxhttp.send(paramPost);
			plcLog.debug("apos send");
		}else{
			plcLog.debug("Request abandonado. Ajax ativo")
		}
	}
}

//Monta par?metros do request AJAX quando submiss?o for via m?todo POST
PlcAjax.prototype.ajaxMontaPost = function (nomeForm)
{

	plcLog.debug("##### Entrou para montar parametros de POST");

	var arrayCampos = getCamposEntrada ();
	var strPost = "";

	//plcLog.debug("Qtde. argumentos: "+arrayCampos.length);
	if (arrayCampos && arrayCampos.length > 0){
		var i = 0;
		while(i < arrayCampos.length){
			//plcLog.debug("Tipo argumento: "+arrayCampos[i].type)
			//plcLog.debug("Qtde. valores: "+arrayCampos[i].length)
			var valCampo = encodeURIComponent(get(arrayCampos[i].name, nomeForm));
				//valCampo = valCampo.replace("%",escape("%"));
				//valCampo = valCampo.replace("&",escape("&"));
				//valCampo = valCampo.replace("+","%2B");
				//valCampo = valCampo.replace("\"","%22");
				strPost += arrayCampos[i].name+"=" + valCampo +"&";
			//plcLog.debug("Argumento: "+arrayCampos[i].name+"="+valCampo);
			i++;
		}
	}
	return strPost;
}


//Recebe e trata a resposta do request AJAX
PlcAjax.prototype.ajaxResponse = function(ajaxResponse)
{
	plcLog.debug("##### Entrou para responder AJAX");
	try{
		//plcLog.debug("Valor response: "+ajaxResponse);
		if(plcAjax.ajaxEspecifico && plcAjax.arrayCamadaAjax && plcAjax.arrayCamadaAjax.length > 0){
			//Mostra camada Ajax espec?fica
			plcLog.debug("AJAX ESPECIFICO");
			plcLog.debug("AJAX CAMADA ESPECIFICA: "+plcAjax.ajaxCamadaEspecifica);

			if(plcAjax.ajaxAntesResponseCamadaEspecifica(ajaxResponse)){
				var numCamadas = plcAjax.arrayCamadaAjax.length;
				for(j = 0; j < numCamadas; j++){
					plcLog.debug("CAMADA ATUALIZACAO: "+plcAjax.arrayCamadaAjax[j].camadaAtualizacao);
					plcLog.debug("CAMADA DADOS: "+plcAjax.arrayCamadaAjax[j].camadaDados);
					if (plcAjax.ajaxCamadaEspecifica=="" || plcAjax.ajaxCamadaEspecifica==plcAjax.arrayCamadaAjax[j].camadaAtualizacao) {
						plcLog.debug("USANDO CAMADA: "+plcAjax.arrayCamadaAjax[j].camadaAtualizacao);
						var ajaxCamada	= plcAjax.ajaxPreparaCamada(ajaxResponse, "\<"+plcAjax.arrayCamadaAjax[j].camadaDados+"\>", "\<\/"+plcAjax.arrayCamadaAjax[j].camadaDados+"\>");
						plcAjax.ajaxMostraCamada(ajaxCamada, plcAjax.arrayCamadaAjax[j].camadaAtualizacao);
					}
				}
			}
		}else{
			plcLog.debug("AJAX PADRAO");
			//Camada Ajax padr?o jCompany
			var ajaxCamada	= plcAjax.ajaxPreparaCamada(ajaxResponse, "\<AJAX\>", "\<\/AJAX\>");
			plcAjax.ajaxMostraCamada(ajaxCamada, "AJAX");
		}

		//Monta conteudo especifico
		plcLog.debug("AJAX USA BARRA PROGRESSO: "+plcAjax.ajaxUsaBarraProgresso)
		plcLog.debug("AJAX ESPECIFICO USA BARRA PROGRESSO: "+plcAjax.ajaxEspecificoBarraProgresso)
		if(plcAjax.ajaxUsaBarraProgresso && plcAjax.ajaxEspecificoBarraProgresso)
			pararBarraProgresso();
		plcAjax.aposAjaxSubmit();
		plcAjax.ajaxMantemTabAgil();

		if (!plcAjax.ajaxEspecifico){
			moverFoco();
			executarFuncaoOnLoad();
		}

		//plcLog.debug("Funcoe ajax: "+plcAjax.cacheFunctionAjax.length)
		plcAjax.ajaxExecutaFuncaoAposSubmit();

		//NAO RETIRAR PORQUE TRATA EDI??O DE CAMPOS
		plcAjax.ajaxInicializarEstado();

	}catch(ex){
		if(plcAjax && plcAjax.ajaxUsaBarraProgresso && plcAjax.ajaxEspecificoBarraProgresso)
			pararBarraProgresso();
		plcAjax.ajaxInicializarEstado();
		setVarGlobal("EXCECAO_CALLER",arguments.caller);		
	//	plcLog.alertaExcecao(ex,"Erro ao receber response ajax");
	}

	plcAjax.antesAjaxFinalizar(ajaxResponse);

	plcLog.debug("Finalizando Ajax");
}

PlcAjax.prototype.ajaxInicializarEstado = function(){

	//Limpar vari?veis para camada espec?fica
	plcAjax.ajaxEspecifico = false;
	plcAjax.ajaxEspecificoBarraProgresso = true;

	//Configurar Ajax inativo
	plcAjax.AJAX_ATIVO = false;

	//Limpa cache de fun??es
	//plcAjax.cacheFunctionAjax = new Array();

	//Limpa refer?ncia ao evento Ajax
	plcAjax.ajaxEventoAtual = "";
	
	//Limpa ?rea espec?fica de atualiza??o
	plcAjax.ajaxCamadaEspecifica = "";
	
	
//	$(window).bind("beforeunload",function(event) {	});
//	window.onbeforeunload = "";

}
//Prepara a camada AJAX para atualiza??o
PlcAjax.prototype.ajaxPreparaCamada = function (ajaxResponse, tagIni, tagFim){

	plcLog.debug("##### Entrou para preparar camada AJAX");
	plcLog.debug("TAG INICIO: "+escape(tagIni));
	plcLog.debug("TAG FIM: "+escape(tagFim));
	var ajaxCamada = "";
	if(ajaxResponse){
		plcLog.debug("Filtrando camada AJAX");
		var posIni = ajaxResponse.indexOf(tagIni);
		var posFim = ajaxResponse.indexOf(tagFim);
		plcLog.debug("PosIni: "+posIni+"<br>posFim: "+posFim);
		ajaxCamada = ajaxResponse.substring( posIni, posFim);
	}

	plcLog.debug("Camada AJAX:<br> "+ajaxCamada);
	return ajaxCamada;
}

//Atualiza a camada AJAX no elemento correspondente
PlcAjax.prototype.ajaxMostraCamada= function (ajaxConteudo, elementoID){

	plcLog.debug("##### Entrou para mostrar resultado pesquisa");
	plcLog.debug("ID Elemento atualizacao: "+elementoID);
	var elementoAtualizacao = getElementoPorId(elementoID);
	plcAjax.antesAtualizarCamada();
	if(elementoAtualizacao){
		plcLog.debug("Elemento atualizacao: "+elementoAtualizacao.id);
		if(elementoAtualizacao != null){
			elementoAtualizacao.innerHTML = ajaxConteudo;
			plcAjax.executaScriptsInternos(elementoAtualizacao);
		}
	}
}

PlcAjax.prototype.executaScriptsInternos = function (elemento) {
	plcLog.debug("##### Entrou para executar scripts internos");
	var tags = elemento.getElementsByTagName("SCRIPT");
	for(t = 0; t < tags.length; t++){
		tag = tags[t];
		plcLog.debug("AVALIAR: "+tag.getAttribute("avaliar")+"<br>TEXTO TAG: "+tag.text);
		if (tag.text && tag.text!='' && (tag.getAttribute("avaliar")=='S' || 
		   (typeof tag.getAttribute("id") != 'undefined' && tag.getAttribute("id") != null && tag.getAttribute("id").indexOf('avaliar:')>-1))) {
			window.eval(tag.text);
			plcLog.debug("AVALIADO");
		}
	}
}

//Fun??o para configura??o de submit espec?fico com Ajax
PlcAjax.prototype.ajaxSubmitEspecifico = function(metodo,evento,usaBarra) {
	plcAjax.ajaxHabilitaEspecifico(usaBarra);
	plcAjax.ajaxSubmit(metodo,evento);
}

/**
 * Executa chamada Ajax para m?todo espec?fico e URL espec?fica e ?rea espec?fica
 */
PlcAjax.prototype.ajaxSubmitEspecificoCamada = function (metodo,evento,usaBarra, camada){
	plcLog.debug("#####AJAX SUBMIT CAMADA ESPECIFICA")
	plcAjax.ajaxCamadaEspecifica = camada;
	plcAjax.ajaxSubmitEspecifico(metodo, evento, usaBarra);
}

//Func?o chamada ap?s submit Ajax para manter situa??o de tab folder ?gil
PlcAjax.prototype.ajaxMantemTabAgil = function () {
	mantemAbaSelecionada();
}

//Implementacao de acoes antes de tratar response
PlcAjax.prototype.ajaxAntesResponseCamadaEspecifica = function (ajaxResponse){ return true;}

//Implementa??o de a??es antes de enviar o submit
PlcAjax.prototype.antesAjaxSubmit = function (){ return true;}

//Implementa??o de a??es ap?s retorno submit
PlcAjax.prototype.aposAjaxSubmit = function (){}

//Implementa��o de a��es para complemento do post antes do submit
PlcAjax.prototype.antesAjaxComplementaPost = function (){ return ""}

//Implementa��o de a��es antes de atualizar camada
PlcAjax.prototype.antesAtualizarCamada = function(){
};

//Implementa��o de a��es ap�s inicializa��o de estado
PlcAjax.prototype.antesAjaxFinalizar = function (ajaxResponse){};

/*************************************************************************************************
										IMPRESS�O INTELIGENTE
*************************************************************************************************/
function executaImpressao(){

	if(opener && !opener.executaImpressaoAntes(document)){
		return;
	}

	var bodyOriginal = document.body.innerHTML;
	var bodyImpressao= opener.objImpressao.html;
	
	document.body.innerHTML = "<form>"+bodyOriginal + bodyImpressao+"</form>";

	jQuery("#ifrm-arquivo-detalhe-upload").css("display","none");
	jQuery(".icone_acao_fixo").css("display","none");
	jQuery(".remover-na-impressao").css("display","none");
	
	escondeBotoesEventosTodos();
	//esconderBotoesConformeCriterio("INICIA_COM","Modo,Vis");

	var editoresGerados	= opener.getVarGlobal("editoresGerados");
	if(typeof editoresGerados != "undefined" && editoresGerados != ""){
		var arrEditores = editoresGerados.split(",");
		for(indEditor = 0; indEditor < arrEditores.length; indEditor++){
			var nomeEditor = arrEditores[indEditor];
			jQuery("iframe#"+nomeEditor+"___Frame").css("display","none");
			substituirTagPorLabel(jQuery("TEXTAREA[name="+nomeEditor+"]"));
		}
	}

	plcAjax.executaScriptsInternos(document);

	executaImpressaoApos(document);

	//Verifica se utiliza impress?o inteligente
	var impIntel = getParametroUrl ( "impIntel", document.location.search);
	if(impIntel != null && impIntel.toLowerCase() == "s"){
		gerarImpressaoInteligente(true)
	}
}

//Fun��o template para implementa��es espec�ficas
function executaImpressaoAntes(){}

//Fun��o template para implementa��es espec�ficas
function executaImpressaoApos(){}

//Trasnforma formul�rio em texto para impress�o
function gerarImpressaoInteligente(){
	transformarFormularioEmTexto(true);
}

//Trasnforma formul�rio em texto
function transformarFormularioEmTexto(esconderBotoes){
	substituirInputPorLabel(esconderBotoes)
	substituirTextareaPorLabel();
	substituirSelectPorLabel();
	esconderBotoesConformeCriterio("INICIA_COM","F12-Gravar,Propaga,Ajusta,Inicia,Calcula,Adic,Anexa,Novo,Exclui,Salvar,Importa,Fecha,Atualiza");
	substituirSpanPorLabel("INICIA_COM","download");
	return true;
}

//Esconde bot�es conforme crit�rio. Atualmente apenas crit�rio de in�cio
function esconderBotoesConformeCriterio(criterio, strInicia){
	if("INICIA_COM" == criterio){
		setVarGlobal("INICIA_COM", strInicia);
		$("input[name=evento]").each(function(index){
			try{
				var arrStrInicia = getVarGlobal("INICIA_COM").split(",");
				for(i = 0; i < arrStrInicia.length; i++){
					if($(this).attr("value").toLowerCase().indexOf(arrStrInicia[i].toLowerCase()) == 0){
						$(this).css("display","none");
					}
				}
			}catch(e){}
		});
	}
}

//Esconde todos os bot�es da tela
function escondeBotoesEventosTodos(){
	//esconderBotoesConformeCriterio("INICIA_COM","F7-Novo,F8-Abrir,F12-Gravar,Propaga,Ajusta,Inicia,Calcula,Adic,Anexa,Novo,Exclui,Salvar,Importa,Fecha,Atualiza,Clona,Assiste,Grava,Publica,Organiza,Aprova,Reprova,Modo,Vis");	
	$("input[name=evento]").css("display","none");

}

//Esconde todos os bot�es da tela para impressao
function escondeBotoesParaImpressao(){
	esconderBotoesConformeCriterio("INICIA_COM","F7-Novo,F8-Abrir,F12-Gravar,Propaga,Ajusta,Inicia,Calcula,Adic,Anexa,Novo,Exclui,Salvar,Importa,Fecha,Atualiza,Clona,Assiste,Grava,Publica,Organiza,Aprova,Reprova,Modo,Vis");	
}

//Substitui tags SPAN por texto
function substituirSpanPorLabel(criterio, strInicia){

/*
	$("span.bt").each(function(index){
		substituirTagPorLabel(this);
	});
*/
	
	if("INICIA_COM" == criterio){
		setVarGlobal("INICIA_COM", strInicia);
		$("span.bt").each(function(index){
			try{
				var arrStrInicia = getVarGlobal("INICIA_COM").split(",");
				for(i = 0; i < arrStrInicia.length; i++){
					if($(this).html().toLowerCase().indexOf(arrStrInicia[i].toLowerCase()) == -1){
						substituirTagPorLabel(this);
						break;
					}
				}
			}catch(e){
				substituirTagPorLabel(this);
			}
		});
	}

}

//Substitui tags SELECT por texto
function substituirSelectPorLabel(){
	$("SELECT").each(function(index){
		try{
			substituirTagPorLabel(this);
		}catch(e){
			pararBarraProgresso();
		}
	});
}

//Substitui tags TEXTAREA por texto
function substituirTextareaPorLabel(){
	$("TEXTAREA").each(function(index){
		substituirTagPorLabel(this);
	});
}

//Substitui tags INPUT por texto
function substituirInputPorLabel(esconderBotoes){

	setVarGlobal("ESCONDER_BOTOES", esconderBotoes);
	$("INPUT").each(function(index){
		if($(this).attr("type") == "button" || $(this).attr("type") == "submit" || $(this).attr("type") == "reset"){
			if(getVarGlobal("ESCONDER_BOTOES") ){
				$(this).css("top","-100").css("display","none");
			}
		}else if($(this).attr("type") != "hidden"){
			substituirTagPorLabel(this);
		}
	});
}

//Substitui tags gen�ricas por texto
function substituirTagPorLabel(tag){
	if($(tag).attr("type") == "checkbox" || $(tag).attr("type") == "radio"){
		$(tag).attr("disabled","true");
	}else{
		if($(tag).attr("type") == "select-multiple"){
			for(s = 0; s < tag.options.length; s++){
				if(tag.options[s].selected){
					$(tag).replaceWith("<span style='backgroundColor:yellow'>"+tag.options[s].text+"<br></span>");
				}else{
					$(tag).replaceWith("<span>"+tag.options[s].text+"<br></span>");
				}
			}
		}else if($(tag).attr("type") == "select-one"){
			if(tag.selectedIndex && tag.selectedIndex >=0){
				$(tag).replaceWith("<span>"+tag.options[tag.selectedIndex].text+"&nbsp;</span>");
			}
		}else if($(tag).attr("type") == "textarea"){
			var span =	
						"<PRE class='preFormato'>" +
						"<div class='tam1024_'>" +
						$(tag).val() + 
						"</div>" +
						"</PRE>" ; 
			$(tag).replaceWith(span);
			if(ExpYes){
				$("pre.preFormato div").addClass("tam1024");
			}
		}else{
			$(tag).replaceWith("<span style='"+$(tag).attr("style")+"'>"+$(tag).val()+"&nbsp;</span>");
		}
		$(tag).css("top","-100").css("display","none");
	}
}
/*************************************************************************************************
									FIM IMPRESS�O INTELIGENTE
*************************************************************************************************/

function garanteTamanhoMaximo(campo, tamanhoMaximo){
	return tamanhoMaximo < 0 || campo.value.length < tamanhoMaximo;
}

function converteMaiuscula(evt, campo){
	var key = getKeyCode(evt);
	if(key != 37 && key != 39 && plcGeral.alfabeticoPattern.test(campo.value))
		campo.value = campo.value.toUpperCase();
}

function converteMinuscula(evt, campo){
	var key = getKeyCode(evt);
	if(key != 37 && key != 39 && plcGeral.alfabeticoPattern.test(campo.value))
		campo.value = campo.value.toLowerCase();
}

/******************************************************************
VALIDA??O DE DADOS
******************************************************************/
//Contrutor Validacao
function PlcValida(){}

var plcValida = new PlcValida();

var arrayValidacaoCampos 	= new Array();

function validacaoCampo (argumentos){
	this.nomeCampo 		= argumentos[0];	
	this.formatoCampo 	= argumentos[1];
	this.msgErro		= argumentos[2];
	this.PARAM_0	= "";
	this.PARAM_1	= "";
	this.PARAM_2	= "";
	this.PARAM_3	= "";

	for(i = 3; i < argumentos.length; i++)
	{
		if(argumentos[i] == "PARAM_0")
			this.PARAM_0 = argumentos[++i];
		if(argumentos[i] == "PARAM_1")
			this.PARAM_1 = argumentos[++i];
		if(argumentos[i] == "PARAM_2")
			this.PARAM_2 = argumentos[++i];
		if(argumentos[i] == "PARAM_3")
			this.PARAM_3 = argumentos[++i];
	}
	
	this.msgErro = this.msgErro.replace("{0}", this.PARAM_0);
	this.msgErro = this.msgErro.replace("{1}", this.PARAM_1);
	this.msgErro = this.msgErro.replace("{2}", this.PARAM_2);
	this.msgErro = this.msgErro.replace("{3}", this.PARAM_3);
}

function validacaoCriaCampo(){
	arrayValidacaoCampos[arrayValidacaoCampos.length] = new validacaoCampo(arguments);
}

PlcValida.prototype.validacaoVerificarRegras = function(){
	plcLog.debug("VERIFICAR REGRAS");
	plcLog.newLogErros();
	if(!validacaoExecutar()){
		plcLog.logMostraErros();
		return false;
	}
	return true;
}

function validacaoExecutar(){
	plcLog.debug("VALIDACAO EXECUTAR");
	var validou = true;
	//jaValidou 	= false;
	plcLog.debug("QTDE. CAMPOS: "+arrayValidacaoCampos.length);
	for(var i = 0; i < arrayValidacaoCampos.length; i++){
		plcLog.debug("VAI VALIDAR CAMPO "+i);
		plcLog.debug("CAMPO NOME: "+arrayValidacaoCampos[i].nomeCampo);
		plcLog.debug("CAMPO FORMATO: "+arrayValidacaoCampos[i].formatoCampo);
		try{
			//alteraClasse ("CAMPO",arrayValidacaoCampos[i].nomeCampo,"CLASSE","campoComErro","INICIAL")
			if(!eval("plcValida.regra_"+arrayValidacaoCampos[i].formatoCampo.toLowerCase()+"(arrayValidacaoCampos[i])"))
				validou = false;
		plcLog.debug("VALIDOU CAMPO "+i);
		}catch(ex){
			if(plcLog.logGetDescExcecao(ex) == "Object doesn't support this property or method")
				plcLog.logAdicionaErroCampo("EXCECAO","ALERTA DE ERRO: Formato '"+arrayValidacaoCampos[i].formatoCampo+"' invalido para o campo '"+arrayValidacaoCampos[i].nomeCampo+"'");
			else {
				plcLog.logAdicionaErro(plcLog.montaMsgExcecao(ex));
				}
			return false;
		}
	}
	
	return validou;
}

PlcValida.prototype.regra_numerico = function (objCampo){
	var valCampo = get(objCampo.nomeCampo);
	if(valCampo != "" && !plcGeral.numericoPattern.test(valCampo)){
		//plcLog.logAdicionaErroCampo(objCampo.nomeCampo,objCampo.msgErro);
		return false;
	}
	return true;	
}

PlcValida.prototype.regra_alfabetico= function (objCampo){
	var valCampo = get(objCampo.nomeCampo);
	if(valCampo != "" && !plcGeral.alfabeticoPattern.test(valCampo)){
		//plcLog.logAdicionaErroCampo(objCampo.nomeCampo,objCampo.msgErro);
		return false;
	}
	return true;	
}

PlcValida.prototype.regra_data= function (objCampo){
	var valCampo = get(objCampo.nomeCampo);
	if(valCampo != "" && !plcGeral.dataPattern.test(valCampo)){
		plcLog.logAdicionaErroCampo(objCampo.nomeCampo,objCampo.msgErro);
		return false;
	}
	return true;	
}

PlcValida.prototype.regra_datahora= function (objCampo){
	var valCampo = get(objCampo.nomeCampo);
	if(valCampo != "" && !plcGeral.datahoraPattern.test(valCampo)){
		plcLog.logAdicionaErroCampo(objCampo.nomeCampo,objCampo.msgErro);
		return false;
	}
	return true;	
}

var flagDesprezarA = new Array();

function pegaFlagDesprezar(chaveDet,chaveSubDet) {

   for(var i = 0; i < flagDesprezarA.length; i++){
	
	    if (chaveSubDet!='') { 
	//		alert('chaveSubDet='+chaveSubDet+ ' componente='+flagDesprezarA[i].componente);
	    }
		if ((chaveDet.indexOf(flagDesprezarA[i].componente)>-1 && chaveSubDet=='') ||
			(chaveSubDet!='' && flagDesprezarA[i].componente.indexOf(chaveSubDet)>-1)) {
			return flagDesprezarA[i].flagDesprezar;
		}
		
	}
	
	return '';

}

PlcValida.prototype.regra_obrigatorio= function (objCampo){

	var valCampo = get(objCampo.nomeCampo);
	//alert('obj='+objCampo.nomeCampo+' valor campo='+valCampo);
	var considera = true;
	if (objCampo && objCampo.nomeCampo.indexOf("].")>-1) {
		// Pega valor da coluna flag para a cole?ao corrente
		var fimDet = objCampo.nomeCampo.indexOf("].")+2;
		var prefixoDet = objCampo.nomeCampo.substring(0,fimDet);
		var fimSubDet = objCampo.nomeCampo.indexOf("].",fimDet+1);
		//	alert('fimSubDet'+fimSubDet+ ' para '+objCampo.nomeCampo);
		var prefixoSubDet='';
		if (fimSubDet>-1) {
			var iniSubDet = objCampo.nomeCampo.indexOf("[",fimDet+1);
			prefixoSubDet=objCampo.nomeCampo.substring(fimDet,iniSubDet+1);
		//	alert('achou um subdet='+prefixoSubDet);
			fimSubDet = fimSubDet+2;
			fimDet = fimSubDet;
		}
		var prefixoTotal = objCampo.nomeCampo.substring(0,fimDet);
//		alert('prefixo total='+prefixoTotal+' pref det='+prefixoDet+' pref subdet='+prefixoSubDet);
		var colunaFlag = prefixoTotal + pegaFlagDesprezar(prefixoDet,prefixoSubDet);
	//	alert('colunaFlagNome='+colunaFlag+' valor='+get(colunaFlag));
		considera = get(colunaFlag) != '';
	}
	if (considera && valCampo.trim() == ""){
		plcLog.logAdicionaErroCampo(objCampo.nomeCampo,"OBRIGATORIO" );
		return false;
	}
	return true;	
}

String.prototype.trim = function(){
    var str = this;
    while (str.charAt(0) == " ")
        str = str.substr(1,str.length -1);
    while (str.charAt(str.length-1) == " ")
        str = str.substr(0,str.length-1);
    return str;
} 

/******************************************************************************\
						NAVEGA??O AUTOMATICA TABFOLDER
\******************************************************************************/

//Navega pr?xima aba
function tabFolderNavegaProx(evt){
	plcLog.debug("##### Entrou tabFolderNavegaProx");
	tabFolderNavegaAutomatico(evt,1)
}
//Navega aba anterior
function tabFolderNavegaAnte(evt){
	plcLog.debug("##### Entrou tabFolderNavegaAnte");
	tabFolderNavegaAutomatico(evt,-1)
}
//L?gicas gen?ricas na navega??o autom?tica de tab folder
function tabFolderNavegaAutomatico(evt,nav){

	plcLog.debug("##### Entrou tabFolderNavegaAutomatico");
	if(tabFolderNavegaInibe(evt, nav))
		return;
	if (typeof tabSelecionada != 'undefined') 
		tabFolderNavegaTrocaAba(nav)
}

//L?gicas gen?ricas para troca de aba na navega??o autom?tica de tab folder
function tabFolderNavegaTrocaAba(nav){
	plcLog.debug("tabFolderNavegaTrocaAba - tabSelecionada: "+tabSelecionada)
	var nomeAbaAtual	= tabSelecionada.substring(0,tabSelecionada.indexOf("_"));
	plcLog.debug("tabFolderNavegaTrocaAba - NOME ABA ATUAL: "+nomeAbaAtual)
	var numAbaAtual	= tabSelecionada.substring(tabSelecionada.indexOf("_")+1);
	plcLog.debug("tabFolderNavegaTrocaAba - NUM ABA ATUAL: "+numAbaAtual);
	plcLog.debug("tabFolderNavegaTrocaAba - NAV: "+nav);
	var numNavAba	= (parseInt(numAbaAtual) + parseInt(nav));
	if(numNavAba < 0) 
		numNavAba = 0;
	plcLog.debug("tabFolderNavegaTrocaAba - NUM NAV ABA: "+numNavAba);
	plcLog.debug("tabFolderNavegaTrocaAba - ABA NAV: "+nomeAbaAtual +"_"+numNavAba);
	plcLog.debug("tabFolderNavegaTrocaAba - GET ABA: "+getVarGlobal(numNavAba));
	if(numNavAba < layers.length){
		trocaAba(numNavAba,nomeAbaAtual +"_"+numNavAba,nomeAbaAtual +"_"+numNavAba );
		//set('detCorrPlc',getVarGlobal(numNavAba));
		//showHideAba(nomeAbaAtual +"_"+numNavAba,nomeAbaAtual +"_"+numNavAba );
		tabFolderFocaCampo(numNavAba)		
	}
}

//Foca o campo mais apropriada na tab folder ap?s navega??o autom?tica
function tabFolderFocaCampo(numNavAba){
	
	if (tabFolderCamposFoco != null && tabFolderCamposFoco.length > 0){
		setTimeout("setFocus('"+tabFolderCamposFoco[numNavAba]+"')",200);	
	}else{
		var camposVolta = getVarGlobal("cacheCamposVolta");
		if (camposVolta!=null)
		{
			if(numNavAba == 0 && getVarGlobal('campoFocadoPlc')){
				setTimeout("setFocus('"+getVarGlobal('campoFocadoPlc').name+"')",200);
				return;
			}	
			if(numNavAba > 0)
				numNavAba--;	
			if(camposVolta[numNavAba])
				setTimeout("setFocus('"+camposVolta[numNavAba].name+"')",200);
		}
	}
}

//Verifica se tecla pressionada permite navega??o autom?tica em tab folder
function tabFolderNavegaInibe(evt, nav){
	var key = 0;
   	if (ExpYes){
   		evt = window.event;
		key = evt.keyCode
   	}else{
		key = evt.which;
	}	
	return key != 9 || (nav == -1 && !evt.shiftKey) || (nav == 1 && evt.shiftKey);	
}
var tabFolderCamposIda 			= "";
var tabFolderCamposVolta 		= "";
var tabFolderCamposFoco 		= null;
function setTabFolderCamposIda(campos){
	tabFolderCamposIda = campos;
}
function setTabFolderCamposVolta(campos){
	tabFolderCamposVolta = campos;
}
function setTabFolderCamposFoco(campos){
	tabFolderCamposFoco = separaListaTermos(campos, ",");
}

//Configura eventos onkeydown para marcar campo focado para l?gicas de navega??o em tab folder via onblur
function configuraEventosTabFolder(){
	
		var camposIda 		= separaListaTermos(tabFolderCamposIda,",")
		var camposVolta 	= separaListaTermos(tabFolderCamposVolta,",")
		var cacheCamposIda	= new Array();
		var cacheCamposVolta= new Array();
		var campo		= null;
		var detalhes		= null;
		//Configura campos ida
		for(ci = 0; ci < camposIda.length; ci++){
			campo = null;
			if(camposIda[ci] && camposIda[ci].indexOf(".") > -1){
				detalhes = getCamposDetalhes(camposIda[ci]);
				campo = detalhes.ultimo;
			}	
			else
				campo = getCampo(camposIda[ci]);
			if(campo && campo != null){
				setUpOnEventoTagCampoNome (campo.tagName, "onkeydown", "tabFolderNavegaProx", campo.name);
				cacheCamposIda[cacheCamposIda.length] = campo;
			}
		}
		setVarGlobal("cacheCamposIda",cacheCamposIda);
		//Configura campos volta
		for(cv = 0; cv < camposVolta.length; cv++){
			campo = null;
			//alert("camposVolta[cv]: "+camposVolta[cv])	
			if(camposVolta[cv] && camposVolta[cv].indexOf(".") > -1){
				detalhes = getCamposDetalhes(camposVolta[cv]);
				campo = detalhes.primeiro;
			}
			else
	                        campo = getCampo(camposVolta[cv]);
			//alert("campo.name: "+campo.name)	
			if(campo && campo != null){
				setUpOnEventoTagCampoNome (campo.tagName, "onkeydown", "tabFolderNavegaAnte", campo.name)
				cacheCamposVolta[cacheCamposVolta.length] = campo;
			}
		}
		setVarGlobal("cacheCamposVolta",cacheCamposVolta);	
	
}	

//Recupera primeiro e ?ltimo detalhe de uma lista
function getCamposDetalhes(nomeCampo, nomeLista){

	var ultimoDetalhe = null;
	var primeiroDetalhe = null;
	var nomeCampoAux = nomeCampo;
	var posPonto = nomeCampoAux.indexOf(".");
	if(posPonto > -1){
		nomeLista = nomeCampoAux.substring(0,posPonto);
		nomeCampo = nomeCampoAux.substring(posPonto+1);
	}
	var cont = 0;
	do{
		var campo = getCampo(nomeLista+"["+cont+"]."+nomeCampo);
		if(campo){
			ultimoDetalhe = campo;
			if(primeiroDetalhe == null)
				primeiroDetalhe = ultimoDetalhe;
		}else{
			cont = -1;
			break;	
		} 
		cont++;
	}while(getCampo(nomeLista+"["+cont+"]."+nomeCampo) && cont > 0)
	var retorno = new Object();
	retorno.primeiro = primeiroDetalhe;
	retorno.ultimo = ultimoDetalhe;
	return retorno;
}
//***********************FIM NAVEGA??O AUTOMATICA TABFOLDER *********************
//Reverte configura??es de layout para campos focados no evento onbluir
function reverteDestaqueCampoFocado(evt){
	destacaCampoFocado(evt);
}
//L?gica de destaque autom?tico de campos focados
function destacaCampoFocado(evt){
	if(ExpYes){
		evt = window.event;
		obj = evt.srcElement;
	}	
	else{	
		obj = evt.target;
		if(obj.type == 'checkbox' || obj.type == 'radio')
			obj = obj.parentNode;
	}	
	with (obj){
		try	{
			if(evt.type == 'focus' || typeof oldClassName == "undefined" || oldClassName == null){
				if(className != "adicionaBorda"){
					oldClassName = className;
					if(obj.type && type.indexOf("select") > -1)
						className = "adicionaFundo "+className;
					else	
						className = "adicionaBorda "+className;
				}	
			}else {
				className = oldClassName;
				oldClassName = null;
			}
		}catch(e){}
	}
	if(	evt.type == 'focus')
		eventoTrataonfocus(evt, obj);
	else if(	evt.type == 'blur')
		eventoTrataonblur(evt, obj);
}

/******************************************************************************\
						NAVEGA??O AUTOMATICA 
\******************************************************************************/
//Construtor PlcNavegacao
//function PlcNavegacao (){}
//Objeto plcNavegacao
//var plcNavegacao = new PlcNavegacao();
//Fun??es para navega??o espec?ficas nas setas para extens?o no cliente
//PlcNavegacao.prototype.navegaSetaParaCimaEspecifico = function() {}
//PlcNavegacao.prototype.navegaSetaParaBaixoEspecifico = function() {}
//PlcNavegacao.prototype.navegaSetaParaEsquerdaEspecifico = function() {}
//PlcNavegacao.prototype.navegaSetaParaDireitaEspecifico = function() {}

//Executa navega??o autom?tica com pressionamento de seta para cima
function navegaSetaParaCima(){
	plcLog.debug("##### Entrou navegaSetaParaCima")
	
	//Verificar se inibe navega??o
	if(navegaSetaInibe())
		return;
	//Navega??o no menu de sistema
	if(plcGeral.MENU_ATIVO){
		menuSistemaNavSetaParaCima();
		return;
	}	
	//Verifica se linha de sele??o foi selecionada para navega??o
	if(getVarGlobal("trSelecao") == null)
		return;
	
	var numLinha = "undefined";
	
	if (tecnologia == "Struts"){
		numLinha = getVarGlobal("trSelecao") == null || getVarGlobal("trSelecao") == "undefined" ? -1 : getVarGlobal("trSelecao").id.substring(getVarGlobal("trSelecao").id.lastIndexOf("_")+1);
	} else {
		
		var padrao = new RegExp("corpo\\:(\\w+)\\:(\\d+)\\:(\\w+)");
		
		if (getVarGlobal ("trSelecaoIdIter") == null){
			
			var primeiraLinha = new RegExp("corpo\\:(\\w+)\\:0:(\\w+)");
			
			if (primeiraLinha.exec(document.documentElement.innerHTML) != null){
				//Registrar tokens da primeira linha
				var padraoPrimeiraLinha = primeiraLinha.exec(document.documentElement.innerHTML);
				setVarGlobal("trSelecaoIdIter", padraoPrimeiraLinha[1]);
				setVarGlobal("trSelecaoLinhaSel", padraoPrimeiraLinha[2]);
			}
		}
		
		var linhaSelecao = getVarGlobal("trSelecao");
		if (linhaSelecao != null && linhaSelecao != "undefined"){
			var recebePadrao = padrao.exec(linhaSelecao.id);
			numLinha = recebePadrao[2];
		} else {
			numLinha = -1;
			/*getVarGlobal("trSelecao") == null || getVarGlobal("trSelecao") == "undefined" ? -1 : getVarGlobal("trSelecao").id
			.substring(21,getVarGlobal("trSelecao").id.lastIndexOf(":linhaSel"));*/
		}
	}
	 
	navegaListaSelecao(parseInt(numLinha)-1);
}
//Executa navega??o autom?tica com pressionamento de seta para baixo
function navegaSetaParaBaixo(){
	plcLog.debug("##### Entrou navegaSetaParaBaixo")

	//Verificar se inibe navega??o
	if(navegaSetaInibe())
		return;
	//Navega??o no menu de sistema
	if(plcGeral.MENU_ATIVO){
		menuSistemaNavSetaParaBaixo();
		return;
	}
	//Abrir janela popup
	if(navegaSetaPopup())
		return;
 	var evt = getVarGlobal("event");
	if(typeof evt != "undefined"){
		var elemento = ""; 
		try{
			elemento = plcEvento.getEventoElemento(evt);
		}catch(e){}	
		if(elemento && elemento.id == "LINK_INTELIGENTE")
			dispararEvento(elemento, "onclick");
	}	

	var numLinha = "undefined";
	
	if (tecnologia == "Struts"){
		numLinha = getVarGlobal("trSelecao") == null || getVarGlobal("trSelecao") == "undefined" ? -1 : getVarGlobal("trSelecao").id.substring(getVarGlobal("trSelecao").id.lastIndexOf("_")+1);
	} else {
		
		var padrao = new RegExp("corpo\\:(\\w+)\\:(\\d+)\\:(\\w+)");
		
		if (getVarGlobal ("trSelecaoIdIter") == null){
			
			var primeiraLinha = new RegExp("corpo\\:(\\w+)\\:0:(\\w+)");
			
			if (primeiraLinha.exec(document.documentElement.innerHTML) != null){
				//Registrar tokens da primeira linha
				var padraoPrimeiraLinha = primeiraLinha.exec(document.documentElement.innerHTML);
				setVarGlobal("trSelecaoIdIter", padraoPrimeiraLinha[1]);
				setVarGlobal("trSelecaoLinhaSel", padraoPrimeiraLinha[2]);
			}
		}
		
		var linhaSelecao = getVarGlobal("trSelecao");
		if (linhaSelecao != null && linhaSelecao != "undefined"){
			var recebePadrao = padrao.exec(linhaSelecao.id);
			numLinha = recebePadrao[2];
		} else {
			numLinha = -1;
			/*getVarGlobal("trSelecao") == null || getVarGlobal("trSelecao") == "undefined" ? -1 : getVarGlobal("trSelecao").id
			.substring(21,getVarGlobal("trSelecao").id.lastIndexOf(":linhaSel"));*/
		}
	}
	
	
	navegaListaSelecao(parseInt(numLinha)+1);
}	

function navegaSetaParaDireita(){
	plcLog.debug("##### Entrou navegaSetaParaDireita")
 	//var evt = getVarGlobal("event");
	tabFolderNavegaSetaDireita()		
}
function navegaSetaParaEsquerda(){
	plcLog.debug("##### Entrou navegaSetaParaEsquerda")
 	//var evt = getVarGlobal("event");
	tabFolderNavegaSetaEsquerda()
}

//Fun??es para navega??o espec?ficas em tabfolder para extens?o no cliente
//PlcNavegacao.prototype.tabFolderNavegaSetaDireitaEspecifico = function() {}
//PlcNavegacao.prototype.tabFolderNavegaSetaEsquerda = function() {}

function tabFolderNavegaSetaDireita(){
	plcLog.debug("##### Entrou tabFolderNavegaSetaDireita");
	tabFolderNavegaTrocaAba(1)
}
function tabFolderNavegaSetaEsquerda(){
	plcLog.debug("##### Entrou tabFolderNavegaSetaEsquerda");
	tabFolderNavegaTrocaAba(-1)
}

function navegaSetaInibe(){
	plcLog.debug("##### Entrou navegaSetaInibe")

 	var evt = getVarGlobal("event");
	var elemento = null;
	if(typeof evt != "undefined"){ 
		try{
			elemento = plcEvento.getEventoElemento(evt);
		}catch(e){}	
		if(elemento && elemento.type && (elemento.type.indexOf("select") >= 0 || elemento.type == 'textarea'))
			return true;
	}	
	return false;	
}	

var idElementoPopupPlc = "";
function setIdElementoPopupPlc(id){
	plcLog.debug("##### Entrou setIdElementoPopupPlc")
	idElementoPopupPlc = id;
}
function getIdElementoPopupPlc(){
	plcLog.debug("##### Entrou getIdElementoPopupPlc")
	return idElementoPopupPlc;
}

function navegaSetaPopup(){
	plcLog.debug("##### Entrou navegaSetaPopup")

 	var evt = getVarGlobal("event");
	if(getElementoPorId(getIdElementoPopupPlc()+"SelPop")){
		setNavSetaFocoPlc(true);
		setVarGlobal("campoPopupPlc", getElementoPorId(getIdElementoPopupPlc()+"SelPop"));
		setIdElementoPopupPlc("");
		setTimeout("navegaSetaAbrePopup()", 10);
		return true;
	}	
	setIdElementoPopupPlc("");
	return false;	
}	

function navegaSetaAbrePopup(campoPopupPlc){
	plcLog.debug("##### Entrou navegaSetaAbrePopup")
	
	if(typeof campoPopupPlc == "undefined"){
		campoPopupPlc = getVarGlobal("campoPopupPlc");
		setVarGlobal("campoPopupPlc", null);
	}	
	if(ExpYes)	
		dispararEvento(campoPopupPlc, "onclick")		
	else{
		campoPopupPlc = campoPopupPlc.getAttribute("onclick");
		if(campoPopupPlc.indexOf("return") > -1)
			campoPopupPlc = campoPopupPlc.substring(0, campoPopupPlc.indexOf("return")) 
		eval(campoPopupPlc);
	}
}

function navegaListaSelecao(linha){
	if(typeof linha == "undefined")
		linha = 0;
	
	var trSelecao = "undefined";
	
	if (tecnologia == "Struts"){
		trSelecao = getElementoPorId('linhaSel_'+linha);
	} else if (tecnologia == "JSF"){
		var trSelecaoIdIter = getVarGlobal("trSelecaoIdIter");
		var trSelecaoLinhaSel = getVarGlobal("trSelecaoLinhaSel");
		trSelecao = getElementoPorId('corpo:'+trSelecaoIdIter+':'+linha+':'+trSelecaoLinhaSel);
	}
		
	var evt = plcEvento.getEventoAtual();
	var evtAux = evt;	
	//Marcar linha atual
	if(trSelecao){	
		if(!evtAux || typeof evtAux.type == "undefined"){
			evtAux = new Object()
			evtAux.type = "mouseover";	
		}		
		marcaSelecao(trSelecao, evtAux);
		evtAux = evt;
		var trTagOut =	 getVarGlobal("trSelecao");
		//Desmarcar linha anterior
		if(trTagOut != null){
			if(!evtAux || typeof evtAux.type == "undefined"){
				evtAux = new	 Object()
				evtAux.type = "mouseout";
			}		
		 	marcaSelecao(trTagOut, evtAux);
		 }	
		setVarGlobal("trSelecao", trSelecao)
	 }
}	

/*Desmarca lista de sele??o quando campo de argumento ? focado*/
function desmarcaListaSelecao(){
	if(getVarGlobal("trSelecao") != null){	
		alteraClasse('OBJETO', getVarGlobal("trSelecao"), 'CLASSE', 'campoComErro','INICIAL');
		setVarGlobal("trSelecao", null)
	}
}

/*Simula o click em um link de sele??o*/
function clicarListaSelecao(){
	if(getVarGlobal("trSelecao") != null){
		dispararEvento(getVarGlobal("trSelecao"), "onclick")
	}
}
//***********************FIM NAVEGA??O AUTOMATICA LISTA SELE??O*********************
function executarEnter(){
	if(plcGeral.MENU_ATIVO)
		menuSistemaClicar();
	else	
		clicarListaSelecao();
}
function dispararEvento(elemento, evento){
	evento = evento.toLowerCase();
	if(ExpYes){
		var evObj = document.createEventObject();
		elemento.fireEvent(evento, evObj);
	}
	else{
		var evObj = document.createEvent('MouseEvents');
		evObj.initMouseEvent( evento.replace("on",""), true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
		elemento.dispatchEvent(evObj);
	}		
}

var numMenu = null;
var numItem = null;
var numSubItem = null;
function menuSistemaNavega(nMenu, nItem, nSubItem){
	plcLog.debug("menuSistemaNavega");

	//Temporizador para fechar menu
	if(CloseTmr)
		clearTimeout(CloseTmr);
	CloseTmr = setTimeout('menuSistemaFechar()',DissapearDelay * 2)
	numMenu = parseInt(nMenu);
	numItem = typeof nItem != "undefined" ? parseInt(nItem) : null;
	numSubItem = typeof nSubItem != "undefined" ? parseInt(nSubItem) : null;
	var sufixMenu = numItem != null ? numMenu +"_"+ numItem : numMenu; 
	sufixMenu = numSubItem != null ? numMenu +"_"+ numItem +"_"+ numSubItem : sufixMenu; 
	var menuObj = getElementoPorId("Menu"+sufixMenu);
	if(menuObj){
		setNavSetaFocoPlc(true);
		if((""+sufixMenu).indexOf("_") < 0)
			dispararEvento(menuObj, "onclick");
		else
			dispararEvento(menuObj, "onmouseover");
		setVarGlobal("menuObj", menuObj);
	}
}

function menuSistemaFechar(){
	Init(FrstCntnr);
	IniFlg=0;
	AfterCloseAll();
	ShwFlg=0
}

function menuSistemaClicar(){
	var menuObj = getVarGlobal("menuObj");
	dispararEvento(menuObj, "onclick");
}

function menuSistemaNavSetaParaCima(){
	if(plcGeral.MENU_ATIVO){
		if(numSubItem == null)	
			menuSistemaNavega(numMenu,numItem - 1)
		else	
			menuSistemaNavega(numMenu,numItem, numSubItem - 1)
	}
}
function menuSistemaNavSetaParaBaixo(){
	if(plcGeral.MENU_ATIVO){
		if(numSubItem == null)	
			menuSistemaNavega(numMenu,numItem + 1)
		else	
			menuSistemaNavega(numMenu,numItem, numSubItem + 1)
	}
}

function menuSistemaNavSetaParaDireita(){
	if(plcGeral.MENU_ATIVO){
		if(numSubItem == null)	
			menuSistemaNavega(numMenu,numItem, 1)
	}
}
function menuSistemaNavSetaParaEsquerda(){
	if(plcGeral.MENU_ATIVO){
		if(numSubItem != null)	
			menuSistemaNavega(numMenu,numItem)
	}
}

//Fun??o para foco em campo auxiliar
function setNavSetaFocoPlc(focar){

	if(focar && getElementoPorId("navSetaFocoPlc:inibeFoco"))
		getElementoPorId("navSetaFocoPlc:inibeFoco").focus();
	else{
		if(getVarGlobal("campoFocadoPlc"))
			getVarGlobal("campoFocadoPlc").focus();
	}	
}

function CheckNumerico(campo,tammax,teclapres)
{
	var teclaChar = String.fromCharCode(getKeyCode(teclapres));
	
 	if (teclaChar != 0) {
		if (("0123456789").indexOf(teclaChar) > -1)
			return;
		else{
			while (campo.value.indexOf(teclaChar) > -1 || campo.value.indexOf(teclaChar.toLowerCase()) > -1){
				campo.value = campo.value.replace(teclaChar, "");
				campo.value = campo.value.replace(teclaChar.toLowerCase(), "");
			}
		}
	}
	return false;
}

function FormataValor(campo,tammax,teclapres,prec)
{
	//pegar tecla e definir valor de virgula
	var tecla = teclapres.keyCode;
	var virgula = ',';

	//pegar valor do campo atual e remover todas virgulas, pontos, barras etc...
	vr = campo.value;
	
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );

	//se precisao for 0 definir virgula como inexistente para n?o aparecer
	if (prec==0)
		virgula='';

	//antes de checar tamanho do campo remover 0s da frente do campo
	for (k=0;k<prec;k++)
	{
		if (vr.substr(0,1) == '0')
			vr=vr.substr(1,prec+1);
	}

	//pegar tamanho dos valores j? limpos
	tam = vr.length;
	
	//se tamanho for zero n?o fazer nada
	if (tam==0)
		return

	//se teclas apertadas forem numericas, backspace, del etc.... entrar em if
	if (!tecla || tecla==8 || tecla==46 || ((tecla <= 57 && tecla >= 48) || (tecla <=105 && tecla >= 96)))
	{
		//if para campos de valores fracionais ate 0,999
		if ( tam <= prec + 1)
		{
			campo.value = '0' + virgula;
			for (k=1;k<=prec-tam;k++)
			{	
				campo.value += '0' ;
			}	
			campo.value+=vr;
		}

		//if para campos com valores at? 999,999
		if ( (tam > prec) && (tam <= prec + 3) )
		{
			campo.value = vr.substr(0,tam-prec) + virgula + vr.substr(tam-prec,prec+1); 
		}

		//if para campos com valores at? 999.999,999
		if ( (tam > prec + 3) && (tam <= prec + 6) )
		{
			campo.value = vr.substr(0, tam-(prec+3)) + '.' + vr.substr(tam-(prec+3), 3) + virgula + vr.substr(tam-prec, prec+1) ; 
		}

		//if para campos com valores at? 999.999.999,999
		if ( (tam > prec + 6) && (tam <= prec + 9) ){
			campo.value = vr.substr(0, tam-(prec+6) ) + '.' + vr.substr(tam-(prec+6), 3) + '.' + vr.substr(tam-(prec+3),3 ) + virgula + vr.substr(tam-prec, prec+1); 
		}

		//if para campos com valores at? 999.999.999.999,999
		if ( (tam > prec + 9) && (tam <= prec + 12) )
		{
			campo.value = vr.substr(0, tam-(prec+9)) + '.' + vr.substr(tam-(prec+9), 3) + '.' + vr.substr(tam-(prec+6), 3) + '.' + vr.substr(tam-(prec+3), 3) + virgula + vr.substr(tam-prec,prec+1) ; 
		}

		//if para campos com valores at? 999.999.999.999.999,999
		if ( (tam > prec + 12) && (tam <= prec + 15) )
		{
			campo.value = vr.substr(0, tam-(prec+12)) + '.' + vr.substr(tam-(prec+12), 3) + '.' + vr.substr(tam-(prec+9), 3) + '.' + vr.substr(tam-(prec+6), 3) + '.' + vr.substr(tam-(prec+3), 3) + virgula + vr.substr(tam-prec,prec+1) ; 
		}

//if ( (tam >= 15) && (tam <= 17) ){
// campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + virgula + vr.substr( tam - 2, tam ) ;}
//
	}

	return;
}

/**
* Escreve marca de obrigatorio ao final do campo.
*/
function escrevePlcAfter(tags,nameClass,what)
{
    var l=tags.length;
    for(var i=0;i<l;++i)
    {
        var tag=tags[i];
        if(tag.className.indexOf(nameClass)>-1){
        	var html=tag.innerHTML+what;
        	tag.innerHTML=html;
        }
    }
}

/**
 * Comuta de aba automaticamente - jcompany 5.0.
 * @param posicaoAba Ordem da aba de 0 a N
 */
 function comutaAba(posicaoAba,nomeCampo) {
	
	trocaAba(posicaoAba,'def.tab.automatico_'+posicaoAba,'def.tab.automatico_'+posicaoAba);
	setTimeout('window.focus()',40);
	var comandoFoco = "setFocus('"+nomeCampo+"')";
	setTimeout(comandoFoco,50);

 }

/**
 * Seleciona um agregado pela tecla 40 (seta para baixo)
 */ 
function selecionaPorTecla(event,objeto) {
	var botaoSelecao = objeto.id +"Sel";
	
	if (botaoSelecao.indexOf("lookup_") > -1)
		botaoSelecao = botaoSelecao.replace("lookup_", "");
	
	if (getEvento(event).keyCode==40) {
		dispararEvento(getElementoPorId(botaoSelecao),'onclick');
	}
}
 
 /**
 * Devolve um evento (tecla clicada, por exemplo), cross-browser
 */
function getEvento(evt) {
	if (ExpYes) {
		return window.event;
	} else {
		return evt;
	}
}

/**
*  Dispara botao de visualizar documento, se estiver visivel
*/
function visualizaFormulario() {
		if (document.getElementById('corpo:visualizaDocumento')!=null) {
			dispararEvento(document.getElementById('corpo:visualizaDocumento'),'onclick');
		}
}

/*********************************************************************
						JQUERY
*********************************************************************/
//window.alert = jqueryAlert; 
function jqueryAlert (msg){
	msg = "<table width='100%' align='center' border='0' cellspacing='5%'><tr><td align='center'>"+msg+"</td><tr><td align='center'><input type='button' id='ok' value='Ok' class='botao' style=''/></td></tr></table>";
	$.blockUI(msg, { width: '275px', padding: '20px'}); 
	$('#ok').click($.unblockUI); 
};

//window.confirm = jqueryConfirm; 
function jqueryConfirm (msg){
	var retorno;
	msg = "<table width='100%' align='center' border='0' cellspacing='5%'><tr><td align='center'>"+msg+"</td><tr><td align='center'><input type='button' id='sim' value='Sim' class='botao'/>&nbsp;<input type='button' id='nao' value='N&atilde;o' class='botao'/></td></tr></table>";
	//msg += "<br><br><input type='button' id='sim' value='Sim' class='botao'/>&nbsp;<input type='button' id='nao' value='N&atilde;o' class='botao'/>";
	$.blockUI(msg, { width: '275px', padding: '20px'}); 
	$('#nao').click(function(){
		$.unblockUI();
//		return false;
	}); 
	$('#sim').click(function(){
		$.unblockUI();
		disparouBotao = true;
//		if(botaoParaDisparar != null)
//			disparaBotao(botaoParaDisparar);
//		else
//			disparaBotao(getVarGlobal("THIS"));
//		return true;
	}); 
};

function setUpLinkShadowbox (REL) {

	//Recupera LINKS
	var elementos = document.getElementsByTagName("A");
	if(elementos && elementos.length > 0 && typeof jQuery != "undefined") {
	    for (i = 0; i < elementos.length; i++) {
	    	var umElemento = elementos[i];
			if(umElemento.href.indexOf(".do") > -1 && 
			//umElemento.href.indexOf("evento=Editar") > -1 &&
			(umElemento.getAttribute("rel") == null || umElemento.getAttribute("rel") == "")){
				umElemento.id	= "LINK_"+i;

				var a = document.createElement('A');
				a.href = umElemento.href;
				a.style.zIndex = 10000;
				a.innerHTML = "<img src='"+plcGeral.contextPath+"/plc/midia/ico_perspectiva_treeview.gif' border='0'>";
				a.style.display = "none";
				a.rel	= REL;
				a.title = umElemento.href;
				a.id	= "LINK_"+i+"_PREVIEW";
				a.doHide = false;
				a.index = 0;
				a.className = "option";
				a.timeoutPreview = null;
				a.hide=function(){
					//this.style.display = "none";
					this.timeoutPreview = setTimeout("hidePreviewId('"+this.id+"')",3000);
				};
				a.show=function(){
					clearTimeout(this.timeoutPreview)
					this.style.display = "inline";
				};
				eval("a.onmouseover=showThis");
				eval("a.onmouseout=hideThis");
				eval("a.onclick=ativarPreview");
				eval("umElemento.onmouseover=showPreview");
				eval("umElemento.onmouseout=hidePreview");
				var paiA = umElemento.parentNode;
				paiA.appendChild(a);
			}
		}
		iniciarShadowbox("PREVIEW_LINK");
	}
}

function hidePreviewId(id){
	var linkPreview = getElementoPorId(id);
	linkPreview.style.display = "none";
}

function showPreview(evt){
	var ev = getEvento(evt);
	var ctrlKey   = ev.ctrlKey;
	if(ctrlKey){
		var linkPreview = getElementoPorId(this.id+"_PREVIEW");
		linkPreview.show();
	}	
}
function hidePreview(){
	var linkPreview = getElementoPorId(this.id+"_PREVIEW");
	linkPreview.hide();
}
function ativarPreview(){
	setVarGlobal("PREVIEW_ATIVO","S")
	var linkPreview = getElementoPorId(this.id);
	linkPreview.hide();
}
function desativarPreview(){
	setVarGlobal("PREVIEW_ATIVO",null)
}

function showThis(){
	this.show();
}
function hideThis(){
	this.hide();
}

//-- BPM --
function registraTransicaoBPM (valor){
	if (tecnologia=="Struts"){
		insereValorCampo('proximaTransicao', valor);
	}else if (tecnologia == "JSF"){
		insereValorCampo('corpo:formulario:proximaTransicao', valor);
	}
}

function verificaImagemProcesso(bpm_console, valor){
	var cookie = $.cookie('jBpm-cookie');
	if (cookie && valor){
		exibeImagemProcesso(true, bpm_console, valor);
	}
}

function atualizaDiv (bpm_console, valor){
	if ($('#divImagemProcesso').children("iframe").length == 0){
		$.cookie('jBpm-cookie', 'exibeImagem');
		exibeImagemProcesso(true, bpm_console, valor);
	} else {
		$.cookie('jBpm-cookie', null);
		exibeImagemProcesso(false);
	}
}

function exibeImagemProcesso(exibe, bpm_console, valor){
	if (exibe){
		$('#divImagemProcesso')
			.html("<iframe src='"+bpm_console+"?id="+valor+"&view=img' width='100%' height='600' frameborder='0'></iframe>")
			.show();
	}else{
		$('#divImagemProcesso')
			.hide()
			.children("iframe")
			.remove();
	}
}



/*********************************************************************
 * 						COMPATIBILIZA��ES JCOMPANY
 *********************************************************************/

/**
* Fun��o que limpara os T�tulos ap�s o novo utilizando AJAX
* <br/><small>(copiado do jcompany para corre��o de erro)</small>
* @autor Geraldo Matos, Pedro Neves
*/
function verificarAlteracaoTitulos() {

	var tituloJanela = document.getElementById("inputTituloPagina");
	if (tituloJanela){
		document.title = tituloJanela.value;
		var arrayDivs = document.getElementsByTagName("div");
		for (j = 0; j < arrayDivs.length; j++) {
			if (arrayDivs[j].className == "tituloPagina") {
				arrayDivs[j].innerHTML = tituloJanela.value;
				break;
			}
		}
	}
}

var ajaxUsa = false;
function setAjaxUsa (ajaxUsaArg) {
	ajaxUsa = ajaxUsaArg;
}

function selecaoModal(url, listaCampos, separador, larg, alt, posX, posY, alvo){
	// Registra os campos de retorno, no escopo da janela que pediu o Modal Window!
	window.camposRetorno = registrarCamposRetorno(listaCampos, "nome,id", separador);
	
	// Cria a Janela Modal!
	var dialog = JQPlc.dialogWindow({
		title: 'Sele&ccedil;&atilde;o'
		,url: url.replace('modal','popup')
	});
	
	// Sele��o N�o intrusiva!
	dialog.children('iframe').bind('load', function(){
		var iWindow = $(this).attr('contentWindow');
		iWindow['devolveSelecao'] = iWindow['devolveSelecaoModal'] = function(){
			window.recebeSelecaoPopup.apply(this, arguments);
			dialog.dialog('close');
		}
	});
};

var JQPlc = {

	/*
	 * Cria uma nova Janela Dialog do jQuery UI.
	 * Recebe um objeto de configura��o, que deve ter como par�metro, a url e o tamanho da janela.
	 * {
	 * 	url: '...'
	 *  ,width: ...
	 *  ,height: ...
	 * }
	 * 
	 * No scopo window do iFrame � adicionado o objeto dialogOpener e a fun��o dialogClose,
	 * para auxiliar na manipula��o da janela.
	 * 
	 * @param Objeto de configura��o com URL.
	 * @return Retorna o Objeto jQuery Dialog.
	 */
	dialogWindow: function(c, dialogOpener){
		
		// Possibilita recursividade!
		//if (window.parent && window.parent != window) {
		//	return window.parent.jQuery.plc.dialogWindow(c, (dialogOpener || window));
		//}
		
		// Cria o jQuery UI Dialog com iFrame!
		var dialog = $(
			'<div '+
				'title="'+ (c.title||'') +'" '+
				'style="padding: 0px; margin: 0px; width: '+(c.width || 720)+'px; height: '+(c.height || 480)+'px; display: block;"'+
			'>'+
				'<iframe src="' + c.url + '" style="display: none; width: 99%; height: 99%; border: none;"></iframe>'+
			'</div>'
		);
		
		// Injeta no iFrame o dialogOpener, e a funcao dialogClose!
		var iWindow = dialog.children('iframe')[0].parentNode;
		iWindow.dialogOpener = dialogOpener;
		iWindow.dialogClose = function(){
			dialog.dialog('close');
		};

		var opts = {
			modal: true
			,width: (c.width || 720)
			,height: (c.height || 480)
			,hide: 'slide'
			,open: function(){
				dialog.children('iframe').show();
			}
			,dragStart: function(){
				dialog.children('iframe').hide();
			}
			,resizeStart: function(){
				dialog.children('iframe').hide();
			}
			,dragStop: function(){
				dialog.children('iframe').show();
			}
			,resizeStop: function(){
				dialog.children('iframe').show();
			}
			,beforeClose: function(){
				dialog.children('iframe').hide();
			}
			,close: function(){
				dialog.dialog('destroy');
			}
		};

		opts = $.extend(opts, c);

		dialog.dialog(opts);

		return dialog;
	}
}

/********************************************************************/





/*****************************************************************************\
					GERAL
\*****************************************************************************/
/**
* Construtor para objeto EcpGeral
*/
function EcpGeral(){}
/**
* @variable ecpGeral Instancia do objeto EcpGeral
*/
var ecpGeral = new EcpGeral();
/**
* Define url amig�vel para envio em email
*/
EcpGeral.prototype.uriAmigavelEnvioEmail = "";

/**
 * Define objeto do intervalo de reabertura atendimento online
 */
EcpGeral.prototype.reaberturaAtendOnlineInterval = null;

/**
 * Define objeto do intervalo de verifica��o reabertura atendimento online
 */
EcpGeral.prototype.verificarReaberturaAtendOnlineInterval = null;

/**
* Objeto que representa a janela popup de Atendimento Online
*/
EcpGeral.prototype.winPopupAtendOnline = null;

/**
* Objeto chat popup
*/
EcpGeral.prototype.objWinPopupAtendOnline = function(aberto){
	this.closed = !aberto;
};

/**
* Fun��o para reabrir atendimento online ap�s mudan�a de janela
*/
EcpGeral.prototype.reaberturaAtendimentoOnline = function (){
	ecpGeral.winPopupAtendOnline = ecpGeral.aberturaAtendimentoOnline();
	//ecpGeral.verificarReaberturaAtendOnlineInterval = setInterval("ecpGeral.verificarReaberturaAtendimentoOnline()",5000);
}

/**
* Fun��o para abrir atendimento online
*/
EcpGeral.prototype.aberturaAtendimentoOnline = function (){
	if(ecpGeral.winPopupAtendOnline == null || ecpGeral.winPopupAtendOnline.closed){
		ecpGeral.winPopupAtendOnline = janela('/ecp/chatcontactsalas.do?evento=x',730,600);
		clearInterval(ecpGeral.reaberturaAtendOnlineInterval);
		clearInterval(ecpGeral.verificarReaberturaAtendOnlineInterval);
	}
	ecpGeral.verificarReaberturaAtendOnlineInterval = setInterval("ecpGeral.verificarReaberturaAtendimentoOnline()",5000);
}

/**
* Fun��o para verificar reabertura atendimento online
*/
EcpGeral.prototype.verificarReaberturaAtendimentoOnline = function (){
	if(ecpGeral.winPopupAtendOnline == null || ecpGeral.winPopupAtendOnline.closed){
		ecpGeral.reaberturaAtendOnlineInterval = setInterval("ecpGeral.aberturaAtendimentoOnline()",180000);
		clearInterval(ecpGeral.verificarReaberturaAtendOnlineInterval);
	}
}

/*****************************************************************************\
					CAPITALIZA��O 
\*****************************************************************************/
	String.prototype.capitalize = function(){ //v1.0
	    return this.replace(/\w+/g, function(a){
	        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
	    });
	};
/*****************************************************************************\
					TESTE VAZIO
\*****************************************************************************/
	String.prototype.isEmpty = function(){ 
		this == ""  || this == "null";
	};

	/**
	* Fun��o para inibir clicks em links e bot�es se for preview
	* de estat�stica
	*/
	setFuncaoOnLoad("configEventosPreviewEstatistica()");
	function configEventosPreviewEstatistica(){
		if(getParametroUrl("nca") == 's'){
			setUpOnEventoTag ('INPUT', 'onclick', 'inibeOnClick');
			setUpOnEventoTag ('A', 'onclick', 'inibeOnClick');
			configEventosMouse("mousedown");
			configEventosMouse("contextmenu");
		}	
	}
	function EcpEvento(){}
	var ecpEvento = new EcpEvento();
	EcpEvento.prototype.handlerOnResize = function() {
		ecpEvento.evtOnResize();
	}
	EcpEvento.prototype.evtOnResize = function() {}
	
	if(ExpYes)
		window.attachEvent("onresize", ecpEvento.handlerOnResize);
	else	
		window.addEventListener("resize", ecpEvento.handlerOnResize,true)

	function addToFavorites(title, url){

		if(title == "")
			title = document.title;
		if(url == "")	
			url = document.location.href;
		if (document.all)
			window.external.AddFavorite(url, title);
		else if (window.sidebar)
			window.sidebar.addPanel(title, url, "")
	}
	
    function changeSize(inc) {
    	//var seletor = ".coluna-eventos,.invista,.conheca,.numeros-minas";
    	var seletor = "body";
    	var atual = parseInt(jQuery("body").css("font-size"));
    	var novo = atual+parseInt(inc);
    	jQuery(seletor).css("font-size",novo);
    	jQuery.cookie("siteFontSize",novo,{ expires: 30, path: '/'});
    }
    
	function enviarEmail(assunto, nomeDiv, email, nome){
		var emailPortal = "&emailPortal=S";
		var conteudo = getElementoPorId(nomeDiv).innerHTML;
		conteudo = conteudo.substring(0,conteudo.indexOf("<MENU_OPCOES>")) + conteudo.substring(conteudo.indexOf("</MENU_OPCOES>")+14, conteudo.length);
		var head = getCabecalho();
		conteudo = incluiEndAbsoluto(head+conteudo);
		
		if(email != ""){
			email = "&email="+email
			emailPortal = "&emailPortal=A";
			if(nome != "")
				nome = "&nome="+nome
		}	
		setVarGlobal("emailConteudo",conteudo)
		setVarGlobal("emailAssunto",assunto)
		if(ExpYes)
			janela(plcGeral.contextPath+"/ecp/webmailnovamsg.do?evento=novaMensagem&acao=N&acao=N"+emailPortal+email+nome,400,370);
		else
			janela(plcGeral.contextPath+"/ecp/webmailnovamsg.do?evento=novaMensagem&acao=N&acao=N"+emailPortal+email+nome,405,380);
	}

	function enviarEmailSimples(assunto, remetente, destinatario, nome, corpo){
		var emailPortal = "&emailPortal=S";
		if(destinatario != ""){
			destinatario = "&email="+destinatario
			emailPortal = "&emailPortal=A";
			if(nome != "")
				nome = "&nome="+nome
		}	
		setVarGlobal("emailConteudo",corpo)
		setVarGlobal("emailAssunto",assunto)

		if(ExpYes)
			janela(plcGeral.contextPath+"/ecp/webmailnovamsg.do?evento=novaMensagem&acao=N&acao=N"+emailPortal+destinatario+nome,400,370);
		else
			janela(plcGeral.contextPath+"/ecp/webmailnovamsg.do?evento=novaMensagem&acao=N&acao=N"+emailPortal+destinatario+nome,405,380);
	}

	function incluiEndAbsoluto(conteudo){
		var host = document.location.hostname;
		var port = document.location.port;
		port = typeof port == "undefined" || port == null ? "" : ":"+port;
		var urlBase = "http://"+host+port+plcGeral.contextPath+"/";

		do{
			conteudo = conteudo.replace("href=\""+plcGeral.contextPath+"/","href=\""+urlBase)
		}while(conteudo.indexOf("href=\""+plcGeral.contextPath) > -1)
		do{
			conteudo = conteudo.replace("src=\""+plcGeral.contextPath+"/","src=\""+urlBase)
		}while(conteudo.indexOf("src=\""+plcGeral.contextPath) > -1)
		do{
			conteudo = conteudo.replace("\/ecp\/images.do","images.do")
		}while(conteudo.indexOf("\/ecp\/images.do"+plcGeral.contextPath) > -1)
		do{
			conteudo = conteudo.replace("/ecp/files.do","files.do")
		}while(conteudo.indexOf("/ecp/files.do"+plcGeral.contextPath) > -1)
		
		conteudo = conteudo.replace(/images.do/g,urlBase+"images.do")
		conteudo = conteudo.replace(/files.do/g,urlBase+"/ecp/files.do")
		
		return conteudo;
	}

	function getCabecalho(){

		var head = "";
		if(ExpYes)
			head = document.all.tags('head')[0].innerHTML;
		else	
			head = document.getElementsByTagName('head')[0].innerHTML;
		return head;
	}


	/*
	 * File Authors:
	 * 		Paul Moers (mail@saulmade.nl)
	 * 		Thanks to Christian Fecteau (webmaster@christianfecteau.com)
	 */
	/***************************************************\
		REDIMENSIONA OBJETO PARA TELA CHEIA
	\***************************************************/
	function EcpResize(name,print){
		if(typeof name != "undefined"){
			this.Name = name;
			this.objetoResize = parent.document.getElementById(this.Name);
		}
		this.documentElementOverflow;
		this.bodyCssText;
		this.bodyClassName;
		this.originalCssText;
		this.originalWidth;
		this.originalHeight;
		this.autoFitToResize = true;
		this.objetoCentralizado = true;
	}
	var ecpResize = new EcpResize();
	EcpResize.prototype.hasBeenResized = null;
	EcpResize.prototype.Resize = function(evt, name, resize, print){
			if(typeof name != "undefined"){
					ecpResize.Name = name;
					ecpResize.objetoResize = parent.document.getElementById(ecpResize.Name);
			}	
			if(ExpYes){
				evt = event;
			}
			
			if(evt.type == 'resize'){
					ecpResize.Execute(false);
					ecpResize.Execute(true);
			}	else if(typeof resize == "undefined" || resize == "")
					ecpResize.Execute(!ecpResize.hasBeenResized);
			else 
					ecpResize.Execute(true);
			if(print && ecpResize.hasBeenResized)	
				window.print();
	}

	EcpResize.prototype.Execute = function(hasBeenResized)
	{
		var viewPaneWidth, viewPaneHeight;
		ecpResize.hasBeenResized = (hasBeenResized == null) ? false : hasBeenResized;
		if (ecpResize.originalCssText == null || ecpResize.hasBeenResized == true){
			if (hasBeenResized && ecpResize.autoFitToResize){
				if (ExpYes)
					window.attachEvent("onresize", ecpResize.Resize);
				else 
					window.addEventListener("resize", ecpResize.Resize, true);
			}
			// preparing the body for the editor in fullsize and hiding the scrollbars in Firefox
			with (top.document.getElementsByTagName("body")[0].style){
				ecpResize.bodyCssText= cssText; cssText= "";overflow= "hidden";
				margin= "0px";padding= "0px";height= "0px";width= "0px";
				position= "static";top= "0px";left= "0px";
			}
			// also storing a possible className
			ecpResize.bodyClassName = top.document.getElementsByTagName("body")[0].className;
			// hide IE scrollbars (in strict mode)
			if (ExpYes){
				ecpResize.documentElementOverflow = top.document.documentElement.style.overflow;
				top.document.documentElement.style.overflow = "hidden";
			}
			// now when the scrollbar is hidden, find the viewPane's dimensions
			viewPaneWidth = findViewPaneWidth();
			viewPaneHeight = findViewPaneHeight();
			// resize
			with (ecpResize.objetoResize.style){
				ecpResize.originalCssText					= cssText;
				ecpResize.originalWidth						= ecpResize.objetoResize.width;
				ecpResize.originalHeight						= ecpResize.objetoResize.height;
				position= "absolute";zIndex= "9999999";left= "0px";
				top= "0px";width= viewPaneWidth + "px";
				//height= viewPaneHeight + "px";
				height= viewPaneHeight;
				// giving the frame some (huge) borders on his right and bottom side to hide the background that would otherwise show when the editor is in fullsize mode and the window is increased in size
				// not for IE, because IE immediately adapts the editor on resize, without showing any of the background
				// oddly in firefox, the editor seems not to fill the whole frame, so just setting the background of it to white to cover the page laying behind it anyway
				if (NavYes){
					borderRight= "9999px solid white";borderBottom= "9999px solid white";
				}backgroundColor						= "white";
			}
			// scroll to top left
			top.window.scrollTo(0, 0);
		}// original style properties available? Resize to original size.
		else{
			// Removing the event handler of windowresizing
			if (ecpResize.autoFitToResize == true){
				if (top.detachEvent)
					top.detachEvent("onresize", ecpResize.Resize);
				//else if(top.removeEventListener)
					//top.removeEventListener("resize", ecpResize.Resize, true);
			}
			// restoring the body and restoring the scrollbars in Firefox
			with (top.document.getElementsByTagName("body")[0].style)
				cssText										= ecpResize.bodyCssText;
			// maybe it had a className...
			top.document.getElementsByTagName("body")[0].className = ecpResize.bodyClassName;
			// show IE scrollbars
			if (ExpYes)
				top.document.documentElement.style.overflow = ecpResize.documentElementOverflow;
			// restore original size
			with (ecpResize.objetoResize.style){
				try{
				cssText										= ecpResize.originalCssText;
				width											= ecpResize.originalWidth;
				height										= ecpResize.originalHeight;
				position									= "static";
				}catch(e){}
			}
			// scrolling so that the editor appears centered in the viewPane
			var adjustX, adjustY = 0;
			if (ecpResize.objetoCentralizado){
				viewPaneWidth = findViewPaneWidth();
				viewPaneHeight = findViewPaneHeight();
				adjustX = (viewPaneWidth - ecpResize.objetoResize.width) / 2;
				adjustY = (viewPaneHeight - ecpResize.objetoResize.height) / 2;
				if (adjustX < 1)
					adjustX = 0;
				if (adjustY < 1)
					adjustY = 0;
			}
			// Scroll to the editor
			top.window.scrollTo(findPosX(ecpResize.objetoResize) - adjustX, findPosY(ecpResize.objetoResize) - adjustY);
			// empty CSS buffer
			ecpResize.originalCssText = null;
		}
	}
	// finding the viewPane's width
	function findViewPaneWidth(){
		var viewPaneWidth = 0;
		if (top.window.clientWidth) // all except Explorer
			viewPaneWidth = top.window.clientWidth;
		else if (top.document.documentElement && top.document.documentElement.clientWidth) // Explorer 6 Strict Mode
			viewPaneWidth = top.document.documentElement.clientWidth;
		else if (top.document.body) // other Explorers
			viewPaneWidth = top.document.body.clientWidth;
		return viewPaneWidth;
	}
	// finding the viewPane's height
	function findViewPaneHeight(){
		var viewPaneHeight = "100%";
		//Comentado para que a altura seja retornada como 100%
	/*	if (top.window.clientHeight) // all except Explorer
			viewPaneHeight = top.window.clientHeight;
		else if (top.document.documentElement && top.document.documentElement.clientHeight) // Explorer 6 Strict Mode
			viewPaneHeight = top.document.documentElement.clientHeight;
		else if (top.document.body) // other Explorers
			viewPaneHeight = top.document.body.clientHeight;
	*/	
		return viewPaneHeight;
	}

	function findPosX(obj){
		var curleft = 0;
		if (obj.offsetParent)	{
			while (obj.offsetParent){
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}	else if (obj.x)
			curleft += obj.x;
		return curleft;
	}
	function findPosY(obj){
		var curtop = 0;
		var printstring = '';
		if (obj.offsetParent)	{
			while (obj.offsetParent){
				printstring += ' element ' + obj.tagName + ' has ' + obj.offsetTop;
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}	else if (obj.y)
			curtop += obj.y;
		return curtop;
	}

	/***************************************************\
	MENU FLUTUANTE BUSCA
	\***************************************************/

	/*
	Floating Menu script-  Roy Whittle (http://www.javascript-fx.com/)
	Script featured on/available at http://www.dynamicdrive.com/
	This notice must stay intact for use
	*/
	//Enter "frombottom" or "fromtop"
	var verticalpos="fromtop"
	if (!document.layers)
	document.write('</div>')

	function JSFX_FloatTopDiv()
	{
		var startX = 0,
		startY = 0;
		var ns = (navigator.appName.indexOf("Netscape") != -1);
		var d = document;
		function ml(id)
		{
			var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
			if(d.layers)el.style=el;
			el.sP=function(x,y){this.style.left=x;this.style.top=y;};
			el.x = startX;
			if (verticalpos=="fromtop")
			el.y = startY;
			else{
			el.y = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
			el.y -= startY;
			}
			return el;
		}
		window.stayTopLeft=function()
		{
			if (verticalpos=="fromtop"){
			var pY = ns ? pageYOffset : document.body.scrollTop;
			ftlObj.y += (pY + startY - ftlObj.y)/8;
			}
			else{
			var pY = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
			ftlObj.y += (pY - startY - ftlObj.y)/8;
			}
			ftlObj.sP(ftlObj.x, ftlObj.y);
			setTimeout("stayTopLeft()", 10);
		}
		
		ftlObj = ml("divStayTopLeft");
		stayTopLeft();
	}

	function novaMensagem(email, pele){
		WEBMAIL_ACAO = "MNV";
		email = typeof email != "undefined" ? email : "";
		if(email.indexOf("<") > -1){
			email = email.substring(email.indexOf("<")+1);
			email = email.substring(0,email.indexOf(">"));
		}
		if(email != "")
			email = "&email="+email.toLowerCase();
			
		janela(plcGeral.contextPath+"/ecp/webmailnovamsg.do?evento=novaMensagem&wmAcao="+WEBMAIL_ACAO+email+"&pelePlc"+pele,850,600);
	}

	function verificarEnquete(acao, url, w, h, props,campo, form, caminho){
		var winEnquete;	
		var resposta;
		if(acao == "v")	{
			resposta = get(campo,form);
			url += resposta
			if(resposta == ""){
				exibeMsg(msgErroEnquete)
				return false;
			}
		}
		if(""+url.indexOf("app") == -1)	{
			url += "&app="+getParametroUrl ('app');
		}
		if (caminho){
			jQuery("#enqueteResultado").hide();
			jQuery("#enqueteResultado").load(url+" "+caminho,"",function(){
				jQuery("#enquetePergunta").hide();
				jQuery("#enqueteResultado").show();
				try{alterarTituloEnquete(acao);}catch(e){};
			});
			return;
		}
		if(props == "" || typeof props == "undefined"){
			props = "resizable=no,scrollbars=yes,width="+w+",height="+h;
		}
		
		winEnquete = janela(url,"",props);

	}

	function montaMultiplasRespostasEnquete(check, campoResp, valResp, formResp){
		var respostas = get(campoResp, formResp);
		if(check.checked && respostas.indexOf(""+valResp) == -1){
			respostas += "+"+valResp;
		}else {
			respostas = respostas.replace("+"+valResp,"");
		}
		set(campoResp, respostas,'',formResp);		
	}

	function montaCaminhoNavegacao(prefixo, esconder){

			debug = false;

			if(typeof prefixo == "undefined" || prefixo == ""){
				prefixo = "";
			}else{
				prefixo = prefixo+"_";
			}
			
			var exibeLink 		= getVarGlobal("NAVEGACAO_EXIBE_HIPERLINKS");
			var link	 		= "<a href='"+getVarGlobal(prefixo + "NAVEGACAO_TAX_LINK")+"'>[LINK]</a>";
			if(debug) alert("link: "+link)
			var pagina			= getVarGlobal("NAVEGACAO_ID_PAGINA");
			if(debug) alert("pagina: "+pagina)
			var nivel1Nv		= getVarGlobal(prefixo + "NAVEGACAO_NIVEL_1_NV");
			if(debug) alert("nivel1Nv: "+nivel1Nv)

			var nomeComunidade 	= getVarGlobal("NAVEGACAO_NOME_COMUNIDADE");
			var nomePagina 		= getVarGlobal("NAVEGACAO_NOME_PAGINA");

			var nivel1	 		= getVarGlobal(prefixo + "NAVEGACAO_NIVEL_1") ? getVarGlobal(prefixo + "NAVEGACAO_NIVEL_1") : "";
			var nivel1H	 		= getVarGlobal(prefixo + "NAVEGACAO_NIVEL_1_H");
			var nivel1HArray	= nivel1H ? nivel1H.split("/") : new Array();
			if(debug) alert("nivel1: "+nivel1)
			if(debug) alert("nivel1H: "+nivel1H)
			if(debug) alert("nivel1HArray: "+nivel1HArray)
			
			var	posApp			= nivel1.indexOf("/");
			var nomeApp			= nivel1.substring(0,posApp);
			nivel1 = nivel1.substring(posApp+1);
			var nv1Array		= nivel1.split("/");

			/*
			if(prefixo == "TV_")	{
				posApp			= nivel1.indexOf("/");
				nomeApp			= nivel1.substring(0,posApp);
				nivel1 = nivel1.substring(posApp+1);
				nv1Array		= nivel1.split("/");
			}
			*/
			
			if(debug) alert("nv1Array: "+nv1Array);
			
			var nivelAtual	 		= getVarGlobal(prefixo + "NAVEGACAO_NIVEL_ATUAL");
			if(nivelAtual == null || nivelAtual == "")
				nv1Array.pop();
			if(debug) alert("nivelAtual: "+nivelAtual)

			var nomeConteudo 	= getVarGlobal("NAVEGACAO_NOME_CONTEUDO");

			var divNavegacao 	= getElementoPorId("DIV_CAMINHO_NAVEGACAO");
			if(!divNavegacao)
				return;

			var conteudo 	= divNavegacao.innerHTML;
				
			var tokens 		= new Array("COMUNIDADE","PAGINA","CONTEUDO");
			var tokensVal 	= new Array(nomeComunidade,nomePagina,nomeConteudo);

			for(var ind = 0; ind < nv1Array.length; ind++){
				tokens[tokens.length] = "NIVEL_" + Math.abs(ind + 1);
				tokensVal[tokensVal.length] = nv1Array[ind];
			}
			for(var ind2 = ind; ind2 < 10; ind2++){
				tokens[tokens.length] = "NIVEL_" + Math.abs(ind2 + 1);
				tokensVal[tokensVal.length] = "";
			}

			tokens[tokens.length] = "NIVEL_ATUAL";
			tokensVal[tokensVal.length] = nivelAtual;

			if(debug) alert("tokens: "+tokens)
			if(debug) alert("tokensVal: "+tokensVal)

			var token 		= "";
			var separador	= "";
			var linkAux		= "";
			var linkAnt		= "";
			var contTax		= 2;
			var indChPlc	= 2;
			var titulo		= "";

			if(prefixo == "TV_")	{
				contTax = 0;
			}
			
			for(var indTk = 0; indTk < 14; indTk++){
				
				if(indTk > 7)
					debug = false;

				if(tokens[indTk]){
					token = tokens[indTk];
				} else if (indTk == 10){
					token = "NIVEL_ATUAL";
				}else{
					token = "NIVEL_"+indTk;
				}

				if(token.indexOf("ATUAL") >= 0){
					contTax = contTax - 1;
					if(prefixo == ""){
						indChPlc = indChPlc - 1;					
					}
				}
				
				
				linkAux	= link;
				if(indTk < 4 || ((indTk+4) % 2 == 0) || token.indexOf("ATUAL") >= 0){

					if(debug) alert("NOVO LINK PARA TOKEN "+indTk+": "+token)

					if(	(prefixo + token).indexOf(prefixo + "NIVEL") >= 0 && 
						//token.indexOf("ATUAL") < 0 &&  
						nivel1HArray[contTax]){
						if(debug) alert("contTax: "+ contTax)
						if(indTk >= 4 && contTax < nivel1HArray.length && nivel1HArray[contTax]){
							linkAux = linkAux.replaceAll("[TAX]","&tax="+nivel1HArray[contTax]);
							//linkAux = linkAux.replaceAll("[TAXP]","&taxp="+nivel1HArray[contTax]);
							if(debug) alert("NOVO LINK NIVEL: "+linkAux)
							
							if(prefixo == "TV_")	{
								contTax++;
							}else{
								contTax+=2;
							}
						}
					}else if(token.indexOf("ATUAL") >= 0 && tokensVal[indTk]){
						linkAux = tokensVal[indTk];
					}
					
					if(linkAux != "")
						linkAnt = linkAux;

				}else{
					if(debug) alert("USANDO LINK ANTERIOR: "+linkAnt)
					linkAux = linkAnt;
				}

				if(token.indexOf("CONTEUDO") >= 0 && typeof tokensVal[indTk] != "undefined")
					linkAux = tokensVal[indTk];
				if (token.indexOf("COMUNIDADE") >= 0 || token.indexOf("PAGINA") >= 0)
					linkAux	= link;
				if (exibeLink == 'N' && tokensVal[indTk])
					linkAux	= tokensVal[indTk];
				
				
				//Limpando link
				if(token.indexOf("COMUNIDADE") >= 0)
					linkAux = linkAux.replaceAll("[PAGINA]","");
				if(pagina != null && pagina != "")
					linkAux = linkAux.replaceAll("[PAGINA]","&pg="+pagina);
				linkAux = linkAux.replaceAll("[TAX]","");
				linkAux = linkAux.replaceAll("[TAXP]","");

				if(debug) alert("Trocando token "+ indTk +": "+ prefixo + token+"\nPor: "+linkAux)

				separador	= prefixo + "SEPARADOR_"+ token;
				posToken 	= conteudo.indexOf("$"+ prefixo + token+"$");
				posIni 		= conteudo.indexOf("$"+separador+"$");
				posFim 		= posToken + (("$"+prefixo + token +"$").length - 1);

				if (token.indexOf("CONTEUDO") >= 0 || token.indexOf("COMUNIDADE") >= 0){
					if(typeof tokensVal[indTk] != "undefined" && tokensVal[indTk] != ""){
						titulo += titulo != "" ? " - " + tokensVal[indTk] : tokensVal[indTk];
					}
				}
				
				if(posToken >= 0 && tokensVal[indTk] != null && !tokensVal[indTk] == "" && 
				(!esconder || token.indexOf('COMUNIDADE') > -1 || token.indexOf('PAGINA') > -1 )){
					linkAux = linkAux.replaceAll("[LINK]",tokensVal[indTk]);
					if(typeof nivel1HArray[indChPlc] == "undefined" || nivel1HArray[indChPlc] == ""){
						linkAux = linkAux.replaceAll("[CHPLC]","&chPlc="+nivel1HArray[contTax-1]);
					}else{
						linkAux = linkAux.replaceAll("[CHPLC]","&chPlc="+nivel1HArray[indChPlc]);
					}
					indChPlc++;
					conteudo = conteudo.replaceAll("$"+ prefixo + token+"$",linkAux);
					conteudo = conteudo.replaceAll("$"+ separador +"$", "");
					
				}	
				else{
					var rplc = "";
					if(posIni > 0){
						rplc = conteudo.substring(posIni, posFim + 1);
					}
					else{
						rplc = "$"+ prefixo + token+"$";
					}
					
					// Codigo para compatibilizar com IE7
					for(i = 0; i <= 14; i++){
						conteudo = conteudo.replaceAll("<LI nodeIndex=\""+i+"\">"+rplc+"</LI>","");
						conteudo = conteudo.replaceAll("<li nodeIndex=\""+i+"\">"+rplc+"</li>","");
						conteudo = conteudo.replaceAll("<LI nodeIndex=\""+i+"\">"+rplc+" </LI>","");
						conteudo = conteudo.replaceAll("<li nodeIndex=\""+i+"\">"+rplc+" </li>","");
					}
					
					conteudo = conteudo.replaceAll("<li>"+rplc+"</li>", "");
					conteudo = conteudo.replaceAll("<LI>"+rplc+"</LI>", "");
					conteudo = conteudo.replaceAll(rplc+"</li>", "");
					conteudo = conteudo.replaceAll(rplc+"</LI>", "");
					conteudo = conteudo.replaceAll(rplc, "");
					conteudo = conteudo.replaceAll("<LI></LI>", "");
					conteudo = conteudo.replaceAll("<LI> </LI>", "");
					
				}

				divNavegacao.innerHTML = conteudo;
			}
			
			
			//if(typeof titulo != "undefined" && titulo != ""){
				//document.title = getVarGlobal("NAVEGACAO_NOME_COMUNIDADE") getVarGlobal("NAVEGACAO_NOME_CONTEUDO");
			//}
			//divNavegacao.style.display = 'block';
	}

	function alterarTituloPagina(){
		var titulo = getVarGlobal("NAVEGACAO_NOME_COMUNIDADE");
		var nomeConteudo = getVarGlobal("NAVEGACAO_NOME_CONTEUDO_TITULO");
		if(typeof  nomeConteudo != "undefined" && nomeConteudo != null && !nomeConteudo.isEmpty()){
			titulo += " - " + nomeConteudo;
		}
		if(typeof titulo != "undefined" && titulo != null && !titulo.isEmpty()){
			//var tituloCap = new String(titulo);
			//document.title = tituloCap.capitalize();
			document.title = titulo;
		}
	}
	
	setAtalho("CTRL#SHIFT#R", "executaRefresh()");
	function executaRefresh(){

		var url = location.href;
		removerParametroUrl(url,"refresh");
		removerParametroUrl(url,"refreshAll");
		incluirParametroUrl(url,"refresh","s")
		redirect(url);
	}

	function removerParametroUrl(url,param)
	{
		var paramUrl = getParametroUrl(param,url);
		url = url.replaceAll("&"+param+"="+paramUrl,"");
		url = url.replaceAll(param+"="+paramUrl,"");
		return url;
	}

	function incluirParametroUrl(url,paramNome,paramVal)
	{
		var posAncora = url.indexOf("#");
		var ancora = "";
		if(posAncora > 0){
			ancora = "#"+url.substring(posAncora+1, url.length);
			url = url.replace(ancora , "");
		}
		url = removerParametroUrl(url,paramNome);
		url += url.indexOf("?") >= 0 ?	"&" : "?";
		url += paramNome+"="+paramVal;
		return url +  ancora;
	}

	function getAlturaInternaJanela() {
	  var myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	  } else if( document.documentElement && document.documentElement.clientHeight) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	  } else if( document.body && document.body.clientHeight) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	  }

	  return myHeight;
	}

/*
	var initMediaBox = false;
	var GALERIA_1	= "GALERIA_1";
	var IMAGENS		= "IMAGENS";
	//setFuncaoOnLoad("setUpMediaShadowbox('GALERIA_1', 'shadowbox[GALERIA_1]')");
	//setFuncaoOnLoad("iniciarShadowbox()");
	function setUpMediaShadowbox (NOME, REL) {

		//Recupera LINKS
		var elementos = document.getElementsByName(NOME);
		if(elementos && elementos.length > 0 && typeof jQuery != "undefined") {
			var elementoAnterior = elementos;
			if(!elementos.length){
				elementos = new Array();
				elementos[elementos.length] = elementoAnterior
			}
			initMediaBox = true;
			for (e = 0; e < elementos.length; e++) {
				var umElemento = elementos[e];
				if(umElemento && umElemento.tagName == 'A'){
					umElemento.rel	= REL;
				}
				else if (umElemento && umElemento.tagName == 'IMG'){
					var a = document.createElement('A');
					a.href = umElemento.src;
					a.className = "ESCONDIDO";
					a.rel	= REL;
					document.body.appendChild(a);
				}

			}

			//Recupera IMAGENS
			var elementos = document.getElementsByTagName("IMG");
			if(elementos && elementos.length > 0 && typeof jQuery != "undefined") {
				initMediaBox = true;
				var elementoAnterior = elementos;
				if(!elementos.length){
					elementos = new Array();
					elementos[elementos.length] = elementoAnterior
				}
				for (i = 0; i < elementos.length; i++) {
					var umElemento = elementos[i];
					if(umElemento.id == NOME){
						var a = document.createElement('A');
						a.href = umElemento.src;
						a.className = "ESCONDIDO";
						a.rel	= REL;
						document.body.appendChild(a);
					}
				}
			}
		}
	}

	function gerarArrayElementos(origElem){
		var elementoAnterior = origElem;
		origElem = new Array();
		origElem[origElem.length] = elementoAnterior
		return origElem;
	}

*/

/**********************************************************************************
							JQUERY NIVO SLIDER
**********************************************************************************/

function JQNivoSlider(){};

var jqNivoSlider = new JQNivoSlider();

JQNivoSlider.prototype.criarSlideshow = function (seletor, efeito, optsSlideshow){

	var tFx = traduzEfeitoSlideshow(efeito);

	var opts = {
        effect: tFx // Specify sets like: 'fold,fade,sliceDown'
		,animSpeed: 1000
		,pause: 10000
		,directionNav:false
		,controlNav:false
	};

	opts = $.extend(opts, optsSlideshow);

	$(seletor).nivoSlider(opts);

}

function traduzEfeitoSlideshow(fx){

	if("Rolar Hor." == fx)
		return 'slideInLeft';
	else if("Rolar Vert." == fx)
		return 'sliceDown';
	else if("Trocar" == fx)
		return 'fade';
	else if("Cortina" == fx)
		return 'fold';
	else if("Aleat�rio" == fx)
		return 'random';
	else return "fold"
}

/**********************************************************************************
								JQUERY CYCLE
**********************************************************************************/

function JQCycle(){};

var jqCycle = new JQCycle();

JQCycle.prototype.criarComNavegador = function (seletor, optsCycle){

	var opts = { 
		fx:     "fade", 
		speed:  300, 
		timeout: 10000,
		continuous: true,
		pause: true,
		prev:   '#prev', 
		next:   '#next',
		pager:  '#pager'
		//,pagerAnchorBuilder: function(idx, slide) {
		//	return '#pager li:eq(' + idx + ') a';
		//}	
	};

	opts = $.extend(opts, optsCycle);

	$(seletor).cycle(opts);

}

function criarBanner(idBanner, velocidade, efeito, possuiLinks, permitirTransicao, usarNavegador){

	var tFx = traduzEfeito(efeito);

	var proximo = "";

	if(permitirTransicao == 'S'){
		proximo = '#'+idBanner+" > .prt-banner-img" ;
	}

	var opcoes = { 
		fx:     tFx, 
		pause: true,
		speed:  300, 
		next:   proximo,
		timeout: velocidade
	};

	if(usarNavegador == 'S'){
		var opcoesNav = { 
			prev:   '#prev', 
			next:   proximo != "" ? proximo + ", #prox"  : "#prox",
			pager:  '#pager'
		};
		$.extend(opcoes, opcoesNav);
	}

	criarBannerComOpcoes(idBanner, opcoes, possuiLinks);

}

function criarBannerComOpcoes(idBanner, opcoes, possuiLinks){

	var proximo = '#'+idBanner+" > .prt-banner-img" ;
	var config = { 
			fx:     "slideX", 
			pause: true,
			speed:  300, 
			next:   proximo,
			timeout: 10000 
	}

	$.extend(config, opcoes);

	if(typeof idBanner != "undefined" && idBanner != "" && idBanner != null){
		$('#'+idBanner).cycle(config);
	}

}

function traduzEfeito(fx){

	if("Rolar Hor." == fx)
		return 'scrollHorz';
	else if("Rolar Vert." == fx)
		return 'scrollVert';
	else if("Trocar" == fx)
		return 'fade';
	else if("Aleat�rio" == fx)
		return 'shuffle';
	else return "fade"
}

/***********************************************************************************
								PORTLET GALERIA
************************************************************************************/

var opcoesPadrao = {
		loadingImage: "/plc/javascript/jquery/shadowbox/images/loading.gif", //The URL of an image to use as a loading indicator while loading content. Defaults to "images/loading.gif".
		resizeLgImages:     false,
		handleLgImages:		"drag", //The mode to use for handling images that are too large for the viewport. May be one of "none", "resize", or "drag". Defaults to "resize".
		displayNav:         true, //Set this false to hide the gallery navigation controls. Defaults to true.
		continuous: true, //Set this true to enable "continuous" galleries. 
		counterType: 'default', //The mode to use for the gallery counter. May be either 'default' or 'skip'. Defaults to "default".
		initialHeight: 160, //The height of Shadowbox (in pixels) when it first appears on the screen. Defaults to 160. 
		initialWidth: 320, //The width of Shadowbox (in pixels) when it first appears on the screen. Defaults to 320. 
		animate: true, //Set this false to disable all fancy dimension and opacity animations. This can improve the overall effect on computers with poor performance. Defaults to true.
		overlayColor: "#000", //The color to use for the overlay. Defaults to "#000".
		overlayOpacity: 0.85, //The transparency of the overlay. Defaults to 0.85.
		resizeDuration: 0.35,//The duration (in seconds) of the resizing animations. Defaults to 0.35.
		fadeDuration: 0.35, //The duration (in seconds) of the resizing animations. Defaults to 0.35.
		displayCounter: true, //Set this false to hide the gallery counter. Defaults to true.
		viewportPadding: 20, //The amount of padding (in pixels) to maintain around the edge of the browser window. Defaults to 20.
		enableKeys: true, //Set this false to disable keyboard navigation of galleries. Defaults to true.
		keysClose:     ['c', 27], // c or esc
		text:           {
			loading: 'Carregando...',   
			cancel: 'Cancelar',
			close: 'Fechar',
			next: '<b>></b>' ,
			prev: '<b><</b>'
		},
		skin: 	{		
			main:	'<div id="shadowbox_overlay"></div>' + 
					'<div id="shadowbox_container">' + 
						'<div id="shadowbox">' + 
							'<div id="shadowbox_title">' + 
								'<div id="shadowbox_title_inner"></div>' + 
							'</div>' + 
							'<div id="shadowbox_body">' + 
								'<div id="shadowbox_body_inner"></div>' + 
								'<div id="shadowbox_loading"></div>' + 
							'</div>' + 
							'<div id="shadowbox_toolbar">' + 
									'<div id="shadowbox_toolbar_inner"></div>' + 
							'</div>' + 
						'</div>' + 
					'</div>', 
			loading:    '<img src="{0}" alt="{1}" />' +
						'<span><a href="javascript:Shadowbox.close();">{2}</a></span>',
			counter: '<div id="shadowbox_counter">{0}</div>', 
			close: '<div id="shadowbox_nav_close">' + '<a href="javascript:Shadowbox.close();">{0}</a>' + '</div>', 
			next: '<div id="shadowbox_nav_next">' + '<a href="javascript:Shadowbox.next();">{0}</a>' + '</div>', 
			prev: '<div id="shadowbox_nav_previous">' + '<a href="javascript:Shadowbox.previous();">{0}</a>' + '</div>' 
	}

};

function criarGaleria(nomeGaleria, opcoes){

	$(document).ready(function(){
		iniciarShadowbox(nomeGaleria, opcoes)
	});
}

function iniciarShadowbox(nomeGaleria, opcoes){

	if(typeof opcoes == "undefined")
		opcoes = {};
	var options = {
		//gallery: nomeGaleria,
		loadingImage:		typeof opcoes.loadingImage != "undefined" ? opcoes.loadingImage : plcGeral.contextPath+opcoesPadrao.loadingImage,
		resizeLgImages:     typeof opcoes.resizeLgImages != "undefined" ? opcoes.resizeLgImages : opcoesPadrao.resizeLgImages,
		handleLgImages:		typeof opcoes.handleLgImages != "undefined" ? opcoes.handleLgImages : opcoesPadrao.handleLgImages,
		displayNav:         typeof opcoes.displayNav != "undefined" ? opcoes.displayNav : opcoesPadrao.displayNav,
		continuous:			typeof opcoes.continuous != "undefined" ? opcoes.continuous : opcoesPadrao.continuous,
		counterType:		typeof opcoes.counterType != "undefined" ? opcoes.counterType : opcoesPadrao.counterType,
		initialHeight:		typeof opcoes.initialHeight != "undefined" ? opcoes.initialHeight : opcoesPadrao.initialHeight,
		initialWidth:		typeof opcoes.initialWidth != "undefined" ? opcoes.initialWidth : opcoesPadrao.initialWidth,
		keysClose:			typeof opcoes.keysClose != "undefined" ? opcoes.keysClose : opcoesPadrao.keysClose,
		animate:			typeof opcoes.animate != "undefined" ? opcoes.animate : opcoesPadrao.animate,
		overlayColor:		typeof opcoes.overlayColor != "undefined" ? opcoes.overlayColor : opcoesPadrao.overlayColor,
		overlayOpacity:		typeof opcoes.overlayOpacity != "undefined" ? opcoes.overlayOpacity : opcoesPadrao.overlayOpacity,
		resizeDuration:		typeof opcoes.resizeDuration != "undefined" ? opcoes.resizeDuration : opcoesPadrao.resizeDuration,
		fadeDuration:		typeof opcoes.fadeDuration != "undefined" ? opcoes.fadeDuration : opcoesPadrao.fadeDuration,
		displayCounter:		typeof opcoes.displayCounter != "undefined" ? opcoes.displayCounter : opcoesPadrao.displayCounter,
		counterType:		typeof opcoes.counterType != "undefined" ? opcoes.counterType : opcoesPadrao.counterType,
		viewportPadding:	typeof opcoes.viewportPadding != "undefined" ? opcoes.viewportPadding : opcoesPadrao.viewportPadding,
		enableKeys:			typeof opcoes.enableKeys != "undefined" ? opcoes.enableKeys : opcoesPadrao.enableKeys,
		skin:				typeof opcoes.skin != "undefined" ? opcoes.skin : opcoesPadrao.skin,
		text:           {
			cancel:     typeof opcoes.cancel != "undefined" ? opcoes.cancel : opcoesPadrao.text.cancel,
			loading:    'Carregando...',   
			close:      typeof opcoes.close != "undefined" ? opcoes.close : opcoesPadrao.text.close,
			next:       typeof opcoes.next != "undefined" ? opcoes.next : opcoesPadrao.text.next,
			prev:       typeof opcoes.prev != "undefined" ? opcoes.prev : opcoesPadrao.text.prev,
			errors:     {
				single: 'Para ver este conte�do � necess�rio instala��o deste plugin: <a href="{0}">{1}</a>.',
				shared: 'Para ver este conte�do � necess�rio instala��o destes plugins: <a href="{0}">{1}</a> e <a href="{2}">{3}</a>.',
				either: 'Para ver este conte�do � necess�rio instala��o de algum destes plugins: <a href="{0}">{1}</a> ou <a href="{2}">{3}</a>.'
			}
		},
		ext:     {
			img:        ['png', 'jpg', 'jpeg', 'gif', 'bmp'],
			qt:         ['dv', 'mov', 'moov', 'movie', 'mp4'],
			wmp:        ['asf', 'wm', 'wmv'],
			qtwmp:      ['avi', 'mpg', 'mpeg'],
			iframe:     ['asp', 'aspx', 'cgi', 'cfm', 'htm', 'html', 'pl', 'php',
						'php3', 'php4', 'php5', 'phtml', 'rb', 'rhtml', 'shtml',
						'txt', 'vbs', 'do']
		}
		//onClose: "desativarPreview"
		
	};

	Shadowbox.init(options);
}

/*****************************************************************************\
					MENU DESTAQUE (JQUERY JQMODAL E JQDNR)
\*****************************************************************************/

var termosBusca = "";
function criarMenuDestaque(){
	var listaTermos = getParametroUrl("termos");
	if(termosBusca != ""){
		listaTermos = termosBusca;
	}
	listaTermos = unescape(listaTermos)
	if(listaTermos){
		listaTermos = listaTermos.replaceAll("%20"," ");
		listaTermos = listaTermos.replaceAll("+"," ");
		var termos = listaTermos.split(' ');
		var linkTermos = "";
		var c = 0;
		for(var i=0; i<termos.length; i++){
			linkTermos += "<a href='#' onclick=\"destacarTermo('"+termos[i]+"', 'destaque"+getContadorDestaque()+"');   return false;\" title='Clique para destacar este termo.'><span class='bt'>"+termos[i].toLowerCase()+"</span></a>&nbsp;";
			//c = c++ > 4 ? 0 : c;
		}
		var campoBusca = "<form class=\"form\" name=\"destaqueForm\" style=\"margin-top:10px;\">Outro Termo: <input class=\"campo\" type=\"text\" name=\"novoTermo\" value=\"\"  style=\"height:20px;\"><input type=\"button\" value=\"Destacar\" onclick=\"destacarTermo(get('novoTermo','destaqueForm'), 'destaque'+getContadorDestaque()); set('novoTermo','','','destaqueForm'); return false;\" style=\"height:20px;\"></form>"
		$("#MENU_DESTAQUE").prepend("<b>Termos para destaque:</b>&nbsp;<span>"+linkTermos+"</span> [<a href='#' onclick='removerDestaqueTermo(); return false;' title='Clique pare remover todos os destaques.'>Limpar</a>]");
		$(".jqmdMSG").html("<span>"+linkTermos+"</span> [<a href='#' onclick='removerDestaqueTermo(); return false;' title='Clique pare remover todos os destaques.'>Limpar</a>]"+campoBusca);
		$("#ex3aTrigger").click(function(){
			esconderMenuDestaque();
		});
		$("#MENU_DESTAQUE_FECHAR").click(function(){
			mostraMenuDestaque();
		});
		mostraMenuDestaque()
	}
}

var contadorDestaque = 0;
function getContadorDestaque(){
	return contadorDestaque++ > 4 ? 0 : contadorDestaque;
}

function buscaDestaque(){
	if(listaTermos){
		var listaTermos = getParametroUrl("busca", document.location.search);
		var ultPosicao = listaTermos.length;
		listaTermos = listaTermos.replaceAll("%20"," ");
		listaTermos = listaTermos.replaceAll("+"," ");
		var termos = listaTermos.split(' ');
		for(var i=0; i<termos.length; i++){
			if(termos[i].length > 1)
				$('#RESULTADO_BUSCA').each(function() { $.highlight(this,termos[i].toUpperCase(), "destaqueResBusca"); }); 
		}
	}
	if(getParametroUrl("grp") == "I")
		$('#RESULTADO_BUSCA').each(function() { $.highlight(this,"Imagens", "destaqueResBusca"); }); 
}


function destacarTermo(termo, classe){
	if(typeof termo != "undefined" && termo != ""){
		$('#CONTEUDO_DESTAQUE').each(function() { $.highlight(this,termo.toUpperCase(), classe); }); 
	}else{
		alert("Informe termo para destaque.");
	}
}
function removerDestaqueTermo(){
	$('#CONTEUDO_DESTAQUE').removeHighlight();
}

function esconderMenuDestaque(){
	$("#MENU_DESTAQUE").css("display","none");
}

function mostraMenuDestaque(){
	$("#MENU_DESTAQUE").css("display","block");
}

/*****************************************************************************\
							PORTLET BUSCA
\*****************************************************************************/
function executaBuscaPadrao(escopoBusca, idTemplateBusca, urlBusca, usaUrlAmigavel){
	guardaValorEscopoBusca(escopoBusca);
	var url = urlBusca;
	if(typeof idTemplateBusca != "undefined" && idTemplateBusca != ""){
		var urlAplicacao = getParametroUrl("app");
		if(typeof usaUrlAmigavel != "undefined" && usaUrlAmigavel == "S"){
			url += "/"+idTemplateBusca;
		}else{
		url += "?app="+urlAplicacao+"&pg="+idTemplateBusca;
		}
	}
	url = montaParamBuscaPadrao(url);
	redirect(url);
}
function montaParamBuscaPadrao(url, form){
	return montaParamBusca(url, "portalForm")
}

function montaParamBusca(url, form){
	if(ExpYes && form != "buscaAvancadaForm"){
		form = "";
	}

	var busca = get("busca",form);
	//busca = busca.replace("\"","'");
	busca	= busca.trim();
	//busca	= busca.replaceAll("'","\"");
	if(typeof busca == "undefined" || busca == ""){
		busca = getValorCampoBusca();
	}
	busca = jQuery.trim(busca);
	//jQuery("input[name=busca]").val("");
	url = url.replaceAll("&busca="+busca,"");
	url = url.replaceAll("busca="+busca,"");
	url = url.replaceAll("busca="+escape(busca),"");
	url = incluirParametroUrl(url,"busca", escape(busca));
	url = url.replaceAll("?&busca","?busca");


	var escopoBusca = getValorEscopoBusca();
	url = url.replaceAll("&escBusca="+escopoBusca,"");
	url = url.replaceAll("escBusca="+escopoBusca,"");
	url = url.replaceAll("escBusca="+escape(escopoBusca),"");
	//if("aplicacaoCorrente" == escopoBusca){
		//url = incluirParametroUrl(url,"escBusca", escape(getParametroUrl("app")));
		url = incluirParametroUrl(url,"escBusca", escopoBusca);
	//}

	return url;
}

function getValorCampoBusca(){
	//$(btBusca).parent().parent().find("input[name=busca]").val();
	var termoBusca = getVarGlobal("termoBusca");
	setVarGlobal("termoBusca", "");
	return termoBusca;
}

function getValorEscopoBusca(){
	var escopoBusca = getVarGlobal("escopoBusca");
	if(typeof escopoBusca == "undefined"){
		escopoBusca = "";
	}
	setVarGlobal("escopoBusca", "");
	return escopoBusca;
}

function guardaValorCampoBusca(campoBusca){
	setVarGlobal("termoBusca", $(campoBusca).val());
	//setVarGlobal("escopoBusca", $(campoBusca).siblings("input[name=escBusca]").val());
}

function guardaValorEscopoBusca(escopoBusca){
	setVarGlobal("escopoBusca", escopoBusca);
}

var disparouBusca = false;
function buscarSlide(botao, tipo)
{
  var numForms 	= document.forms.length;
  var numCampos	= ""; 

	if(tipo != "" && ""+tipo != "undefined")
	{
		var url = document.location.pathname+document.location.search;
		
		var _argumento = get('busca','buscaAvancadaForm');
		var _metadado = get('metadadoSlide','buscaAvancadaForm');
		
		if(_argumento.length < 2){
			alert("Informe termo para busca com pelo menos 2 caracteres.");
			return;
		}
		//url = incluirParametroUrl(url,"busca",escape(_argumento));
		url = montaParamBuscaAvancada(url);
		url = incluirParametroUrl(url,"dirSlide",tipo);
		url = incluirParametroUrl(url,"mtSlide",_metadado);
		url += "#slide_"+tipo;

		url = montaUrlBuscaAvancadaSlide(url)

		//alert(url)

		redirect(url);
	}

  if(disparouBusca){
		disparouBusca = false;
  		return true;
  }
  
  for (var i = 0; i < numForms; i++){
    numCampos = document.forms[i].elements.length;
    for (var j = 0; j < numCampos; j++){
      if (document.forms[i].elements[j].value == botao && 
		  (document.forms[i].elements[j].id == "SUBMIT_BUSCA" || document.forms[i].elements[j].id == "SUBMIT_BUSCA_SLIDE")){
		if(!disparouBusca){
			disparaBotao(document.forms[i].elements[j]);
			return false;
		}
      }
    }
  }
  
  if(!disparouBusca){
  		return false;
  }else{
  		return true;
  }
}

function montaUrlBuscaAvancadaSlide(url){

	limparUrlBuscaAvancada(url);
	
	var fmt = get("fmt","buscaAvancadaForm");
	if(typeof fmt != "undefined"){
		url = incluirParametroUrl(url, "fmt", fmt);
	}

	var aprox = get("aprox","buscaAvancadaForm");
	if(typeof aprox == "undefined"){
		aprox = 10;
	}
	if(typeof aprox != "undefined"){
		url = incluirParametroUrl(url, "aprox", aprox);
	}

	return url;
}


var argumento = "";
function guardaArgumento(arg){
	argumento = arg;
}

var metadado = "";
function guardaMetadado(meta){
	metadado = meta;
}

function abrirAjuda(){
	var win = janela(plcGeral.contextPath+"/ecp/ajudabusca.do?evento=x",400);
}

function janelaDownload(url){
	url = url.substring(0,url.indexOf("?f="))+"?td=conf&f="+url.substring(url.indexOf("?f=")+3);
	url = url.substring(url.indexOf("dSldAt=")+7)
	win = janela(url,200,200);
}

/*****************************************************************************\
					GRID TABELA (JQUERY TABLESORTER)
\*****************************************************************************/
function criarGridTabela(seletor, opcoes, temNav, opcoesPager){

	var ops = {widthFixed: true, widgets: ['zebra']};
	var opsPager = {
				container: $(seletor+"pager"),
				positionFixed: false,
				size: 5,
				seperator: " de "
		};

	$.extend(true, ops, opcoes);
	$.extend(true, opsPager, opcoesPager);

	if(temNav || temNav == "S"){
		$(seletor)
		.tablesorter(ops)
		.tablesorterPager(opsPager);
	}else{
		$(seletor)
		.tablesorter(ops);
		$(seletor+"pager").css("display","none");
	}
}


/*****************************************************************************\
					TREE VIEW (JQUERY TREEVIEW)
\*****************************************************************************/

function JQTreeView(){};

var jqTreeView = new JQTreeView();

JQTreeView.prototype.gerar = function (seletor, opcoes){
	criarTreeView(seletor, opcoes);
}

function criarTreeView(seletor, opcoes){

	var ops = {
		control: "#treecontrol",
		//animated: "normal",
//		collapsed: true,
//		unique: true,
		persist: "location"
//		cookieId: "treeview-"+seletor
//		prerendered: true,
	};

	$.extend(true, ops, opcoes);

	$(seletor).treeview(ops);
}


function recuperaNivelPaiTreeView(nivel){
	//alert("troca nivel pai")
	var url = document.location.href;
	url = removerParametroUrl(url,"mpNvF")
	url = incluirParametroUrl(url,"mpNv",nivel)
	//plcAjax.ajaxGet(url, true, false, "");
	redirect(url)
}

function recuperaNivelFilhoTreeView(nivel){
	//alert("troca nivel filho")
	var url = document.location.href;
	url = removerParametroUrl(url,"mpNv")
	url = incluirParametroUrl(url,"mpNvF",nivel)
	//plcAjax.ajaxGet(url, true, false, "");
	redirect(url);
}
/*****************************************************************************\
							PORTLET SLIDE
\*****************************************************************************/

function navDiretoriAnteriorSlide(dirRetorno){

	var url = document.location.href;
	url = incluirParametroUrl(url,"pAcDir",dirRetorno);
	url = removerParametroUrl(url,"busca");
	redirect(url);
}

/*****************************************************************************\
							PROCURA TERMO
\*****************************************************************************/

/*
function procurarTermo(termo){
	if(ExpYes)
		procurarTermoIE(termo);
	else
		procurarTermoFF(termo);
}

function procurarTermoIE(termo) {
   // get the selection range and text range
   //var findRange = document.selection.createRange();
   //var textRange = document.body.createTextRange();

   var findRange = ($("#CONTEUDO_DESTAQUE").get()[0]).createTextRange();
   var textRange = ($("#CONTEUDO_DESTAQUE").get()[0]).createTextRange();
   // make sure selection is in editor 
   if (!textRange.inRange(findRange)) {
	  // if selection not in editor place it in editor en re-execute button
	  textRange.collapse(true);
	  textRange.select();          
	  findRange = textRange;
	  //procurarTermoIE(termo);
   } //else {
	  var text_length = textRange.htmlText.length;
	  var updown = 1;
	  // set the searchflags
	  var iFlags = 2;
	  // set the searchscope
	  var iSearchScope  = text_length  * updown;
	  // search the string and position  
	  if ( updown == 1 ) {
		 if (findRange.htmlText != '') {
			// nondegenerate range : deplace start position
			findRange.moveStart("word");
		 }
		 //findRange.moveEnd("textedit");
	  } else {
		 iFlags = iFlags + 1;
		 findRange.moveStart("character",1);
		 findRange.moveEnd("character",-1);
	  }
	  if (findRange.findText(termo,iSearchScope,iFlags)){
		 // found: select the text
		 findRange.select();
		 findRange.scrollIntoView();
	  } else {
		 // not found : give a warning
		 alert('Fim da busca.');
	  }
   //}
}
function procurarTermoFF(termo){
	// window.find( searchString, caseSensitive, backwards, wrapAround, wholeWord, searchInFrames, showDialog ) ;
	//window.find( termo, false, false, false, true, false, false );

}
*/

/*****************************************************************************\
							JQUERY AUTOCOMPLETE
\*****************************************************************************/
function JQAutocompletar(){};

var jqAutocompletar = new JQAutocompletar();

var jqAutocompletar_Args = null;	
JQAutocompletar.prototype.adicionarArgumentoExtra = function (nomeProp, valorProp, nomeCampo){

	if(typeof nomeCampo == "undefined"){
		nomeCampo = "generico";
	}
	jqAutocompletar_Args = getVarGlobal(nomeCampo+"_argumento_extra");
	if(jqAutocompletar_Args == null || typeof jqAutocompletar_Args == "undefined"){
		jqAutocompletar_Args = new Array();
	}
	jqAutocompletar_Args[jqAutocompletar_Args.length] = new jqAutocompletar.argumento(nomeProp, valorProp); 

	setVarGlobal(nomeCampo+"_argumento_extra",jqAutocompletar_Args);
}

var jqAutocompletar_Retornos = null;
JQAutocompletar.prototype.adicionarRetornoExtra = function (nomeProp, nomeCampo){

	if(typeof nomeCampo == "undefined"){
		nomeCampo = "generico";
	}
	jqAutocompletar_Retornos = getVarGlobal(nomeCampo+"_retorno_extra");
	if(jqAutocompletar_Retornos == null || typeof jqAutocompletar_Retornos == "undefined"){
		jqAutocompletar_Retornos = new Array();
	}
	jqAutocompletar_Retornos[jqAutocompletar_Retornos.length] = new jqAutocompletar.argumento(nomeProp); 
	setVarGlobal(nomeCampo+"_retorno_extra",jqAutocompletar_Retornos);
}

JQAutocompletar.prototype.argumento = function(nomeProp, valorProp){
	this.nome 	= nomeProp;
	this.valor	= valorProp;
}

JQAutocompletar.prototype.criarArgumentosExtras = function(nomeCampo){

	var strArgs = "";
	if(getVarGlobal(nomeCampo+"_argumento_extra") != null){
		jqAutocompletar_Args = getVarGlobal(nomeCampo+"_argumento_extra");
	}
	if(getVarGlobal("generico_argumento_extra") != null){
		jqAutocompletar_Args = getVarGlobal("generico_argumento_extra");
	}
	if(jqAutocompletar_Args && jqAutocompletar_Args.length > 0){
		for(j = 0; j < jqAutocompletar_Args.length; j++){
			var umArg = jqAutocompletar_Args[j];
			strArgs += strArgs != "" ? "&" : ""; 
			strArgs += umArg.nome+"="+umArg.valor;
		}
		setVarGlobal("generico_argumento_extra",null);
	}
	setVarGlobal(nomeCampo+"_argumento_extra",jqAutocompletar_Args);
	jqAutocompletar_Args = null;
	return strArgs;
}
			
JQAutocompletar.prototype.criarRetornosExtras = function(nomeCampo){

	var strArgsRetornos = "";
	
	if(getVarGlobal(nomeCampo+"_retorno_extra") != null){
		jqAutocompletar_Retornos = getVarGlobal(nomeCampo+"_retorno_extra");
	}
	if(getVarGlobal("generico_retorno_extra") != null){
		jqAutocompletar_Retornos = getVarGlobal("generico_retorno_extra");
	}
	if(jqAutocompletar_Retornos && jqAutocompletar_Retornos.length > 0){
		for(j = 0; j < jqAutocompletar_Retornos.length; j++){
			var umArg = jqAutocompletar_Retornos[j];
			strArgsRetornos += strArgsRetornos != "" ? "#" : ""; 
			strArgsRetornos += umArg.nome;
		}
		setVarGlobal("generico_retorno_extra",null);
	}
	setVarGlobal(nomeCampo+"_retorno_extra",jqAutocompletar_Retornos);
	jqAutocompletar_Retornos = null;
	return strArgsRetornos;
}

JQAutocompletar.prototype.adicionarAoCampoComMultiplosValores = function (nomeCampo, nomeAction, propPadrao, listaCamposAutocompletar, optsExtras, seletor){

	if(!jqAutocompletar.antesAdicionarAoCampo(nomeCampo)){
		return;
	}

	var lookup = getCampo(nomeCampo);
	if(typeof lookup == "undefined"){
		lookup = jqAutocompletar.getCampoPorSeletor(seletor);
	}
	var optsMultiple = {
		matchContains: true,
		autoFill: false,
		multiple: true,
		multipleSeparator: ",",
		fieldBind: $(lookup),
		formatItem: function(row) {
			var campoVal = this.fieldBind[0].value;
			if(campoVal != "" && campoVal.indexOf(row[0]+optsMultiple["multipleSeparator"]) == -1){
				return row[0];
			}
			return false;
		}
	};
	optsExtras = $.extend(optsMultiple,optsExtras);

	var optsMultiple2 = {
		formatItem: function(row) {
			var campoVal = this.fieldBind[0].value;
			if(campoVal != "" && campoVal.indexOf(row[0]+optsExtras["multipleSeparator"]) == -1){
				return row[0];
			}
			return false;
		}
	};
	optsExtras = $.extend(optsMultiple2,optsExtras);

	$(lookup).blur(function() {
		var campoVal = $(this).val();
		campoVal = campoVal.replace(",,",",");
		campoVal = campoVal.replace(",,,",",");
		if(campoVal.lastIndexOf(optsExtras["multipleSeparator"]) == campoVal.length - 1){
			$(this).val(campoVal.substring(0,campoVal.length - 1));
		}
	});

	$(lookup).focus(function() {
		var campoVal = $(this).val();
		if(campoVal != "" && (campoVal.lastIndexOf(optsExtras["multipleSeparator"]) != campoVal.length - 1)){
			$(this).val(campoVal + optsExtras["multipleSeparator"]);
		}
	});

	jqAutocompletar.adicionarAoCampo(nomeCampo, nomeAction, propPadrao, listaCamposAutocompletar, optsExtras, seletor);
}

JQAutocompletar.prototype.antesAutocompletar = function (nomeCampo, data){};

JQAutocompletar.prototype.aposAutocompletar = function (nomeCampo, data){};

JQAutocompletar.prototype.antesAutocompletarFormatarItem = function (nomeCampo, data){};

JQAutocompletar.prototype.aoAutocompletarClicarItem = function (item){};

JQAutocompletar.prototype.aoAutocompletarSairCampo = function (eventoBlur){};

JQAutocompletar.prototype.getUrlRestAutocompletar = function (nomeAction,propPadrao){
	return plcGeral.contextPath+"/soa/struts/plc/listaac/"+nomeAction+"/"+propPadrao;
};

JQAutocompletar.prototype.adicionarAoCampo = function (nomeCampo, nomeAction, propPadrao, listaCamposAutocompletar, optsExtras, seletor){

	if(!jqAutocompletar.antesAdicionarAoCampo(nomeCampo)){
		return;
	}

	jqAutocompletar.retirarDoCampo(nomeCampo, seletor);

	var lookup = getCampo(nomeCampo);
	if(typeof lookup == "undefined"){
		lookup = jqAutocompletar.getCampoPorSeletor(seletor);
	}

	if(typeof lookup != "undefined"){
		var opts = {
			scrollHeight: 200,
			cacheLength: 0,
			width: 260, 
			delay: 200, 
			minChars: 3,
			fieldBind: $(lookup),
			extraParams: {querySel: jqAutocompletar.criarArgumentosExtras(nomeCampo),
						  argSel: jqAutocompletar.criarRetornosExtras(nomeCampo)},
						  
				formatItem: function(row) {
					var campoVal = this.fieldBind[0].value;
					var retorno = jqAutocompletar.antesAutocompletarFormatarItem(this.fieldBind[0].name, row, listaCamposAutocompletar);					
					if(retorno === false){
						return false;
					}
					return row[0];
				}
			};

		opts = $.extend(opts, optsExtras);

		$(lookup).focus(function(){
			$(this).select();
		});
		var url = jqAutocompletar.getUrlRestAutocompletar(nomeAction, propPadrao);
		if(typeof opts.urlRest != "undefined"){
			url = opts.urlRest;
		}
		$(lookup).autocomplete(url, opts);
/*
		$(lookup).bind("result", function(handler) {
			jqAutocompletar.aoAutocompletarClicarItem(this);
		}).blur(function(eventoBlur) {
			jqAutocompletar.aoAutocompletarSairCampo(this);
			hasFocus = 0;
			if (!$(lookup).config.mouseDownOnSelect) {
				hideResults();
			}
		});
*/		
		if(!opts["multiple"]){
			$(lookup).result(function(event, data, formatted) {
				jqAutocompletar.antesAutocompletar($(this).attr("name"), data);
				 if (data){
					setVarGlobal("VALOR_ORIGINAL_"+$(this).attr("name"), null);
					jqAutocompletar.completaCampos(data, listaCamposAutocompletar);
				 }
				jqAutocompletar.aposAutocompletar($(this).attr("name"), data);
			});
		}
	}
}

JQAutocompletar.prototype.completaCampos = function (data, listaCamposAutocompletar){
	var campos = listaCamposAutocompletar.split(",");
	for(c = 0; c < campos.length; c++){
		$(getCampo(campos[c])).val(data[c]);
	}
};

JQAutocompletar.prototype.retirarDoCampo = function (nomeCampo, seletor){
	var lookup = getCampo(nomeCampo);
	if(typeof lookup == "undefined"){
		lookup = jqAutocompletar.getCampoPorSeletor(seletor);
	}
	
	jqAutocompletar_Args = new Array();
	$(lookup).unautocomplete();
}

JQAutocompletar.prototype.limparCache = function (nomeCampo){
	setVarGlobal(nomeCampo+"_retorno_extra",null);
	setVarGlobal(nomeCampo+"_argumento_extra",null);
}

JQAutocompletar.prototype.mudarOpcoes = function (nomeCampo, novasOpcoes){
	var lookup = getCampo(nomeCampo);
	$(lookup).setOptions(novasOpcoes);
}

JQAutocompletar.prototype.antesAdicionarAoCampo = function (nomeCampo){
	return true;
};

JQAutocompletar.prototype.getCampoPorSeletor = function (seletor){
	return jQuery(seletor);
};

/*****************************************************************************\
							JQUERY DATEPICKER
\*****************************************************************************/
function JQCalendario(){};

var jqCalendario = new JQCalendario();

function montarArrayDatas(seletor){

	var valData = $(seletor).val();
//alert("valData: "+valData)
	var datas	= null;
	if(valData && valData != ""){
		datas = valData.split("\/");
		var dia = datas[0];
		var mes = datas[1];
		var ano = datas[2];
	}
	return datas;
}

JQCalendario.prototype.adicionarAoCampoComPeriodo = function(seletor, seletorMin, seletorMax, optsExtras){

//	alert("seletor: "+seletor)
	var opcoes = {};
	var datasMin = montarArrayDatas(seletorMin);
//	alert("datasMin: "+datasMin)
	var datasMax = montarArrayDatas(seletorMax);
//	alert("datasMax: "+datasMax)
	if(datasMin != null && datasMax != null){
		opcoes = {minDate: new Date(datasMin[2], datasMin[1] - 1, datasMin[0]), maxDate: new Date(datasMax[2], datasMax[1] - 1, datasMax[0])};
	}else if(datasMin != null && datasMax == null){
		opcoes = {minDate: new Date(datasMin[2], datasMin[1] - 1, datasMin[0])};
	}else if(datasMin == null && datasMax != null){
		opcoes = {maxDate: new Date(datasMax[2], datasMax[1] - 1, datasMax[0])};
	}
	opcoes = $.extend(opcoes, optsExtras);

	jqCalendario.adicionarAoCampo(seletor, opcoes);

}


JQCalendario.prototype.adicionarAoCampoDataMinima = function(seletor, seletorMin, optsExtras){

//	alert("seletor: "+seletor)
	var datasMin = montarArrayDatas(seletorMin);
//	alert("datasMin: "+datasMin)
	var opcoes = {};
	if(datasMin != null){
		opcoes = {minDate: new Date(datasMin[2], datasMin[1] - 1, datasMin[0])};
	}
	opcoes = $.extend(opcoes, optsExtras);
	
	jqCalendario.adicionarAoCampo(seletor, opcoes);

}

JQCalendario.prototype.adicionarAoCampoDataMaxima = function(seletor, seletorMax, optsExtras){

	var datasMax = montarArrayDatas(seletorMax);
	var opcoes = {};
	if(datasMax != null){
		opcoes = {maxDate: new Date(datasMax[2], datasMax[1] - 1 , datasMax[0])}
	}
	opcoes = $.extend(opcoes, optsExtras);
	
	jqCalendario.adicionarAoCampo(seletor, opcoes);

}

JQCalendario.prototype.adicionarAoCampoHoraUsa = function(seletor, optsExtras){
	
	try{
		var opts = {
				constrainInput: false, 
				onSelect: function(dateText, inst) { 
			
					var hoje = new Date();
					dateText += hoje.getHours()+":"+hoje.getMinutes();
				}
		};
		opts = $.extend(opts, optsExtras);
		jqCalendario.adicionarAoCampo(seletor, opts);
	}catch(e){
		jQuery(seletor).css("display","block");
	}
};

JQCalendario.prototype.adicionarAoCampo = function(seletor, optsExtras){

	var hoje = new Date();
	var anoHoje		= hoje.getFullYear();
	var ajusteAnos	= anoHoje - 1900;	
	try{
	var opts = {
//			startDate: lookup,
			numberOfMonths: 3, 
			showButtonPanel: true, 
			buttonText: '...',
			//buttonText: '<img src=\'./plc/midia/ico_calendario.gif\' border=\'0\'>',
			showOn: 'button',
			changeMonth: true,
			changeYear: true,
			beforeShow: function (campo, instancia){
				try{
					if(getVarGlobal("seletor:beforeShow") != "S"){
						jqCalendario.antesMostrar(campo, instancia);
						setVarGlobal("seletor:beforeShow","S");
					}else{
						setVarGlobal("seletor:beforeShow","");
					}
				}catch(e){}
			},
			yearRange: '-'+ajusteAnos+':+20'
	};

	opts = $.extend(opts, optsExtras);

	var optsTimer = {
        hour: 0,
        minute: 0,
        second: 0,
        ampm: 'false',
		stepHour: 1,
		stepMinute: 10,
		stepSecond: 30,
		holdDatepickerOpen: false,
		alwaysSetTime: false
    };

	opts = $.extend(opts, optsTimer);


	jQuery(seletor).datepicker('destroy');
	//jQuery(seletor).datepicker(opts);
	jQuery(seletor).datetimepicker(opts);

	}catch(e){
		jQuery(seletor).css("display","block");
	}

};

JQCalendario.prototype.substituirAutomatico = function(seletor, optsExtras){

	if(plcGeral.contextPath == "/ecp"){
		var optsEcp = {
				numberOfMonths: 1, 
				buttonText: '<img src=\'./plc/midia/ico_calendario.gif\' border=\'0\'>'
		};
		optsExtras = $.extend(optsEcp, optsExtras);
	}

	//if(plcGeral.contextPath == "/eprj"){
		$("a[href=#]").each(function(i){
			try{
			if(($(this).attr("onclick")+"").indexOf("abrirCalendario") > -1){
				var nomeCampo = $(this).prev("input").attr("name");
				$(this).css("display","none"); // esconde bot�o anterior de calend�rio
				if(jQuery(this).attr("class").indexOf("hora-usa") == -1){
					jqCalendario.adicionarAoCampo("input[name="+nomeCampo+"]", optsExtras); //inclui novo bot�o de calend�rio
				}else{
					jqCalendario.adicionarAoCampoHoraUsa("input[name="+nomeCampo+"]", optsExtras); //inclui novo bot�o de calend�rio
				}
			} 
			}catch(e){
				$(this).css("display","block"); // mostra bot�o anterior de calend�rio
			}
		});
	//}

	//Retira a borda dos bot�es de popup de calendario
	if(plcGeral.contextPath == "/ecp"){
		jQuery(".ui-datepicker-trigger").css("border","0");
	}
	
}


/*****************************************************************************\
							JQUERY CASCADE
\*****************************************************************************/

function JQCascata(){};

var jqCascata = new JQCascata();
var naoColocaSelected;

JQCascata.prototype.adicionarArgumentoExtra = function (nomeProp, valorProp, nomeAction){

	jqAutocompletar.adicionarArgumentoExtra(nomeProp, valorProp,nomeAction);
}

JQCascata.prototype.criarArgumentosExtras = function(nomeAction){

	var querySel = jqAutocompletar.criarArgumentosExtras(nomeAction);
	while(querySel.indexOf("&") > -1){
		querySel = querySel.replace("&","*");
	}
	while(querySel.indexOf("=") > -1){
		querySel = querySel.replace("=","$");
	}
	return querySel;
}

JQCascata.prototype.aposCarregarComboAninhado = function (combo){};
JQCascata.prototype.aposComplementaCamposComboAninhado = function ( valorParam ){};

JQCascata.prototype.adicionarAoCampo = function (seletorDe, seletorPara, nomeAction, propDe, optsExtras) {

	var querySel	= "?querySel=" + jqCascata.criarArgumentosExtras(nomeAction);

	var opts = {
		template: function(item) {
			return "<option value='" + item.value + "'>" + item.text + "</option>"; 
		},
		match: function(selectedValue) {
			return true;
		},
		timeout: 200, //just to show loading indicator				
		//data: { myotherdata: jQuery("#ajax_header").html() }
		//event: "blur",
		getParentValue: function(parent){ 
			var selecionado = jQuery(parent).val();
			//alert("selecionado: "+selecionado)
			return  selecionado; 
		},
		ajax: { 
			url: plcGeral.contextPath+"/soa/struts/plc/comboaninhado/"+nomeAction+"/"+propDe + querySel
			//complete: function(){ 
			//	alert('Combo recuperado.'); 
			//}
		}
	};
	opts = $.extend(opts, optsExtras);
	
	jqCascata.retirarDoCampo(seletorPara);
	jQuery(seletorPara).cascade(seletorDe, opts)
	.bind("loaded.cascade",function(source , target) {
		var textFirstItem	= "";
		var textEmpty		= "";
		if(typeof optsExtras.textFirstItem != "undefined") {
			textFirstItem = optsExtras.textFirstItem;
		}

		var indexUltItem = this.options.length;	
		do{
			if(this.options[indexUltItem - 1].text == "EXECUTA_FUNCAO") {
				var funcao = this.options[indexUltItem - 1].value;
				var nameField = $(source)[0].target.name;
				funcao = funcao.replace(")","");
				//Adicionar origem e destino
				funcao += ",'"+nameField+"')";
				eval(funcao);
				jQuery(this.options[indexUltItem - 1]).remove();
			}
			indexUltItem = this.options.length;	
		}while(this.options[indexUltItem - 1].text == "EXECUTA_FUNCAO")

		if(this.options[0].value === "VAZIO") {
			if(typeof optsExtras.textEmpty != "undefined") {
				textFirstItem = optsExtras.textEmpty;
				jQuery(this).empty();
				jQuery(this).prepend("<option value='' selected='true'>"+textFirstItem+"</option>");
				jQuery(this).attr("disable", true);
				jQuery(this).find("option:first")[0].selected = true;
			}
		} else if(typeof naoColocaSelected == "undefined"){
			jQuery(this).prepend("<option value='' selected='true'>"+textFirstItem+"</option>");
			var nameField = ""+$(source)[0].target.name;
			nameField = nameField.replace("_Arg","");
			nameField = nameField.replace("_",".");
			var valSelected = "";			
			try{
				valSelected = eval("val"+nameField);				
			}catch(e){}

			jQuery(this).find("option").each(function(){
				var val = jQuery(this).val();
				valSelected = valSelected == val ? valSelected : "";
			});
			if(typeof valSelected != "undefined" && valSelected != ""){
				jQuery(this).val(valSelected)
			}else if(optsExtras.cascata == "S"){
				jQuery(this).find("option")[1].selected = true;
			} else {
				jQuery(this).find("option:first")[0].selected = true;
			}
		}

	})
	.bind("loading.cascade",function(e , target) {
		jqCascata.aposCarregarComboAninhado(target);
	})
};

JQCascata.prototype.getValComboManter = function (nameField){
	var valSelected = eval("val"+nameField);
	return valSelected;
}

JQCascata.prototype.retirarDoCampo = function (seletorPara){
	jQuery(seletorPara).unbind("loaded.cascade").unbind("cascade");
}

JQCascata.prototype.complementaParamentrosComboAninhado = function( valorParam, nomesCampo ) {	
	naoColocaSelected = "S";
	for ( var n in valorParam ) {
		if(typeof n != "undefined") {
			$(getCampo(n)).val(valorParam[n]);
		}
	}
	
	this.aposComplementaCamposComboAninhado(valorParam);
}

/*****************************************************************************\
							JQUERY TRACK CHANGES
\*****************************************************************************/

function JQTrackChange(){};

var jqTrackChange = new JQTrackChange();

JQTrackChange.prototype.nomeCacheListaAlteracoes	= "TRACK_CHANGE_CACHE_ALTERACOES";

JQTrackChange.prototype.nomeCacheValoresOriginais	= "TRACK_CHANGE_CACHE_VALORES_ORIGINAIS";

JQTrackChange.prototype.nomeCampoListaAlteracoes	= "formModificadoLista";

JQTrackChange.prototype.listaEventosPadrao			= "change keypress keydow";

JQTrackChange.prototype.executandoGravacao			= false;

var oldValuesTrack = "";
JQTrackChange.prototype.adicionarCampos = function (seletorForm, nomeListaAlteracoes, listaEventos){
	jqTrackChange.nomeCacheListaAlteracoes
	oldValuesTrack = $(seletorForm).trackChanges({
		  changeListName: nomeListaAlteracoes,
		  events: listaEventos,
		  changeListVisible: false
	});
	if(jqTrackChange.recuperarListaAlteracoes() == null){
		jqTrackChange.executandoGravacao = false;
		jqTrackChange.guardarListaAlteracoes(nomeListaAlteracoes);
		jqTrackChange.guardarValoresOriginais();
	}else{
		jqTrackChange.montarCacheListaAlteracoes(nomeListaAlteracoes, jqTrackChange.recuperarListaAlteracoes());
	}
}

JQTrackChange.prototype.itemLista = function (nome, valor){
	this.nome	= nome;
	this.valor	= valor;
}

JQTrackChange.prototype.guardarListaAlteracoes = function (nomeListaAlteracoes){
	var listaItens = new Array();
	$("#"+nomeListaAlteracoes+" option").each(function(i) {
		listaItens[listaItens.length] = new jqTrackChange.itemLista(this.text, this.value);
	});
	setVarGlobal(jqTrackChange.nomeCacheListaAlteracoes, listaItens);
}

JQTrackChange.prototype.recuperarListaAlteracoes = function (){
	return getVarGlobal(jqTrackChange.nomeCacheListaAlteracoes);
}

JQTrackChange.prototype.limparListaAlteracoes = function (){
	setVarGlobal(jqTrackChange.nomeCacheListaAlteracoes, null)
}

JQTrackChange.prototype.guardarValoresOriginais = function (){
	setVarGlobal(jqTrackChange.nomeCacheValoresOriginais, oldValuesTrack);
}

JQTrackChange.prototype.recuperarValoresOriginais = function (){
	return getVarGlobal(jqTrackChange.nomeCacheValoresOriginais)
}

JQTrackChange.prototype.limparValoresOriginais = function (){
	setVarGlobal(jqTrackChange.nomeCacheValoresOriginais, null)
}

JQTrackChange.prototype.montarCacheListaAlteracoes = function (nomeListaAlteracoes, novaListaAlteracoes){
	var atualListaAlteracoes = jQuery("select[name='"+nomeListaAlteracoes+"']")[0];
	$.each($(novaListaAlteracoes), function (index , obj){
		try{
			atualListaAlteracoes.options[atualListaAlteracoes.length] = new Option(obj.nome, obj.valor, true, true);		
		}catch(e){}
	});
}

/*****************************************************************************\
					JQUERY JANELA MODAL
\*****************************************************************************/

function JQJanelaModal(){};

var jqJanelaModal = new JQJanelaModal();

JQJanelaModal.prototype.abrirAntes = function (url){
	return true;
}

JQJanelaModal.prototype.fecharApos = function (){}

JQJanelaModal.prototype.abrir = function (url, optsExtras){

	var opts = {
			title: ''
			,url: url.replace('modal','popup')
			,width: (optsExtras.largura || 720)
			,height: (optsExtras.altura || 480)
			,hide: ''
		};
	
	opts = $.extend(opts, optsExtras);

	if(!jqJanelaModal.abrirAntes(url)){
		return null;
	}

	// Cria a Janela Modal!
	var dialogModal = JQPlc.dialogWindow(opts);
	
	dialogModal.dialog.dialogClose = function(){
		jQuery(dialogModal).parent().jqJanelaModal.fechar(dialogModal);
	};

	return dialogModal;
	
}

JQJanelaModal.prototype.fechar = function (dialogModal){

	//dialogModal.close();

	dialogModal.dialog('close');
	jqJanelaModal.fecharApos();

}

/*****************************************************************************\
							JQUERY TAG CLOUD
\*****************************************************************************/

function JQTagCloud(){};

var jqTagCloud = new JQTagCloud();

JQTagCloud.prototype.gerar = function (seletor, optsTag){


	if(optsTag.tipo == "Destaque"){
			jqTagCloud.gerarTipoDestaque(seletor, optsTag);
	}else{
		jqTagCloud.montarLista(seletor, optsTag);
		if(optsTag.formato == 'Texto'){
			jqTagCloud.gerarFormatoTexto(seletor, optsTag);
		}
		if(optsTag.formato == 'Animado'){
			jqTagCloud.gerarFormatoAnimado(seletor, optsTag);
		}
	}
	
};

JQTagCloud.prototype.gerarTipoDestaque = function (seletor, optsTag){

	$.dynaCloud.max = optsTag.numMaxTags;
	$.dynaCloud.sort = true;
	$.dynaCloud.auto = true;
	$(seletor).dynaCloud(optsTag.seletorSaida);

}

JQTagCloud.prototype.gerarFormatoTexto = function (seletor, optsTag){
	$("#LISTA-TAG-CLOUD").tagcloud(optsTag).find("li").tsort();
}

JQTagCloud.prototype.gerarFormatoAnimado = function (seletor, optsTag){

		var opts = {
			speed: 1,
			slower: 0.7,
			timer: 10,
			radius: optsTag.width / 2.6,
			fontMultiplier: optsTag.sizemin
		}

		opts = $.extend(opts, optsTag);
		
		$('#CONTAINER-TAG-CLOUD').tagoSphere(opts);
		$('#CONTAINER-TAG-CLOUD').css("width",optsTag.width);

	/*
		var rtInterval = setInterval("rotacionar()",1000);
		$('#CONTAINER-TAG-CLOUD').mouseover( function(){
			clearInterval();
		})
		.mouseout(function(){
			rtInterval = setInterval("rotacionar()",1000);
		});
		
		function rotacionar(){
			$('#CONTAINER-TAG-CLOUD').mouseover();
			$('#CONTAINER-TAG-CLOUD').mouseover();
		}
*/
}


JQTagCloud.prototype.montarLista = function (seletor, opts){
		
	var htmlItens = "";
	$.each(opts.dados.dados, function(nomeVar, dados) {
		htmlItens += jqTagCloud.formatarLista(opts.tipo, dados);
	});
	$(seletor).append($("<ul id='LISTA-TAG-CLOUD' class='LISTA-TAG-CLOUD'></ul>").html(htmlItens));

};

JQTagCloud.prototype.formatarLista = function (tipo, dados){
	return "<li class='item-tag-cloud' title='"+dados.valor+"' value='"+dados.valor+"'>"+dados.nome+" </li>";
};
	

function buscarDadosTagCloud (optsTag) {	 

	var optsTagCloud = optsTag;

	var optsAjax = {
		url: optsTag.url,
		type: "GET",
		dataType:"json",
		success: function(json) { 
			var optsJson = {
				dados: json
			};
			optsTagCloud = $.extend(optsTagCloud, optsJson);
			jqTagCloud.gerar(optsTagCloud.seletor, optsTagCloud);
			return optsJson.dados;
		},
		error:	function() { 
			var optsErro = {
				dados: {ERRO_MONTAGEM_TAG_CLOUD: 100}
			};
			optsTagCloud = $.extend(optsTagCloud, optsErro);
			jqTagCloud.gerar(optsTagCloud.seletor, optsTagCloud);
			return optsErro.dados;
		}
	};
	try{
		$.ajax(optsAjax);
	}catch(e){}
}


/*****************************************************************************\
							JQUERY UI MULTISELECT
\*****************************************************************************/

function JQUIMultiselect(){};

var jqUIMultiselect = new JQUIMultiselect();

JQUIMultiselect.prototype.gerar = function (seletor, optsMulti){

		var opts = {
			defaults: {
				sortable: true,
				searchable: true,
				animated: 'fast',
				show: 'slideDown',
				hide: 'slideUp',
				dividerLocation: 0.6,
				nodeComparator: function(node1,node2) {
					var text1 = node1.text(),
						text2 = node2.text();
					return text1 == text2 ? 0 : (text1 < text2 ? -1 : 1);
				}
			},
			locale: {
				addAll:'Adicionar tudo',
				removeAll:'Remover tudo',
				itemsCount:'itens selecionados'
			}
		};

		opts = $.extend(opts, optsMulti);

		$.extend($.ui.multiselect, opts);

		jQuery(seletor).multiselect();

};
		
JQUIMultiselect.prototype.manterSelecao = function (seletor, itensSelecionados){
	var comunidades = ","+itensSelecionados+",";
	jQuery(jQuery(seletor)[0].options).each(function(){
		var opt = this;
		if(comunidades.indexOf(","+opt.value+",") >= 0){
			opt.selected = true;
		}
	});
}


/*****************************************************************************\
							JQUERY TAGGER
\*****************************************************************************/

function JQTagger(){};

var jqTagger = new JQTagger();

JQTagger.prototype.gerar = function (seletor, tagsSelecionadas){

	// add to unnamed element by index
	jQuery(seletor).eq(0).addTag(tagsSelecionadas);
	adicionarFundoTagSelecionada();
	jQuery(seletor)
	.bind('keypress', function(e){
		if( 13 == e.keyCode){
			adicionarTagParaBusca();
			$(this).val('');
			$(this).stop();
			return false;
		}
	});
	adicionarContagemTagSelecionada();

	jQuery("#TD_TAG")
		.append("<b><a href='#' onclick='adicionarTagParaBusca(); return false;' style='color:black;'><span class='bt' id='BT_ADD'>Adicionar tag</span></a></b>")
		//.css("padding","5px")
	;
	jQuery(".tagAdd").css("position","absolute").css("top","100").css("visibility","hidden");
	jQuery(".tagger").addClass("search empty ui-widget-content ui-corner-all");
	jQuery(".tagList").appendTo(jQuery("#TD_LIST_TAG"));
	jQuery("#BT_ADD").css("font-size","10");
	
};
		
function adicionarTagParaBusca(){
	jQuery(".tagAdd").click();
	adicionarFundoTagSelecionada();
	adicionarContagemTagSelecionada();
}

var removerTodasTags = false;
function removerTodasTagSelecionada(){
	jQuery("li.tagName").each(function(){
		jQuery(this).remove();
	});
	adicionarContagemTagSelecionada();
}

function retornarTagsParaBusca(){
	jQuery("li.tagName").each(function(){
		var separador = jQuery(".tags").val() == "" ? "" : ",";
		jQuery(".tags").val(jQuery(".tags").val() + separador + jQuery(this).html() );
	});
}

function adicionarContagemTagSelecionada(){
	jQuery("#NUM_TAG").html(jQuery(".tagName").size()+" tags selecionadas")
}

/*****************************************************************************\
							JQUERY UI SORTABLE
\*****************************************************************************/

function JQUISortable(){};

var jqUISortable = new JQUISortable();

JQUISortable.prototype.gerar = function (seletorContainer, seletorDrag, optsDrag){

	var opts = {
		accept: seletorDrag,
		helperclass: 'sort_placeholder',
		opacity: 0.7,
		//ghosting: true,
		tolerance: 'intersect'
		,onStart: jqUISortable.aoIniciarDragDrop
		,onChange: jqUISortable.aoMudarDragDrop
		,onStop: jqUISortable.aoPararDragDrop
	};

	opts = $.extend(opts, optsDrag);

	try{$(seletorContainer).Sortable(opts);	}catch(e){}
}

JQUISortable.prototype.destruir = function (seletorContainer){
	$(seletorContainer).SortableDestroy();
}

JQUISortable.prototype.aoIniciarDragDrop = function (bandas){}

JQUISortable.prototype.aoMudarDragDrop = function (bandas){}

JQUISortable.prototype.aoPararDragDrop = function (bandas){}

/*****************************************************************************\
							JQUERY BLOCK UI
\*****************************************************************************/
function JQBlockUI(){};

var jqBlockUI = new JQBlockUI();

JQBlockUI.prototype.optsBlockUI = {
	message:  "Aguarde processamento...",
	css: {
		width:'300px', 
		margin:'-50px 0 0 -125px', 
		top:'50%', 
		left:'50%', 
		textAlign:'center', 
		fontWeight: 'bold',
		fontSize: '20px',
		color:'#000',
		backgroundColor:'#eee', 
		border:'2px solid #000', 
		cursor: 'none',
		padding:'20px' 
	},
	overlayCSS:  { 
		backgroundColor:'coral'
	},
	fadeOut: 0
};

JQBlockUI.prototype.gerarMensagem = function (optsMsg){


	var opts = $.extend(jqBlockUI.optsBlockUI, optsMsg);

	$.blockUI(opts); 
}

JQBlockUI.prototype.bloquearPagina = function (optsBloqueio){

	var opts = {
		message:  null
	};

	opts = $.extend(jqBlockUI.optsBlockUI, optsBloqueio);

	$.blockUI(opts); 
}

JQBlockUI.prototype.desbloquearPagina = function (){

	$.unblockUI()
}

JQBlockUI.prototype.bloquearElemento = function (seletor, optsBloqueio){

	var opts = {
		message:  '<h1>Aguarde processamento...</h1>'
	};
	opts = $.extend(jqBlockUI.optsBlockUI, optsBloqueio);

	jQuery(seletor).block(opts); 
}

JQBlockUI.prototype.desbloquearElemento= function (seletor){

	jQuery(seletor).unblock(); 
}


/*****************************************************************************\
						PORTLET MENU FERRAMENTA
\*****************************************************************************/

function ferramentaImprimir(urlImpressao){

	var winImp = null;
	if(typeof urlImpressao != "undefined" && urlImpressao != ""){
		winImp = janelaMaximizada(urlImpressao);
	}else{
		winImp = window;	
		winImp.print();	
	}
}

function printElementID(id, pg) {
    var oPrint, oJan;
    oPrint  = window.document.getElementById(id);
    if (oPrint!=null){
		oPrint = window.document.getElementById(id).innerHTML;
	    oJan    = window.open(pg);
	    oJan.document.write(oPrint);
	    oJan.history.go();
	    oJan.window.print();
    }else {
    	ferramentaImprimir(pg);
    }
}

function ferramentaFavorito(nome){

	var url = document.location.href;
	var titulo = document.title;
	if(typeof nome != "undefined" && nome != ""){
		titulo = nome;
	}

	if (window.sidebar){ // firefox
		//window.sidebar.addPanel(title, url, ""); Dont use until it's fixed
		if(confirm( "Este favorito, criado para Mozilla Firefox, vai ser mostrado em uma barra lateral."+
					" \nPara alterar este comportamento, selecione o favorito com botao direito do mouse, clique em 'Propriedades' " +
					" e desmarque a caixa 'Carregar no painel'\n"+
					" \nQuer incluir este favorito?\n\n" +
					" Se desejar criar um link sem este comportamento por favor pressione juntas as teclas CTRL + D.")){
			window.sidebar.addPanel(titulo, url, ""); 		
		}
	}else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',titulo);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}else if(document.all){// ie
		window.external.AddFavorite(url, titulo);
	}

/*
	if(typeof nome != "undefined" && nome != ""){
		addToFavorites( nome ,url);
	}else{
		addToFavorites(document.title,url);
	}
*/
}

function ferramentaFonte(contexto, operador, unidade, valor){

	var numRedim = getVarGlobal("NUM_REDIMENSIONAMENTO_"+contexto);
	if(typeof numRedim == "undefined"){
		numRedim = 0;
	}

	if("+val" == operador){
		numRedim++;
	}else{
		numRedim--;
	}
	
	if(numRedim > 3 || numRedim < -2){
		return;
	}

	var opts = {
		size: valor,
		sizemethod: operador, // /*can be: "+val", "pc",, "-pc", "val", "-val"*/
		type: unidade //can be "px", "em" (ONLY VALID FOR THE VAL METHOD)
	};

	jQuery("DIV,TD,LI,strong,em,u,sub,sup,font,b,ul,li,ol,strike,h1,h2,h3,p,span,a", contexto).jFontSizer(opts);

	//Quando utilizar layout em colunas
	try{
		jQuery("DIV,TD,LI,strong,em,u,sub,sup,font,b,ul,li,ol,strike,h1,h2,h3,p,span,a", contexto.replace("#",".")).jFontSizer(opts);
	}catch(e){}

	setVarGlobal("NUM_REDIMENSIONAMENTO_"+contexto, numRedim)
}

var modoConstraste = false;
function ferramentaContraste(){
	if(modoConstraste){
		ferramentaContrasteLigar();
	}else{
		ferramentaContrasteDesligar();
	}
}

function ferramentaContrasteLigar(){
	jQuery("#PRT_LINK_CSS_CONTRASTE").click();
	modoConstraste = true;
	eraseCookie("style");
}

function ferramentaContrasteDesligar(){
	jQuery("#PRT_LINK_CSS_PADRAO").click();
	modoConstraste = false;
	eraseCookie("style");
}

function setUpImageShadowbox (REL, CONTEXTO) {

	var listaImg = "";
	if(typeof CONTEXTO == "undefined"){
		CONTEXTO = "BODY";
	}
	jQuery("img", CONTEXTO).each(function(i){ 
		if(listaImg.indexOf(this.src+",") == -1){
			listaImg += this.src+",";
			$(CONTEXTO).append("<a id='"+REL+"_"+i+"' class='ESCONDIDO' rel='shadowbox["+REL+"]' href='"+this.src+"'>"+this.src+"</a><br>");
		}
	});
	criarGaleria(CONTEXTO, {});

}

function ferramentaGaleria (SELETOR) {

	jQuery(SELETOR).click();
}

function ferramentaEmail (tipo, assunto, id, email, nome){
	var emailPortal = "&emailPortal=S";
	if(typeof email != "undefined"){
		email = "&email="+email
		emailPortal = "&emailPortal=A";
	}else{
		email = "";
	}

	if(typeof nome != "undefined"){
		nome = "&nome="+nome
	}else{
		nome = "";
	}

	var paramAssunto = "";
	if(typeof id != "undefined" && id != ""){
		id = "&id="+id;
	}else{
		id = "";
		if(typeof document.title != "undefined"){
			paramAssunto = "&assunto="+document.title;
			assunto = document.title;
		}else{
			paramAssunto = "&assunto=Conte&uacute;do do Portal";
			assunto = "Conte&uacute;do do Portal";
		}
	}
	if(typeof tipo != "undefined"){
		tipo = "&tipo="+tipo
	}else{
		tipo = "";
	}
	var url = plcGeral.contextPath+"/ecp/webmailnovamsg.do?evento=novaMensagem&wmAcao=MNV"+emailPortal+id+email+nome+tipo+paramAssunto;
	/*
	if(ExpYes)
		janela(url,450,390);
	else
		janela(url,410,380);
	*/
	var janelaEmail = jqJanelaModal.abrir(url,{title: 'Enviar e-mail<br>'+assunto, largura: 500, altura: 450});
	
	//Informar url para envio no email
	janelaEmail.children('iframe').bind('load', function(){
		var iWindow = $(this).attr('contentWindow');
		iWindow.informarUrlEnvioEmail(ecpGeral.uriAmigavelEnvioEmail, ecpGeral.uriNaoAmigavelEnvioEmail);
	});
}


function ferramentaLayout(seletor, numeroColunas){
	if(numeroColunas == 1){
		jQuery("#IMG_LAYOUT_"+seletor).attr("src",plcGeral.contextPath+"/midia/duas_colunas.gif");
	}else{
		jQuery("#IMG_LAYOUT_"+seletor).attr("src",plcGeral.contextPath+"/midia/uma_coluna.gif");
	}
	gerarConteudoColunas(seletor, numeroColunas);
}

function ferramentaTag (id, tipoObjeto){
	var url = plcGeral.contextPath+"/ecp/tag.do?evento=x&id="+id+"&tipoObjeto="+tipoObjeto;
	jqJanelaModal.abrir(url,{title: 'Adicionar tags', largura: 300, altura: 180});
}

/*****************************************************************************\
					C�DIGOS GERAIS
\*****************************************************************************/

function configuraCssPortalParaTransitional(){}

/**
 * para podermos manter compatibilidade na chamada fun��o, 
 * estamos especializando ela dessa forma, quando existir 
 * editor ela sera sobreposta no config.js
 * 
 * @return uma fun��o vazia
 */
function montarEditorAba(){}

function fecharChamado(idRequisito, conceitoNome){
	if (idRequisito != null && idRequisito != ""){
		var msgFechamento = "Foi criado um item do tipo \""+conceitoNome+"\" com o c�digo: "+idRequisito+". Atendimento fechado automatico na cria��o do item.";
		if(!document.forms[0].descricaoSolucao.disabled){
			var ok = confirm('Deseja fechar o chamado?');
			if(ok){
				setBotaoAcaoEnter('<fmt:message key="jcompany.evt.gravar"/>');
				regBotaoEvento('<fmt:message key="jcompany.evt.gravar"/>','GRAVAR');
				document.forms[0].descricaoSolucao.value = msgFechamento;
				disparaBotaoAcao(getBotaoArray('GRAVAR'));
			}
		}
	}
}

/**
 * Remove um item da lista de itens de um campo, entre um determinado separador.
 * Este item deve estar no formato "separador item separador", onde o separador pode ser qualquer caracter. Exemplo: ,111,
 * 
 * @param nomeCampo Nome do campo que contem a lista
 * @param itemValor Valor do item que deve ser removido
 * @param separador Caracter que representa o separador
 */
function removerItemListaCampo(nomeCampo, itemValor, separador){

	var campo = getCampo(nomeCampo);
	var listaCampo = campo.value;

	listaCampo = listaCampo.replace(separador+itemValor+separador,",");

	if(listaCampo.lastIndexOf(",") == 0){
		listaCampo = listaCampo.replace(",","");
	}
	
	campo.value = listaCampo;
	
	return campo.value;
}

/**
 * Adiciona um item a uma lista de itens de um campo, entre um determinado separador.
 * 
 * @param nomeCampo Nome do campo que contem a lista
 * @param itemValor Valor do item que deve ser adicionado
 * @param separador Caracter que representa o separador
 */
function adicionarItemListaCampo(nomeCampo, itemValor, separador){

	var campo = getCampo(nomeCampo);
	var listaCampo = campo.value;

	if(listaCampo.indexOf(separador+itemValor+separador) == -1){
		listaCampo += separador+itemValor+separador;
		listaCampo = listaCampo.replace(",,",",");
		campo.value = listaCampo;
	}
}

/*****************************************************************************\
								ACCORDION
\*****************************************************************************/

function JQAccordion(){};

var jqAccordion = new JQAccordion();

JQAccordion.prototype.criar = function(seletor, optsAcc){

	var opts = {
		active: false ,
		autoHeight: false
	};

	opts = $.extend(opts, optsAcc);

	$(seletor).accordion(opts);
}

/*****************************************************************************\
							JQUERY QUICKSEARCH
\*****************************************************************************/

function JQQuicksearch(){};

var jqQuicksearch = new JQQuicksearch();

JQQuicksearch.prototype.criar = function(seletor, optsQs){

	var opts = {
		attached: "#quicksearch",
		formId: 'form-quicksearch',
		position: 'append',
		inputClass: 'texto',
		loaderText: 'Buscando...',
		labelText: 'Buscar por:',
		loaderImg: plcGeral.contextPath+'/plc/midia/carregando.gif',
		delay: 500,
		focusOnLoad: false
	};

	opts = $.extend(opts, optsQs);

	$(seletor).quicksearch(opts);

}

/*****************************************************************************\
							JQUERY MEDIA
\*****************************************************************************/

function JQMedia(){};

var jqMedia = new JQMedia();

JQMedia.prototype.gerar = function(seletor, optsMedia){

	var opts = { 
		autoplay:	0,         // normalized cross-player setting 
		bgColor:	'#ffffff' // background color 
	};

	opts = $.extend(opts, optsMedia);

	$(seletor).media(opts);

}

JQMedia.prototype.gerarYouTube = function(seletorBase, optsYouTube){

	var opts = { 
		autoplay:	0,         // normalized cross-player setting 
		type:	'swf',
		bgColor:	'#ffffff' // background color 
	};

	opts = $.extend(opts, optsYouTube);
	$(seletorBase+"-youtube").media(opts);
}


JQMedia.prototype.ajustarUrl = function(seletor){
	$(seletor).each(function(){
		seletor = seletor.replace(".","");
		var url = "";
		if(this.tagName == "A"){
			url = $(this).attr("href");
		}else if(this.tagName == "IMG"){
			url = $(this).attr("src");
		}
		if(url.indexOf("www.youtube.com") > 0){
			url = url.replace("/watch?v=","/v/")
			if(this.tagName == "A"){
				$(this).attr("href",url).removeClass(seletor).addClass(seletor+"-youtube");
			}else if(this.tagName == "IMG"){
				$(this).attr("src",url).removeClass(seletor).addClass(seletor+"-youtube");
			}
		}
	});
}

JQMedia.prototype.ajustarUrlYouTube = function(seletorImg){
	$(seletorImg).each(function(){
		//seletorImg = seletor.replace(".","");
		var url = "";
		if(this.tagName == "A"){
			url = $(this).attr("href");
		}else if(this.tagName == "IMG"){
			url = $(this).attr("src");
		}
		if(url.indexOf("www.youtube.com") > 0){
			url = url.replace("/watch?v=","/v/")
			url = url.replace("www.youtube.com/v","img.youtube.com/vi")
			url += "/2.jpg";
			if(this.tagName == "A"){
				$(this).attr("href",url);
			}else if(this.tagName == "IMG"){
				$(this).attr("src",url);
			}
		}
	});

}
/*****************************************************************************\
					EMPRESAS FILIADAS COM QUICKSEARCH
\*****************************************************************************/

function agruparPorInicialNome(seletorAgrupamento){
	$.each( $(seletorAgrupamento), function(i, n){ 

		var cap = new String($(n).text().substring(0,1));
		if(n.tagName == 'A' || n.tagName == 'DIV'){
			n = $(n).parent();
		}
		
		var keychar = cap.charCodeAt(cap)
		if(keychar <= "F".charCodeAt("F")){
			$(n).addClass("AF");
			$(n).parent().addClass("AF");
		}else if(keychar <= "M".charCodeAt("M")){
			$(n).addClass("GM");
			$(n).parent().addClass("GM");
		}else if(keychar <= "S".charCodeAt("S")){
			$(n).addClass("NS");
			$(n).parent().addClass("NS");
		}else {
			$(n).addClass("TZ");
			$(n).parent().addClass("TZ");
		}
	});

	mostraTotalUnidadesPorGrupo(".prt-empresa-count-T", seletorAgrupamento)
	mostraTotalUnidadesPorGrupo(".prt-empresa-count-AF", seletorAgrupamento+".AF")
	mostraTotalUnidadesPorGrupo(".prt-empresa-count-GM", seletorAgrupamento+".GM")
	mostraTotalUnidadesPorGrupo(".prt-empresa-count-NS", seletorAgrupamento+".NS")
	mostraTotalUnidadesPorGrupo(".prt-empresa-count-TZ", seletorAgrupamento+".TZ")


	$(".prt-empresas-linha").addClass("lista-navegacao");
	$(".prt-empresa-label-filtro").addClass("bt");
	//$(".prt-empresa-label-filtro").css("font-weight","bold");
	//$(".prt-empresa-count").css("font-size","9px").css("font-weight","normal");
	//$(".prt-empresa-label-filtro a").css("text-decoration","none");

}


function mostraTotalUnidadesPorGrupo(seletorAtualiza, seletorConta){
	
	var qte = $(seletorConta).length;
	$(seletorAtualiza).html("("+qte+")");
	$(seletorAtualiza).parent().attr("title", qte+" Empresa(s)");
	if(qte == 0){
		$(seletorAtualiza).parent().attr("onclick","return false;");
	}
}

function filtrarPorNome(seletorFiltro, seletorFiltroNav, filtro, seletorPai){
	
	var displayNone = "none";
	var displayList	= "block";
	
	$(".prt-empresa-link").removeClass("current");
	$(".prt-empresa-link-"+filtro).addClass("current");

	$("div"+seletorPai+" div.unidades").remove();

	if($(seletorFiltro).length > 0){
		if( $(seletorFiltro)[0].tagName == "LI"){
			displayList	= "list-item";
		}else if( $(seletorFiltro)[0].tagName == "TR"){
			displayList	= "table-row";
		}
	}

	$("#quicksearch").val("");
	$(seletorFiltro).css("display",displayNone).removeClass("lista-navegacao");
		
	filtro = filtro == "T" ? "" : "."+filtro;
	$(seletorFiltro+filtro).attr("style","display:'"+displayList+"'").addClass("lista-navegacao");
	recriarNavegadorAgrupamentoEmpresas(seletorFiltro+filtro+".lista-navegacao");
	
}

function recriarNavegadorAgrupamentoEmpresas(){}

function criarNavegadorAgrupamentoEmpresas(idTable, optsNav){
		jqCycle.criarComNavegador(idTable, optsNav);
}

function montarJsonAgrupamentoEmpresas(seletorBase){

	var json = "[{";
	var incluiuAlgum = false;
	$.each( $(seletorBase), function(i, n){
		if("table-row" == $(n).css("display") || "block" == $(n).css("display")){
			if(i != 0 && incluiuAlgum){
				json += ",";
			}
			json += "dados_"+i+": {" +
				"empresa: '"+$(n).find(".prt-empresas-item-empresa").find("a").html()+"'" +
				",cidade: '"+$(n).find(".prt-empresas-item-cidade").html()+"'" +
				",url: '"+$(n).find(".prt-empresas-item-empresa").find("a").attr("href")+"'"+
				"}";
			incluiuAlgum = true;
		}
	});
	json += "}]";

	return eval(json)[0];
}

function acertaLinkUrlEmpresa(urlEmpresa){return urlEmpresa};

var numPorPg = 10;
function gerarTabelaAgrupamentoEmpresas(jsonTable, idTable, sufixo){
	
	var htmlTabela = "<div class='unidades'>";
	
		count = 0;
		$.each( jsonTable, function(i, data) {
		 
		if( data.listaVazia == "" || typeof data.listaVazia == "undefined") {
			if( count != 0 && (count % numPorPg ) == 0 ) {
			  htmlTabela += "</tbody></table></div><div class='unidades' style='display:none'>" 
			}
			if( count == 0 || (count % numPorPg ) == 0 ) {
			  htmlTabela += "<table class='vafanapoli' cellspacing='0' cellpadding='0'  border='0'>"+
							"<thead><tr class='par'><th>Munic&iacute;pio</th><th>Unidade</th></tr></thead><tbody>";
			}			
			
			htmlTabela += "<tr class='prt-empresas-linha lista-navegacao'>"+
						  "<td class='prt-empresas-item prt-empresas-item-cidade'>"+data.cidade+"</td>"+
						  "<td class='prt-empresas-item prt-empresas-item-empresa'>"+
						  "<a href='"+acertaLinkUrlEmpresa(data.urlEmpresa)+"#posto'>"+data.nomeEmpresa+"</a>"+
						  "</td></tr>";
			count++;			
			} else {			
				htmlTabela += "<p>"+data.listaVazia+"</p>";				
				$("#"+idTable+sufixo+" div.unidades").remove();
				$(htmlTabela).appendTo("#"+idTable+sufixo);
			}
		});		 
	
	htmlTabela += "</tbody></table></div>";
	
	$("#"+idTable+sufixo+" div.unidades").remove();
	$(htmlTabela).appendTo("#"+idTable+sufixo);
}

/**
 * Recebe uma tabela contedo a quantidade de dados que seram apresentados durante a nagega��o. 
 * @param jsonTable
 */
function montaNavegadorAgrupaUnidades(jsonTable, idTable, sufixo, filtro, paraVerifica) {

	var qtParamAba;
	var htmlPesquisaUnidade = "";	
	
	switch( filtro ) {
	
		case 'T':
			qtParamAba = ecpQuantidadeParamentro.qttotal;
			break;
		case 'AF':
			qtParamAba = ecpQuantidadeParamentro.qtaf;
			break;
		case 'GM':
			qtParamAba = ecpQuantidadeParamentro.qtgm;
			break;
		case 'NS':
			qtParamAba = ecpQuantidadeParamentro.qtns;
			break;
		case 'TZ':
			qtParamAba =ecpQuantidadeParamentro.qttz;
			break;
	}
	
	htmlPesquisaUnidade = montaLinksPaginador( qtParamAba, idTable, filtro, paraVerifica );		
	
	$("#"+idTable+sufixo+" div#id-prt-empresa-navegador:last").remove();
	$(htmlPesquisaUnidade).appendTo("#"+idTable+sufixo);	

	$("a.unidadePagina").click(function() {
		destacaPaginaNavegador(this);
	});
	$("a.unidadePagina:first").addClass("activeSlide");	    

}

/**
* monta a nova quantidade pesquisa pela busca
*
*/
function visualizaNovoNavegador( jsonTable, idTable, filtro, paraVerifica, totalRegistros ) {		
	
	var qtBuscas = 20;
	if(typeof totalRegistros != "undefines"){
		qtBuscas = totalRegistros;
	}else{
		qtBuscas = jsonTable.length;
	}
	var htmlNovoResultado  = "";
	
	if( qtBuscas > 20 ) {
		htmlNovoResultado = montaLinksPaginador( qtBuscas, idTable, filtro, paraVerifica);		
	}
	
	$("div#id-prt-empresa-navegador:last").remove();
	$(htmlNovoResultado).appendTo( "#"+idTable+filtro );

	$("a.unidadePagina").click(function() {
		destacaPaginaNavegador(this);
	});
	$("a.unidadePagina:first").addClass("activeSlide");	    
	showLoading(false);

}

/**
* destaca a pagina clicada no navegador
*
*/
function destacaPaginaNavegador(pagina){
	$("a.unidadePagina").removeClass("activeSlide");
	$(pagina).addClass("activeSlide");
}

/*
* retorna links que seram utilizados no navegador
*
*/
function montaLinksPaginador( qtParamBusca, idTable, filtro, paramVerifica, totalRegistros ) {
	
	var linksJsonTable = "";
	var numeroPaginas = Math.ceil(qtParamBusca/20);
	var paramBusca = $("#"+idTable+"-base input[name='nomeUnidadePagina']").val()
	
	var urlNav = ""
	if(paramVerifica == "E"){
		urlNav = "'empfiliadas/empresafiliadas?idEmp'";
	}else if(paramVerifica == "S"){
		urlNav = "'unidades/pesqunidade?idServico'";
	}

	if(numeroPaginas > 1){
		for ( var contador = 1; contador <= numeroPaginas; contador++ ) {
			linksJsonTable += "<a href='#' onclick=\"recuperarUnidadesPaginador('"+contador+"','"+filtro+"', '"+idTable+"', '-base', '"+paramVerifica+"',"+urlNav+",'"+paramBusca+"'); return false;\"' class='unidadePagina'> "+contador+"</a>";
		}		
		var htmlBusca = "<div id='id-prt-empresa-navegador' class='navegacao'>"+linksJsonTable+"</div>";
	}

	return htmlBusca;
}

/**
* mostra a quantidade de municipios que est�o sendo pesquisados.
*/
function mostrarQuantidadePaginacao( quantidade ) {

	var htmlPaginacao = "<span class='resultados'>Mostrando'"+quantidade+"'</span>";	
	$(htmlPaginacao).appendTo( ".busca-unidades" );
		
}

var ecpQuantidadeParamentro;
var ecpAbaSelecionada;

/**
 * Recebe como paramentro o id do servi�o e retorna as empresa relacionadas. para montar as abas.
 * @param idPai pode ser o servico ou idemp pai
 * @param tipo se servico ou empresa
 */
function agruparPorNomeEQuantidade( idPai, urlJson, paramObj ) {	
	if (urlJson.indexOf("/soa/")<0)
		urlJson="/ecp/soa/"+urlJson;
	
	$.getJSON(urlJson+"="+idPai, function(data,i){
		
		var jSontable; 
		
		//para recebe portlet de servi�o
		if( paramObj == "S" ){			
			jSontable = $(data.unidades)[0].unidades;
		}else if( paramObj == "E" ) { //para recebe portlet de empresa 		
			jSontable = $(data.empfiliadas)[0].empresasFiliadas;
		}
		
		//complementa a quantidade de nomes por abas
		preencheNomeQuantidade(jSontable);
		
		montaNavegadorAgrupaUnidades( jSontable, idPai, "-pagina", "T", paramObj);
		
	});
}

function preencheNomeQuantidade(jSonTable){
	
	ecpQuantidadeParamentro = {"qttotal": jSonTable.quantidadeTotal , "qtaf": jSonTable.quantidadeAF, "qtgm": jSonTable.quantidadeGM, "qtns": jSonTable.quantidadeNS, "qttz": jSonTable.quantidadeTZ} 

	$(".prt-empresa-count-T").append("("+jSonTable.quantidadeTotal+")")
	$(".prt-empresa-count-AF").append("("+jSonTable.quantidadeAF+")")
	$(".prt-empresa-count-GM").append("("+jSonTable.quantidadeGM+")")
	$(".prt-empresa-count-NS").append("("+jSonTable.quantidadeNS+")")
	$(".prt-empresa-count-TZ").append("("+jSonTable.quantidadeTZ+")")
			
	ecpAbaSelecionada = {"abaSel": "T"};

}


/**
 *  monta a tabela com as empresas iniciais 
 *
 *  @param idPai
 *
 */
function configTabelaEmpresas( idPai, paramLinkViewMode, paramVerifica, urlJson ) {
	if (urlJson.indexOf("/soa/")<0)
		urlJson="/ecp/soa/"+urlJson;

		$.getJSON(urlJson+"="+idPai+"&linkViewMode="+paramLinkViewMode, function(data,i){

		var jsonTable = vereficaRetornoJsonUndefined(data, paramVerifica);
		var jsonsublista = sublistaJson(jsonTable, numPorPg);
		gerarTabelaAgrupamentoEmpresas(jsonsublista, idPai, "-base");
	});
}

/**
 * verifica se o json retorna um unico objeto, quando ele retorna um �nico objeto
 * ele traz como undefined. 
 *
 * @param data - unidades
 *
 */
function vereficaRetornoJsonUndefined( data, paramVerifica ){
	
	if( paramVerifica == "S") {	
		if(typeof data.unidades.unidades != "undefined" ) {  
			jsonTable = jQuery.makeArray(data.unidades.unidades);
		} else if(data.unidades.listaVazia == ""){
			jsonTable = data.unidades;
		} else{
			jsonTable = data;
		}
	}else if( paramVerifica == "E" ) { //para receber portlet de empresa
		if(typeof data.empfiliadas.empresasFiliadas != "undefined" ) {  
			jsonTable =  jQuery.makeArray(data.empfiliadas.empresasFiliadas);
		} else if (data.empfiliadas.listaVazia == ""){
			jsonTable = data.empfiliadas;
		} else{
			jsonTable = data;
		}
	}

	return jsonTable
}

function determinaQuantidadeDeRegistros(data, paramVerifica){
	if( paramVerifica == "S") {	
		if(typeof data.unidades.unidades != "undefined" ) {  
			//jsonTable = jQuery.makeArray(data.unidades.unidades);
			if(typeof data.unidades.totalRegistros != "undefined"){
				jQuery("#resultado-busca-unidades").html(data.unidades.totalRegistros);
				return data.unidades.totalRegistros;
			}else{
				jQuery("#resultado-busca-unidades").html(data.unidades.unidades[0].tamanhoRetornoBusca);
				return data.unidades.unidades[0].tamanhoRetornoBusca;
			}
		} else if(data.unidades.listaVazia == ""){
			jsonTable = data.unidades;
		} else{
			jQuery("#resultado-busca-unidades").html("Nenhuma");
			return 0;
			//jsonTable = data;
		}
	}else if( paramVerifica == "E" ) { //para receber portlet de empresa
		if(typeof data.empfiliadas.empresasFiliadas != "undefined" ) {  
			//jsonTable =  jQuery.makeArray(data.empfiliadas.empresasFiliadas);
			jQuery("#resultado-busca-unidades").html(data.empfiliadas.totalRegistros);
			return data.empfiliadas.totalRegistros;
		} else if (data.empfiliadas.listaVazia == ""){
			jsonTable = data.empfiliadas;
		} else{
			jQuery("#resultado-busca-unidades").html("Nenhuma");
			//jsonTable = data;
			return 0;
		}
	}
	jQuery("#resultado-busca-unidades").html(jsonTable.length);
	return jsonTable.length;
}

/**
* 
* recebe como paramentro um valor at� a quantidade desejada e retorna a pesquisa apartir do contador informado
* recupera a partir do filtro informado(AF, GM. etc);
* 
* @param  contador
* @param filtro
* @param idTable id do servi�o responsav�l par montar o div + sufixo
* @param sufixo complento do id do div para 
*/
function recuperarUnidadesPaginador( contador, paramAba, idTable, sufixo, paramVerifica, urlJson,paramBusca ){
	if (urlJson.indexOf("/soa/") < 0){
		urlJson = "/soa/" + urlJson;
	}

	urlJson = adicionarContextoUrlRest(urlJson);
	
//	$("a.unidadePagina").removeClass("activeSlide");
//	$(this).addClass("activeSlide");
	
	$.getJSON(urlJson+"="+idTable+"&paramAba="+paramAba+"&paramPagina="+contador+"&linkViewMode="+linkViewModeAlterado+"&paramBusca="+paramBusca, function(data,i){			
		var jsonTable = vereficaRetornoJsonUndefined(data, paramVerifica);		
		jsonTable = sublistaJson(jsonTable,numPorPg);
		gerarTabelaAgrupamentoEmpresas(jsonTable, idTable, "-base");
	});
}

/**
 * Recebe url REST para adicionar contexto
 * Retorno url REST com contexto configurado
 */
function adicionarContextoUrlRest(urlRestSemContexto){
	var urlRestComContexto = plcGeral.contextPath + urlRestSemContexto;
	return urlRestComContexto;
}

/**
 * retorna objeto json com o retorno da cidade pesquisada 
 *
 * @param textoCompletar, neste ponto e inserido o texto que ser� completado 
 */
 var filaEsperaPesquisa = new Array();
 function itemPesquisa (id, paramBusca, idPai, linkViewModeAlterado, paraVerifica, urljsonPesq, executado){
	this.id	   = id;	
	this.idPai = idPai;
	this.paramBusca = paramBusca
	this.linkViewModeAlterado = linkViewModeAlterado;
	this.paraVerifica = paraVerifica;
	this.urljsonPesq = urljsonPesq;
	this.executado = executado;
	this.dados = null;
}


var pesquisaAtual; 
var timeoutPesquisaUnidades;
function autoCompletarJsonTable(idPai, linkViewModeAlterado, paraVerifica, urljsonPesq) {
	if (urljsonPesq.indexOf("/soa/")<0){
		urljsonPesq="/ecp/soa/"+urljsonPesq;
	}

	var tempoEspera = 1000; //tempo para esperar a pr�xima tecla antes de pesquisar
	var tamanhoRetornoBusca;
    $("input#idUnidadePagina").keyup(function () {
		var paramBusca = $(this).val();	
		clearTimeout(timeoutPesquisaUnidades);
		timeoutPesquisaUnidades = setTimeout("pesquisarJsonUnidades('"+unescape(paramBusca)+"',"+ idPai +",'"+ linkViewModeAlterado+"','"+ paraVerifica+"','"+ urljsonPesq+"')",tempoEspera);
	});	
}

function pesquisarJsonUnidades(paramBusca, idPai, linkViewModeAlterado, paraVerifica, urljsonPesq){

	var idPesq = filaEsperaPesquisa.length;
	var umaPesquisa = new itemPesquisa(idPesq, paramBusca, idPai, linkViewModeAlterado, paraVerifica, urljsonPesq, false);
	filaEsperaPesquisa[filaEsperaPesquisa.length] = umaPesquisa;
//	timeoutPesquisaUnidades = setTimeout("executarUmaPesquisaJsonUnidades('"+ escape(umaPesquisa.paramBusca) +"',"+umaPesquisa.idPai+",'"+umaPesquisa.linkViewModeAlterado+"','"+umaPesquisa.paraVerifica+"','"+umaPesquisa.urljsonPesq+"',"+umaPesquisa.id+")",tempoEspera);
	executarUmaPesquisaJsonUnidades(escape(umaPesquisa.paramBusca), umaPesquisa.idPai, umaPesquisa.linkViewModeAlterado, umaPesquisa.paraVerifica, umaPesquisa.urljsonPesq, umaPesquisa.id);

}

function executarUmaPesquisaJsonUnidades(paramBusca, idPai, linkViewModeAlterado, paraVerifica, urljsonPesq, psqAtualId){

	pesquisaAtual = filaEsperaPesquisa[psqAtualId];
	$.getJSON(urljsonPesq+"="+idPai+"&paramAba="+ecpAbaSelecionada.abaSel+"&paramBusca="+unescape(paramBusca)+"&linkViewMode="+linkViewModeAlterado, function(data,i){
		//pesquisaAtual.executado = true;
		pesquisaAtual.dados = data;
/*
		if((filaEsperaPesquisa.length-1) > pesquisaAtual.id){
			for(i = 0; i < filaEsperaPesquisa.length; i++){
				var pesquisa = filaEsperaPesquisa[i];
				if(!pesquisa.executado){
					executarUmaPesquisaJsonUnidades(pesquisa.paramBusca, pesquisa.idPai, pesquisa.linkViewModeAlterado, pesquisa.paraVerifica, pesquisa.urljsonPesq, pesquisa);
				}
			}
		}
*/
		mostrarPesquisaJsonUnidades(pesquisaAtual);

	});
	showLoading(true);
}

function mostrarPesquisaJsonUnidades(pesquisa){
	var	jsonTable = vereficaRetornoJsonUndefined(pesquisa.dados, pesquisa.paraVerifica);	
	var jsonsub = sublistaJson(jsonTable, numPorPg);
	gerarTabelaAgrupamentoEmpresas( jsonsub, pesquisa.idPai, "-base" );						
	$(".prt-empresa-link").removeClass("current");			
	/*
	if( pesquisa.paramBusca.trim() == '' ) {
		montaNavegadorAgrupaUnidades( jsonTable, pesquisa.idPai, "-pagina", "T", pesquisa.paraVerifica );
		$(".prt-empresa-link-T").addClass("current");
	} else 
	*/
//	if( pesquisa.paramBusca.trim() != '') {
		//contador();	
		$(".prt-empresa-link-T").addClass("current");
		visualizaNovoNavegador(jsonTable, pesquisa.idPai, "-pagina", pesquisa.paraVerifica, determinaQuantidadeDeRegistros(pesquisa.dados,pesquisa.paraVerifica));											
//	}
	showLoading(false);
	//filaEsperaPesquisa = new Array();
}


function sublistaJson(jsonlista, numMin, numMax){

	numMim = numMin || 20;
	numMax = numMax || numMin;
	var jsonsublista = $.grep( jsonlista, function(obj, index){ 
		if(numMax > numMin){
			return (index >= numMin || index <= numMax); 
		}else{
			return (index <= numMax); 
		}
	});
	return jsonsublista;
}

function showLoading(active) {
	
    if (active === false) {
        $('#partial-loading').remove();
		jQuery("#texto-resultado").css("display","block");
    } else {
		jQuery("#texto-resultado").css("display","none");
        var el = $('#partial-loading');
        if (el.length == 0) {
            var el = $('<div id="partial-loading" class="partial-loading"/>');
            if ($('.busca-unidades').length != 0) {
                $('.busca-unidades').append(el);
            }  else {
                $('body').append(el);
            }
        } else {
            el.show();
        }
    }	
}

/*
var cont = 5;
function contador() {
	
	$('.busca-unidades').innerHTML = cont;
	
	if(cont == 0) {
		showLoading(false);
	}
	if (cont != 0){
		cont = cont-1;
		setTimeout("contador()", 1000);
	}
}
*/

function mostrarUnidadesAdicionadas(unidadesAdicionadas, transformarCampoEmTexto){
	
	//setTimeout("jqBlockUI.gerarMensagem(optsBlock)",0);
	var numUnidades = jQuery(unidadesAdicionadas["unidades"]).length;
	jQuery.each(unidadesAdicionadas["unidades"],function(k,j){
		var item = this;
		if (item["ecoEmpresaServico.nomeEcoEmpresa"]){
			if (k==0){
		    	jQuery("div.unidades-selecionadas").hide();
		    	//setTimeout("jqBlockUI.gerarMensagem(optsBlock)",0);
			}
			var div = jQuery("<div/>")
			var itensEscondidos = "<input type=\"hidden\" name=\"ecoEmpresaServico.idEcoEmpresa\" value=\""+item["ecoEmpresaServico.idEcoEmpresa"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.id\" value=\""+item["ecoEmpresaServico.id"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.versao\" value=\""+item["ecoEmpresaServico.versao"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.nomeEcoEmpresa\" value=\""+item["ecoEmpresaServico.nomeEcoEmpresa"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.cidadeEcoEmpresa\" value=\""+item["ecoEmpresaServico.cidadeEcoEmpresa"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.nomePaiEcoEmpresa\" value=\""+item["ecoEmpresaServico.nomePaiEcoEmpresa"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.idPaiEcoEmpresa\" value=\""+item["ecoEmpresaServico.idPaiEcoEmpresa"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.ufEcoEmpresa\" value=\""+item["ecoEmpresaServico.ufEcoEmpresa"]+"\">";
			itensEscondidos += "<input type=\"hidden\" name=\"ecoEmpresaServico.idAtividadeEconomica\" value=\""+item["ecoEmpresaServico.idAtividadeEconomica"]+"\">";
			var imagem = "";
			if(transformarCampoEmTexto == "" || transformarCampoEmTexto != "S"){
				if (item["ecoEmpresaServico.idAtividadeEconomica"] == "9"){
					imagem = "<img class='img-unidade-remover' src=\"/ecp/midia/ico-excluir-servico.gif\" onclick=\"jQuery(this).parent(0).remove()\" />";
				}
			}
			var texto = "<p>"+item["ecoEmpresaServico.nomeEcoEmpresa"]+"</p>"
			texto += "<span>"+((item["ecoEmpresaServico.nomePaiEcoEmpresa"])?item["ecoEmpresaServico.nomePaiEcoEmpresa"]+" - ":"")+item["ecoEmpresaServico.cidadeEcoEmpresa"]+"/"+item["ecoEmpresaServico.ufEcoEmpresa"]+"</span>";
			div.html(itensEscondidos+imagem+texto);
			setTimeout(function(){anexaItem(k,div,numUnidades);},0);
		}else{
			numUnidades--;
		}
	});
	
}

function anexaItem(k,div,numUnidades){
	var indice = k; //arguments[0];
	jQuery("div.unidades-selecionadas").append(jQuery(div));
	if (indice==numUnidades-1){
		jQuery("div.unidades-selecionadas").show();	
		desbloquearPaginaServicos(false);
	}
}

function desbloquearPaginaServicos(forcado){
	
	//clearTimeout(timeoutBloqueio);
	//jqBlockUI.desbloquearPagina();
	setVarGlobal("IMPRESSAO_LIBERADA","S");
	
}

/*****************************************************************************\
				MEU PORTAL
\*****************************************************************************/
function mensagemAdicionarPortlet(){
	jqBlockUI.gerarMensagem({message:  "Aguarde, adicionando portlet ...", width:'500px' });
}

jqUISortable.aoMudarDragDrop = function (bandas){
		var fazerRefresh = false;
		for(var indB = 0; indB < bandas.length; indB++){
			var idContainer = jQuery("#"+bandas[indB].id).attr("idContainer");
			if(idContainer != "selecaoMeuportalPlc"){
				if(fazerRefresh){
					mensagemAdicionarPortlet();
				}
				var portlets = jQuery(bandas[indB].o).attr(bandas[indB].id);
				for(var indP = 0; indP < portlets.length; indP++){
					gravaPosicaoPortlet("", portlets[indP], (indP + 1 * 2), idContainer);
				}
			}else{
				fazerRefresh = true;
			}
		}
		if(fazerRefresh){
			location.reload(true);
		}
}

/*****************************************************************************\
								PORTLETS
\*****************************************************************************/

//Executa as configura��es de layout de todos os portlets ap�s carregamento da p�gina
function configuraLayoutPortlets(){

	//CONTEUDO
	jQuery(".prt-noticia-view-lista").css("margin","3px").css("padding","0");
	jQuery(".prt-noticia-item").css("display","inline");
	jQuery(".prt-noticia-item-cabecalho").css("font-weight","bold");

} 

//Redimensiona portlet de iframe
function redimensionaIframe(seletor){

/*
	var funcResize = function(){
		var hgt		= $($($(seletor).attr("contentWindow").document).attr("body")).attr("offsetHeight");
		var scrHgt	= $($($(seletor).attr("contentWindow").document).attr("body")).attr("scrollHeight");
		hgt = scrHgt > hgt ? scrHgt : hgt;
		$(seletor).css("height", hgt).css("overflow","visible");
	}
	setTimeout(function() { try{funcResize();}catch(e){} },100);
*/

	jqEventResize.redimensionarIframeAutomatico(seletor);
	
}

//Portlet formul�rio
function montarConfirmacaoFormulario(){

	var portletForm =	opener.getElementoPorId(opener.prtFormEntrada);
	var txtSaida	= 	portletForm.elements['txtSaida'].value;
	var camposForm 	= 	portletForm.elements['camposForm'].value;
	var titulo 		= 	portletForm.elements['titulo'].value;
	var btEnvia 	= 	portletForm.elements['btEnvia'].value;
	var btCancela 	= 	portletForm.elements['btCancela'].value;

	var strForm = 
			"<form name=\"popupForm\" action=\""+portletForm.action+"\"  id=\"PRT-FORM-SAIDA\"  method=\"POST\" enctype=\""+portletForm.enctype+"\" accept-charset=\"UTF-8\" >";

	var formValoresStr	= opener.jqGetFormValores();
//	formValoresStr		= unescape(formValoresStr);
	var formValores		= formValoresStr.split("&");
	var formElements		= portletForm.elements;
	var formCampo		= null;

	var nomeCampo	= "";
	var valCampo	= "";
	var valTxtSaida = "";
	for(f = 0; f < formValores.length; f++){
		formCampo	= formValores[f].split("=");
		nomeCampo	= formCampo[0];
		valCampo	= formCampo[1];
		formCampo	= portletForm.elements[nomeCampo];

//		valCampo	= unescape(formCampo[1]);
//		nomeCampo	= formCampo.name;
		if(typeof formCampo.type != "undefined" && formCampo.type != "select" && formCampo.type != "radio"){
			valCampo	= portletForm.elements[nomeCampo].value;
		}
		valCampo	= valCampo.replace("+"," ");

		if(nomeCampo != "txtSaida"){
			strForm += "<input  type=\"hidden\" name=\""+nomeCampo+"\" value=\""+valCampo+"\">"
		}
		txtSaida = txtSaida.replace("$"+nomeCampo+"$",valCampo);
	}

	camposForm = camposForm.split(",");
	for(f2 = 0; f2 < camposForm.length; f2++){
		txtSaida = txtSaida.replace("$"+camposForm[f2]+"$","Vazio");
	}

	strForm += "<textarea name=\"txtSaida\" style=\"position: absolute; top: -100px; visibility: hidden;\">"+txtSaida+"</textarea>";

	txtSaida = txtSaida.replace("$BOTAO_CONFIRMAR$","$botao_confirmar$");
	txtSaida = txtSaida.replace("$BOTAO_LIMPAR$","$botao_limpar$");
	txtSaida = txtSaida.replace("$BOTAO_ENVIAR$","$botao_enviar$");
	txtSaida = txtSaida.replace("$BOTAO_CANCELAR$","$botao_cancelar$");

	var strBtEnviar		= "<input  id=\"PRT-FORM-BT-ENVIAR\" type=\"submit\" name=\"enviar\" value=\"Enviar\" >";
	var strBtCancelar	= "<input  id=\"PRT-FORM-BT-CANCELAR\" type=\"button\" name=\"cancelar\" value=\"Cancelar\"  onclick='window.close();'>";

	if(!btEnvia == "") {
		if(txtSaida.indexOf("$botao_enviar$") > -1) {
			txtSaida = txtSaida.replace("$botao_enviar$",strBtEnviar.replace("Enviar",btEnvia));
		}else {
			txtSaida += strBtEnviar;
		}
	}else {
		if(txtSaida.indexOf("$botao_enviar$") > -1) {
			txtSaida = txtSaida.replace("$botao_enviar$",strBtEnviar);
		}else {
			txtSaida += strBtEnviar;
		}	
	}
	
	if(!btCancela == "") {
		if(txtSaida.indexOf("$botao_cancelar$") > -1) {
			txtSaida = txtSaida.replace("$botao_cancelar$",strBtCancelar.replace("Limpar",btCancela));
		}else {
			txtSaida += "&nbsp;"+strBtCancelar;
		}
	}else {
		if(txtSaida.indexOf("$botao_cancelar$") > -1) {
			txtSaida = txtSaida.replace("$botao_cancelar$",strBtCancelar);
		}else {
			txtSaida += "&nbsp;"+strBtCancelar;
		}
	}

	strForm += txtSaida;
	strForm += "</form>";

	//document.getElementById("CONFIRMACAO_FORMULARIO").innerHTML = strForm;
	jQuery("#CONFIRMACAO_FORMULARIO").html(strForm);

}

var prtFormEntrada = "PRT-FORM-ENTRADA";
function confirmaFormulario(){
	$("div#PRT-FORM-VALIDATE-ERROR").text("").css("display","none");
	jqValidarForm(prtFormEntrada, regras);
}

function jqLimparFormulario(){
	if(confirm("Tem certeza que deseja limpar todos os dados do formul�rio?")){
		getElementoPorId(prtFormEntrada).reset();
	}
}

function jqGetFormValores(){
	return $("#"+prtFormEntrada).serialize();
}

function jqValidarForm(nomeForm, regras){

	$("#"+nomeForm).validate({
		rules: regras,
		errorPlacement: function(error, element) {
			var imgError = "<img id='PRT-FORM-VALIDATE-ERROR-IMG' src='"+plcGeral.contextPath+"/plc/midia/ico_status_erro.gif' border='0' align='absmiddle'>&nbsp;";
			var nomeElemento	= element.attr("name");
			var msgElemento		= error.html();
			var nomeCampo		= $(".frm-"+nomeElemento).html();
			if(typeof nomeCampo == "undefined" || nomeCampo == "" || nomeCampo == null){
				if($("label[for='"+nomeElemento+"']").size() > 0){
					nomeCampo		= $("label[for='nomeElemento']").text();
				}else{
					nomeCampo = "";
					var nomeClasse 	= $(element).attr("class");
					var arrClasses	= nomeClasse.split(" ");
					for(var ic = 0; ic < arrClasses.length && nomeCampo == ""; ic++){
						if($("label[for='"+arrClasses[ic]+"']").size() > 0){
							nomeCampo = $("label[for='"+arrClasses[ic]+"']").text();
							nomeCampo = nomeCampo.replace(" *","");
							nomeCampo = nomeCampo.replace("*","");
						}
					}
				}
			}
			msgElemento = imgError + msgElemento.replace("{nomeCampo}", nomeCampo);
			error.html(msgElemento);
			$("div#PRT-FORM-VALIDATE-ERROR").append(error);
			$("div#PRT-FORM-VALIDATE-ERROR").css("display","block");
		}
	});
}


/*****************************************************************************\
					ORGANIZA��O AUTOM�TICA M�LTIPLA
\*****************************************************************************/

var indiceAtual		= 0;
var indicesRemovidos= "";
var taxAdicionadas	= "#";

function antesDevolveSelecaoTreePopup(listaValores){
	var parValores	= listaValores.split(",");
	var valores		= parValores[0].split("#");
	
	if(taxAdicionadas.indexOf("#"+valores[1]+"#") > -1){
		alert(getVarGlobal("avisoTaxonomiaDuplicada"));
		return false;
	}

	registraCamposDevolveSelecaoTreePopup(indiceAtual);
	var novaLinha =  getNovaLinhaTaxonomia(indiceAtual, "", false);
	$(novaLinha).appendTo("#id-tabela-organizar-tax");
	incluiTaxAdicionada(valores[1]);
	return true;
}

function aposDevolveSelecaoTreePopup(listaValores){
	var hierarquia = jQuery("#id-hierarquia-tax-"+indiceAtual).val();
	//Retira nivel pai da organiza��o
	hierarquia = hierarquia.substr(hierarquia.indexOf("/")+1,hierarquia.length);
	jQuery("#id-hierarquia-tax-"+indiceAtual).val(hierarquia);
	indiceAtual++;
	jQuery("#id-img-tax-"+indiceAtual).css("display","block");
}

function registraCamposDevolveSelecaoTreePopup(indice){
	camposRetorno = registrarCamposRetorno('detalheOrganizacao['+indice+'].idTaxonomia#id,detalheOrganizacao['+indice+'].nomeTaxonomiaAux#nome,detalheOrganizacao['+indice+'].endDiretorio#hierarquia', "nome,id", "");
}

function incluiTaxAdicionada(novaTax){
	taxAdicionadas += novaTax+"#";
}

function setExclusao(check){
	if(check.checked){
		check.value = "S";
	}else{
		check.value = "N";
	}
}

function removerTaxonomia(indice){

	taxAdicionadas = taxAdicionadas.replace(jQuery("#id-codigo-tax-"+indice).val()+"#","");
	jQuery("#id-indexc-tax-"+indice).val("S");
	jQuery("#id-linha-tax-"+indice).remove();
}

/*****************************************************************************\
								JQUERY SORT
\*****************************************************************************/
function JQSort(){};

var jqSort = new JQSort();


JQSort.prototype.ordenar = function(seletor, atributo){

	$(seletor).sortElements(function(primeiro, ultimo){
		if(typeof atributo == "undefined"){
			return $.trim($(primeiro).text()) > $.trim($(ultimo).text()) ? 1 : -1;
		}else{
			return $.trim($(primeiro).attr(atributo)) > $.trim($(ultimo).attr(atributo)) ? 1 : -1;
		}
	});
}

function atualizarBarraProgresso(seletor, propProgresso, propTotal){
	
	var opcoes = {	
			intervalo:3000
	};
	
	var url = "${pageContext.request.contextPath}/soa/progresso/"+propProgresso+"/"+propTotal;
	jQuery.ajax(
			{url:url,
				scriptCharsetString:"UTF-8",
				contentType:"application/x-www-form-urlencoded; charset=UTF-8",
				success:function(data, textStatus, XMLHttpRequest){
				jQuery(seletor).html(data);
		}});
}

/*****************************************************************************\
							JQUERY EVENT RESIZE
\*****************************************************************************/
function JQEventResize(){};

var jqEventResize = new JQEventResize();

JQEventResize.prototype.redimensionarIframeAutomatico= function(seletor){

	// Append an iFrame to the page.
	var iframe = jQuery(seletor);
	
	//Adiciona evento de redimensionamento ao carregar IFRAME
	iframe.load(function(){
		//Recupera o corpo do IFRAME
		var iframe_content = iframe.contents().find('body');
		//Adiciona o evento resize ao corpo do IFRAME. 
		//Assim, altera��es no tamanho do IFRAME ir�o alterar tamanho deste na p�gina
		iframe_content.resize(function(){
			var elem = $(this);
			// Resize the IFrame.
			iframe.css({ height: (elem.outerHeight( true )+20) });
		});
		iframe_content.resize();
	});
}

function redimensionaIframeNovo(seletor){
	jQuery("body",document).resize(function(){
		acertaTamanhoIframe(seletor);
	});
	acertaTamanhoIframe(seletor);
}

function acertaTamanhoIframe(seletor){
	jQuery(parent.document).find(seletor).height(jQuery("body",document).height()+20);
}

function redimensionarAlturaTabelaPrincipal(novaAltura){
	jQuery("table.principal").css("height", jQuery("table.principal").height() + novaAltura);
}

/*****************************************************************************\
							JQUERY TIMER
\*****************************************************************************/
function JQTimer(){};

var jqTimer = new JQTimer();

JQTimer.prototype.opcoesTimer = {
		dataTimer: new Date()
		,seletor: "#id-timer"
		,timeout: 3600 				//em segundos
		,periodo: 1					//em minutos
		,sessaoTempoUsa: "S"
		,sessaoManter: "N"
		,sessaoReconectarUsa: "N" 
		,sessaoMsgTempo: "<b>Sua sessao expira em: $TIMEOUT_SESSAO$</b>" 
		,sessaoFunc: "jqTimer.iniciarTempoSessao(opts.seletor)"
		,funcPeriodo: "jqTimer.atualizarTimeoutSessao(opts.seletor)"
		,urlPeriodo: "/ecp/ecpportlet.do"
};

JQTimer.prototype.iniciarTempoSessao = function(opts){

	if(typeof opts == "string"){
		opts = getVarGlobal(opts);
	}

	opts = $.extend(jqTimer.opcoesTimer, opts);

	var dataTimer 	= new Date();
	opts.dataTimer.setHours(0);
	opts.dataTimer.setMinutes(0);
	opts.dataTimer.setSeconds(opts.timeout);
	var timerTimeout = setTimeout("jqTimer.mostrarTempoRestanteSessao('"+opts.seletor+"')",1000);
	opts.timerTimeout = timerTimeout;
	setVarGlobal(opts.seletor, opts);
};

JQTimer.prototype.mostrarTempoRestanteSessao = function(opts){
	
	if(typeof opts == "string"){
		opts = getVarGlobal(opts);
	}
	clearTimeout(opts.timerTimeout);
	opts.dataTimer.setSeconds(opts.dataTimer.getSeconds()-1);
	var tempoTimeout = "";
	if(opts.dataTimer.getHours() == 0 && opts.dataTimer.getMinutes() == opts.periodo && opts.dataTimer.getSeconds() == 0 &&
	   opts.sessaoManter == "S"){
		
		eval(opts.funcPeriodo);

	}else{
		var timerTimeout = setTimeout("jqTimer.mostrarTempoRestanteSessao('"+opts.seletor+"')",1000);
		opts.timerTimeout = timerTimeout;
		setVarGlobal(opts.seletor, opts);
	}
		
	if(opts.sessaoTempoUsa != "N"){

		if(opts.dataTimer.getHours() == 0 && opts.dataTimer.getMinutes() == 0 && opts.dataTimer.getSeconds() == 0){
			tempoTimeout = "<a href='javascript:location.href = location.href' class='bt'>Reconectar</a>";
			jQuery(opts.seletor+" .prt-temposessao-expirou").css("display","block");
			jQuery(opts.seletor+" .prt-temposessao-expira").css("display","none");
			if(opts.sessaoReconectarUsa != "N"){
				jQuery(opts.seletor+" .prt-temposessao-expirou .prt-temposessao-timeout-reconectar").html(tempoTimeout);
			}
		}else{
			tempoTimeout = opts.dataTimer.getMinutes()+"min "+opts.dataTimer.getSeconds()+"s"
			if(opts.dataTimer.getHours() > 0){
				tempoTimeout = opts.dataTimer.getHours()+"hs "+ tempoTimeout
			}		
			jQuery(opts.seletor+" .prt-temposessao-expira").css("display","block");
			jQuery(opts.seletor+" .prt-temposessao-expira .prt-temposessao-timeout").html(tempoTimeout);
			jQuery(opts.seletor+" .prt-temposessao-expirou").css("display","none");
		}
	}

		
	
};


JQTimer.prototype.executarPeriodicoSessao = function (opts){

	if(typeof opts == "string"){
		opts = getVarGlobal(opts);
	}

	var optsAjax = {
		url: opts.urlPeriodo
		,type: "GET"
		,dataType:"html"
		,success: function(html) { 
			eval(opts.sessaoFunc);
		}
		,error:	function() { 
		}
	};

	try{
		$.ajax(optsAjax);
	}catch(e){}
};


JQTimer.prototype.atualizarTimeoutSessao = function (opts){

	if(typeof opts == "string"){
		opts = getVarGlobal(opts);
	}

	var	optsTimeout = {
		urlPeriodo: "/ecp/ecpportlet.do"
		,sessaoFunc: "jqTimer.iniciarTempoSessao(opts.seletor)"
	};
	
	opts = $.extend(opts, optsTimeout);

	jqTimer.executarPeriodicoSessao(opts);
};


function informarTotalRegistros(labelTotal, total){
	if(jQuery(".lista")){
		jQuery("<tr><td colspan='"+jQuery(".lista").find("tr:first").find("> td").length+"' class='subsecao'>"+labelTotal+" "+total+"</td></tr>")
		.insertBefore(jQuery(".lista").find("tr:first"));
	}
}


/*****************************************************************************\
							PORTLET PESQUISA AGRUPADA
\*****************************************************************************/

function initPesqComponente(paramObj){

	paramObj.paramPagina	= 1;
	paramObj.paramNome		= "T";

	//Montagem dos navegadores por nome e por p�gina
	montarNavegadorNomes(paramObj);

	//Montagem dos dados iniciais
	montarDadosIniciais(paramObj);

	var timeoutPesquisa;
	jQuery("#"+paramObj.idTermo).val("")
	.keyup(function(){
	
		clearTimeout(timeoutPesquisa);
		var termo = $(this).val();
		if(termo == "" || termo.length >= 3){
			timeoutPesquisa = setTimeout("recuperarPesqPorTermo('"+termo+"')", 500);
		}
		return true;

	});

}

/*Recupera a lista inicial de dados*/
function montarDadosIniciais(paramObj){

	if(paramObj.listaInicial != 'S'){
		return;
	}

	paramObj.urlJson		= paramObj.urlJsonPesq;
	paramObj.paramPagina	= 1;
	paramObj.paramNome		= "T";
	ajustarPesqUrlJson(paramObj);
	montarTabelaDados(paramObj);

}

/**
 *  Monta a tabela com dados iniciais
 */
function montarTabelaDados(paramObj) {
	
	$.getJSON(paramObj.urlJson, function(data,i){

		var tabelaJson = data.listapesquisa.resultados;
		if(tabelaJson){
			var subListaJson	= getSubListaJson(tabelaJson, paramObj);
			
			if(tabelaJson.tamanhoRetornoBusca == 1){
				subListaJson	= jQuery.makeArray(tabelaJson);
			}

			montarPesqDados(subListaJson, paramObj);

			if(paramObj.listaInicial != 'S'){
				ecpQuantidadeParametro = {"qttotal": subListaJson[0].tamanhoRetornoBusca};
			}
			montarPesqNavegador(tabelaJson, paramObj);
			$("#"+paramObj.idResultado+"-nenhum-resultado").css("display","none");
			$("#"+paramObj.idNavegador).css("display","block");

			//Destacar itens ativos	
			$(".prt-pqa-nome-link").removeClass("ativo");
			$("a#id-prt-pqa-nome-link-"+paramObj.paramNome).addClass("ativo");
			$(".prt-pqa-navegador-item ativo").removeClass("ativo");
			$("a#id-prt-pqa-navegador-item-"+paramObj.paramPagina).addClass("ativo");

		}else{
			$("#"+paramObj.idNavegador).css("display","none");
			$("#"+paramObj.idResultado).css("display","none");
			$("#"+paramObj.idResultado+"-nenhum-resultado").css("display","block");
		}

	});
}

/**
 * Recebe url e par�metros para pesquisa de dados
 */
function montarNavegadorNomes(paramObj ) {	

	if(paramObj.filtroNomes != 'S' || paramObj.listaInicial != 'S'){
		return;
	}

	if($("#prt-pqa-filtro-nome").size() > 0){
		$("#prt-pqa-filtro-nome").css("display","block");
	}

	paramObj.urlJson = paramObj.urlJsonQtdeNome;

	ajustarPesqUrlJson(paramObj);

	$.getJSON(paramObj.urlJson, function(data, sitReq){
		
		var tabelaJSon = data.listapesquisa.quantidades;
		
		montarPesqNomeQuantidade(tabelaJSon);
		
	});
}

/**
* Monta o cabe�alho de navega��o de nomes por quantidades
*/
var ecpQuantidadeParametro;
var ecpAbaSelecionada;
function montarPesqNomeQuantidade(tabelaJSon){
	
	ecpQuantidadeParametro = {"qttotal": tabelaJSon.quantidadeTotal , "qtaf": tabelaJSon.quantidadeAF, "qtgm": tabelaJSon.quantidadeGM, "qtns": tabelaJSon.quantidadeNS, "qttz": tabelaJSon.quantidadeTZ} 

	$(".prt-pqa-nome-count-T").html("").append("("+tabelaJSon.quantidadeTotal+")")
	$(".prt-pqa-nome-count-AF").html("").append("("+tabelaJSon.quantidadeAF+")")
	$(".prt-pqa-nome-count-GM").html("").append("("+tabelaJSon.quantidadeGM+")")
	$(".prt-pqa-nome-count-NS").html("").append("("+tabelaJSon.quantidadeNS+")")
	$(".prt-pqa-nome-count-TZ").html("").append("("+tabelaJSon.quantidadeTZ+")")
			
	ecpAbaSelecionada = {"abaSel": "T"};

}

/**
 * Recebe uma tabela contedo a quantidade de dados que seram apresentados durante a navega��o. 
 */
function montarPesqNavegador(tabelaJSon, paramObj) {

	switch( paramObj.paramNome ) {
		case 'T':
			paramObj.qtdeAba = ecpQuantidadeParametro.qttotal;
			break;
		case 'AF':
			paramObj.qtdeAba = ecpQuantidadeParametro.qtaf;
			break;
		case 'GM':
			paramObj.qtdeAba = ecpQuantidadeParametro.qtgm;
			break;
		case 'NS':
			paramObj.qtdeAba = ecpQuantidadeParametro.qtns;
			break;
		case 'TZ':
			paramObj.qtdeAba = ecpQuantidadeParametro.qttz;
			break;
	}
	
	var htmlPesquisa = montarPesqLinksNavegador(paramObj );		
	
	$("#"+ (paramObj.idNavegador)).children().remove();
	if(typeof htmlPesquisa != "undefined"){
		$(htmlPesquisa).appendTo("#"+ (paramObj.idNavegador));	
	}

}

/*
* Retorna links que seram utilizados no navegador
*/
function montarPesqLinksNavegador(paramObj) {
	
	var linksJsonTable = "";
	var numeroPaginas = Math.ceil(paramObj.qtdeAba/paramObj.navNumeroPorPagina);
	var paramBusca = $("#"+(paramObj.idNavegador)+" input[name='termoPesquisa']").val()
	
	if(numeroPaginas > 1){
		for ( var contador = 1; contador <= numeroPaginas; contador++ ) {
			linksJsonTable += "<a href='#' id='id-prt-pqa-navegador-item-"+contador+"' onclick=\"recuperarPesqResultadosNavegador('"+contador+"','"+paramObj.paramNome+"','"+paramObj.urlJson+"','"+linkViewMode+"'); return false;\"' class='prt-pqa-navegador-item'> "+contador+"</a>";
		}		
		var htmlBusca = linksJsonTable;
	}

	return htmlBusca;
}

function recuperarPesqResultadosNavegador( paramPagina, paramNome, urlJson, linkViewMode){

	paramObj.paramPagina	= paramPagina;
	paramObj.linkViewMode	= linkViewMode;
	paramObj.urlJson		= paramObj.urlJsonPesq;

	ajustarPesqUrlJson(paramObj);
	montarTabelaDados(paramObj);

}

function recuperarPesqPorTermo(termo){

	if(termo == ""){
		if(paramObj.listaInicial != 'S'){
		   if($("#"+paramObj.idResultado).size() > 0){
				$("#"+paramObj.idResultado).css("display","none");
		   }
		   if($("#"+paramObj.idNavegador).size() > 0){
				$("#"+paramObj.idNavegador).css("display","none");
		   }
		   if($("#"+paramObj.idResultado+"-nenhum-resultado").size() > 0){
				$("#"+paramObj.idResultado+"-nenhum-resultado").css("display","none");
		   }
		   return;
		}
		paramObj.paramNome		= "T";
	}

	montarNavegadorNomes(paramObj);

	paramObj.paramPagina	= 1;
	paramObj.urlJson		= paramObj.urlJsonPesq;
	ajustarPesqUrlJson(paramObj);
	montarTabelaDados(paramObj);

}

/**
* Monta os dados da pesquisa para visualiza��o
*/
function montarPesqDados(tabelaJSon, paramObj){
	
	var resultadoTabela			= $("#"+paramObj.idResultado);
	var resultadoTabelaTemplate = $("#"+paramObj.idResultado+"-template");
	if(resultadoTabelaTemplate.length == 0){
		$(resultadoTabela).clone().attr("id", paramObj.idResultado+"-template").insertBefore(resultadoTabela);
		resultadoTabelaTemplate = $("#"+paramObj.idResultado+"-template");
	}
	var resultadoLinha	= resultadoTabelaTemplate.find("tbody").html();
	resultadoTabela.find("tbody").find("tr").remove();
	var campos				= paramObj.campos.split(",");

	count = 0;
	$.each( tabelaJSon, function(sitResposta, data) {
			
			var resLinhaAux = resultadoLinha;
			for(i = 0; i < campos.length; i++){
				resLinhaAux = resLinhaAux.replace("$"+campos[i].toUpperCase()+"$", eval("data."+campos[i]));
			}
			resLinhaAux = antesFinalizarMontarPesqDados(data, resLinhaAux);
			$(resLinhaAux).appendTo(resultadoTabela.find("tbody"));
			count++;			
	});		 
	
	if($("#"+paramObj.idResultado).size() > 0){
		$("#"+paramObj.idResultado).css("display","block");
	}
}

function antesFinalizarMontarPesqDados(data, html){}

/**
 * Recebe como paramentro iniciais de palavras para realizar a pesquisa via REST.
 */
function filtrarPesqPorIniciaisNome( filtro ) {
	
	paramObj.urlJson		= paramObj.urlJsonPesq;
	paramObj.paramPagina	= 1;
	paramObj.paramNome		= filtro;

	ajustarPesqUrlJson(paramObj);
	montarTabelaDados(paramObj);

}

/**
 * Monta uma sublista de dados de um lista jSon
 */
function getSubListaJson(listaJson, paramObj){

	var numMin = paramObj.paramPagina - 1 || 0;
	var numMax = paramObj.navNumeroPorPagina || 20;
	var subListaJson = $.grep( listaJson, function(obj, index){ 
		if(numMax > numMin){
			return (index >= numMin || index <= numMax); 
		}else{
			return (index <= numMax); 
		}
	});
	return subListaJson;
}


function ajustarPesqUrlJson(paramObj){

	var urlJson = ajustarUrlJson(paramObj.urlJson);
	var termo	= $("#"+paramObj.idTermo).val();
	paramObj.paramTermo = termo;
	urlJson = urlJson + "?linkViewMode="+paramObj.linkViewMode +
						"&navNumeroPorPagina="+paramObj.navNumeroPorPagina +
						"&paramPagina="+paramObj.paramPagina +
						"&paramTermo="+paramObj.paramTermo +
						"&paramNome="+paramObj.paramNome;
	paramObj.urlJson = urlJson;

}


function ajustarUrlJson(urlJson){
	if (urlJson.indexOf("/soa/") < 0){
		urlJson="/soa/"+urlJson;
	}
	urlJson = adicionarContextoUrlRest(urlJson);
	return urlJson
}

/*****************************************************************************\
							REQUEST/RESPONSE PROFILE 
\*****************************************************************************/

function ligaDesligaProfile(){
	var url = document.location.href;
//	var ligado = "${sessionScope.COLETA_PROFILE_LIGADO}";

	url = removerParametroUrl(url, "lpf");

	if(ligado == 'S'){
		url = incluirParametroUrl(url, "lpf","n");
	}else{
		url = incluirParametroUrl(url, "lpf","s");
	}
	redirect(url);
}

function mostraDadosProfile(){
	//var ligado = "${sessionScope.COLETA_PROFILE_LIGADO}";
	if(ligado == 'S'){
		var popProfile = janelaMaximizada("");
		var browseProfile = montaDadosBrowser(profileBrowse);
		var htmlProfile = $("#COLETA_PROFILE_HTML").html();
		popProfile.document.write(htmlProfile + browseProfile );
		popProfile.window.focus();
	}
}
function coletarProfile(){
	profileBrowse = new Profile("Browser","chegada", new Date());
}

var profileBrowse = "";
function Profile (nome, acao, data){
	this.nome = nome;
	this.acao = acao;
	this.data = data;
}
function montaDadosBrowser(profile){

	var htmlProfileBrowse = "<table class='delimitador' cellpadding='2' cellspacing='2'>";
	htmlProfileBrowse += "<tr><td>Nome</td><td>"+profile.nome+"</td></tr>";
	htmlProfileBrowse += "<tr><td>A&ccedil;&atilde;o</td><td>"+profile.acao+"</td></tr>";
	htmlProfileBrowse += "<tr><td>Data Cliente</td><td>"+profile.data.getDate()+"/"+(profile.data.getMonth()+ 1)+"/"+profile.data.getFullYear()+" "; htmlProfileBrowse += profile.data.getHours()+":"+profile.data.getMinutes()+":"+profile.data.getSeconds()+"</td></tr>";
	htmlProfileBrowse += "</table>";

	return htmlProfileBrowse;
}


/*****************************************************************************\
					PORTLET AJUDA TOOLTIP 
\*****************************************************************************/
function mostrarAjudaOnClick(evt,tituloAjuda,textoAjuda){
	//criarTooltip(evt,'AJUDA',textoAjuda,'ONCLOSE','ALTURA',200,'LARGURA',350,'LABELCLOSE','Fechar','TITULO',tituloAjuda,'ONMOVE','CLASSECONTEUDO','sobre');

	var optsAjuda = {
			mensagem: textoAjuda
			,title: tituloAjuda
//			,height: 200
			,width: 350
			,closeText: "Fechar"
			,modal: true
	};
	
	jqMensagem.criar(optsAjuda);
}

/*****************************************************************************\
						JQUERY DIALOG / TOOLTIP
					  Utilizando jQuery UI Dialog
\*****************************************************************************/
function JQMensagem(){};

var jqMensagem = new JQMensagem();

JQMensagem.prototype.optsMsg = {
		seletor: ''
		,mensagem: ''
		,title: ''
		,closeText: "X"
};

JQMensagem.prototype.criar = function (opts){
	var divMensagem = $("<div id='id-mensagem'>"+opts.mensagem+"</div>");
	opts = $.extend(jqMensagem.optsMsg, opts);
	opts.seletor = divMensagem;
	jqMensagem.mostrar(opts);
}
JQMensagem.prototype.mostrar = function (opts){
	
	opts = $.extend(jqMensagem.optsMsg, opts);
	$( opts.seletor ).dialog(opts);
}

/***********************************************************************************
						PORTLET MENU REDE SOCIAL
************************************************************************************/

function JQSocial(){};

var jqSocial = new JQSocial();

JQSocial.prototype.optsFB = {
	appID: ''
	,siteTitle: ''
	,siteName: ''
	,href:''
	,mode: 'insert'
	,showfaces: true
	,layout: 'normal'	//box_count|button_count|standard
	,action: 'like'		// like|recommend
	,send:true
	,comments:false
	,lang: 'pt_BR'
	,onlike: function(){return true;}
	,onunlike: function(){return true;}
};

JQSocial.prototype.jqGetImagemCompartilharApos = function(rsImagem){ return rsImagem};

JQSocial.prototype.getImagemCompartilhar = function(seletor, rsImagem, servidorHomologa){
	var jqImagens = jQuery("img",seletor);
	if(jqImagens.size() > 0){
		rsImagem = jqImagens.get(0).src;
	}
	rsImagem = jqSocial.jqGetImagemCompartilharApos(rsImagem);
	if(servidorHomologa != ""){
		rsImagem = rsImagem.replace("localhost:8080",servidorHomologa);
		rsImagem = rsImagem.replace("localhost",servidorHomologa);
	}
	return rsImagem;
};

JQSocial.prototype.optsTW = {
	user:''
	,title:''
	,url: ''
	,layout: 'none'		//vertical|horizontal|none
	,action: 'tweet'	//tweet|follow
};  

JQSocial.prototype.optsGP = {
  	size: 'standard'										
	,count: false	
	,url: false
}  

JQSocial.prototype.gerarFacebook = function (seletor, opts){
	opts = $.extend(jqSocial.optsFB, opts);
	$(seletor).fbjlike(opts);
}

JQSocial.prototype.gerarTwitter = function (seletor, opts){
	opts = $.extend(jqSocial.optsTW, opts);
	$(seletor).twitterbutton(opts);
}

JQSocial.prototype.gerarGPlus = function (seletor, opts){
	opts = $.extend(jqSocial.optsGP, opts);
	$(seletor).gplusone(opts);
}





setAtalho("CTRL#SHIFT#0", "ligarSpy(0)");
setAtalho("CTRL#SHIFT#1", "ligarSpy(1)");
setAtalho("CTRL#SHIFT#2", "ligarSpy(2)");
setAtalho("CTRL#SHIFT#3", "ligarSpy(3)");
function ligarSpy(nivel){

	var url = document.location.href;
	var separador = url.indexOf("?") > 0? "&" : "?"; 
	url = removerParametroUrl(url,"laySpyPlc");
	url += separador + "laySpyPlc="+nivel; 
	document.location.href = url;
	
}

/********************************************************
 * Configura��es iniciais jQuery
********************************************************/

jQuery(document).ready(function(){
	
	configurarPortletNoticia();
	
});

function configurarPortletNoticia(){
	
	jQuery(".prt-noticia-view-lista").css("margin","3px").css("padding","0");
	jQuery(".prt-noticia-item").css("display","inline");
	jQuery(".prt-noticia-item-cabecalho").css("font-weight","bold").css("font-size","10px");
	jQuery(".prt-noticia-item-titulo").css("font-weight","bold").css("font-size","15px");	
	jQuery(".prt-noticia-item-resumo").css("font-weight","bold").css("color","#5B5B5B");
	
}

/********************************************************
 * Mudanca tamanho de fonte do portal
********************************************************/
function changeSize(inc, seletor) {
	
	jQuery("*", seletor).each(function(){
		var fontSize = parseInt(jQuery(this).css("font-size"));
		var fontSizeMin = 11;
		var fontSizeMax = 21;
		if(!isNaN(fontSize)){
			fontSize = fontSize + parseInt(inc);
			if(fontSize >= fontSizeMin && fontSize <= fontSizeMax){
				jQuery(this).css("font-size",fontSize);
			}
		}
	});
}

/**
* Configurar menu de sistema simples para portal
*/
function configurarMenuPortalSistemaJquery (seletorMenu){

	$(seletorMenu).hover(function(){
		configHoverInMenu(this);
	}, function(){    
		configHoverOutMenu(this);
	});

	$(seletorMenu)
	.focus(function(){
		configHoverInMenu(this);
	})
	.blur(function(){
		configHoverOutMenu(this);
	});
}

function configHoverInMenu(menu){
	$(menu).addClass("hover");
	$('ul:first',menu).css('display', 'block');
	//$('ul.inicial',menu).css('display', 'none');
}

function configHoverOutMenu(menu){
	$(menu).removeClass("hover");
	$('ul:first',menu).css('display', 'none');
}





//Objetos para cria��o de itens, menus, a�oes de menu e  divs
var divsMenuRaio 	= new Array();									//Objeto que cont�m todos os divs (cada div pode ter v�rios menus)
var menus 	= new Array();									//Objeto que cont�m todos os menus (cont�m um objeto de seus itens)
var itens 	= new Array();									//Objeto para montagem dos itens do menu
var acaoMenu = new Array();									//Objeto que cont�m a��es definidas para itens e menus

//Fun��es de cria��o
function itemMenu (text, link, target, props, acao, width)
{
	this.text 	= text;										//Texto mostrado no item do menu
	this.link 	= link;										//Link para item do menu
	this.target	= target;									//Frame alvo para abrir o link associado
	this.props 	= props;									//Propriedades da janela aberta pelo link (caso target=new)
	this.acao	= acao;										//N�mero da a��o associada ao item no onclick
}

//Fun��o que cria um menu
//Os valores informados como "" ser�o substitu�dos pelos valores padr�o
function menu (itensMenu, fontFamily, fontColor, fontSize, bgImage, bgColor, imgEsq, imgDir, imgSeparador, tamTab, tamCell, cellPad, cellSpa, borderTab, posVertical)
{
	fontFamily 	= fontFamily 	== "" ? pdFontFamily 	: fontFamily;			//Tipo de fonte
	fontColor	= fontColor	 	== "" ? pdFontColor  	: fontColor;			//Cor de fonte
	fontSize 	= fontSize 	 	== "" ? pdFontSize   	: fontSize;				//Tamanho de fonte
	bgImage 	= bgImage 	 	== "" ? pdBgImage    	: bgImage;				//Imagem de fundo
	bgColor 	= bgColor 	 	== "" ? pdBgColor    	: bgColor;				//Cor de fundo
	imgEsq		= imgEsq		== "" ? pdImgEsq		: imgEsq;				//Imagem da esquerda
	imgDir		= imgDir		== "" ? pdImgDir		: imgDir;				//Imagem da direita
	imgSeparador= imgSeparador	== "" ? pdImgSeparador	: imgSeparador;			//Imagem separadora
	cellPad 	= cellPad 		== "" ? pdCellPad 		: cellPad;				//Cellpadding da tabela
	cellSpa 	= cellSpa 		== "" ? pdCellSpa 		: cellSpa;				//Cellspacing da tabela
	borderTab  	= borderTab  	== "" ? pdBorderTab		: borderTab;			//Tamanho da borda da tabela
	tamCell 	= tamCell 		== "" ? pdTamCell 		: tamCell;				//Tamanho da c�lula da tabela
	tamTab  	= tamTab  		== "" ? pdTamTab  		: tamTab;				//Tamanho da tabela

	this.posVertical	= posVertical;											//Menu vertical ou horizontal (true ou false)
	this.itensMenu 		= itensMenu;											//Objeto que cont�m os itens do menu
	this.fontFamily 	= fontFamily;
	this.fontColor		= fontColor;
	this.fontSize		= fontSize;
	this.bgImage		= bgImage;
	this.bgColor		= bgColor;
	this.imgEsq			= imgEsq;
	this.imgDir			= imgDir;
	this.imgSeparador	= imgSeparador;
	this.tamTab			= tamTab;
	this.tamCell		= tamCell;
	this.cellPad		= cellPad;
	this.cellSpa		= cellSpa;
	this.borderTab		= borderTab;
																				
	
	//Limpando array de itens
	itens = new Array();
}

//Fun��o que cria um div (camada para conter menus)
//Os valores informados como "" ser�o substitu�dos pelos valores padr�o
function div(nome, html, posLeft, posTop, menuDiv, align, move)
{
	posTop   = posTop   == "" ? pdPosTop 	: posTop;			//Posi��o superior do div
	posLeft  = posLeft  == "" ? pdPosLeft	: posLeft;			//Posi��o esquerda do div
	align    = align    == "" ? pdAlign  	: align;			//Alinhamento do div
	move	 = move     == "" ? 1		  	: move;				//Movimento do div (-1: aparece; 1: desaparece)
	var acao = "";
	var posVertical = menuDiv.posVertical;
	if(html == "")
	{
		html += "<DIV ID="+nome+" onmouseout=\"className=\'n\'\" style=\"visibility:visible; cursor:pointer; position:absolute; left:"+posLeft+"px; top:"+(-posTop)+"px; z-index:1;\">";
		html += "<table width = "+menuDiv.tamTab+" border=\""+menuDiv.borderTab+"\" cellpadding=\""+menuDiv.cellPad+"\" cellspacing=\""+menuDiv.cellSpa+"\"  bgcolor=\""+menuDiv.bgColor+"\">";
		if(!posVertical)
		{
			html += "<TR>";
			html += "<TD HEIGHT="+menuDiv.tamCell+"><IMG SRC="+menuDiv.imgEsq+"></TD>";
		}
		for (i=0; i<=menuDiv.itensMenu.length-1; i++)
		{
			acao = menuDiv.itensMenu[i].acao;
			if(posVertical)
			{
				html += "<TR>";
				if(menuDiv.imgEsq != "")
					html += "<TD HEIGHT="+menuDiv.tamCell+"><IMG SRC="+menuDiv.imgEsq+"></TD>";
			}
    		else if(i > 0)
    			html += "<TD HEIGHT="+menuDiv.tamCell+"><IMG SRC="+menuDiv.imgSeparador+"></TD>";
			html += "<TD BGCOLOR = "+menuDiv.bgColor+" BACKGROUND=\""+menuDiv.bgImage+"\" ALIGN="+align+" onClick=\"";
			if(acao != "")
				html += " mover("+acao+",\'acaoItem\');";
			else
			{
				html += " navegar(\'"+menuDiv.itensMenu[i].target+"\',\'"+menuDiv.itensMenu[i].link+"\',\'"+menuDiv.itensMenu[i].props+"\'); ";
//				html += " mover("+(-posTop)+",\'"+nome+"\')";
			}
			html += "\">";
			html += "<SPAN STYLE=\"font-family:"+menuDiv.fontFamily+"; font-size:"+menuDiv.fontSize+"px; color:"+menuDiv.fontColor+";\">";
			html += menuDiv.itensMenu[i].text;
			html += "</SPAN>";
			html += "</TD>";
			if(posVertical)
			{
				if(menuDiv.imgDir)
					html += "<TD HEIGHT="+menuDiv.tamCell+"><IMG SRC="+menuDiv.imgDir+"></TD>";
				html += "</TR>";
			}
		}
		if(!posVertical)
		{
			html += "<TD HEIGHT="+menuDiv.tamCell+"><IMG SRC="+menuDiv.imgDir+"></TD>";
			html += "</TR>";
		}
		html += "</table>";
		html += "</DIV>";
	}
	this.html = html;
	this.nome = nome;
	this.move = -1;
}


//Fun��o para criar a��es para menus e itens
function setAcao(moveTop, nomeMenu, navItem)
{
	//A a��o criada apenas ir� mover o menu para cima e para baixo
	this.moveTop 	= moveTop;			//Valor para movimenta��o do topo do menu
	this.nomeMenu 	= nomeMenu;			//Nome do menu a ser movimentado
	this.navItem 	= navItem;			//Indicador de a��o para item
}

//Fun��o que cria bot�o de navega��o
function criarBotaoNavegacao(nome, left, top, border, cellpad, cellspa, bgcolor, image, align)
{
	var botNavegacao = "";
	//botNavegacao += "<DIV ID=\""+nome+"\" style=\"cursor:pointer; position:absolute ;left:"+left+"px; top:"+top+"px; z-index:10; width:100%; \">";
	//botNavegacao += "<table border=\""+border+"\" cellspacing="+cellpad+" cellppading="+cellspa+">";
	//botNavegacao += "<tr>";
	//botNavegacao += "<td bgcolor=\""+bgcolor+"\" align="+align+">";
	botNavegacao += "<IMG  HREF='#' SRC='"+image+"'";
	if(acaoMenu.length > 0)
	{
		botNavegacao += "onclick='";
		for(i=0; i < acaoMenu.length; i++)
			if(!acaoMenu[i].navItem)
				botNavegacao += "mover("+acaoMenu[i].moveTop+",\""+acaoMenu[i].nomeMenu+"\");"; 
		botNavegacao += "moverItem();'";
	}
	botNavegacao += " ID='"+nome+"' style='cursor:pointer; position:absolute ;left:"+left+"px; top:"+top+"px; z-index:10;'>";
	//botNavegacao += "</td>";
	//botNavegacao += "</tr>";
	//botNavegacao += "</table>";
	//botNavegacao += "</DIV>";
	divsMenuRaio[divsMenuRaio.length] = new div("raiozinho", botNavegacao, "", "", "", "", "", "", "", "", "", "");
}

//Fun��o que retorna a��o associada ao menu
function getMoveAcao(acao)
{
	return acaoMenu[acao].moveTop;
}
//Fun��o que retorna nome associado ao menu
function getNomeMenuAcao(acao)
{
	return acaoMenu[acao].nomeMenu;
}

//Fun��o que retorna um div
function getDiv(nome)
{
	for(i=0; i < divsMenuRaio.length; i++)
	{
		if(divsMenuRaio[i].nome == nome)
			return divsMenuRaio[i];
	}
	return "";
}

//Fun��o para mover div
function mover(x, paramObj) 
{
	var mov 	= 1;
	var div 	= "";
	var objMenu = "";
	var idDiv	= "";
	if(paramObj == "acaoItem")	
	{
		idDiv = getNomeMenuAcao(x);
		objMenu = eval(idDiv);
		div = getDiv(idDiv);
		x 	= getMoveAcao(x);
	}
	else	
	{
		objMenu = document.getElementById(paramObj);
		div = getDiv(objMenu.id);
	}
	if(div != "")
	{
		mov = -div.move
		document.getElementById(paramObj).style.top = parseInt(document.getElementById(paramObj).style.top)+ x*mov;
		div.move = mov;
	}
}
//Fun��o para mover div associado ao a��o de item
function moverItem()
{
	for(var j=0; j < acaoMenu.length; j++)
	{
		if(acaoMenu[j].navItem)
		{
			var div = getDiv(acaoMenu[j].nomeMenu);
			if(div.move == 1)
				mover(acaoMenu[j].moveTop, acaoMenu[j].nomeMenu);
		}
	}
}
//Fun��o para navega��o dos itens do menu
function navegar(target, link, props)
{
	if(link == "logoutRaio()"){
		eval(link);
	}
	else 
	if (target == "")
		window.location = link;
	else if (target == "new")
		window.open(link, "new", props);
	else
	{
		temp_var=eval("window.parent."+target)
		temp_var.location = link
	}
}

//Fun��o para montar todos os divsMenuRaio e menus
function criarMenus()
{
    for(i=0; i < divsMenuRaio.length; i++)
    	document.write(divsMenuRaio[i].html);
}




var camadas       = [];
var nCamadas      = 8;

// Demo variables
// iMouseDown represents the current mouse button state: up or down
/*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;

// Demo 0 variables
var DragDrops   = [];
var curTarget   = null;
var lastTarget  = null;
var dragHelper  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;

//by Rodrigo Magno
var activeCont  	= null;
var beforeNodePos = null;
var reordena			= false;
// Demo1 variables
var D1Target    = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function EcpDrag(){}
var ecpDrag = new EcpDrag();

EcpDrag.prototype.aposDrag = function (box, param){
//PARA EXECUTAR L�GICAS AP�S FIM DRAG
};

function CreateDragContainer(){
	/*
	Create a new "Container Instance" so that items from one "Set" can not
	be dragged into items from another "Set"
	*/
	var cDrag        = DragDrops.length;
	DragDrops[cDrag] = [];

	/*
	Each item passed to this function should be a "container".  Store each
	of these items in our current container
	*/
	for(var i=0; i<arguments.length; i++){
		var cObj = arguments[i];
		DragDrops[cDrag].push(cObj);
		cObj.setAttribute('DropObj', cDrag);

		/*
		Every top level item in these containers should be draggable.  Do this
		by setting the DragObj attribute on each item and then later checking
		this attribute in the mouseMove function
		*/
		for(var j=0; j<cObj.childNodes.length; j++){

			// Firefox puts in lots of #text nodes...skip these
			if(cObj.childNodes[j].nodeName=='#text') continue;

			if(cObj.childNodes[j] && cObj.childNodes[j].setAttribute)
				cObj.childNodes[j].setAttribute('DragObj', cDrag);
		}
	}
}

function getPosition(e){
	var left = 0;
	var top  = 0;
	if(e){
		while (e.offsetParent){
			left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
			top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
			e     = e.offsetParent;
		}
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
	}
	return {x:left, y:top};
}

function mouseCoords(ev){
	
	var objRetorno = {};
	try{
		if(ev.pageX || ev.pageY){
			return {x:ev.pageX, y:ev.pageY};
		}
		objRetorno = {
			x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:ev.clientY + document.body.scrollTop  - document.body.clientTop
		};
	}catch(e){
	}
	return objRetorno;
}

function writeHistory(object, message){
	if(!debug || !object || !object.parentNode || object.parentNode == null || !object.parentNode.getAttribute) 
		return;
	var historyDiv = object.parentNode.getAttribute('History');
	if(historyDiv){
		historyDiv = document.getElementById(historyDiv);
		if(historyDiv){
			historyDiv.appendChild(document.createTextNode(object.id+': '+message));
			historyDiv.appendChild(document.createElement('BR'));
			historyDiv.scrollTop += 50;
		}	
	}
}
var debug = false;
function habilitaDebug(){
	debug = !debug;
	if(debug){
		getElementoPorId("caixaHistorico").style.display = 'block';
	}else{
		getElementoPorId("caixaHistorico").style.display = 'none';
	}	
}

function limparHistorico(){
	getElementoPorId("History").innerHTML = "";
}
function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function mouseMove(ev){
	ev         = ev || window.event;

	/*
	We are setting target to whatever item the mouse is currently on

	Firefox uses event.target here, MSIE uses event.srcElement
	*/
	var target   = ev.target || ev.srcElement;
	var mousePos = mouseCoords(ev);


	if(camadas[0] && target.nodeName != 'scrollbar'){
		// mouseOut event - fires if the item the mouse is on has changed
		if(lastTarget && (target!==lastTarget)){
			//writeHistory(lastTarget, 'Mouse Out Fired');

			// reset the classname for the target element
			var origClass = lastTarget.getAttribute('origClass');
			if(origClass) lastTarget.className = origClass;
		}


		/*
		dragObj is the grouping our item is in (set from the createDragContainer function).
		if the item is not in a grouping we ignore it since it can't be dragged with this
		script.
		*/
		var dragObj = target.getAttribute('DragObj');

		 // if the mouse was moved over an element that is draggable
		if(dragObj!=null){


			// mouseOver event - Change the item's class if necessary
			if(target!=lastTarget){
				//writeHistory(target, 'Mouse Over Fired');

				var oClass = target.getAttribute('overClass');
				if(oClass){
					//Retirado by Rodrigo Magno
					//target.setAttribute('origClass', target.className);
					//target.className = oClass;
				}
			}

			// if the user is just starting to drag the element
			if(iMouseDown && !lMouseState){
				//writeHistory(target, 'Start Dragging');


				// mouseDown target
				curTarget     = target;

				// Record the mouse x and y offset for the element
				rootParent    = curTarget.parentNode;
				rootSibling   = curTarget.nextSibling;

				mouseOffset   = getMouseOffset(target, ev);

				// We remove anything that is in our dragHelper DIV so we can put a new item in it.
				for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);

				// Make a copy of the current item and put it in our drag helper.
				dragHelper.appendChild(curTarget.cloneNode(true));
				dragHelper.style.display = 'block';

				// set the class on our helper DIV if necessary
				var dragClass = curTarget.getAttribute('dragClass');
				if(dragClass){
					dragHelper.firstChild.className = dragClass;
				}

				// disable dragging from our helper DIV (it's already being dragged)
				dragHelper.firstChild.removeAttribute('DragObj');

				/*
				Record the current position of all drag/drop targets related
				to the element.  We do this here so that we do not have to do
				it on the general mouse move event which fires when the mouse
				moves even 1 pixel.  If we don't do this here the script
				would run much slower.
				*/
				var dragConts = DragDrops[dragObj];

				/*
				first record the width/height of our drag item.  Then hide it since
				it is going to (potentially) be moved out of its parent.
				*/
				curTarget.setAttribute('startWidth',  parseInt(curTarget.offsetWidth));
				curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
				curTarget.style.display  = 'none';

				if(!dragConts)
					return;
				// loop through each possible drop container
				for(var i=0; i<dragConts.length; i++){
					with(dragConts[i]){
						var pos = getPosition(dragConts[i]);

						/*
						save the width, height and position of each container.

						Even though we are saving the width and height of each
						container back to the container this is much faster because
						we are saving the number and do not have to run through
						any calculations again.  Also, offsetHeight and offsetWidth
						are both fairly slow.  You would never normally notice any
						performance hit from these two functions but our code is
						going to be running hundreds of times each second so every
						little bit helps!

						Note that the biggest performance gain here, by far, comes
						from not having to run through the getPosition function
						hundreds of times.
						*/
						setAttribute('startWidth',  parseInt(offsetWidth));
						setAttribute('startHeight', parseInt(offsetHeight));
						setAttribute('startLeft',   pos.x);
						setAttribute('startTop',    pos.y);
					}

					// loop through each child element of each container
					for(var j=0; j<dragConts[i].childNodes.length; j++){
						with(dragConts[i].childNodes[j]){
							if((nodeName=='#comment') || (nodeName=='B') || (nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;

							var pos = getPosition(dragConts[i].childNodes[j]);
							// save the width, height and position of each element
							setAttribute('startWidth',  parseInt(offsetWidth));
							setAttribute('startHeight', parseInt(offsetHeight));
							setAttribute('startLeft',   pos.x);
							setAttribute('startTop',    pos.y);
						}
					}
				}
			}
		}

		// If we get in here we are dragging something
		if(curTarget){

			// move our helper div to wherever the mouse is (adjusted by mouseOffset)
			dragHelper.style.top  = mousePos.y - mouseOffset.y;
			dragHelper.style.left = mousePos.x - mouseOffset.x;

			var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
			//var activeCont = null;
			activeCont = null;

			var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
			var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);

			// check each drop container to see if our target object is "inside" the container
			for(var i=0; dragConts && i<dragConts.length; i++){
				with(dragConts[i]){
					if((parseInt(getAttribute('startLeft'))                                           < xPos) &&
						(parseInt(getAttribute('startTop'))                                            < yPos) &&
						((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
						((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){

							/*
							our target is inside of our container so save the container into
							the activeCont variable and then exit the loop since we no longer
							need to check the rest of the containers
							*/
							activeCont = dragConts[i];

							// exit the for loop
							break;
					}
				}
			}
			
			// Our target object is in one of our containers.  Check to see where our div belongs
			if(activeCont){
				if(activeCont!=curTarget.parentNode){
					writeHistory(curTarget, 'Moved into '+activeCont.id);
				}

				//Altera a classe do container para marcar em qual est�
				//by Rodrigo Magno
				for(d = 0; d < dragConts.length; d++){
					activeDrag = dragConts[d];
					var oClass = activeDrag.className;
					if(activeCont == activeDrag)
						activeDrag.className = oClass.replace("DragContainerClass","OverDragContainer");
					else 
						activeDrag.className = oClass.replace("OverDragContainer","DragContainerClass");
				}
				//Fim
				
				// beforeNode will hold the first node AFTER where our div belongs
				var beforeNode 	= null;
				beforeNodePos 	= null;

				// loop through each child node (skipping text nodes).
				for(var i=activeCont.childNodes.length-1; i>=0; i--){
					with(activeCont.childNodes[i]){
						if(nodeName == '#comment' || nodeName=='#text') continue;

						// if the current item is "After" the item being dragged
						if(curTarget != activeCont.childNodes[i]                                                  &&
							((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth')))  > xPos) &&
							((parseInt(getAttribute('startTop'))  + parseInt(getAttribute('startHeight'))) > yPos)){
								beforeNode = activeCont.childNodes[i];

								//by Rodrigo Magno
								beforeNodePos = i;
								if(activeCont!=curTarget.parentNode){
										writeHistory(curTarget, 'curTarget ['+curTarget.id+'], ordem antes '+curTarget.getAttribute("ordem"));
										curTarget.setAttribute("ordem",beforeNodePos*10);
										writeHistory(curTarget, 'curTarget ['+curTarget.id+'], ordem depois '+curTarget.getAttribute("ordem"));
								}
								
						}
					}
				}

				// the item being dragged belongs before another item
				if(beforeNode){
					if(beforeNode!=curTarget.nextSibling){
						writeHistory(curTarget, 'Inserted Before '+beforeNode.id);
						//by Rodrigo Magno
						//writeHistory(curTarget, activeCont.id+', idContainer '+activeCont.getAttribute("idContainer"));
						writeHistory(curTarget, beforeNode.id+', idBox '+beforeNode.getAttribute("idBox"));
						writeHistory(curTarget, beforeNode.id+', ordem '+beforeNode.getAttribute("ordem"));

					  var sibling = curTarget.nextSibling;
						writeHistory(curTarget, curTarget.id+'----------BEFORE NODE-----------');
						writeHistory(curTarget, 'CONTAINER '+activeCont.id);
						writeHistory(curTarget, 'CONTAINERINI '+curTarget.getAttribute("containerIni"));
						writeHistory(curTarget, 'BEFORENODEPOS '+beforeNodePos);

						if(curTarget.nextSibling && curTarget.nextSibling.parentNode != activeCont)
							sibling = activeCont.childNodes[beforeNodePos-1]

						if(sibling && sibling.id)
							writeHistory(curTarget, 'nextSibling ['+sibling.id+'], ordem antes '+sibling.getAttribute("ordem"));
						writeHistory(curTarget, 'curTarget ['+curTarget.id+'], ordem antes '+curTarget.getAttribute("ordem"));
						writeHistory(curTarget, 'beforeNode ['+beforeNode.id+'], ordem antes '+beforeNode.getAttribute("ordem"));

						if(parseInt(curTarget.getAttribute("ordem")) <= parseInt(beforeNode.getAttribute("ordem"))){
							writeHistory(curTarget, "Descendo");
							//if(curTarget.nextSibling && curTarget.nextSibling.parentNode == activeCont)
							if(sibling && sibling.nodeName != "#text")
								sibling.setAttribute("ordem", curTarget.getAttribute("ordem"))	
							curTarget.setAttribute("ordem", parseInt(curTarget.getAttribute("ordem")) + 10)
							beforeNode.setAttribute("ordem", parseInt(beforeNode.getAttribute("ordem")) + 10)
						}
						else if(parseInt(curTarget.getAttribute("ordem")) >= parseInt(beforeNode.getAttribute("ordem"))){
							writeHistory(curTarget, "Subindo");
							curTarget.setAttribute("ordem", parseInt(curTarget.getAttribute("ordem")) - 10)
							beforeNode.setAttribute("ordem", parseInt(beforeNode.getAttribute("ordem")) + 10)
						}						
						if(sibling && sibling.id)
							writeHistory(curTarget, 'nextSibling ['+sibling.id+'], ordem depois '+sibling.getAttribute("ordem"));
						
						writeHistory(curTarget, 'curTarget ['+curTarget.id+'], ordem depois '+curTarget.getAttribute("ordem"));
						writeHistory(curTarget, 'beforeNode ['+beforeNode.id+'], ordem depois '+beforeNode.getAttribute("ordem"));
						writeHistory(curTarget, curTarget.id+'------------------------------------');
						
//							gravaAjax(curTarget)						
	
						if(beforeNode.id != "NODRAG")
							activeCont.insertBefore(curTarget, beforeNode);
					}
				// the item being dragged belongs at the end of the current container
				} else {
					if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
						writeHistory(curTarget, 'Inserted at end of '+activeCont.id);

						//by Rodrigo Magno
						writeHistory(curTarget, curTarget.id+'--------------END NODE-----------------');
						if(curTarget.nextSibling && curTarget.nextSibling.parentNode == activeCont && curTarget.nextSibling.getAttribute)
							writeHistory(curTarget, 'nextSibling ['+curTarget.nextSibling.id+'], ordem antes '+curTarget.nextSibling.getAttribute("ordem"));
						writeHistory(curTarget, 'curTarget ['+curTarget.id+'], ordem antes '+curTarget.getAttribute("ordem"));
						if(curTarget.nextSibling && curTarget.nextSibling.parentNode == activeCont && curTarget.nextSibling.getAttribute)
							curTarget.nextSibling.setAttribute("ordem", parseInt(curTarget.nextSibling.getAttribute("ordem")) - 10)	
						curTarget.setAttribute("ordem", parseInt(curTarget.getAttribute("ordem")) + 10)
						if(curTarget.nextSibling && curTarget.nextSibling.parentNode == activeCont && curTarget.nextSibling.getAttribute)
							writeHistory(curTarget, 'nextSibling ['+curTarget.nextSibling.id+'], ordem depois '+curTarget.nextSibling.getAttribute("ordem"));
						writeHistory(curTarget, 'curTarget ['+curTarget.id+'], ordem depois '+curTarget.getAttribute("ordem"));
						
						activeCont.appendChild(curTarget);
					}
				}
							
				// the timeout is here because the container doesn't "immediately" resize
				setTimeout(function(){
						var contPos = getPosition(activeCont);
								if(activeCont){
									activeCont.setAttribute('startWidth',  parseInt(activeCont.offsetWidth));
									activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
									activeCont.setAttribute('startLeft',   contPos.x);
									activeCont.setAttribute('startTop',    contPos.y);
								}						
						}, 5);

				// make our drag item visible
				if(curTarget.style.display!=''){
					//writeHistory(curTarget, 'Made Visible');
					curTarget.style.display    = '';
					curTarget.style.visibility = 'hidden';
				}
			} else {

				// our drag item is not in a container, so hide it.
				if(curTarget.style.display!='none'){
					writeHistory(curTarget, 'Hidden');
					curTarget.style.display  = 'none';
				}
			}
		}
		// track the current mouse state so we can compare against it next time
		lMouseState = iMouseDown;

		// mouseMove target
		lastTarget  = target;
	}

	if(dragObject){
		dragObject.style.position = 'absolute';
		dragObject.style.top      = mousePos.y - mouseOffset.y;
		dragObject.style.left     = mousePos.x - mouseOffset.x;
	}

	// track the current mouse state so we can compare against it next time
	lMouseState = iMouseDown;

	// this prevents items on the page from being highlighted while dragging
	if(curTarget || dragObject) return false;
}

function mouseUp(ev){

	if(camadas[0]){
		if(curTarget){
			writeHistory(curTarget, 'Mouse Up Fired');

			dragHelper.style.display = 'none';
			if(curTarget.style.display == 'none'){
				if(rootSibling){
					rootParent.insertBefore(curTarget, rootSibling);
				} else {
					rootParent.appendChild(curTarget);
				}
			}
			curTarget.style.display    = '';
			curTarget.style.visibility = 'visible';
		}

		//Altera a classe do container para classe original
		//by Rodrigo Magno
		if(curTarget){
			var curClass = curTarget.parentNode.className;
			curTarget.parentNode.className = curClass.replace("OverDragContainer","DragContainerClass");
		}	
		//Fim

		//by Rodrigo Magno
		ev         = ev || window.event;
		var target = ev.target || ev.srcElement;
		if(target.parentNode.id && target.parentNode.id == "caixaHistorico") return true;
		if(target.parentNode.id && target.parentNode.id != null)
			target.setAttribute("containerIni",target.parentNode.id);	
		reordenarNodes(curTarget);
		var param = recuperaDadosPosicao(curTarget);
		mostrarOrdem(curTarget);
		ecpDrag.aposDrag(curTarget, param);
		//Fim
		
		curTarget  = null;
	}
	if(dragObject){
		ev           = ev || window.event;
		var mousePos = mouseCoords(ev);

		var dT = dragObject.getAttribute('droptarget');
		if(dT){
			var targObj = document.getElementById(dT);
			var objPos  = getPosition(targObj);
			if((mousePos.x > objPos.x) && (mousePos.y > objPos.y) && 
			(mousePos.x<(objPos.x+parseInt(targObj.offsetWidth))) && 
			(mousePos.y<(objPos.y+parseInt(targObj.offsetHeight)))){
				var nSrc = targObj.getAttribute('newSrc');
				if(nSrc){
					dragObject.src = nSrc;
					setTimeout(function(){
						if(!dragObject || !dragObject.parentNode) return;
						dragObject.parentNode.removeChild(dragObject);
						dragObject = null;
					}, parseInt(targObj.getAttribute('timeout')));
				} else {
					dragObject.parentNode.removeChild(dragObject);
				}
			}
		}
	}

	
	dragObject = null;

	iMouseDown = false;
}

function mouseDown(ev){
	ev         = ev || window.event;
	var target = ev.target || ev.srcElement;

	iMouseDown = true;
	//iMouseDown = !iMouseDown
	/*
	target.setAttribute("containerIni",target.parentNode.id);	
	if(!iMouseDown){
		//by Rodrigo Magno
		reordenarNodes(curTarget);
		var param = recuperaDadosPosicao(curTarget);
		mostrarOrdem(curTarget);
		ecpDrag.aposDrag(curTarget, param);
	}
	*/
	if(camadas[0]){
		if(lastTarget){
			writeHistory(lastTarget, 'Mouse Down Fired');
		}
	}
	if(target.onmousedown || target.getAttribute('DragObj')){
		return false;
	}
}

function makeDraggable(item){
	if(!item) return;
	item.onmousedown = function(ev){
		dragObject  = this;
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
}

function makeClickable(item){
	if(!item) return;
	item.onmousedown = function(ev){
		document.getElementById('ClickImage').value = this.name;
	}
}

function addDropTarget(item, target){
	item.setAttribute('droptarget', target);
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup   = mouseUp;

function reordenarNodes(curTarget){
	  writeHistory(curTarget,"REORDENANDO");
		var reordena = false;
		var novaOrdem= null;		
		if(activeCont && activeCont.childNodes && activeCont.childNodes != null && activeCont.childNodes.length){
			writeHistory(curTarget, 'CONTAINER '+activeCont.id);
			for(var bfp=0; bfp < activeCont.childNodes.length; bfp++){
				var curNode			= null;
				var ordem				= null;
				var ordemIni		= null;
				var idBox 			= null;
				var containerIni= null;
				with(activeCont.childNodes[bfp]){
					curNode 	= activeCont.childNodes[bfp];
					if(curNode && curNode.getAttribute){
						ordem 		= parseInt(curNode.getAttribute("ordem"));
						ordemIni 	= parseInt(curNode.getAttribute("ordemIni"));
						idBox			= parseInt(curNode.getAttribute("idBox"));
						containerIni	= curNode.getAttribute("containerIni");
						if(!reordena && (ordemIni != ordem || 
						(containerIni != null && containerIni != activeCont.id))){
							writeHistory(curTarget, 'REORDENA A PARTIR DA ORDEM: '+ordem);
							reordena = true;
						}
						if(reordena){	
								novaOrdem = ((bfp+1)*10);
								curNode.setAttribute("ordem", novaOrdem);
						}		
							
						writeHistory(curTarget, curNode.id+' - idBox: '+idBox+', ordemIni: '+ordemIni+', ordem: '+ordem+', containerIni: '+containerIni);
					}
				}
			}
		}
}

function mostrarOrdem(curTarget){
  writeHistory(curTarget,"ORDEM ATUAL");
	if(activeCont && activeCont.childNodes && activeCont.childNodes != null && activeCont.childNodes.length){
		for(var bfp=0; bfp < activeCont.childNodes.length; bfp++){
			var curNode 	= null;
			with(activeCont.childNodes[bfp]){
				curNode 	= activeCont.childNodes[bfp];
				if(curNode && curNode.getAttribute){
					idBox = curNode.getAttribute("idBox");
					ordem 		= curNode.getAttribute("ordem");
					writeHistory(curTarget, curNode.id+' - idBox: '+idBox+', ordem: '+ordem);
				}	
			}
		}
	}
}

function recuperaDadosPosicao(curTarget){
	if(activeCont){
		writeHistory(curTarget, 'RECUPERANDO DADOS POSICAO');
		var idContainer	= activeCont.getAttribute("idContainer");
		var containerIni= null;
		var curNode			= null;
		var idBox 			= null;
		var ordem				= null;
		var url 				= "";
		var paramOrdem	= "";
		var paramId			= "";
		for(var bfp=0; bfp < activeCont.childNodes.length; bfp++){
			curNode		= null;
			ordem			= null;
			ordemIni	= null;
			idBox			= null;
			with(activeCont.childNodes && activeCont.childNodes[bfp]){
				curNode 	= activeCont.childNodes[bfp];
				if(curNode && curNode.getAttribute){
					idBox		= curNode.getAttribute("idBox");
					ordem 		= parseInt(curNode.getAttribute("ordem"));
					ordemIni 	= parseInt(curNode.getAttribute("ordemIni"));
					containerIni	= curNode.getAttribute("containerIni");
					writeHistory(curTarget, curNode.id+' - idBox '+idBox+', idContainer: '+idContainer+', ordemIni: '+ordemIni+', ordem: '+ordem);
						if(idBox && (ordemIni != ordem || 
						(containerIni != null && containerIni != activeCont.id)))
					{
							paramId 	+= paramId == "" ? idBox : "$"+idBox;
							paramOrdem 	+= paramOrdem == "" ? ordem : "$" + ordem;
							writeHistory(curTarget, curNode.id+' - idBox '+idBox+', idContainer: '+idContainer+', ordemIni: '+ordemIni+', ordem: '+ordem);
							curNode.setAttribute("ordemIni", ordem);
					}		
				}
			}
		}
		writeHistory(curTarget, 'PARAMETROS RETORNADOS');
		writeHistory(curTarget, 'paramId: '+paramId);
		writeHistory(curTarget, 'paramOrdem: '+paramOrdem);
		writeHistory(curTarget, 'idContainer: '+idContainer);
		if(paramId == "" && paramOrdem == "")
			writeHistory(curTarget, "NENHUMA POSICAO ALTERADA");
		
		return {paramId: paramId, paramOrdem: paramOrdem, idContainer: idContainer}				
	}
}

function createDragDrop(){
	var cont = 1;
	var createConteiner = "";
	camadas[0] = document.getElementById('CAMADA0');
	do{
		//alert("CRIANDO CAMADAS")
		if(document.getElementById('DragContainer'+cont)){
			//alert("document.getElementById('DragContainer'"+cont+") "+document.getElementById('DragContainer'+cont).id)
			if(createConteiner != "")
				createConteiner += ",";
			createConteiner += "document.getElementById('DragContainer"+(cont)+"')"
		}
		else{
			cont = -1;
			break;	
		}
		cont++;
	}while(document.getElementById('DragContainer'+cont) && cont > 0)
	
	if(createConteiner != ""){
		//alert("createConteiner: "+createConteiner)
		eval("CreateDragContainer("+createConteiner+")");
	}
	// Create our helper object that will show the item while dragging
	dragHelper = document.createElement('DIV');
	dragHelper.style.cssText = 'position:absolute;display:none;';
	document.body.appendChild(dragHelper);
}


setAtalho("CTRL#SHIFT#H", "habilitaDebug()")

function gravaPosicaoPortlet(box, paramId, paramOrdem, idContainer){
		writeHistory(box, 'GRAVANDO POSICAO');
		var url = "";
		url = "/ecp/ecpportlet.do?evento=atualizapagina&idPortlet="+paramId+"&idBanda="+idContainer+"&ordem="+paramOrdem+"&pg="+getParametroUrl("pg");
		writeHistory(box, 'URL: '+url);
		if(url && url != "")	{
			gravaPaginaAposDrag(url);
		}		
}

plcAjax.aposAjaxSubmit = function(){
	atualizaPaginaAposDrag();
}

function atualizaPaginaAposDrag(){
	var url = document.location.href
	plcLog.debug("URL APOS DRAG: "+url)
	if(atualizarAposRemoverPortlet){
		url = url.replace("&refresh=s","");
		url = url.replace("&refreshAll=s","");
		redirect(url+"&refresh=s");
	}
}

function gravaPaginaAposDrag (url) {	 

	var optsAjax = {
		url: url,
		type: "GET",
		dataType:"json",
		complete : function(json) { 
			//atualizaPaginaAposDrag();
		},
		error:	function() { 
		}
	};
	try{
		$.ajax(optsAjax);
	}catch(e){}
}

var atualizarAposRemoverPortlet = false;
function removerPortletPagina(idPortlet, banda){
		
		atualizarAposRemoverPortlet = false;	
		var url = "";
		url = "/ecp/templatert.do?evento=portlet&pIdPlc="+idPortlet+"&acao=retira&pBPlc="+banda+"&pOPlc=0";
		if(url && url != "")	{
			atualizarAposRemoverPortlet = true;
			jqBlockUI.gerarMensagem({message:  "Aguarde, removendo portlet ..."});
			plcAjax.ajaxHabilitaEspecifico(false);
			plcAjax.ajaxSubmit('GET','',url);
		}		
}




/*
 * jQuery Cycle Plugin for light-weight slideshows
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2008 M. Alsup
 * Version: 2.10 (02/10/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.1.3.1 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.10';
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);

$.fn.cycle = function(options) {
    return this.each(function() {
        options = options || {};
        if (options.constructor == String) {
            switch(options) {
            case 'stop':
                if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
                this.cycleTimeout = 0;
                return;
            case 'pause':
                this.cyclePause = 1;
                return;
            case 'resume':
                this.cyclePause = 0;
                return;
            default:
                options = { fx: options };
            };
        }
        var $cont = $(this);
        var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
        var els = $slides.get();
        if (els.length < 2) 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;
            
        opts.before = opts.before ? [opts.before] : [];
        opts.after = opts.after ? [opts.after] : [];
        opts.after.unshift(function(){ opts.busy=0; });

        // clearType corrections
        if (ie6 && opts.cleartype && !opts.cleartypeNoBg)
            clearTypeFix($slides);

        // allow shorthand overrides of width, height and timeout
        var cls = this.className;
        var w = parseInt((cls.match(/w:(\d+)/)||[])[1]) || opts.width;
        var h = 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 (w) 
            $cont.width(w);
        if (h && h != 'auto') 
            $cont.height(h);

        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')
			.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]).show();
        if (opts.fit && w) 
            $slides.width(w);
        if (opts.fit && h && h != 'auto') 
            $slides.height(h);
        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);

        $slides.each(function() {
            var $el = $(this);
            this.cycleH = (opts.fit && h) ? h : $el.height();
            this.cycleW = (opts.fit && w) ? w : $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) {
            // ensure that timeout and speed settings are sane
            if (opts.speed.constructor == String)
                opts.speed = {slow: 600, fast: 200}[opts.speed] || 400;
            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);
        if (opts.timeout)
            this.cycleTimeout = setTimeout(function(){go(els,opts,0,!opts.rev)}, opts.timeout + (opts.delay||0));
    });
};

function go(els, opts, manual, fwd) {
    if (opts.busy) return;
    var p = els[0].parentNode, 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)))
        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);
        }
        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)
            $(opts.pager).find('a').removeClass('activeSlide').filter('a:eq('+opts.currSlide+')').addClass('activeSlide');
    }
    if (opts.timeout)
        p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, opts.timeout);
};

// advance slide forward or back
function advance(els, opts, val) {
    var p = els[0].parentNode, timeout = p.cycleTimeout;
    if (timeout) {
        clearTimeout(timeout);
        p.cycleTimeout = 0;
    }
    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) {
        var $a = (typeof opts.pagerAnchorBuilder == 'function')
            ? $(opts.pagerAnchorBuilder(i,o))
            : $('<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('click',function() {
            opts.nextSlide = i;
            var p = els[0].parentNode, 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.rev);
            return false;
        });
    });
   $p.find('a').filter('a:eq('+opts.startingSlide+')').addClass('activeSlide');
};

// 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) {
    var $l = $(curr), $n = $(next);
    $n.css(opts.cssBefore);
    var fn = function() {$n.animate(opts.animIn, opts.speedIn, opts.easeIn, cb)};
    $l.animate(opts.animOut, opts.speedOut, opts.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.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, slideX, slideY, scrollUp/Down/Left/Right
    timeout:       4000,  // milliseconds between slide transitions (0 to disable auto advance)
    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
    click:         null,  // @deprecated; please use the 'next' option
    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)
    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)
    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"
    autostop:      0,     // true to end slideshow after X transitions (where X == slide count)
    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
};

})(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 M. Alsup
 * Version:  2.07
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

//
// 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
jQuery.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        jQuery(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' };
};
jQuery.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        jQuery(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' };
};
jQuery.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        jQuery(this).show();
        opts.cssBefore.left = next.offsetWidth;
        opts.animOut.left = 0-curr.offsetWidth;
    });
    opts.cssFirst = { left: 0 };
    opts.animIn   = { left: 0 };
};
jQuery.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        jQuery(this).show();
        opts.cssBefore.left = 0-next.offsetWidth;
        opts.animOut.left = curr.offsetWidth;
    });
    opts.cssFirst = { left: 0 };
    opts.animIn   = { left: 0 };
};
jQuery.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
    $cont.css('overflow','hidden').width();
//    $slides.show();
    opts.before.push(function(curr, next, opts, fwd) {
        jQuery(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' }
};
jQuery.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
//    $slides.show();
    opts.before.push(function(curr, next, opts, fwd) {
        jQuery(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
jQuery.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
    opts.animIn  = { width: 'show' };
    opts.animOut = { width: 'hide' };
};
jQuery.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
    opts.animIn  = { height: 'show' };
    opts.animOut = { height: 'hide' };
};

// shuffle
jQuery.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() { jQuery(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 ? jQuery(curr) : jQuery(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++)
                    jQuery(opts.els[i]).css('z-index', len-i);
            else {
                var z = jQuery(curr).css('z-index');
                $el.css('z-index', parseInt(z)+1);
            }
            $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
                jQuery(fwd ? this : curr).hide();
                if (cb) cb();
            });
        });
    };
};

// turnUp/Down/Left/Right
jQuery.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        jQuery(this).show();
        opts.cssBefore.top = next.cycleH;
        opts.animIn.height = next.cycleH;
    });
    opts.cssFirst  = { top: 0 };
    opts.cssBefore = { height: 0 };
    opts.animIn    = { top: 0 };
    opts.animOut   = { height: 0 };
    opts.cssAfter  = { display: 'none' };
};
jQuery.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        jQuery(this).show();
        opts.animIn.height = next.cycleH;
        opts.animOut.top   = curr.cycleH;
    });
    opts.cssFirst  = { top: 0 };
    opts.cssBefore = { top: 0, height: 0 };
    opts.animOut   = { height: 0 };
    opts.cssAfter  = { display: 'none' };
};
jQuery.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        jQuery(this).show();
        opts.cssBefore.left = next.cycleW;
        opts.animIn.width = next.cycleW;
    });
    opts.cssBefore = { width: 0 };
    opts.animIn    = { left: 0 };
    opts.animOut   = { width: 0 };
    opts.cssAfter  = { display: 'none' };
};
jQuery.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        jQuery(this).show();
        opts.animIn.width = next.cycleW;
        opts.animOut.left = curr.cycleW;
    });
    opts.cssBefore = { left: 0, width: 0 };
    opts.animIn    = { left: 0 };
    opts.animOut   = { width: 0 };
    opts.cssAfter  = { display: 'none' };
};

// zoom
jQuery.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) {
        jQuery(this).show();
        opts.cssBefore = { width: 0, height: 0, top: next.cycleH/2, left: next.cycleW/2 };
        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 };
    });    
};

// fadeZoom
jQuery.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 };
};




/*
 * jQuery Nivo Slider v2.5.1
 * http://nivo.dev7studios.com
 *
 * Copyright 2011, Gilbert Pellegrom
 * Free to use and abuse under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * March 2010
 */

(function($){var NivoSlider=function(element,options){var settings=$.extend({},$.fn.nivoSlider.defaults,options);var vars={currentSlide:0,currentImage:'',totalSlides:0,randAnim:'',running:false,paused:false,stop:false};var slider=$(element);slider.data('nivo:vars',vars);slider.css('position','relative');slider.addClass('nivoSlider');var kids=slider.children();kids.each(function(){var child=$(this);var link='';if(!child.is('img')){if(child.is('a')){child.addClass('nivo-imageLink');link=child;}
child=child.find('img:first');}
var childWidth=child.width();if(childWidth==0)childWidth=child.attr('width');var childHeight=child.height();if(childHeight==0)childHeight=child.attr('height');if(childWidth>slider.width()){slider.width(childWidth);}
if(childHeight>slider.height()){slider.height(childHeight);}
if(link!=''){link.css('display','none');}
child.css('display','none');vars.totalSlides++;});if(settings.startSlide>0){if(settings.startSlide>=vars.totalSlides)settings.startSlide=vars.totalSlides-1;vars.currentSlide=settings.startSlide;}
if($(kids[vars.currentSlide]).is('img')){vars.currentImage=$(kids[vars.currentSlide]);}else{vars.currentImage=$(kids[vars.currentSlide]).find('img:first');}
if($(kids[vars.currentSlide]).is('a')){$(kids[vars.currentSlide]).css('display','block');}
slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');slider.append($('<div class="nivo-caption"><p></p></div>').css({display:'none',opacity:settings.captionOpacity}));var processCaption=function(settings){var nivoCaption=$('.nivo-caption',slider);if(vars.currentImage.attr('title')!=''){var title=vars.currentImage.attr('title');if(title.substr(0,1)=='#')title=$(title).html();if(nivoCaption.css('display')=='block'){nivoCaption.find('p').fadeOut(settings.animSpeed,function(){$(this).html(title);$(this).fadeIn(settings.animSpeed);});}else{nivoCaption.find('p').html(title);}
nivoCaption.fadeIn(settings.animSpeed);}else{nivoCaption.fadeOut(settings.animSpeed);}}
processCaption(settings);var timer=0;if(!settings.manualAdvance&&kids.length>1){timer=setInterval(function(){nivoRun(slider,kids,settings,false);},settings.pauseTime);}
if(settings.directionNav){slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+settings.prevText+'</a><a class="nivo-nextNav">'+settings.nextText+'</a></div>');if(settings.directionNavHide){$('.nivo-directionNav',slider).hide();slider.hover(function(){$('.nivo-directionNav',slider).show();},function(){$('.nivo-directionNav',slider).hide();});}
$('a.nivo-prevNav',slider).live('click',function(){if(vars.running)return false;clearInterval(timer);timer='';vars.currentSlide-=2;nivoRun(slider,kids,settings,'prev');});$('a.nivo-nextNav',slider).live('click',function(){if(vars.running)return false;clearInterval(timer);timer='';nivoRun(slider,kids,settings,'next');});}
if(settings.controlNav){var nivoControl=$('<div class="nivo-controlNav"></div>');slider.append(nivoControl);for(var i=0;i<kids.length;i++){if(settings.controlNavThumbs){var child=kids.eq(i);if(!child.is('img')){child=child.find('img:first');}
if(settings.controlNavThumbsFromRel){nivoControl.append('<a class="nivo-control" rel="'+i+'"><img src="'+child.attr('rel')+'" alt="" /></a>');}else{nivoControl.append('<a class="nivo-control" rel="'+i+'"><img src="'+child.attr('src').replace(settings.controlNavThumbsSearch,settings.controlNavThumbsReplace)+'" alt="" /></a>');}}else{nivoControl.append('<a class="nivo-control" rel="'+i+'">'+(i+1)+'</a>');}}
$('.nivo-controlNav a:eq('+vars.currentSlide+')',slider).addClass('active');$('.nivo-controlNav a',slider).live('click',function(){if(vars.running)return false;if($(this).hasClass('active'))return false;clearInterval(timer);timer='';slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');vars.currentSlide=$(this).attr('rel')-1;nivoRun(slider,kids,settings,'control');});}
if(settings.keyboardNav){$(window).keypress(function(event){if(event.keyCode=='37'){if(vars.running)return false;clearInterval(timer);timer='';vars.currentSlide-=2;nivoRun(slider,kids,settings,'prev');}
if(event.keyCode=='39'){if(vars.running)return false;clearInterval(timer);timer='';nivoRun(slider,kids,settings,'next');}});}
if(settings.pauseOnHover){slider.hover(function(){vars.paused=true;clearInterval(timer);timer='';},function(){vars.paused=false;if(timer==''&&!settings.manualAdvance){timer=setInterval(function(){nivoRun(slider,kids,settings,false);},settings.pauseTime);}});}
slider.bind('nivo:animFinished',function(){vars.running=false;$(kids).each(function(){if($(this).is('a')){$(this).css('display','none');}});if($(kids[vars.currentSlide]).is('a')){$(kids[vars.currentSlide]).css('display','block');}
if(timer==''&&!vars.paused&&!settings.manualAdvance){timer=setInterval(function(){nivoRun(slider,kids,settings,false);},settings.pauseTime);}
settings.afterChange.call(this);});var createSlices=function(slider,settings,vars){for(var i=0;i<settings.slices;i++){var sliceWidth=Math.round(slider.width()/settings.slices);if(i==settings.slices-1){slider.append($('<div class="nivo-slice"></div>').css({left:(sliceWidth*i)+'px',width:(slider.width()-(sliceWidth*i))+'px',height:'0px',opacity:'0',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((sliceWidth+(i*sliceWidth))-sliceWidth)+'px 0%'}));}else{slider.append($('<div class="nivo-slice"></div>').css({left:(sliceWidth*i)+'px',width:sliceWidth+'px',height:'0px',opacity:'0',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((sliceWidth+(i*sliceWidth))-sliceWidth)+'px 0%'}));}}}
var createBoxes=function(slider,settings,vars){var boxWidth=Math.round(slider.width()/settings.boxCols);var boxHeight=Math.round(slider.height()/settings.boxRows);for(var rows=0;rows<settings.boxRows;rows++){for(var cols=0;cols<settings.boxCols;cols++){if(cols==settings.boxCols-1){slider.append($('<div class="nivo-box"></div>').css({opacity:0,left:(boxWidth*cols)+'px',top:(boxHeight*rows)+'px',width:(slider.width()-(boxWidth*cols))+'px',height:boxHeight+'px',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((boxWidth+(cols*boxWidth))-boxWidth)+'px -'+((boxHeight+(rows*boxHeight))-boxHeight)+'px'}));}else{slider.append($('<div class="nivo-box"></div>').css({opacity:0,left:(boxWidth*cols)+'px',top:(boxHeight*rows)+'px',width:boxWidth+'px',height:boxHeight+'px',background:'url("'+vars.currentImage.attr('src')+'") no-repeat -'+((boxWidth+(cols*boxWidth))-boxWidth)+'px -'+((boxHeight+(rows*boxHeight))-boxHeight)+'px'}));}}}}
var nivoRun=function(slider,kids,settings,nudge){var vars=slider.data('nivo:vars');if(vars&&(vars.currentSlide==vars.totalSlides-1)){settings.lastSlide.call(this);}
if((!vars||vars.stop)&&!nudge)return false;settings.beforeChange.call(this);if(!nudge){slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');}else{if(nudge=='prev'){slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');}
if(nudge=='next'){slider.css('background','url("'+vars.currentImage.attr('src')+'") no-repeat');}}
vars.currentSlide++;if(vars.currentSlide==vars.totalSlides){vars.currentSlide=0;settings.slideshowEnd.call(this);}
if(vars.currentSlide<0)vars.currentSlide=(vars.totalSlides-1);if($(kids[vars.currentSlide]).is('img')){vars.currentImage=$(kids[vars.currentSlide]);}else{vars.currentImage=$(kids[vars.currentSlide]).find('img:first');}
if(settings.controlNav){$('.nivo-controlNav a',slider).removeClass('active');$('.nivo-controlNav a:eq('+vars.currentSlide+')',slider).addClass('active');}
processCaption(settings);$('.nivo-slice',slider).remove();$('.nivo-box',slider).remove();if(settings.effect=='random'){var anims=new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade','boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse');vars.randAnim=anims[Math.floor(Math.random()*(anims.length+1))];if(vars.randAnim==undefined)vars.randAnim='fade';}
if(settings.effect.indexOf(',')!=-1){var anims=settings.effect.split(',');vars.randAnim=anims[Math.floor(Math.random()*(anims.length))];if(vars.randAnim==undefined)vars.randAnim='fade';}
vars.running=true;if(settings.effect=='sliceDown'||settings.effect=='sliceDownRight'||vars.randAnim=='sliceDownRight'||settings.effect=='sliceDownLeft'||vars.randAnim=='sliceDownLeft'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;var slices=$('.nivo-slice',slider);if(settings.effect=='sliceDownLeft'||vars.randAnim=='sliceDownLeft')slices=$('.nivo-slice',slider)._reverse();slices.each(function(){var slice=$(this);slice.css({'top':'0px'});if(i==settings.slices-1){setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;i++;});}
else if(settings.effect=='sliceUp'||settings.effect=='sliceUpRight'||vars.randAnim=='sliceUpRight'||settings.effect=='sliceUpLeft'||vars.randAnim=='sliceUpLeft'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;var slices=$('.nivo-slice',slider);if(settings.effect=='sliceUpLeft'||vars.randAnim=='sliceUpLeft')slices=$('.nivo-slice',slider)._reverse();slices.each(function(){var slice=$(this);slice.css({'bottom':'0px'});if(i==settings.slices-1){setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;i++;});}
else if(settings.effect=='sliceUpDown'||settings.effect=='sliceUpDownRight'||vars.randAnim=='sliceUpDown'||settings.effect=='sliceUpDownLeft'||vars.randAnim=='sliceUpDownLeft'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;var v=0;var slices=$('.nivo-slice',slider);if(settings.effect=='sliceUpDownLeft'||vars.randAnim=='sliceUpDownLeft')slices=$('.nivo-slice',slider)._reverse();slices.each(function(){var slice=$(this);if(i==0){slice.css('top','0px');i++;}else{slice.css('bottom','0px');i=0;}
if(v==settings.slices-1){setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({height:'100%',opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;v++;});}
else if(settings.effect=='fold'||vars.randAnim=='fold'){createSlices(slider,settings,vars);var timeBuff=0;var i=0;$('.nivo-slice',slider).each(function(){var slice=$(this);var origWidth=slice.width();slice.css({top:'0px',height:'100%',width:'0px'});if(i==settings.slices-1){setTimeout(function(){slice.animate({width:origWidth,opacity:'1.0'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){slice.animate({width:origWidth,opacity:'1.0'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=50;i++;});}
else if(settings.effect=='fade'||vars.randAnim=='fade'){createSlices(slider,settings,vars);var firstSlice=$('.nivo-slice:first',slider);firstSlice.css({'height':'100%','width':slider.width()+'px'});firstSlice.animate({opacity:'1.0'},(settings.animSpeed*2),'',function(){slider.trigger('nivo:animFinished');});}
else if(settings.effect=='slideInRight'||vars.randAnim=='slideInRight'){createSlices(slider,settings,vars);var firstSlice=$('.nivo-slice:first',slider);firstSlice.css({'height':'100%','width':'0px','opacity':'1'});firstSlice.animate({width:slider.width()+'px'},(settings.animSpeed*2),'',function(){slider.trigger('nivo:animFinished');});}
else if(settings.effect=='slideInLeft'||vars.randAnim=='slideInLeft'){createSlices(slider,settings,vars);var firstSlice=$('.nivo-slice:first',slider);firstSlice.css({'height':'100%','width':'0px','opacity':'1','left':'','right':'0px'});firstSlice.animate({width:slider.width()+'px'},(settings.animSpeed*2),'',function(){firstSlice.css({'left':'0px','right':''});slider.trigger('nivo:animFinished');});}
else if(settings.effect=='boxRandom'||vars.randAnim=='boxRandom'){createBoxes(slider,settings,vars);var totalBoxes=settings.boxCols*settings.boxRows;var i=0;var timeBuff=0;var boxes=shuffle($('.nivo-box',slider));boxes.each(function(){var box=$(this);if(i==totalBoxes-1){setTimeout(function(){box.animate({opacity:'1'},settings.animSpeed,'',function(){slider.trigger('nivo:animFinished');});},(100+timeBuff));}else{setTimeout(function(){box.animate({opacity:'1'},settings.animSpeed);},(100+timeBuff));}
timeBuff+=20;i++;});}
else if(settings.effect=='boxRain'||vars.randAnim=='boxRain'||settings.effect=='boxRainReverse'||vars.randAnim=='boxRainReverse'||settings.effect=='boxRainGrow'||vars.randAnim=='boxRainGrow'||settings.effect=='boxRainGrowReverse'||vars.randAnim=='boxRainGrowReverse'){createBoxes(slider,settings,vars);var totalBoxes=settings.boxCols*settings.boxRows;var i=0;var timeBuff=0;var rowIndex=0;var colIndex=0;var box2Darr=new Array();box2Darr[rowIndex]=new Array();var boxes=$('.nivo-box',slider);if(settings.effect=='boxRainReverse'||vars.randAnim=='boxRainReverse'||settings.effect=='boxRainGrowReverse'||vars.randAnim=='boxRainGrowReverse'){boxes=$('.nivo-box',slider)._reverse();}
boxes.each(function(){box2Darr[rowIndex][colIndex]=$(this);colIndex++;if(colIndex==settings.boxCols){rowIndex++;colIndex=0;box2Darr[rowIndex]=new Array();}});for(var cols=0;cols<(settings.boxCols*2);cols++){var prevCol=cols;for(var rows=0;rows<settings.boxRows;rows++){if(prevCol>=0&&prevCol<settings.boxCols){(function(row,col,time,i,totalBoxes){var box=$(box2Darr[row][col]);var w=box.width();var h=box.height();if(settings.effect=='boxRainGrow'||vars.randAnim=='boxRainGrow'||settings.effect=='boxRainGrowReverse'||vars.randAnim=='boxRainGrowReverse'){box.width(0).height(0);}
if(i==totalBoxes-1){setTimeout(function(){box.animate({opacity:'1',width:w,height:h},settings.animSpeed/1.3,'',function(){slider.trigger('nivo:animFinished');});},(100+time));}else{setTimeout(function(){box.animate({opacity:'1',width:w,height:h},settings.animSpeed/1.3);},(100+time));}})(rows,prevCol,timeBuff,i,totalBoxes);i++;}
prevCol--;}
timeBuff+=100;}}}
var shuffle=function(arr){for(var j,x,i=arr.length;i;j=parseInt(Math.random()*i),x=arr[--i],arr[i]=arr[j],arr[j]=x);return arr;}
var trace=function(msg){if(this.console&&typeof console.log!="undefined")
console.log(msg);}
this.stop=function(){if(!$(element).data('nivo:vars').stop){$(element).data('nivo:vars').stop=true;trace('Stop Slider');}}
this.start=function(){if($(element).data('nivo:vars').stop){$(element).data('nivo:vars').stop=false;trace('Start Slider');}}
settings.afterLoad.call(this);return this;};$.fn.nivoSlider=function(options){return this.each(function(key,value){var element=$(this);if(element.data('nivoslider'))return element.data('nivoslider');var nivoslider=new NivoSlider(this,options);element.data('nivoslider',nivoslider);});};$.fn.nivoSlider.defaults={effect:'random',slices:15,boxCols:8,boxRows:4,animSpeed:500,pauseTime:3000,startSlide:0,directionNav:true,directionNavHide:true,controlNav:true,controlNavThumbs:false,controlNavThumbsFromRel:false,controlNavThumbsSearch:'.jpg',controlNavThumbsReplace:'_thumb.jpg',keyboardNav:true,pauseOnHover:true,manualAdvance:false,captionOpacity:0.8,prevText:'Prev',nextText:'Next',beforeChange:function(){},afterChange:function(){},slideshowEnd:function(){},lastSlide:function(){},afterLoad:function(){}};$.fn._reverse=[].reverse;})(jQuery);



/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.2",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/*
 * jQuery UI Draggable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {

	_init: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.addClasses && this.element.addClass("ui-draggable"));
		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element
			.removeData("draggable")
			.unbind(".draggable")
			.removeClass("ui-draggable"
				+ " ui-draggable-dragging"
				+ " ui-draggable-disabled");
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._trigger("start", event);

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			this._trigger('drag', event, ui);
			this.position = ui.position;
		}

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			dropped = $.ui.ddmanager.drop(this, event);

		//if a drop comes from outside (a sortable)
		if(this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				self._trigger("stop", event);
				self._clear();
			});
		} else {
			this._trigger("stop", event);
			this._clear();
		}

		return false;
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
			var ce = $(o.containment)[0]; if(!ce) return;
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		} else if(o.containment.constructor == Array) {
			this.containment = o.containment;
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return $.widget.prototype._trigger.call(this, type, event, ui);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs, //deprecated
			offset: this.positionAbs
		};
	}

}));

$.extend($.ui.draggable, {
	version: "1.7.2",
	eventPrefix: "drag",
	defaults: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		cancel: ":input,option",
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		delay: 0,
		distance: 1,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false
	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, 'sortable');
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
				if(this.shouldRevert) this.instance.options.revert = true;

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper == 'original')
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {
			
			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;
			
			if(this.instance._intersectsWith(this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					
					//Prevent reverting on this forced stop
					this.instance.options.revert = false;
					
					// The out event needs to be triggered independently
					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
					
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), o = $(this).data('draggable').options;
		if (t.css("cursor")) o._cursor = t.css("cursor");
		t.css("cursor", o.cursor);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if (o._cursor) $('body').css("cursor", o._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		var o = $(this).data('draggable').options;
		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data('draggable').options;
		if(t.css("opacity")) o._opacity = t.css("opacity");
		t.css('opacity', o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("draggable");
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	drag: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if(!o.axis || o.axis != 'x') {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
			}

			if(!o.axis || o.axis != 'y') {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
			}

		} else {

			if(!o.axis || o.axis != 'x') {
				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}

			if(!o.axis || o.axis != 'y') {
				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options;
		i.snapElements = [];

		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != i.element[0]) i.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options;
		var d = o.snapTolerance;

		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(o.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
			}

			var first = (ts || bs || ls || rs);

			if(o.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {

		var o = $(this).data("draggable").options;

		var group = $.makeArray($(o.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || o.stack.min) - (parseInt($(b).css("zIndex"),10) || o.stack.min);
		});

		$(group).each(function(i) {
			this.style.zIndex = o.stack.min + i;
		});

		this[0].style.zIndex = o.stack.min + group.length;

	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("draggable").options;
		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
		t.css('zIndex', o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("draggable").options;
		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
	}
});

})(jQuery);
/*
 * jQuery UI Droppable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 */
(function($) {

$.widget("ui.droppable", {

	_init: function() {

		var o = this.options, accept = o.accept;
		this.isover = 0; this.isout = 1;

		this.options.accept = this.options.accept && $.isFunction(this.options.accept) ? this.options.accept : function(d) {
			return d.is(accept);
		};

		//Store the droppable's proportions
		this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };

		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[this.options.scope] = $.ui.ddmanager.droppables[this.options.scope] || [];
		$.ui.ddmanager.droppables[this.options.scope].push(this);

		(this.options.addClasses && this.element.addClass("ui-droppable"));

	},

	destroy: function() {
		var drop = $.ui.ddmanager.droppables[this.options.scope];
		for ( var i = 0; i < drop.length; i++ )
			if ( drop[i] == this )
				drop.splice(i, 1);

		this.element
			.removeClass("ui-droppable ui-droppable-disabled")
			.removeData("droppable")
			.unbind(".droppable");
	},

	_setData: function(key, value) {

		if(key == 'accept') {
			this.options.accept = value && $.isFunction(value) ? value : function(d) {
				return d.is(value);
			};
		} else {
			$.widget.prototype._setData.apply(this, arguments);
		}

	},

	_activate: function(event) {
		var draggable = $.ui.ddmanager.current;
		if(this.options.activeClass) this.element.addClass(this.options.activeClass);
		(draggable && this._trigger('activate', event, this.ui(draggable)));
	},

	_deactivate: function(event) {
		var draggable = $.ui.ddmanager.current;
		if(this.options.activeClass) this.element.removeClass(this.options.activeClass);
		(draggable && this._trigger('deactivate', event, this.ui(draggable)));
	},

	_over: function(event) {

		var draggable = $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element

		if (this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.hoverClass) this.element.addClass(this.options.hoverClass);
			this._trigger('over', event, this.ui(draggable));
		}

	},

	_out: function(event) {

		var draggable = $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element

		if (this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
			this._trigger('out', event, this.ui(draggable));
		}

	},

	_drop: function(event,custom) {

		var draggable = custom || $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element

		var childrenIntersection = false;
		this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() {
			var inst = $.data(this, 'droppable');
			if(inst.options.greedy && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)) {
				childrenIntersection = true; return false;
			}
		});
		if(childrenIntersection) return false;

		if(this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.activeClass) this.element.removeClass(this.options.activeClass);
			if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
			this._trigger('drop', event, this.ui(draggable));
			return this.element;
		}

		return false;

	},

	ui: function(c) {
		return {
			draggable: (c.currentItem || c.element),
			helper: c.helper,
			position: c.position,
			absolutePosition: c.positionAbs, //deprecated
			offset: c.positionAbs
		};
	}

});

$.extend($.ui.droppable, {
	version: "1.7.2",
	eventPrefix: 'drop',
	defaults: {
		accept: '*',
		activeClass: false,
		addClasses: true,
		greedy: false,
		hoverClass: false,
		scope: 'default',
		tolerance: 'intersect'
	}
});

$.ui.intersect = function(draggable, droppable, toleranceMode) {

	if (!droppable.offset) return false;

	var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
		y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height;
	var l = droppable.offset.left, r = l + droppable.proportions.width,
		t = droppable.offset.top, b = t + droppable.proportions.height;

	switch (toleranceMode) {
		case 'fit':
			return (l < x1 && x2 < r
				&& t < y1 && y2 < b);
			break;
		case 'intersect':
			return (l < x1 + (draggable.helperProportions.width / 2) // Right Half
				&& x2 - (draggable.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (draggable.helperProportions.height / 2) // Bottom Half
				&& y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
			break;
		case 'pointer':
			var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left),
				draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top),
				isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width);
			return isOver;
			break;
		case 'touch':
			return (
					(y1 >= t && y1 <= b) ||	// Top edge touching
					(y2 >= t && y2 <= b) ||	// Bottom edge touching
					(y1 < t && y2 > b)		// Surrounded vertically
				) && (
					(x1 >= l && x1 <= r) ||	// Left edge touching
					(x2 >= l && x2 <= r) ||	// Right edge touching
					(x1 < l && x2 > r)		// Surrounded horizontally
				);
			break;
		default:
			return false;
			break;
		}

};

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { 'default': [] },
	prepareOffsets: function(t, event) {

		var m = $.ui.ddmanager.droppables[t.options.scope];
		var type = event ? event.type : null; // workaround for #2317
		var list = (t.currentItem || t.element).find(":data(droppable)").andSelf();

		droppablesLoop: for (var i = 0; i < m.length; i++) {

			if(m[i].options.disabled || (t && !m[i].options.accept.call(m[i].element[0],(t.currentItem || t.element)))) continue;	//No disabled and non-accepted
			for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item
			m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; 									//If the element is not visible, continue

			m[i].offset = m[i].element.offset();
			m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };

			if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables

		}

	},
	drop: function(draggable, event) {

		var dropped = false;
		$.each($.ui.ddmanager.droppables[draggable.options.scope], function() {

			if(!this.options) return;
			if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance))
				dropped = this._drop.call(this, event);

			if (!this.options.disabled && this.visible && this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
				this.isout = 1; this.isover = 0;
				this._deactivate.call(this, event);
			}

		});
		return dropped;

	},
	drag: function(draggable, event) {

		//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
		if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event);

		//Run through all droppables and check their positions based on specific tolerance options

		$.each($.ui.ddmanager.droppables[draggable.options.scope], function() {

			if(this.options.disabled || this.greedyChild || !this.visible) return;
			var intersects = $.ui.intersect(draggable, this, this.options.tolerance);

			var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null);
			if(!c) return;

			var parentInstance;
			if (this.options.greedy) {
				var parent = this.element.parents(':data(droppable):eq(0)');
				if (parent.length) {
					parentInstance = $.data(parent[0], 'droppable');
					parentInstance.greedyChild = (c == 'isover' ? 1 : 0);
				}
			}

			// we just moved into a greedy child
			if (parentInstance && c == 'isover') {
				parentInstance['isover'] = 0;
				parentInstance['isout'] = 1;
				parentInstance._out.call(parentInstance, event);
			}

			this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0;
			this[c == "isover" ? "_over" : "_out"].call(this, event);

			// we just moved out of a greedy child
			if (parentInstance && c == 'isout') {
				parentInstance['isout'] = 0;
				parentInstance['isover'] = 1;
				parentInstance._over.call(parentInstance, event);
			}
		});

	}
};

})(jQuery);
/*
 * jQuery UI Resizable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.resizable", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this, o = this.options;
		this.element.addClass("ui-resizable");

		$.extend(this, {
			_aspectRatio: !!(o.aspectRatio),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null
		});

		//Wrap the element if it cannot hold child nodes
		if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {

			//Opera fix for relative positioning
			if (/relative/.test(this.element.css('position')) && $.browser.opera)
				this.element.css({ position: 'relative', top: 'auto', left: 'auto' });

			//Create a wrapper element and set the wrapper to the new current internal element
			this.element.wrap(
				$('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
					position: this.element.css('position'),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css('top'),
					left: this.element.css('left')
				})
			);

			//Overwrite the original this.element
			this.element = this.element.parent().data(
				"resizable", this.element.data('resizable')
			);

			this.elementIsWrapper = true;

			//Move margins to the wrapper
			this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
			this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});

			//Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css('resize');
			this.originalElement.css('resize', 'none');

			//Push the actual element to our proportionallyResize internal array
			this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' }));

			// avoid IE jump (hard set the margin)
			this.originalElement.css({ margin: this.originalElement.css('margin') });

			// fix handlers offset
			this._proportionallyResize();

		}

		this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' });
		if(this.handles.constructor == String) {

			if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw';
			var n = this.handles.split(","); this.handles = {};

			for(var i = 0; i < n.length; i++) {

				var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle;
				var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>');

				// increase zIndex of sw, se, ne, nw axis
				//TODO : this modifies original option
				if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex });

				//TODO : What's going on here?
				if ('se' == handle) {
					axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se');
				};

				//Insert into internal handles object and append to element
				this.handles[handle] = '.ui-resizable-'+handle;
				this.element.append(axis);
			}

		}

		this._renderAxis = function(target) {

			target = target || this.element;

			for(var i in this.handles) {

				if(this.handles[i].constructor == String)
					this.handles[i] = $(this.handles[i], this.element).show();

				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {

					var axis = $(this.handles[i], this.element), padWrapper = 0;

					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					//The padding type i have to apply...
					var padPos = [ 'padding',
						/ne|nw|n/.test(i) ? 'Top' :
						/se|sw|s/.test(i) ? 'Bottom' :
						/^e$/.test(i) ? 'Right' : 'Left' ].join("");

					target.css(padPos, padWrapper);

					this._proportionallyResize();

				}

				//TODO: What's that good for? There's not anything to be executed left
				if(!$(this.handles[i]).length)
					continue;

			}
		};

		//TODO: make renderAxis a prototype function
		this._renderAxis(this.element);

		this._handles = $('.ui-resizable-handle', this.element)
			.disableSelection();

		//Matching axis name
		this._handles.mouseover(function() {
			if (!self.resizing) {
				if (this.className)
					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				//Axis, default = se
				self.axis = axis && axis[1] ? axis[1] : 'se';
			}
		});

		//If we want to auto hide the elements
		if (o.autoHide) {
			this._handles.hide();
			$(this.element)
				.addClass("ui-resizable-autohide")
				.hover(function() {
					$(this).removeClass("ui-resizable-autohide");
					self._handles.show();
				},
				function(){
					if (!self.resizing) {
						$(this).addClass("ui-resizable-autohide");
						self._handles.hide();
					}
				});
		}

		//Initialize the mouse interaction
		this._mouseInit();

	},

	destroy: function() {

		this._mouseDestroy();

		var _destroy = function(exp) {
			$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
				.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
		};

		//TODO: Unwrap at same DOM position
		if (this.elementIsWrapper) {
			_destroy(this.element);
			var wrapper = this.element;
			wrapper.parent().append(
				this.originalElement.css({
					position: wrapper.css('position'),
					width: wrapper.outerWidth(),
					height: wrapper.outerHeight(),
					top: wrapper.css('top'),
					left: wrapper.css('left')
				})
			).end().remove();
		}

		this.originalElement.css('resize', this.originalResizeStyle);
		_destroy(this.originalElement);

	},

	_mouseCapture: function(event) {

		var handle = false;
		for(var i in this.handles) {
			if($(this.handles[i])[0] == event.target) handle = true;
		}

		return this.options.disabled || !!handle;

	},

	_mouseStart: function(event) {

		var o = this.options, iniPos = this.element.position(), el = this.element;

		this.resizing = true;
		this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };

		// bugfix for http://dev.jquery.com/ticket/1749
		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
			el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left });
		}

		//Opera fixing relative position
		if ($.browser.opera && (/relative/).test(el.css('position')))
			el.css({ position: 'relative', top: 'auto', left: 'auto' });

		this._renderProxy();

		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft() || 0;
			curtop += $(o.containment).scrollTop() || 0;
		}

		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		//Aspect Ratio
		this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);

	    var cursor = $('.ui-resizable-' + this.axis).css('cursor');
	    $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);

		el.addClass("ui-resizable-resizing");
		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		//Increase performance, avoid regex
		var el = this.helper, o = this.options, props = {},
			self = this, smp = this.originalMousePosition, a = this.axis;

		var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
		var trigger = this._change[a];
		if (!trigger) return false;

		// Calculate the attrs that will be change
		var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;

		if (this._aspectRatio || event.shiftKey)
			data = this._updateRatio(data, event);

		data = this._respectSize(data, event);

		// plugins callbacks need to be called first
		this._propagate("resize", event);

		el.css({
			top: this.position.top + "px", left: this.position.left + "px",
			width: this.size.width + "px", height: this.size.height + "px"
		});

		if (!this._helper && this._proportionallyResizeElements.length)
			this._proportionallyResize();

		this._updateCache(data);

		// calling the user callback at the end
		this._trigger('resize', event, this.ui());

		return false;
	},

	_mouseStop: function(event) {

		this.resizing = false;
		var o = this.options, self = this;

		if(this._helper) {
			var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
						soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;

			var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
				left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
				top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

			if (!o.animate)
				this.element.css($.extend(s, { top: top, left: left }));

			self.helper.height(self.size.height);
			self.helper.width(self.size.width);

			if (this._helper && !o.animate) this._proportionallyResize();
		}

		$('body').css('cursor', 'auto');

		this.element.removeClass("ui-resizable-resizing");

		this._propagate("stop", event);

		if (this._helper) this.helper.remove();
		return false;

	},

	_updateCache: function(data) {
		var o = this.options;
		this.offset = this.helper.offset();
		if (isNumber(data.left)) this.position.left = data.left;
		if (isNumber(data.top)) this.position.top = data.top;
		if (isNumber(data.height)) this.size.height = data.height;
		if (isNumber(data.width)) this.size.width = data.width;
	},

	_updateRatio: function(data, event) {

		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;

		if (data.height) data.width = (csize.height * this.aspectRatio);
		else if (data.width) data.height = (csize.width / this.aspectRatio);

		if (a == 'sw') {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a == 'nw') {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function(data, event) {

		var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis,
				ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
					isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height);

		if (isminw) data.width = o.minWidth;
		if (isminh) data.height = o.minHeight;
		if (ismaxw) data.width = o.maxWidth;
		if (ismaxh) data.height = o.maxHeight;

		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);

		if (isminw && cw) data.left = dw - o.minWidth;
		if (ismaxw && cw) data.left = dw - o.maxWidth;
		if (isminh && ch)	data.top = dh - o.minHeight;
		if (ismaxh && ch)	data.top = dh - o.maxHeight;

		// fixing jump error on top/left - bug #2330
		var isNotwh = !data.width && !data.height;
		if (isNotwh && !data.left && data.top) data.top = null;
		else if (isNotwh && !data.top && data.left) data.left = null;

		return data;
	},

	_proportionallyResize: function() {

		var o = this.options;
		if (!this._proportionallyResizeElements.length) return;
		var element = this.helper || this.element;

		for (var i=0; i < this._proportionallyResizeElements.length; i++) {

			var prel = this._proportionallyResizeElements[i];

			if (!this.borderDif) {
				var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
					p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];

				this.borderDif = $.map(b, function(v, i) {
					var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
					return border + padding;
				});
			}

			if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length)))
				continue;

			prel.css({
				height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
				width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
			});

		};

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if(this._helper) {

			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');

			// fix ie6 offset TODO: This seems broken
			var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
			pxyoffset = ( ie6 ? 2 : -1 );

			this.helper.addClass(this._helper).css({
				width: this.element.outerWidth() + pxyoffset,
				height: this.element.outerHeight() + pxyoffset,
				position: 'absolute',
				left: this.elementOffset.left - ie6offset +'px',
				top: this.elementOffset.top - ie6offset +'px',
				zIndex: ++o.zIndex //TODO: Don't modify option
			});

			this.helper
				.appendTo("body")
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function(event, dx, dy) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this.ui()]);
		(n != "resize" && this._trigger(n, event, this.ui()));
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

}));

$.extend($.ui.resizable, {
	version: "1.7.2",
	eventPrefix: "resize",
	defaults: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		cancel: ":input,option",
		containment: false,
		delay: 0,
		distance: 1,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		zIndex: 1000
	}
});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "alsoResize", {

	start: function(event, ui) {

		var self = $(this).data("resizable"), o = self.options;

		_store = function(exp) {
			$(exp).each(function() {
				$(this).data("resizable-alsoresize", {
					width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
					left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
				});
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0];	_store(o.alsoResize); }
			else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		}
	},

	resize: function(event, ui){
		var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition;

		var delta = {
			height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
			top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
		},

		_alsoResize = function(exp, c) {
			$(exp).each(function() {
				var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];

				$.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
					var sum = (start[prop]||0) + (delta[prop]||0);
					if (sum && sum >= 0)
						style[prop] = sum || null;
				});

				//Opera fixing relative position
				if (/relative/.test(el.css('position')) && $.browser.opera) {
					self._revertToRelativePosition = true;
					el.css({ position: 'absolute', top: 'auto', left: 'auto' });
				}

				el.css(style);
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) {
			$.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},

	stop: function(event, ui){
		var self = $(this).data("resizable");

		//Opera fixing relative position
		if (self._revertToRelativePosition && $.browser.opera) {
			self._revertToRelativePosition = false;
			el.css({ position: 'relative' });
		}

		$(this).removeData("resizable-alsoresize-start");
	}
});

$.ui.plugin.add("resizable", "animate", {

	stop: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options;

		var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
					soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
						soffsetw = ista ? 0 : self.sizeDiff.width;

		var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
					left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
						top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

		self.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(self.element.css('width'), 10),
						height: parseInt(self.element.css('height'), 10),
						top: parseInt(self.element.css('top'), 10),
						left: parseInt(self.element.css('left'), 10)
					};

					if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height });

					// propagating resize, and updating values for each animation step
					self._updateCache(data);
					self._propagate("resize", event);

				}
			}
		);
	}

});

$.ui.plugin.add("resizable", "containment", {

	start: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options, el = self.element;
		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
		if (!ce) return;

		self.containerElement = $(ce);

		if (/document/.test(oc) || oc == document) {
			self.containerOffset = { left: 0, top: 0 };
			self.containerPosition = { left: 0, top: 0 };

			self.parentData = {
				element: $(document), left: 0, top: 0,
				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
			};
		}

		// i'm a node, so compute top, left, right, bottom
		else {
			var element = $(ce), p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });

			self.containerOffset = element.offset();
			self.containerPosition = element.position();
			self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };

			var co = self.containerOffset, ch = self.containerSize.height,	cw = self.containerSize.width,
						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);

			self.parentData = {
				element: ce, left: co.left, top: co.top, width: width, height: height
			};
		}
	},

	resize: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options,
				ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
				pRatio = self._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;

		if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;

		if (cp.left < (self._helper ? co.left : 0)) {
			self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left));
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
			self.position.left = o.helper ? co.left : 0;
		}

		if (cp.top < (self._helper ? co.top : 0)) {
			self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top);
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
			self.position.top = self._helper ? co.top : 0;
		}

		self.offset.left = self.parentData.left+self.position.left;
		self.offset.top = self.parentData.top+self.position.top;

		var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ),
					hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height );

		var isParent = self.containerElement.get(0) == self.element.parent().get(0),
		    isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position'));

		if(isParent && isOffsetRelative) woset -= self.parentData.left;

		if (woset + self.size.width >= self.parentData.width) {
			self.size.width = self.parentData.width - woset;
			if (pRatio) self.size.height = self.size.width / self.aspectRatio;
		}

		if (hoset + self.size.height >= self.parentData.height) {
			self.size.height = self.parentData.height - hoset;
			if (pRatio) self.size.width = self.size.height * self.aspectRatio;
		}
	},

	stop: function(event, ui){
		var self = $(this).data("resizable"), o = self.options, cp = self.position,
				co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;

		var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height;

		if (self._helper && !o.animate && (/relative/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

		if (self._helper && !o.animate && (/static/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function(event, ui) {

		var self = $(this).data("resizable"), o = self.options, cs = self.size;

		self.ghost = self.originalElement.clone();
		self.ghost
			.css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
			.addClass('ui-resizable-ghost')
			.addClass(typeof o.ghost == 'string' ? o.ghost : '');

		self.ghost.appendTo(self.helper);

	},

	resize: function(event, ui){
		var self = $(this).data("resizable"), o = self.options;
		if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });
	},

	stop: function(event, ui){
		var self = $(this).data("resizable"), o = self.options;
		if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey;
		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);

		if (/^(se|s|e)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
		}
		else if (/^(ne)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
		}
		else if (/^(sw)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.left = op.left - ox;
		}
		else {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
			self.position.left = op.left - ox;
		}
	}

});

var num = function(v) {
	return parseInt(v, 10) || 0;
};

var isNumber = function(value) {
	return !isNaN(parseInt(value, 10));
};

})(jQuery);
/*
 * jQuery UI Selectable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Selectables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.selectable", $.extend({}, $.ui.mouse, {

	_init: function() {
		var self = this;

		this.element.addClass("ui-selectable");

		this.dragged = false;

		// cache selectee children based on filter
		var selectees;
		this.refresh = function() {
			selectees = $(self.options.filter, self.element[0]);
			selectees.each(function() {
				var $this = $(this);
				var pos = $this.offset();
				$.data(this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass('ui-selected'),
					selecting: $this.hasClass('ui-selecting'),
					unselecting: $this.hasClass('ui-unselecting')
				});
			});
		};
		this.refresh();

		this.selectees = selectees.addClass("ui-selectee");

		this._mouseInit();

		this.helper = $(document.createElement('div'))
			.css({border:'1px dotted black'})
			.addClass("ui-selectable-helper");
	},

	destroy: function() {
		this.element
			.removeClass("ui-selectable ui-selectable-disabled")
			.removeData("selectable")
			.unbind(".selectable");
		this._mouseDestroy();
	},

	_mouseStart: function(event) {
		var self = this;

		this.opos = [event.pageX, event.pageY];

		if (this.options.disabled)
			return;

		var options = this.options;

		this.selectees = $(options.filter, this.element[0]);

		this._trigger("start", event);

		$(options.appendTo).append(this.helper);
		// position helper (lasso)
		this.helper.css({
			"z-index": 100,
			"position": "absolute",
			"left": event.clientX,
			"top": event.clientY,
			"width": 0,
			"height": 0
		});

		if (options.autoRefresh) {
			this.refresh();
		}

		this.selectees.filter('.ui-selected').each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.startselected = true;
			if (!event.metaKey) {
				selectee.$element.removeClass('ui-selected');
				selectee.selected = false;
				selectee.$element.addClass('ui-unselecting');
				selectee.unselecting = true;
				// selectable UNSELECTING callback
				self._trigger("unselecting", event, {
					unselecting: selectee.element
				});
			}
		});

		$(event.target).parents().andSelf().each(function() {
			var selectee = $.data(this, "selectable-item");
			if (selectee) {
				selectee.$element.removeClass("ui-unselecting").addClass('ui-selecting');
				selectee.unselecting = false;
				selectee.selecting = true;
				selectee.selected = true;
				// selectable SELECTING callback
				self._trigger("selecting", event, {
					selecting: selectee.element
				});
				return false;
			}
		});

	},

	_mouseDrag: function(event) {
		var self = this;
		this.dragged = true;

		if (this.options.disabled)
			return;

		var options = this.options;

		var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY;
		if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; }
		if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; }
		this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});

		this.selectees.each(function() {
			var selectee = $.data(this, "selectable-item");
			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element == self.element[0])
				return;
			var hit = false;
			if (options.tolerance == 'touch') {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance == 'fit') {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					selectee.$element.removeClass('ui-selected');
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					selectee.$element.removeClass('ui-unselecting');
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					selectee.$element.addClass('ui-selecting');
					selectee.selecting = true;
					// selectable SELECTING callback
					self._trigger("selecting", event, {
						selecting: selectee.element
					});
				}
			} else {
				// UNSELECT
				if (selectee.selecting) {
					if (event.metaKey && selectee.startselected) {
						selectee.$element.removeClass('ui-selecting');
						selectee.selecting = false;
						selectee.$element.addClass('ui-selected');
						selectee.selected = true;
					} else {
						selectee.$element.removeClass('ui-selecting');
						selectee.selecting = false;
						if (selectee.startselected) {
							selectee.$element.addClass('ui-unselecting');
							selectee.unselecting = true;
						}
						// selectable UNSELECTING callback
						self._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
				if (selectee.selected) {
					if (!event.metaKey && !selectee.startselected) {
						selectee.$element.removeClass('ui-selected');
						selectee.selected = false;

						selectee.$element.addClass('ui-unselecting');
						selectee.unselecting = true;
						// selectable UNSELECTING callback
						self._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
			}
		});

		return false;
	},

	_mouseStop: function(event) {
		var self = this;

		this.dragged = false;

		var options = this.options;

		$('.ui-unselecting', this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass('ui-unselecting');
			selectee.unselecting = false;
			selectee.startselected = false;
			self._trigger("unselected", event, {
				unselected: selectee.element
			});
		});
		$('.ui-selecting', this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass('ui-selecting').addClass('ui-selected');
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			self._trigger("selected", event, {
				selected: selectee.element
			});
		});
		this._trigger("stop", event);

		this.helper.remove();

		return false;
	}

}));

$.extend($.ui.selectable, {
	version: "1.7.2",
	defaults: {
		appendTo: 'body',
		autoRefresh: true,
		cancel: ":input,option",
		delay: 0,
		distance: 0,
		filter: '*',
		tolerance: 'touch'
	}
});

})(jQuery);
/*
 * jQuery UI Sortable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.sortable", $.extend({}, $.ui.mouse, {
	_init: function() {

		var o = this.options;
		this.containerCache = {};
		this.element.addClass("ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine if the items are floating
		this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

	},

	destroy: function() {
		this.element
			.removeClass("ui-sortable ui-sortable-disabled")
			.removeData("sortable")
			.unbind(".sortable");
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- )
			this.items[i].item.removeData("sortable-item");
	},

	_mouseCapture: function(event, overrideHandle) {

		if (this.reverting) {
			return false;
		}

		if(this.options.disabled || this.options.type == 'static') return false;

		//We have to refresh the items data once first
		this._refreshItems(event);

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
			if($.data(this, 'sortable-item') == self) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);

		if(!currentItem) return false;
		if(this.options.handle && !overrideHandle) {
			var validHandle = false;

			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
			if(!validHandle) return false;
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

		var o = this.options, self = this;
		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css("position", "absolute");
		this.cssPosition = this.helper.css("position");

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Cache the former DOM position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
		if(this.helper[0] != this.currentItem[0]) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		if(o.cursor) { // cursor option
			if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
			$('body').css("cursor", o.cursor);
		}

		if(o.opacity) { // opacity option
			if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
			this.helper.css("opacity", o.opacity);
		}

		if(o.zIndex) { // zIndex option
			if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
			this.helper.css("zIndex", o.zIndex);
		}

		//Prepare scrolling
		if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
			this.overflowOffset = this.scrollParent.offset();

		//Call callbacks
		this._trigger("start", event, this._uiHash());

		//Recache the helper size
		if(!this._preserveHelperProportions)
			this._cacheHelperProportions();


		//Post 'activate' events to possible containers
		if(!noActivation) {
			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
		}

		//Prepare possible droppables
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.dragging = true;

		this.helper.addClass("ui-sortable-helper");
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			var o = this.options, scrolled = false;
			if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {

				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;

				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;

			} else {

				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

			}

			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
				$.ui.ddmanager.prepareOffsets(this, event);
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';

		//Rearrange
		for (var i = this.items.length - 1; i >= 0; i--) {

			//Cache variables and intersection, continue if no intersection
			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
			if (!intersection) continue;

			if(itemElement != this.currentItem[0] //cannot intersect with itself
				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
			) {

				this.direction = intersection == 1 ? "down" : "up";

				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
					this._rearrange(event, item);
				} else {
					break;
				}

				this._trigger("change", event, this._uiHash());
				break;
			}
		}

		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		//Call callbacks
		this._trigger('sort', event, this._uiHash());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function(event, noPropagation) {

		if(!event) return;

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			$.ui.ddmanager.drop(this, event);

		if(this.options.revert) {
			var self = this;
			var cur = self.placeholder.offset();

			self.reverting = true;

			$(this.helper).animate({
				left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
				top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
			}, parseInt(this.options.revert, 10) || 500, function() {
				self._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},

	cancel: function() {

		var self = this;

		if(this.dragging) {

			this._mouseUp();

			if(this.options.helper == "original")
				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
			else
				this.currentItem.show();

			//Post deactivating events to containers
			for (var i = this.containers.length - 1; i >= 0; i--){
				this.containers[i]._trigger("deactivate", null, self._uiHash(this));
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", null, self._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
		if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();

		$.extend(this, {
			helper: null,
			dragging: false,
			reverting: false,
			_noFinalSort: null
		});

		if(this.domPosition.prev) {
			$(this.domPosition.prev).after(this.currentItem);
		} else {
			$(this.domPosition.parent).prepend(this.currentItem);
		}

		return true;

	},

	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var str = []; o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
			if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
		});

		return str.join('&');

	},

	toArray: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var ret = []; o = o || {};

		items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height;

		var l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height;

		var dyClick = this.offset.click.top,
			dxClick = this.offset.click.left;

		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;

		if(	   this.options.tolerance == "pointer"
			|| this.options.forcePointerForContainers
			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 2) // Right Half
				&& x2 - (this.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function(item) {

		var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement)
			return false;

		return this.floating ?
			( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (this.floating && horizontalDirection) {
			return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
		} else {
			return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta != 0 && (delta > 0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta != 0 && (delta > 0 ? "right" : "left");
	},

	refresh: function(event) {
		this._refreshItems(event);
		this.refreshPositions();
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor == String
			? [options.connectWith]
			: options.connectWith;
	},
	
	_getItemsAsjQuery: function(connected) {

		var self = this;
		var items = [];
		var queries = [];
		var connectWith = this._connectWith();

		if(connectWith && connected) {
			for (var i = connectWith.length - 1; i >= 0; i--){
				var cur = $(connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper"), inst]);
					}
				};
			};
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper"), this]);

		for (var i = queries.length - 1; i >= 0; i--){
			queries[i][0].each(function() {
				items.push(this);
			});
		};

		return $(items);

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(sortable-item)");

		for (var i=0; i < this.items.length; i++) {

			for (var j=0; j < list.length; j++) {
				if(list[j] == this.items[i].item[0])
					this.items.splice(i,1);
			};

		};

	},

	_refreshItems: function(event) {

		this.items = [];
		this.containers = [this];
		var items = this.items;
		var self = this;
		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
		var connectWith = this._connectWith();

		if(connectWith) {
			for (var i = connectWith.length - 1; i >= 0; i--){
				var cur = $(connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				};
			};
		}

		for (var i = queries.length - 1; i >= 0; i--) {
			var targetData = queries[i][1];
			var _queries = queries[i][0];

			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				var item = $(_queries[j]);

				item.data('sortable-item', targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			};
		};

	},

	refreshPositions: function(fast) {

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent && this.helper) {
			this.offset.parent = this._getParentOffset();
		}

		for (var i = this.items.length - 1; i >= 0; i--){
			var item = this.items[i];

			//We ignore calculating positions of all connected containers when we're not over them
			if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
				continue;

			var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

			if (!fast) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			var p = t.offset();
			item.left = p.left;
			item.top = p.top;
		};

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (var i = this.containers.length - 1; i >= 0; i--){
				var p = this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			};
		}

	},

	_createPlaceholder: function(that) {

		var self = that || this, o = self.options;

		if(!o.placeholder || o.placeholder.constructor == String) {
			var className = o.placeholder;
			o.placeholder = {
				element: function() {

					var el = $(document.createElement(self.currentItem[0].nodeName))
						.addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
						.removeClass("ui-sortable-helper")[0];

					if(!className)
						el.style.visibility = "hidden";

					return el;
				},
				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) return;

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
					if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
				}
			};
		}

		//Create the placeholder
		self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));

		//Append it after the actual current item
		self.currentItem.after(self.placeholder);

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update(self, self.placeholder);

	},

	_contactContainers: function(event) {
		for (var i = this.containers.length - 1; i >= 0; i--){

			if(this._intersectsWith(this.containers[i].containerCache)) {
				if(!this.containers[i].containerCache.over) {

					if(this.currentContainer != this.containers[i]) {

						//When entering a new container, we will find the item with the least distance and append our item near it
						var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top'];
						for (var j = this.items.length - 1; j >= 0; j--) {
							if(!$.ui.contains(this.containers[i].element[0], this.items[j].item[0])) continue;
							var cur = this.items[j][this.containers[i].floating ? 'left' : 'top'];
							if(Math.abs(cur - base) < dist) {
								dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
							}
						}

						if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
							continue;

						this.currentContainer = this.containers[i];
						itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[i].element, true);
						this._trigger("change", event, this._uiHash());
						this.containers[i]._trigger("change", event, this._uiHash(this));

						//Update the placeholder
						this.options.placeholder.update(this.currentContainer, this.placeholder);

					}

					this.containers[i]._trigger("over", event, this._uiHash(this));
					this.containers[i].containerCache.over = 1;
				}
			} else {
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", event, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		};
	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);

		if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);

		if(helper[0] == this.currentItem[0])
			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };

		if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
		if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {


		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.currentItem.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			var ce = $(o.containment)[0];
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var self = this, counter = this.counter;

		window.setTimeout(function() {
			if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
		},0);

	},

	_clear: function(event, noPropagation) {

		this.reverting = false;
		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
		// everything else normalized again
		var delayedTriggers = [], self = this;

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
		if(!this._noFinalSort && this.currentItem[0].parentNode) this.placeholder.before(this.currentItem);
		this._noFinalSort = null;

		if(this.helper[0] == this.currentItem[0]) {
			for(var i in this._storedCSS) {
				if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
			}
			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
		} else {
			this.currentItem.show();
		}

		if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
		if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
		if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
			if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
			for (var i = this.containers.length - 1; i >= 0; i--){
				if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) {
					delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
					delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
				}
			};
		};

		//Post events to containers
		for (var i = this.containers.length - 1; i >= 0; i--){
			if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
			if(this.containers[i].containerCache.over) {
				delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
				this.containers[i].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
		if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset cursor
		if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index

		this.dragging = false;
		if(this.cancelHelperRemoval) {
			if(!noPropagation) {
				this._trigger("beforeStop", event, this._uiHash());
				for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
				this._trigger("stop", event, this._uiHash());
			}
			return false;
		}

		if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

		if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;

		if(!noPropagation) {
			for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
			this._trigger("stop", event, this._uiHash());
		}

		this.fromOutside = false;
		return true;

	},

	_trigger: function() {
		if ($.widget.prototype._trigger.apply(this, arguments) === false) {
			this.cancel();
		}
	},

	_uiHash: function(inst) {
		var self = inst || this;
		return {
			helper: self.helper,
			placeholder: self.placeholder || $([]),
			position: self.position,
			absolutePosition: self.positionAbs, //deprecated
			offset: self.positionAbs,
			item: self.currentItem,
			sender: inst ? inst.element : null
		};
	}

}));

$.extend($.ui.sortable, {
	getter: "serialize toArray",
	version: "1.7.2",
	eventPrefix: "sort",
	defaults: {
		appendTo: "parent",
		axis: false,
		cancel: ":input,option",
		connectWith: false,
		containment: false,
		cursor: 'auto',
		cursorAt: false,
		delay: 0,
		distance: 1,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: '> *',
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000
	}
});

})(jQuery);
/*
 * jQuery UI Accordion 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.accordion", {

	_init: function() {

		var o = this.options, self = this;
		this.running = 0;

		// if the user set the alwaysOpen option on init
		// then we need to set the collapsible option
		// if they set both on init, collapsible will take priority
		if (o.collapsible == $.ui.accordion.defaults.collapsible &&
			o.alwaysOpen != $.ui.accordion.defaults.alwaysOpen) {
			o.collapsible = !o.alwaysOpen;
		}

		if ( o.navigation ) {
			var current = this.element.find("a").filter(o.navigationFilter);
			if ( current.length ) {
				if ( current.filter(o.header).length ) {
					this.active = current;
				} else {
					this.active = current.parent().parent().prev();
					current.addClass("ui-accordion-content-active");
				}
			}
		}

		this.element.addClass("ui-accordion ui-widget ui-helper-reset");
		
		// in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix
		if (this.element[0].nodeName == "UL") {
			this.element.children("li").addClass("ui-accordion-li-fix");
		}

		this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all")
			.bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); })
			.bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); })
			.bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); })
			.bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); });

		this.headers
			.next()
				.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");

		this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");
		this.active.next().addClass('ui-accordion-content-active');

		//Append icon elements
		$("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers);
		this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected);

		// IE7-/Win - Extra vertical space in lists fixed
		if ($.browser.msie) {
			this.element.find('a').css('zoom', '1');
		}

		this.resize();

		//ARIA
		this.element.attr('role','tablist');

		this.headers
			.attr('role','tab')
			.bind('keydown', function(event) { return self._keydown(event); })
			.next()
			.attr('role','tabpanel');

		this.headers
			.not(this.active || "")
			.attr('aria-expanded','false')
			.attr("tabIndex", "-1")
			.next()
			.hide();

		// make sure at least one header is in the tab order
		if (!this.active.length) {
			this.headers.eq(0).attr('tabIndex','0');
		} else {
			this.active
				.attr('aria-expanded','true')
				.attr('tabIndex', '0');
		}

		// only need links in taborder for Safari
		if (!$.browser.safari)
			this.headers.find('a').attr('tabIndex','-1');

		if (o.event) {
			this.headers.bind((o.event) + ".accordion", function(event) { return self._clickHandler.call(self, event, this); });
		}

	},

	destroy: function() {
		var o = this.options;

		this.element
			.removeClass("ui-accordion ui-widget ui-helper-reset")
			.removeAttr("role")
			.unbind('.accordion')
			.removeData('accordion');

		this.headers
			.unbind(".accordion")
			.removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top")
			.removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex");

		this.headers.find("a").removeAttr("tabindex");
		this.headers.children(".ui-icon").remove();
		var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");
		if (o.autoHeight || o.fillHeight) {
			contents.css("height", "");
		}
	},
	
	_setData: function(key, value) {
		if(key == 'alwaysOpen') { key = 'collapsible'; value = !value; }
		$.widget.prototype._setData.apply(this, arguments);	
	},

	_keydown: function(event) {

		var o = this.options, keyCode = $.ui.keyCode;

		if (o.disabled || event.altKey || event.ctrlKey)
			return;

		var length = this.headers.length;
		var currentIndex = this.headers.index(event.target);
		var toFocus = false;

		switch(event.keyCode) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[(currentIndex + 1) % length];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[(currentIndex - 1 + length) % length];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				return this._clickHandler({ target: event.target }, event.target);
		}

		if (toFocus) {
			$(event.target).attr('tabIndex','-1');
			$(toFocus).attr('tabIndex','0');
			toFocus.focus();
			return false;
		}

		return true;

	},

	resize: function() {

		var o = this.options, maxHeight;

		if (o.fillSpace) {
			
			if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); }
			maxHeight = this.element.parent().height();
			if($.browser.msie) { this.element.parent().css('overflow', defOverflow); }
	
			this.headers.each(function() {
				maxHeight -= $(this).outerHeight();
			});

			var maxPadding = 0;
			this.headers.next().each(function() {
				maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
			}).height(Math.max(0, maxHeight - maxPadding))
			.css('overflow', 'auto');

		} else if ( o.autoHeight ) {
			maxHeight = 0;
			this.headers.next().each(function() {
				maxHeight = Math.max(maxHeight, $(this).outerHeight());
			}).height(maxHeight);
		}

	},

	activate: function(index) {
		// call clickHandler with custom event
		var active = this._findActive(index)[0];
		this._clickHandler({ target: active }, active);
	},

	_findActive: function(selector) {
		return selector
			? typeof selector == "number"
				? this.headers.filter(":eq(" + selector + ")")
				: this.headers.not(this.headers.not(selector))
			: selector === false
				? $([])
				: this.headers.filter(":eq(0)");
	},

	_clickHandler: function(event, target) {

		var o = this.options;
		if (o.disabled) return false;

		// called only when using activate(false) to close all parts programmatically
		if (!event.target && o.collapsible) {
			this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
				.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
			this.active.next().addClass('ui-accordion-content-active');
			var toHide = this.active.next(),
				data = {
					options: o,
					newHeader: $([]),
					oldHeader: o.active,
					newContent: $([]),
					oldContent: toHide
				},
				toShow = (this.active = $([]));
			this._toggle(toShow, toHide, data);
			return false;
		}

		// get the click target
		var clicked = $(event.currentTarget || target);
		var clickedIsActive = clicked[0] == this.active[0];

		// if animations are still active, or the active header is the target, ignore click
		if (this.running || (!o.collapsible && clickedIsActive)) {
			return false;
		}

		// switch classes
		this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
			.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
		this.active.next().addClass('ui-accordion-content-active');
		if (!clickedIsActive) {
			clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top")
				.find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected);
			clicked.next().addClass('ui-accordion-content-active');
		}

		// find elements to show and hide
		var toShow = clicked.next(),
			toHide = this.active.next(),
			data = {
				options: o,
				newHeader: clickedIsActive && o.collapsible ? $([]) : clicked,
				oldHeader: this.active,
				newContent: clickedIsActive && o.collapsible ? $([]) : toShow.find('> *'),
				oldContent: toHide.find('> *')
			},
			down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] );

		this.active = clickedIsActive ? $([]) : clicked;
		this._toggle(toShow, toHide, data, clickedIsActive, down);

		return false;

	},

	_toggle: function(toShow, toHide, data, clickedIsActive, down) {

		var o = this.options, self = this;

		this.toShow = toShow;
		this.toHide = toHide;
		this.data = data;

		var complete = function() { if(!self) return; return self._completed.apply(self, arguments); };

		// trigger changestart event
		this._trigger("changestart", null, this.data);

		// count elements to animate
		this.running = toHide.size() === 0 ? toShow.size() : toHide.size();

		if (o.animated) {

			var animOptions = {};

			if ( o.collapsible && clickedIsActive ) {
				animOptions = {
					toShow: $([]),
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: o.autoHeight || o.fillSpace
				};
			} else {
				animOptions = {
					toShow: toShow,
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: o.autoHeight || o.fillSpace
				};
			}

			if (!o.proxied) {
				o.proxied = o.animated;
			}

			if (!o.proxiedDuration) {
				o.proxiedDuration = o.duration;
			}

			o.animated = $.isFunction(o.proxied) ?
				o.proxied(animOptions) : o.proxied;

			o.duration = $.isFunction(o.proxiedDuration) ?
				o.proxiedDuration(animOptions) : o.proxiedDuration;

			var animations = $.ui.accordion.animations,
				duration = o.duration,
				easing = o.animated;

			if (!animations[easing]) {
				animations[easing] = function(options) {
					this.slide(options, {
						easing: easing,
						duration: duration || 700
					});
				};
			}

			animations[easing](animOptions);

		} else {

			if (o.collapsible && clickedIsActive) {
				toShow.toggle();
			} else {
				toHide.hide();
				toShow.show();
			}

			complete(true);

		}

		toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur();
		toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus();

	},

	_completed: function(cancel) {

		var o = this.options;

		this.running = cancel ? 0 : --this.running;
		if (this.running) return;

		if (o.clearStyle) {
			this.toShow.add(this.toHide).css({
				height: "",
				overflow: ""
			});
		}

		this._trigger('change', null, this.data);
	}

});


$.extend($.ui.accordion, {
	version: "1.7.2",
	defaults: {
		active: null,
		alwaysOpen: true, //deprecated, use collapsible
		animated: 'slide',
		autoHeight: true,
		clearStyle: false,
		collapsible: false,
		event: "click",
		fillSpace: false,
		header: "> li > :first-child,> :not(li):even",
		icons: {
			header: "ui-icon-triangle-1-e",
			headerSelected: "ui-icon-triangle-1-s"
		},
		navigation: false,
		navigationFilter: function() {
			return this.href.toLowerCase() == location.href.toLowerCase();
		}
	},
	animations: {
		slide: function(options, additions) {
			options = $.extend({
				easing: "swing",
				duration: 300
			}, options, additions);
			if ( !options.toHide.size() ) {
				options.toShow.animate({height: "show"}, options);
				return;
			}
			if ( !options.toShow.size() ) {
				options.toHide.animate({height: "hide"}, options);
				return;
			}
			var overflow = options.toShow.css('overflow'),
				percentDone,
				showProps = {},
				hideProps = {},
				fxAttrs = [ "height", "paddingTop", "paddingBottom" ],
				originalWidth;
			// fix width before calculating height of hidden element
			var s = options.toShow;
			originalWidth = s[0].style.width;
			s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - (parseInt(s.css("borderLeftWidth"),10) || 0) - (parseInt(s.css("borderRightWidth"),10) || 0) );
			
			$.each(fxAttrs, function(i, prop) {
				hideProps[prop] = 'hide';
				
				var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/);
				showProps[prop] = {
					value: parts[1],
					unit: parts[2] || 'px'
				};
			});
			options.toShow.css({ height: 0, overflow: 'hidden' }).show();
			options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{
				step: function(now, settings) {
					// only calculate the percent when animating height
					// IE gets very inconsistent results when animating elements
					// with small values, which is common for padding
					if (settings.prop == 'height') {
						percentDone = (settings.now - settings.start) / (settings.end - settings.start);
					}
					
					options.toShow[0].style[settings.prop] =
						(percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit;
				},
				duration: options.duration,
				easing: options.easing,
				complete: function() {
					if ( !options.autoHeight ) {
						options.toShow.css("height", "");
					}
					options.toShow.css("width", originalWidth);
					options.toShow.css({overflow: overflow});
					options.complete();
				}
			});
		},
		bounceslide: function(options) {
			this.slide(options, {
				easing: options.down ? "easeOutBounce" : "swing",
				duration: options.down ? 1000 : 200
			});
		},
		easeslide: function(options) {
			this.slide(options, {
				easing: "easeinout",
				duration: 700
			});
		}
	}
});

})(jQuery);
/*
 * jQuery UI Dialog 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function($) {

var setDataSwitch = {
		dragStart: "start.draggable",
		drag: "drag.draggable",
		dragStop: "stop.draggable",
		maxHeight: "maxHeight.resizable",
		minHeight: "minHeight.resizable",
		maxWidth: "maxWidth.resizable",
		minWidth: "minWidth.resizable",
		resizeStart: "start.resizable",
		resize: "drag.resizable",
		resizeStop: "stop.resizable"
	},
	
	uiDialogClasses =
		'ui-dialog ' +
		'ui-widget ' +
		'ui-widget-content ' +
		'ui-corner-all ';

$.widget("ui.dialog", {

	_init: function() {
		this.originalTitle = this.element.attr('title');

		var self = this,
			options = this.options,

			title = options.title || this.originalTitle || '&nbsp;',
			titleId = $.ui.dialog.getTitleId(this.element),

			uiDialog = (this.uiDialog = $('<div/>'))
				.appendTo(document.body)
				.hide()
				.addClass(uiDialogClasses + options.dialogClass)
				.css({
					position: 'absolute',
					overflow: 'hidden',
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(event) {
					(options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && self.close(event));
				})
				.attr({
					role: 'dialog',
					'aria-labelledby': titleId
				})
				.mousedown(function(event) {
					self.moveToTop(false, event);
				}),

			uiDialogContent = this.element
				.show()
				.removeAttr('title')
				.addClass(
					'ui-dialog-content ' +
					'ui-widget-content')
				.appendTo(uiDialog),

			uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>'))
				.addClass(
					'ui-dialog-titlebar ' +
					'ui-widget-header ' +
					'ui-corner-all ' +
					'ui-helper-clearfix'
				)
				.prependTo(uiDialog),

			uiDialogTitlebarClose = $('<a href="#"/>')
				.addClass(
					'ui-dialog-titlebar-close ' +
					'ui-corner-all'
				)
				.attr('role', 'button')
				.hover(
					function() {
						uiDialogTitlebarClose.addClass('ui-state-hover');
					},
					function() {
						uiDialogTitlebarClose.removeClass('ui-state-hover');
					}
				)
				.focus(function() {
					uiDialogTitlebarClose.addClass('ui-state-focus');
				})
				.blur(function() {
					uiDialogTitlebarClose.removeClass('ui-state-focus');
				})
				.mousedown(function(ev) {
					ev.stopPropagation();
				})
				.click(function(event) {
					self.close(event);
					return false;
				})
				.appendTo(uiDialogTitlebar),

			uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>'))
				.addClass(
					'ui-icon ' +
					'ui-icon-closethick'
				)
				.text(options.closeText)
				.appendTo(uiDialogTitlebarClose),

			uiDialogTitle = $('<span/>')
				.addClass('ui-dialog-title')
				.attr('id', titleId)
				.html(title)
				.prependTo(uiDialogTitlebar);

		uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		(options.draggable && $.fn.draggable && this._makeDraggable());
		(options.resizable && $.fn.resizable && this._makeResizable());

		this._createButtons(options.buttons);
		this._isOpen = false;

		(options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
		(options.autoOpen && this.open());
		
	},

	destroy: function() {
		(this.overlay && this.overlay.destroy());
		this.uiDialog.hide();
		this.element
			.unbind('.dialog')
			.removeData('dialog')
			.removeClass('ui-dialog-content ui-widget-content')
			.hide().appendTo('body');
		this.uiDialog.remove();

		(this.originalTitle && this.element.attr('title', this.originalTitle));
	},

	close: function(event) {
		var self = this;
		
		if (false === self._trigger('beforeclose', event)) {
			return;
		}

		(self.overlay && self.overlay.destroy());
		self.uiDialog.unbind('keypress.ui-dialog');

		(self.options.hide
			? self.uiDialog.hide(self.options.hide, function() {
				self._trigger('close', event);
			})
			: self.uiDialog.hide() && self._trigger('close', event));

		$.ui.dialog.overlay.resize();

		self._isOpen = false;
		
		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
		if (self.options.modal) {
			var maxZ = 0;
			$('.ui-dialog').each(function() {
				if (this != self.uiDialog[0]) {
					maxZ = Math.max(maxZ, $(this).css('z-index'));
				}
			});
			$.ui.dialog.maxZ = maxZ;
		}
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force, event) {

		if ((this.options.modal && !force)
			|| (!this.options.stack && !this.options.modal)) {
			return this._trigger('focus', event);
		}
		
		if (this.options.zIndex > $.ui.dialog.maxZ) {
			$.ui.dialog.maxZ = this.options.zIndex;
		}
		(this.overlay && this.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = ++$.ui.dialog.maxZ));

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') };
		this.uiDialog.css('z-index', ++$.ui.dialog.maxZ);
		this.element.attr(saveScroll);
		this._trigger('focus', event);
	},

	open: function() {
		if (this._isOpen) { return; }

		var options = this.options,
			uiDialog = this.uiDialog;

		this.overlay = options.modal ? new $.ui.dialog.overlay(this) : null;
		(uiDialog.next().length && uiDialog.appendTo('body'));
		this._size();
		this._position(options.position);
		uiDialog.show(options.show);
		this.moveToTop(true);

		// prevent tabbing out of modal dialogs
		(options.modal && uiDialog.bind('keypress.ui-dialog', function(event) {
			if (event.keyCode != $.ui.keyCode.TAB) {
				return;
			}

			var tabbables = $(':tabbable', this),
				first = tabbables.filter(':first')[0],
				last  = tabbables.filter(':last')[0];

			if (event.target == last && !event.shiftKey) {
				setTimeout(function() {
					first.focus();
				}, 1);
			} else if (event.target == first && event.shiftKey) {
				setTimeout(function() {
					last.focus();
				}, 1);
			}
		}));

		// set focus to the first tabbable element in the content area or the first button
		// if there are no tabbable elements, set focus on the dialog itself
		$([])
			.add(uiDialog.find('.ui-dialog-content :tabbable:first'))
			.add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first'))
			.add(uiDialog)
			.filter(':first')
			.focus();

		this._trigger('open');
		this._isOpen = true;
	},

	_createButtons: function(buttons) {
		var self = this,
			hasButtons = false,
			uiDialogButtonPane = $('<div></div>')
				.addClass(
					'ui-dialog-buttonpane ' +
					'ui-widget-content ' +
					'ui-helper-clearfix'
				);

		// if we already have a button pane, remove it
		this.uiDialog.find('.ui-dialog-buttonpane').remove();

		(typeof buttons == 'object' && buttons !== null &&
			$.each(buttons, function() { return !(hasButtons = true); }));
		if (hasButtons) {
			$.each(buttons, function(name, fn) {
				$('<button type="button"></button>')
					.addClass(
						'ui-state-default ' +
						'ui-corner-all'
					)
					.text(name)
					.click(function() { fn.apply(self.element[0], arguments); })
					.hover(
						function() {
							$(this).addClass('ui-state-hover');
						},
						function() {
							$(this).removeClass('ui-state-hover');
						}
					)
					.focus(function() {
						$(this).addClass('ui-state-focus');
					})
					.blur(function() {
						$(this).removeClass('ui-state-focus');
					})
					.appendTo(uiDialogButtonPane);
			});
			uiDialogButtonPane.appendTo(this.uiDialog);
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = this.options,
			heightBeforeDrag;

		this.uiDialog.draggable({
			cancel: '.ui-dialog-content',
			handle: '.ui-dialog-titlebar',
			containment: 'document',
			start: function() {
				heightBeforeDrag = options.height;
				$(this).height($(this).height()).addClass("ui-dialog-dragging");
				(options.dragStart && options.dragStart.apply(self.element[0], arguments));
			},
			drag: function() {
				(options.drag && options.drag.apply(self.element[0], arguments));
			},
			stop: function() {
				$(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag);
				(options.dragStop && options.dragStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = this.options,
			resizeHandles = typeof handles == 'string'
				? handles
				: 'n,e,s,w,se,sw,ne,nw';

		this.uiDialog.resizable({
			cancel: '.ui-dialog-content',
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: options.minHeight,
			start: function() {
				$(this).addClass("ui-dialog-resizing");
				(options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
			},
			resize: function() {
				(options.resize && options.resize.apply(self.element[0], arguments));
			},
			handles: resizeHandles,
			stop: function() {
				$(this).removeClass("ui-dialog-resizing");
				options.height = $(this).height();
				options.width = $(this).width();
				(options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
				$.ui.dialog.overlay.resize();
			}
		})
		.find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se');
	},

	_position: function(pos) {
		var wnd = $(window), doc = $(document),
			pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
			minTop = pTop;

		if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
			pos = [
				pos == 'right' || pos == 'left' ? pos : 'center',
				pos == 'top' || pos == 'bottom' ? pos : 'middle'
			];
		}
		if (pos.constructor != Array) {
			pos = ['center', 'middle'];
		}
		if (pos[0].constructor == Number) {
			pLeft += pos[0];
		} else {
			switch (pos[0]) {
				case 'left':
					pLeft += 0;
					break;
				case 'right':
					pLeft += wnd.width() - this.uiDialog.outerWidth();
					break;
				default:
				case 'center':
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
			}
		}
		if (pos[1].constructor == Number) {
			pTop += pos[1];
		} else {
			switch (pos[1]) {
				case 'top':
					pTop += 0;
					break;
				case 'bottom':
					pTop += wnd.height() - this.uiDialog.outerHeight();
					break;
				default:
				case 'middle':
					pTop += (wnd.height() - this.uiDialog.outerHeight()) / 2;
			}
		}

		// prevent the dialog from being too high (make sure the titlebar
		// is accessible)
		pTop = Math.max(pTop, minTop);
		this.uiDialog.css({top: pTop, left: pLeft});
	},

	_setData: function(key, value){
		(setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
		switch (key) {
			case "buttons":
				this._createButtons(value);
				break;
			case "closeText":
				this.uiDialogTitlebarCloseText.text(value);
				break;
			case "dialogClass":
				this.uiDialog
					.removeClass(this.options.dialogClass)
					.addClass(uiDialogClasses + value);
				break;
			case "draggable":
				(value
					? this._makeDraggable()
					: this.uiDialog.draggable('destroy'));
				break;
			case "height":
				this.uiDialog.height(value);
				break;
			case "position":
				this._position(value);
				break;
			case "resizable":
				var uiDialog = this.uiDialog,
					isResizable = this.uiDialog.is(':data(resizable)');

				// currently resizable, becoming non-resizable
				(isResizable && !value && uiDialog.resizable('destroy'));

				// currently resizable, changing handles
				(isResizable && typeof value == 'string' &&
					uiDialog.resizable('option', 'handles', value));

				// currently non-resizable, becoming resizable
				(isResizable || this._makeResizable(value));
				break;
			case "title":
				$(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;');
				break;
			case "width":
				this.uiDialog.width(value);
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);
	},

	_size: function() {
		/* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		 * divs will both have width and height set, so we need to reset them
		 */
		var options = this.options;

		// reset content sizing
		this.element.css({
			height: 0,
			minHeight: 0,
			width: 'auto'
		});

		// reset wrapper sizing
		// determine the height of all the non-content elements
		var nonContentHeight = this.uiDialog.css({
				height: 'auto',
				width: options.width
			})
			.height();

		this.element
			.css({
				minHeight: Math.max(options.minHeight - nonContentHeight, 0),
				height: options.height == 'auto'
					? 'auto'
					: Math.max(options.height - nonContentHeight, 0)
			});
	}
});

$.extend($.ui.dialog, {
	version: "1.7.2",
	defaults: {
		autoOpen: true,
		bgiframe: false,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		dialogClass: '',
		draggable: true,
		hide: null,
		height: 'auto',
		maxHeight: false,
		maxWidth: false,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: 'center',
		resizable: true,
		show: null,
		stack: true,
		title: '',
		width: 300,
		zIndex: 1000
	},

	getter: 'isOpen',

	uuid: 0,
	maxZ: 0,

	getTitleId: function($el) {
		return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
	},

	overlay: function(dialog) {
		this.$el = $.ui.dialog.overlay.create(dialog);
	}
});

$.extend($.ui.dialog.overlay, {
	instances: [],
	maxZ: 0,
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				// handle $(el).dialog().dialog('close') (see #4065)
				if ($.ui.dialog.overlay.instances.length) {
					$(document).bind($.ui.dialog.overlay.events, function(event) {
						var dialogZ = $(event.target).parents('.ui-dialog').css('zIndex') || 0;
						return (dialogZ > $.ui.dialog.overlay.maxZ);
					});
				}
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				(dialog.options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
		}

		var $el = $('<div></div>').appendTo(document.body)
			.addClass('ui-widget-overlay').css({
				width: this.width(),
				height: this.height()
			});

		(dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());

		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		this.instances.splice($.inArray(this.instances, $el), 1);

		if (this.instances.length === 0) {
			$([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
		
		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
		var maxZ = 0;
		$.each(this.instances, function() {
			maxZ = Math.max(maxZ, this.css('z-index'));
		});
		this.maxZ = maxZ;
	},

	height: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ui.dialog.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ui.dialog.overlay.width(),
			height: $.ui.dialog.overlay.height()
		});
	}
});

$.extend($.ui.dialog.overlay.prototype, {
	destroy: function() {
		$.ui.dialog.overlay.destroy(this.$el);
	}
});

})(jQuery);
/*
 * jQuery UI Slider 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */

(function($) {

$.widget("ui.slider", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this, o = this.options;
		this._keySliding = false;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();

		this.element
			.addClass("ui-slider"
				+ " ui-slider-" + this.orientation
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all");

		this.range = $([]);

		if (o.range) {

			if (o.range === true) {
				this.range = $('<div></div>');
				if (!o.values) o.values = [this._valueMin(), this._valueMin()];
				if (o.values.length && o.values.length != 2) {
					o.values = [o.values[0], o.values[0]];
				}
			} else {
				this.range = $('<div></div>');
			}

			this.range
				.appendTo(this.element)
				.addClass("ui-slider-range");

			if (o.range == "min" || o.range == "max") {
				this.range.addClass("ui-slider-range-" + o.range);
			}

			// note: this isn't the most fittingly semantic framework class for this element,
			// but worked best visually with a variety of themes
			this.range.addClass("ui-widget-header");

		}

		if ($(".ui-slider-handle", this.element).length == 0)
			$('<a href="#"></a>')
				.appendTo(this.element)
				.addClass("ui-slider-handle");

		if (o.values && o.values.length) {
			while ($(".ui-slider-handle", this.element).length < o.values.length)
				$('<a href="#"></a>')
					.appendTo(this.element)
					.addClass("ui-slider-handle");
		}

		this.handles = $(".ui-slider-handle", this.element)
			.addClass("ui-state-default"
				+ " ui-corner-all");

		this.handle = this.handles.eq(0);

		this.handles.add(this.range).filter("a")
			.click(function(event) {
				event.preventDefault();
			})
			.hover(function() {
				if (!o.disabled) {
					$(this).addClass('ui-state-hover');
				}
			}, function() {
				$(this).removeClass('ui-state-hover');
			})
			.focus(function() {
				if (!o.disabled) {
					$(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus');
				} else {
					$(this).blur();
				}
			})
			.blur(function() {
				$(this).removeClass('ui-state-focus');
			});

		this.handles.each(function(i) {
			$(this).data("index.ui-slider-handle", i);
		});

		this.handles.keydown(function(event) {

			var ret = true;

			var index = $(this).data("index.ui-slider-handle");

			if (self.options.disabled)
				return;

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					ret = false;
					if (!self._keySliding) {
						self._keySliding = true;
						$(this).addClass("ui-state-active");
						self._start(event, index);
					}
					break;
			}

			var curVal, newVal, step = self._step();
			if (self.options.values && self.options.values.length) {
				curVal = newVal = self.values(index);
			} else {
				curVal = newVal = self.value();
			}

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
					newVal = self._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = self._valueMax();
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if(curVal == self._valueMax()) return;
					newVal = curVal + step;
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if(curVal == self._valueMin()) return;
					newVal = curVal - step;
					break;
			}

			self._slide(event, index, newVal);

			return ret;

		}).keyup(function(event) {

			var index = $(this).data("index.ui-slider-handle");

			if (self._keySliding) {
				self._stop(event, index);
				self._change(event, index);
				self._keySliding = false;
				$(this).removeClass("ui-state-active");
			}

		});

		this._refreshValue();

	},

	destroy: function() {

		this.handles.remove();
		this.range.remove();

		this.element
			.removeClass("ui-slider"
				+ " ui-slider-horizontal"
				+ " ui-slider-vertical"
				+ " ui-slider-disabled"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.removeData("slider")
			.unbind(".slider");

		this._mouseDestroy();

	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (o.disabled)
			return false;

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		var distance = this._valueMax() - this._valueMin() + 1, closestHandle;
		var self = this, index;
		this.handles.each(function(i) {
			var thisDistance = Math.abs(normValue - self.values(i));
			if (distance > thisDistance) {
				distance = thisDistance;
				closestHandle = $(this);
				index = i;
			}
		});

		// workaround for bug #3736 (if both handles of a range are at 0,
		// the first is always used as the one with least distance,
		// and moving it is obviously prevented by preventing negative ranges)
		if(o.range == true && this.values(1) == o.min) {
			closestHandle = $(this.handles[++index]);
		}

		this._start(event, index);

		self._handleIndex = index;

		closestHandle
			.addClass("ui-state-active")
			.focus();
		
		var offset = closestHandle.offset();
		var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle');
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - (closestHandle.width() / 2),
			top: event.pageY - offset.top
				- (closestHandle.height() / 2)
				- (parseInt(closestHandle.css('borderTopWidth'),10) || 0)
				- (parseInt(closestHandle.css('borderBottomWidth'),10) || 0)
				+ (parseInt(closestHandle.css('marginTop'),10) || 0)
		};

		normValue = this._normValueFromMouse(position);
		this._slide(event, index, normValue);
		return true;

	},

	_mouseStart: function(event) {
		return true;
	},

	_mouseDrag: function(event) {

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);
		
		this._slide(event, this._handleIndex, normValue);

		return false;

	},

	_mouseStop: function(event) {

		this.handles.removeClass("ui-state-active");
		this._stop(event, this._handleIndex);
		this._change(event, this._handleIndex);
		this._handleIndex = null;
		this._clickOffset = null;

		return false;

	},
	
	_detectOrientation: function() {
		this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal';
	},

	_normValueFromMouse: function(position) {

		var pixelTotal, pixelMouse;
		if ('horizontal' == this.orientation) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
		}

		var percentMouse = (pixelMouse / pixelTotal);
		if (percentMouse > 1) percentMouse = 1;
		if (percentMouse < 0) percentMouse = 0;
		if ('vertical' == this.orientation)
			percentMouse = 1 - percentMouse;

		var valueTotal = this._valueMax() - this._valueMin(),
			valueMouse = percentMouse * valueTotal,
			valueMouseModStep = valueMouse % this.options.step,
			normValue = this._valueMin() + valueMouse - valueMouseModStep;

		if (valueMouseModStep > (this.options.step / 2))
			normValue += this.options.step;

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat(normValue.toFixed(5));

	},

	_start: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("start", event, uiHash);
	},

	_slide: function(event, index, newVal) {

		var handle = this.handles[index];

		if (this.options.values && this.options.values.length) {

			var otherVal = this.values(index ? 0 : 1);

			if ((this.options.values.length == 2 && this.options.range === true) && 
				((index == 0 && newVal > otherVal) || (index == 1 && newVal < otherVal))){
 				newVal = otherVal;
			}

			if (newVal != this.values(index)) {
				var newValues = this.values();
				newValues[index] = newVal;
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: this.handles[index],
					value: newVal,
					values: newValues
				});
				var otherVal = this.values(index ? 0 : 1);
				if (allowed !== false) {
					this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true);
				}
			}

		} else {

			if (newVal != this.value()) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: this.handles[index],
					value: newVal
				});
				if (allowed !== false) {
					this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate ));
				}
					
			}

		}

	},

	_stop: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("stop", event, uiHash);
	},

	_change: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("change", event, uiHash);
	},

	value: function(newValue) {

		if (arguments.length) {
			this._setData("value", newValue);
			this._change(null, 0);
		}

		return this._value();

	},

	values: function(index, newValue, animated, noPropagation) {

		if (arguments.length > 1) {
			this.options.values[index] = newValue;
			this._refreshValue(animated);
			if(!noPropagation) this._change(null, index);
		}

		if (arguments.length) {
			if (this.options.values && this.options.values.length) {
				return this._values(index);
			} else {
				return this.value();
			}
		} else {
			return this._values();
		}

	},

	_setData: function(key, value, animated) {

		$.widget.prototype._setData.apply(this, arguments);

		switch (key) {
			case 'disabled':
				if (value) {
					this.handles.filter(".ui-state-focus").blur();
					this.handles.removeClass("ui-state-hover");
					this.handles.attr("disabled", "disabled");
				} else {
					this.handles.removeAttr("disabled");
				}
			case 'orientation':

				this._detectOrientation();
				
				this.element
					.removeClass("ui-slider-horizontal ui-slider-vertical")
					.addClass("ui-slider-" + this.orientation);
				this._refreshValue(animated);
				break;
			case 'value':
				this._refreshValue(animated);
				break;
		}

	},

	_step: function() {
		var step = this.options.step;
		return step;
	},

	_value: function() {

		var val = this.options.value;
		if (val < this._valueMin()) val = this._valueMin();
		if (val > this._valueMax()) val = this._valueMax();

		return val;

	},

	_values: function(index) {

		if (arguments.length) {
			var val = this.options.values[index];
			if (val < this._valueMin()) val = this._valueMin();
			if (val > this._valueMax()) val = this._valueMax();

			return val;
		} else {
			return this.options.values;
		}

	},

	_valueMin: function() {
		var valueMin = this.options.min;
		return valueMin;
	},

	_valueMax: function() {
		var valueMax = this.options.max;
		return valueMax;
	},

	_refreshValue: function(animate) {

		var oRange = this.options.range, o = this.options, self = this;

		if (this.options.values && this.options.values.length) {
			var vp0, vp1;
			this.handles.each(function(i, j) {
				var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
				var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
				$(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
				if (self.options.range === true) {
					if (self.orientation == 'horizontal') {
						(i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate);
						(i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
					} else {
						(i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate);
						(i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			var value = this.value(),
				valueMin = this._valueMin(),
				valueMax = this._valueMax(),
				valPercent = valueMax != valueMin
					? (value - valueMin) / (valueMax - valueMin) * 100
					: 0;
			var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
			this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);

			(oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate);
			(oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
			(oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate);
			(oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
		}

	}
	
}));

$.extend($.ui.slider, {
	getter: "value values",
	version: "1.7.2",
	eventPrefix: "slide",
	defaults: {
		animate: false,
		delay: 0,
		distance: 0,
		max: 100,
		min: 0,
		orientation: 'horizontal',
		range: false,
		step: 1,
		value: 0,
		values: null
	}
});

})(jQuery);
/*
 * jQuery UI Tabs 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.tabs", {

	_init: function() {
		if (this.options.deselectable !== undefined) {
			this.options.collapsible = this.options.deselectable;
		}
		this._tabify(true);
	},

	_setData: function(key, value) {
		if (key == 'selected') {
			if (this.options.collapsible && value == this.options.selected) {
				return;
			}
			this.select(value);
		}
		else {
			this.options[key] = value;
			if (key == 'deselectable') {
				this.options.collapsible = value;
			}
			this._tabify();
		}
	},

	_tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') ||
			this.options.idPrefix + $.data(a);
	},

	_sanitizeSelector: function(hash) {
		return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":"
	},

	_cookie: function() {
		var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + $.data(this.list[0]));
		return $.cookie.apply(null, [cookie].concat($.makeArray(arguments)));
	},

	_ui: function(tab, panel) {
		return {
			tab: tab,
			panel: panel,
			index: this.anchors.index(tab)
		};
	},

	_cleanup: function() {
		// restore all former loading tabs labels
		this.lis.filter('.ui-state-processing').removeClass('ui-state-processing')
				.find('span:data(label.tabs)')
				.each(function() {
					var el = $(this);
					el.html(el.data('label.tabs')).removeData('label.tabs');
				});
	},

	_tabify: function(init) {

		this.list = this.element.children('ul:first');
		this.lis = $('li:has(a[href])', this.list);
		this.anchors = this.lis.map(function() { return $('a', this)[0]; });
		this.panels = $([]);

		var self = this, o = this.options;

		var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash
		this.anchors.each(function(i, a) {
			var href = $(a).attr('href');

			// For dynamically created HTML that contains a hash as href IE < 8 expands
			// such href to the full page url with hash and then misinterprets tab as ajax.
			// Same consideration applies for an added tab with a fragment identifier
			// since a[href=#fragment-identifier] does unexpectedly not match.
			// Thus normalize href attribute...
			var hrefBase = href.split('#')[0], baseEl;
			if (hrefBase && (hrefBase === location.toString().split('#')[0] ||
					(baseEl = $('base')[0]) && hrefBase === baseEl.href)) {
				href = a.hash;
				a.href = href;
			}

			// inline tab
			if (fragmentId.test(href)) {
				self.panels = self.panels.add(self._sanitizeSelector(href));
			}

			// remote tab
			else if (href != '#') { // prevent loading the page itself if href is just "#"
				$.data(a, 'href.tabs', href); // required for restore on destroy

				// TODO until #3808 is fixed strip fragment identifier from url
				// (IE fails to load from such url)
				$.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data

				var id = self._tabId(a);
				a.href = '#' + id;
				var $panel = $('#' + id);
				if (!$panel.length) {
					$panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
						.insertAfter(self.panels[i - 1] || self.list);
					$panel.data('destroy.tabs', true);
				}
				self.panels = self.panels.add($panel);
			}

			// invalid tab href
			else {
				o.disabled.push(i);
			}
		});

		// initialization from scratch
		if (init) {

			// attach necessary classes for styling
			this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');
			this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
			this.lis.addClass('ui-state-default ui-corner-top');
			this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');

			// Selected tab
			// use "selected" option or try to retrieve:
			// 1. from fragment identifier in url
			// 2. from cookie
			// 3. from selected class attribute on <li>
			if (o.selected === undefined) {
				if (location.hash) {
					this.anchors.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							return false; // break
						}
					});
				}
				if (typeof o.selected != 'number' && o.cookie) {
					o.selected = parseInt(self._cookie(), 10);
				}
				if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) {
					o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
				}
				o.selected = o.selected || 0;
			}
			else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release
				o.selected = -1;
			}

			// sanity check - default to first tab...
			o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0;

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = $.unique(o.disabled.concat(
				$.map(this.lis.filter('.ui-state-disabled'),
					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);
			}

			// highlight selected tab
			this.panels.addClass('ui-tabs-hide');
			this.lis.removeClass('ui-tabs-selected ui-state-active');
			if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list
				this.panels.eq(o.selected).removeClass('ui-tabs-hide');
				this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active');

				// seems to be expected behavior that the show callback is fired
				self.element.queue("tabs", function() {
					self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected]));
				});
				
				this.load(o.selected);
			}

			// clean up to avoid memory leaks in certain versions of IE 6
			$(window).bind('unload', function() {
				self.lis.add(self.anchors).unbind('.tabs');
				self.lis = self.anchors = self.panels = null;
			});

		}
		// update selected after add/remove
		else {
			o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
		}

		// update collapsible
		this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible');

		// set or update cookie after init and add/remove respectively
		if (o.cookie) {
			this._cookie(o.selected, o.cookie);
		}

		// disable tabs
		for (var i = 0, li; (li = this.lis[i]); i++) {
			$(li)[$.inArray(i, o.disabled) != -1 &&
				!$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled');
		}

		// reset cache if switching from cached to not cached
		if (o.cache === false) {
			this.anchors.removeData('cache.tabs');
		}

		// remove all handlers before, tabify may run on existing tabs after add or option change
		this.lis.add(this.anchors).unbind('.tabs');

		if (o.event != 'mouseover') {
			var addState = function(state, el) {
				if (el.is(':not(.ui-state-disabled)')) {
					el.addClass('ui-state-' + state);
				}
			};
			var removeState = function(state, el) {
				el.removeClass('ui-state-' + state);
			};
			this.lis.bind('mouseover.tabs', function() {
				addState('hover', $(this));
			});
			this.lis.bind('mouseout.tabs', function() {
				removeState('hover', $(this));
			});
			this.anchors.bind('focus.tabs', function() {
				addState('focus', $(this).closest('li'));
			});
			this.anchors.bind('blur.tabs', function() {
				removeState('focus', $(this).closest('li'));
			});
		}

		// set up animations
		var hideFx, showFx;
		if (o.fx) {
			if ($.isArray(o.fx)) {
				hideFx = o.fx[0];
				showFx = o.fx[1];
			}
			else {
				hideFx = showFx = o.fx;
			}
		}

		// Reset certain styles left over from animation
		// and prevent IE's ClearType bug...
		function resetStyle($el, fx) {
			$el.css({ display: '' });
			if ($.browser.msie && fx.opacity) {
				$el[0].style.removeAttribute('filter');
			}
		}

		// Show a tab...
		var showTab = showFx ?
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.hide().removeClass('ui-tabs-hide') // avoid flicker that way
					.animate(showFx, showFx.duration || 'normal', function() {
						resetStyle($show, showFx);
						self._trigger('show', null, self._ui(clicked, $show[0]));
					});
			} :
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.removeClass('ui-tabs-hide');
				self._trigger('show', null, self._ui(clicked, $show[0]));
			};

		// Hide a tab, $show is optional...
		var hideTab = hideFx ?
			function(clicked, $hide) {
				$hide.animate(hideFx, hideFx.duration || 'normal', function() {
					self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
					$hide.addClass('ui-tabs-hide');
					resetStyle($hide, hideFx);
					self.element.dequeue("tabs");
				});
			} :
			function(clicked, $hide, $show) {
				self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
				$hide.addClass('ui-tabs-hide');
				self.element.dequeue("tabs");
			};

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.anchors.bind(o.event + '.tabs', function() {
			var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'),
					$show = $(self._sanitizeSelector(this.hash));

			// If tab is already selected and not collapsible or tab disabled or
			// or is already loading or click callback returns false stop here.
			// Check if click handler returns false last so that it is not executed
			// for a disabled or loading tab!
			if (($li.hasClass('ui-tabs-selected') && !o.collapsible) ||
				$li.hasClass('ui-state-disabled') ||
				$li.hasClass('ui-state-processing') ||
				self._trigger('select', null, self._ui(this, $show[0])) === false) {
				this.blur();
				return false;
			}

			o.selected = self.anchors.index(this);

			self.abort();

			// if tab may be closed
			if (o.collapsible) {
				if ($li.hasClass('ui-tabs-selected')) {
					o.selected = -1;

					if (o.cookie) {
						self._cookie(o.selected, o.cookie);
					}

					self.element.queue("tabs", function() {
						hideTab(el, $hide);
					}).dequeue("tabs");
					
					this.blur();
					return false;
				}
				else if (!$hide.length) {
					if (o.cookie) {
						self._cookie(o.selected, o.cookie);
					}
					
					self.element.queue("tabs", function() {
						showTab(el, $show);
					});

					self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171
					
					this.blur();
					return false;
				}
			}

			if (o.cookie) {
				self._cookie(o.selected, o.cookie);
			}

			// show new tab
			if ($show.length) {
				if ($hide.length) {
					self.element.queue("tabs", function() {
						hideTab(el, $hide);
					});
				}
				self.element.queue("tabs", function() {
					showTab(el, $show);
				});
				
				self.load(self.anchors.index(this));
			}
			else {
				throw 'jQuery UI Tabs: Mismatching fragment identifier.';
			}

			// Prevent IE from keeping other link focussed when using the back button
			// and remove dotted border from clicked link. This is controlled via CSS
			// in modern browsers; blur() removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabs('rotate').
			if ($.browser.msie) {
				this.blur();
			}

		});

		// disable click in any case
		this.anchors.bind('click.tabs', function(){return false;});

	},

	destroy: function() {
		var o = this.options;

		this.abort();
		
		this.element.unbind('.tabs')
			.removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible')
			.removeData('tabs');

		this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');

		this.anchors.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.unbind('.tabs').add(this.panels).each(function() {
			if ($.data(this, 'destroy.tabs')) {
				$(this).remove();
			}
			else {
				$(this).removeClass([
					'ui-state-default',
					'ui-corner-top',
					'ui-tabs-selected',
					'ui-state-active',
					'ui-state-hover',
					'ui-state-focus',
					'ui-state-disabled',
					'ui-tabs-panel',
					'ui-widget-content',
					'ui-corner-bottom',
					'ui-tabs-hide'
				].join(' '));
			}
		});

		if (o.cookie) {
			this._cookie(null, o.cookie);
		}
	},

	add: function(url, label, index) {
		if (index === undefined) {
			index = this.anchors.length; // append by default
		}

		var self = this, o = this.options,
			$li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)),
			id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]);

		$li.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true);

		// try to find an existing element before creating a new one
		var $panel = $('#' + id);
		if (!$panel.length) {
			$panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true);
		}
		$panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide');

		if (index >= this.lis.length) {
			$li.appendTo(this.list);
			$panel.appendTo(this.list[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.anchors.length == 1) { // after tabify
			$li.addClass('ui-tabs-selected ui-state-active');
			$panel.removeClass('ui-tabs-hide');
			this.element.queue("tabs", function() {
				self._trigger('show', null, self._ui(self.anchors[0], self.panels[0]));
			});
				
			this.load(0);
		}

		// callback
		this._trigger('add', null, this._ui(this.anchors[index], this.panels[index]));
	},

	remove: function(index) {
		var o = this.options, $li = this.lis.eq(index).remove(),
			$panel = this.panels.eq(index).remove();

		// If selected tab was removed focus tab to the right or
		// in case the last tab was removed the tab to the left.
		if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) {
			this.select(index + (index + 1 < this.anchors.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();

		// callback
		this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0]));
	},

	enable: function(index) {
		var o = this.options;
		if ($.inArray(index, o.disabled) == -1) {
			return;
		}

		this.lis.eq(index).removeClass('ui-state-disabled');
		o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index]));
	},

	disable: function(index) {
		var self = this, o = this.options;
		if (index != o.selected) { // cannot disable already selected tab
			this.lis.eq(index).addClass('ui-state-disabled');

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index]));
		}
	},

	select: function(index) {
		if (typeof index == 'string') {
			index = this.anchors.index(this.anchors.filter('[href$=' + index + ']'));
		}
		else if (index === null) { // usage of null is deprecated, TODO remove in next release
			index = -1;
		}
		if (index == -1 && this.options.collapsible) {
			index = this.options.selected;
		}

		this.anchors.eq(index).trigger(this.options.event + '.tabs');
	},

	load: function(index) {
		var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs');

		this.abort();

		// not remote or from cache
		if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) {
			this.element.dequeue("tabs");
			return;
		}

		// load remote from here on
		this.lis.eq(index).addClass('ui-state-processing');

		if (o.spinner) {
			var span = $('span', a);
			span.data('label.tabs', span.html()).html(o.spinner);
		}

		this.xhr = $.ajax($.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				$(self._sanitizeSelector(a.hash)).html(r);

				// take care of tab labels
				self._cleanup();

				if (o.cache) {
					$.data(a, 'cache.tabs', true); // if loaded once do not load them again
				}

				// callbacks
				self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
				try {
					o.ajaxOptions.success(r, s);
				}
				catch (e) {}

				// last, so that load event is fired before show...
				self.element.dequeue("tabs");
			}
		}));
	},

	abort: function() {
		// stop possibly running animations
		this.element.queue([]);
		this.panels.stop(false, true);

		// terminate pending requests from other tabs
		if (this.xhr) {
			this.xhr.abort();
			delete this.xhr;
		}

		// take care of tab labels
		this._cleanup();

	},

	url: function(index, url) {
		this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},

	length: function() {
		return this.anchors.length;
	}

});

$.extend($.ui.tabs, {
	version: '1.7.2',
	getter: 'length',
	defaults: {
		ajaxOptions: null,
		cache: false,
		cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
		collapsible: false,
		disabled: [],
		event: 'click',
		fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
		idPrefix: 'ui-tabs-',
		panelTemplate: '<div></div>',
		spinner: '<em>Loading&#8230;</em>',
		tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
	}
});

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
$.extend($.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {

		var self = this, o = this.options;
		
		var rotate = self._rotate || (self._rotate = function(e) {
			clearTimeout(self.rotation);
			self.rotation = setTimeout(function() {
				var t = o.selected;
				self.select( ++t < self.anchors.length ? t : 0 );
			}, ms);
			
			if (e) {
				e.stopPropagation();
			}
		});
		
		var stop = self._unrotate || (self._unrotate = !continuing ?
			function(e) {
				if (e.clientX) { // in case of a true click
					self.rotate(null);
				}
			} :
			function(e) {
				t = o.selected;
				rotate();
			});

		// start rotation
		if (ms) {
			this.element.bind('tabsshow', rotate);
			this.anchors.bind(o.event + '.tabs', stop);
			rotate();
		}
		// stop rotation
		else {
			clearTimeout(self.rotation);
			this.element.unbind('tabsshow', rotate);
			this.anchors.unbind(o.event + '.tabs', stop);
			delete this._rotate;
			delete this._unrotate;
		}
	}
});

})(jQuery);
/*
 * jQuery UI Datepicker 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.7.2" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false // True to show button panel, false to not show it
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.append = $([]);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))
			return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText) {
			inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
			input[isRTL ? 'before' : 'after'](inst.append);
		}
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
			target.disabled = false;
			inst.trigger.filter('button').
				each(function() { this.disabled = false; }).end().
				filter('img').css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
			target.disabled = true;
			inst.trigger.filter('button').
				each(function() { this.disabled = true; }).end().
				filter('img').css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or retrieve,
	                   when retrieving also 'all' for all instance settings or
	                   'defaults' for all global defaults
	   @param  value   any - the new value for the setting
	                   (omit if above is an object or to retrieve a value) */
	_optionDatepicker: function(target, name, value) {
		var inst = this._getInst(target);
		if (arguments.length == 2 && typeof name == 'string') {
			return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
				(inst ? (name == 'all' ? $.extend({}, inst.settings) :
				this._get(inst, name)) : null));
		}
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			var date = this._getDateDatepicker(target);
			extendRemove(inst.settings, settings);
			this._setDateDatepicker(target, date);
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px'});
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var dims = {width: inst.dpDiv.width() + 4,
			height: inst.dpDiv.height() + 4};
		var self = this;
		inst.dpDiv.empty().append(this._generateHTML(inst))
			.find('iframe.ui-datepicker-cover').
				css({width: dims.width, height: dims.height})
			.end()
			.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1) {
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		} else {
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		}
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
		var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
		offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val() : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			date = defaultDate;
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '') + // highlight selected day
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, monthNames, monthNamesShort) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-year" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				'>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.2";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;

})(jQuery);
/*
 * jQuery UI Progressbar 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   ui.core.js
 */
(function($) {

$.widget("ui.progressbar", {

	_init: function() {

		this.element
			.addClass("ui-progressbar"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.attr({
				role: "progressbar",
				"aria-valuemin": this._valueMin(),
				"aria-valuemax": this._valueMax(),
				"aria-valuenow": this._value()
			});

		this.valueDiv = $('<div class="ui-progressbar-value ui-widget-header ui-corner-left"></div>').appendTo(this.element);

		this._refreshValue();

	},

	destroy: function() {

		this.element
			.removeClass("ui-progressbar"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.removeAttr("role")
			.removeAttr("aria-valuemin")
			.removeAttr("aria-valuemax")
			.removeAttr("aria-valuenow")
			.removeData("progressbar")
			.unbind(".progressbar");

		this.valueDiv.remove();

		$.widget.prototype.destroy.apply(this, arguments);

	},

	value: function(newValue) {
		if (newValue === undefined) {
			return this._value();
		}
		
		this._setData('value', newValue);
		return this;
	},

	_setData: function(key, value) {

		switch (key) {
			case 'value':
				this.options.value = value;
				this._refreshValue();
				this._trigger('change', null, {});
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);

	},

	_value: function() {

		var val = this.options.value;
		if (val < this._valueMin()) val = this._valueMin();
		if (val > this._valueMax()) val = this._valueMax();

		return val;

	},

	_valueMin: function() {
		var valueMin = 0;
		return valueMin;
	},

	_valueMax: function() {
		var valueMax = 100;
		return valueMax;
	},

	_refreshValue: function() {
		var value = this.value();
		this.valueDiv[value == this._valueMax() ? 'addClass' : 'removeClass']("ui-corner-right");
		this.valueDiv.width(value + '%');
		this.element.attr("aria-valuenow", value);
	}

});

$.extend($.ui.progressbar, {
	version: "1.7.2",
	defaults: {
		value: 0
	}
});

})(jQuery);
/*
 * jQuery UI Effects 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/
 */
;jQuery.effects || (function($) {

$.effects = {
	version: "1.7.2",

	// Saves a set of properties in a data storage
	save: function(element, set) {
		for(var i=0; i < set.length; i++) {
			if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]);
		}
	},

	// Restores a set of previously saved properties from a data storage
	restore: function(element, set) {
		for(var i=0; i < set.length; i++) {
			if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i]));
		}
	},

	setMode: function(el, mode) {
		if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle
		return mode;
	},

	getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value
		// this should be a little more flexible in the future to handle a string & hash
		var y, x;
		switch (origin[0]) {
			case 'top': y = 0; break;
			case 'middle': y = 0.5; break;
			case 'bottom': y = 1; break;
			default: y = origin[0] / original.height;
		};
		switch (origin[1]) {
			case 'left': x = 0; break;
			case 'center': x = 0.5; break;
			case 'right': x = 1; break;
			default: x = origin[1] / original.width;
		};
		return {x: x, y: y};
	},

	// Wraps the element around a wrapper that copies position properties
	createWrapper: function(element) {

		//if the element is already wrapped, return it
		if (element.parent().is('.ui-effects-wrapper'))
			return element.parent();

		//Cache width,height and float properties of the element, and create a wrapper around it
		var props = { width: element.outerWidth(true), height: element.outerHeight(true), 'float': element.css('float') };
		element.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');
		var wrapper = element.parent();

		//Transfer the positioning of the element to the wrapper
		if (element.css('position') == 'static') {
			wrapper.css({ position: 'relative' });
			element.css({ position: 'relative'} );
		} else {
			var top = element.css('top'); if(isNaN(parseInt(top,10))) top = 'auto';
			var left = element.css('left'); if(isNaN(parseInt(left,10))) left = 'auto';
			wrapper.css({ position: element.css('position'), top: top, left: left, zIndex: element.css('z-index') }).show();
			element.css({position: 'relative', top: 0, left: 0 });
		}

		wrapper.css(props);
		return wrapper;
	},

	removeWrapper: function(element) {
		if (element.parent().is('.ui-effects-wrapper'))
			return element.parent().replaceWith(element);
		return element;
	},

	setTransition: function(element, list, factor, value) {
		value = value || {};
		$.each(list, function(i, x){
			unit = element.cssUnit(x);
			if (unit[0] > 0) value[x] = unit[0] * factor + unit[1];
		});
		return value;
	},

	//Base function to animate from one class to another in a seamless transition
	animateClass: function(value, duration, easing, callback) {

		var cb = (typeof easing == "function" ? easing : (callback ? callback : null));
		var ea = (typeof easing == "string" ? easing : null);

		return this.each(function() {

			var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || '';
			if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */
			if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; }

			//Let's get a style offset
			var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove);
			var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove);

			// The main function to form the object for animation
			for(var n in newStyle) {
				if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */
				&& n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */
				&& newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */
				&& (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */
				&& (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */
				) offset[n] = newStyle[n];
			}

			that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object
				// Change style attribute back to original. For stupid IE, we need to clear the damn object.
				if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr);
				if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove);
				if(cb) cb.apply(this, arguments);
			});

		});
	}
};


function _normalizeArguments(a, m) {

	var o = a[1] && a[1].constructor == Object ? a[1] : {}; if(m) o.mode = m;
	var speed = a[1] && a[1].constructor != Object ? a[1] : (o.duration ? o.duration : a[2]); //either comes from options.duration or the secon/third argument
		speed = $.fx.off ? 0 : typeof speed === "number" ? speed : $.fx.speeds[speed] || $.fx.speeds._default;
	var callback = o.callback || ( $.isFunction(a[1]) && a[1] ) || ( $.isFunction(a[2]) && a[2] ) || ( $.isFunction(a[3]) && a[3] );

	return [a[0], o, speed, callback];
	
}

//Extend the methods of jQuery
$.fn.extend({

	//Save old methods
	_show: $.fn.show,
	_hide: $.fn.hide,
	__toggle: $.fn.toggle,
	_addClass: $.fn.addClass,
	_removeClass: $.fn.removeClass,
	_toggleClass: $.fn.toggleClass,

	// New effect methods
	effect: function(fx, options, speed, callback) {
		return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: options || {}, duration: speed, callback: callback }) : null;
	},

	show: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])))
			return this._show.apply(this, arguments);
		else {
			return this.effect.apply(this, _normalizeArguments(arguments, 'show'));
		}
	},

	hide: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])))
			return this._hide.apply(this, arguments);
		else {
			return this.effect.apply(this, _normalizeArguments(arguments, 'hide'));
		}
	},

	toggle: function(){
		if(!arguments[0] ||
			(arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])) ||
			($.isFunction(arguments[0]) || typeof arguments[0] == 'boolean')) {
			return this.__toggle.apply(this, arguments);
		} else {
			return this.effect.apply(this, _normalizeArguments(arguments, 'toggle'));
		}
	},

	addClass: function(classNames, speed, easing, callback) {
		return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames);
	},
	removeClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames);
	},
	toggleClass: function(classNames,speed,easing,callback) {
		return ( (typeof speed !== "boolean") && speed ) ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames, speed);
	},
	morph: function(remove,add,speed,easing,callback) {
		return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]);
	},
	switchClass: function() {
		return this.morph.apply(this, arguments);
	},

	// helper functions
	cssUnit: function(key) {
		var style = this.css(key), val = [];
		$.each( ['em','px','%','pt'], function(i, unit){
			if(style.indexOf(unit) > 0)
				val = [parseFloat(style), unit];
		});
		return val;
	}
});

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

// We override the animation for all of these color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		$.fx.step[attr] = function(fx) {
				if ( fx.state == 0 ) {
						fx.start = getColor( fx.elem, attr );
						fx.end = getRGB( fx.end );
				}

				fx.elem.style[attr] = "rgb(" + [
						Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0],10), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1],10), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2],10), 255), 0)
				].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],10), parseInt(result[2],10), parseInt(result[3],10)];

		// 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)];

		// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
		if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
				return colors['transparent'];

		// Otherwise, we're most likely dealing with a named color
		return colors[$.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
		var color;

		do {
				color = $.curCSS(elem, attr);

				// Keep going until we find an element that has color, or we hit the body
				if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
						break;

				attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
};

// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/

var colors = {
	aqua:[0,255,255],
	azure:[240,255,255],
	beige:[245,245,220],
	black:[0,0,0],
	blue:[0,0,255],
	brown:[165,42,42],
	cyan:[0,255,255],
	darkblue:[0,0,139],
	darkcyan:[0,139,139],
	darkgrey:[169,169,169],
	darkgreen:[0,100,0],
	darkkhaki:[189,183,107],
	darkmagenta:[139,0,139],
	darkolivegreen:[85,107,47],
	darkorange:[255,140,0],
	darkorchid:[153,50,204],
	darkred:[139,0,0],
	darksalmon:[233,150,122],
	darkviolet:[148,0,211],
	fuchsia:[255,0,255],
	gold:[255,215,0],
	green:[0,128,0],
	indigo:[75,0,130],
	khaki:[240,230,140],
	lightblue:[173,216,230],
	lightcyan:[224,255,255],
	lightgreen:[144,238,144],
	lightgrey:[211,211,211],
	lightpink:[255,182,193],
	lightyellow:[255,255,224],
	lime:[0,255,0],
	magenta:[255,0,255],
	maroon:[128,0,0],
	navy:[0,0,128],
	olive:[128,128,0],
	orange:[255,165,0],
	pink:[255,192,203],
	purple:[128,0,128],
	violet:[128,0,128],
	red:[255,0,0],
	silver:[192,192,192],
	white:[255,255,255],
	yellow:[255,255,0],
	transparent: [255,255,255]
};

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER 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.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
$.easing.jswing = $.easing.swing;

$.extend($.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert($.easing.default);
		return $.easing[$.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 *
 * Open source under the BSD License.
 *
 * Copyright 2001 Robert Penner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER 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.
 *
 */

})(jQuery);
/*
 * jQuery UI Effects Blind 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.blind = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'vertical') ? 'height' : 'width';
		var distance = (direction == 'vertical') ? wrapper.height() : wrapper.width();
		if(mode == 'show') wrapper.css(ref, 0); // Shift

		// Animation
		var animation = {};
		animation[ref] = mode == 'show' ? distance : 0;

		// Animate
		wrapper.animate(animation, o.duration, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Bounce 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Bounce
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.bounce = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var direction = o.options.direction || 'up'; // Default direction
		var distance = o.options.distance || 20; // Default distance
		var times = o.options.times || 5; // Default # of times
		var speed = o.duration || 250; // Default speed per bounce
		if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3);
		if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift
		if (mode == 'hide') distance = distance / (times * 2);
		if (mode != 'hide') times--;

		// Animate
		if (mode == 'show') { // Show Bounce
			var animation = {opacity: 1};
			animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation, speed / 2, o.options.easing);
			distance = distance / 2;
			times--;
		};
		for (var i = 0; i < times; i++) { // Bounces
			var animation1 = {}, animation2 = {};
			animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
			animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing);
			distance = (mode == 'hide') ? distance * 2 : distance / 2;
		};
		if (mode == 'hide') { // Last Bounce
			var animation = {opacity: 0};
			animation[ref] = (motion == 'pos' ? '-=' : '+=')  + distance;
			el.animate(animation, speed / 2, o.options.easing, function(){
				el.hide(); // Hide
				$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		} else {
			var animation1 = {}, animation2 = {};
			animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
			animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){
				$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		};
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Clip 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Clip
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.clip = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left','height','width'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var animate = el[0].tagName == 'IMG' ? wrapper : el;
		var ref = {
			size: (direction == 'vertical') ? 'height' : 'width',
			position: (direction == 'vertical') ? 'top' : 'left'
		};
		var distance = (direction == 'vertical') ? animate.height() : animate.width();
		if(mode == 'show') { animate.css(ref.size, 0); animate.css(ref.position, distance / 2); } // Shift

		// Animation
		var animation = {};
		animation[ref.size] = mode == 'show' ? distance : 0;
		animation[ref.position] = mode == 'show' ? 0 : distance / 2;

		// Animate
		animate.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Drop 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Drop
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.drop = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left','opacity'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'left'; // Default Direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 2 : el.outerWidth({margin:true}) / 2);
		if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift

		// Animation
		var animation = {opacity: mode == 'show' ? 1 : 0};
		animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Explode 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Explode
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.explode = function(o) {

	return this.queue(function() {

	var rows = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;
	var cells = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;

	o.options.mode = o.options.mode == 'toggle' ? ($(this).is(':visible') ? 'hide' : 'show') : o.options.mode;
	var el = $(this).show().css('visibility', 'hidden');
	var offset = el.offset();

	//Substract the margins - not fixing the problem yet.
	offset.top -= parseInt(el.css("marginTop"),10) || 0;
	offset.left -= parseInt(el.css("marginLeft"),10) || 0;

	var width = el.outerWidth(true);
	var height = el.outerHeight(true);

	for(var i=0;i<rows;i++) { // =
		for(var j=0;j<cells;j++) { // ||
			el
				.clone()
				.appendTo('body')
				.wrap('<div></div>')
				.css({
					position: 'absolute',
					visibility: 'visible',
					left: -j*(width/cells),
					top: -i*(height/rows)
				})
				.parent()
				.addClass('ui-effects-explode')
				.css({
					position: 'absolute',
					overflow: 'hidden',
					width: width/cells,
					height: height/rows,
					left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0),
					top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0),
					opacity: o.options.mode == 'show' ? 0 : 1
				}).animate({
					left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)),
					top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)),
					opacity: o.options.mode == 'show' ? 1 : 0
				}, o.duration || 500);
		}
	}

	// Set a timeout, to call the callback approx. when the other animations have finished
	setTimeout(function() {

		o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide();
				if(o.callback) o.callback.apply(el[0]); // Callback
				el.dequeue();

				$('div.ui-effects-explode').remove();

	}, o.duration || 500);


	});

};

})(jQuery);
/*
 * jQuery UI Effects Fold 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Fold
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.fold = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var size = o.options.size || 15; // Default fold size
		var horizFirst = !(!o.options.horizFirst); // Ensure a boolean value
		var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2;

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var widthFirst = ((mode == 'show') != horizFirst);
		var ref = widthFirst ? ['width', 'height'] : ['height', 'width'];
		var distance = widthFirst ? [wrapper.width(), wrapper.height()] : [wrapper.height(), wrapper.width()];
		var percent = /([0-9]+)%/.exec(size);
		if(percent) size = parseInt(percent[1],10) / 100 * distance[mode == 'hide' ? 0 : 1];
		if(mode == 'show') wrapper.css(horizFirst ? {height: 0, width: size} : {height: size, width: 0}); // Shift

		// Animation
		var animation1 = {}, animation2 = {};
		animation1[ref[0]] = mode == 'show' ? distance[0] : size;
		animation2[ref[1]] = mode == 'show' ? distance[1] : 0;

		// Animate
		wrapper.animate(animation1, duration, o.options.easing)
		.animate(animation2, duration, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Highlight 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.highlight = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['backgroundImage','backgroundColor','opacity'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var color = o.options.color || "#ffff99"; // Default highlight color
		var oldColor = el.css("backgroundColor");

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		el.css({backgroundImage: 'none', backgroundColor: color}); // Shift

		// Animation
		var animation = {backgroundColor: oldColor };
		if (mode == "hide") animation['opacity'] = 0;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == "hide") el.hide();
			$.effects.restore(el, props);
		if (mode == "show" && $.browser.msie) this.style.removeAttribute('filter');
			if(o.callback) o.callback.apply(this, arguments);
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Pulsate 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Pulsate
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.pulsate = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var times = o.options.times || 5; // Default # of times
		var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2;

		// Adjust
		if (mode == 'hide') times--;
		if (el.is(':hidden')) { // Show fadeIn
			el.css('opacity', 0);
			el.show(); // Show
			el.animate({opacity: 1}, duration, o.options.easing);
			times = times-2;
		}

		// Animate
		for (var i = 0; i < times; i++) { // Pulsate
			el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing);
		};
		if (mode == 'hide') { // Last Pulse
			el.animate({opacity: 0}, duration, o.options.easing, function(){
				el.hide(); // Hide
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		} else {
			el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		};
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Scale 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Scale
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.puff = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var options = $.extend(true, {}, o.options);
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var percent = parseInt(o.options.percent,10) || 150; // Set default puff percent
		options.fade = true; // It's not a puff if it doesn't fade! :)
		var original = {height: el.height(), width: el.width()}; // Save original

		// Adjust
		var factor = percent / 100;
		el.from = (mode == 'hide') ? original : {height: original.height * factor, width: original.width * factor};

		// Animation
		options.from = el.from;
		options.percent = (mode == 'hide') ? percent : 100;
		options.mode = mode;

		// Animate
		el.effect('scale', options, o.duration, o.callback);
		el.dequeue();
	});

};

$.effects.scale = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var options = $.extend(true, {}, o.options);
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var percent = parseInt(o.options.percent,10) || (parseInt(o.options.percent,10) == 0 ? 0 : (mode == 'hide' ? 0 : 100)); // Set default scaling percent
		var direction = o.options.direction || 'both'; // Set default axis
		var origin = o.options.origin; // The origin of the scaling
		if (mode != 'effect') { // Set default origin and restore for show/hide
			options.origin = origin || ['middle','center'];
			options.restore = true;
		}
		var original = {height: el.height(), width: el.width()}; // Save original
		el.from = o.options.from || (mode == 'show' ? {height: 0, width: 0} : original); // Default from state

		// Adjust
		var factor = { // Set scaling factor
			y: direction != 'horizontal' ? (percent / 100) : 1,
			x: direction != 'vertical' ? (percent / 100) : 1
		};
		el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state

		if (o.options.fade) { // Fade option to support puff
			if (mode == 'show') {el.from.opacity = 0; el.to.opacity = 1;};
			if (mode == 'hide') {el.from.opacity = 1; el.to.opacity = 0;};
		};

		// Animation
		options.from = el.from; options.to = el.to; options.mode = mode;

		// Animate
		el.effect('size', options, o.duration, o.callback);
		el.dequeue();
	});

};

$.effects.size = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left','width','height','overflow','opacity'];
		var props1 = ['position','top','left','overflow','opacity']; // Always restore
		var props2 = ['width','height','overflow']; // Copy for children
		var cProps = ['fontSize'];
		var vProps = ['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom'];
		var hProps = ['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var restore = o.options.restore || false; // Default restore
		var scale = o.options.scale || 'both'; // Default scale mode
		var origin = o.options.origin; // The origin of the sizing
		var original = {height: el.height(), width: el.width()}; // Save original
		el.from = o.options.from || original; // Default from state
		el.to = o.options.to || original; // Default to state
		// Adjust
		if (origin) { // Calculate baseline shifts
			var baseline = $.effects.getBaseline(origin, original);
			el.from.top = (original.height - el.from.height) * baseline.y;
			el.from.left = (original.width - el.from.width) * baseline.x;
			el.to.top = (original.height - el.to.height) * baseline.y;
			el.to.left = (original.width - el.to.width) * baseline.x;
		};
		var factor = { // Set scaling factor
			from: {y: el.from.height / original.height, x: el.from.width / original.width},
			to: {y: el.to.height / original.height, x: el.to.width / original.width}
		};
		if (scale == 'box' || scale == 'both') { // Scale the css box
			if (factor.from.y != factor.to.y) { // Vertical props scaling
				props = props.concat(vProps);
				el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from);
				el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to);
			};
			if (factor.from.x != factor.to.x) { // Horizontal props scaling
				props = props.concat(hProps);
				el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from);
				el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to);
			};
		};
		if (scale == 'content' || scale == 'both') { // Scale the content
			if (factor.from.y != factor.to.y) { // Vertical props scaling
				props = props.concat(cProps);
				el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from);
				el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to);
			};
		};
		$.effects.save(el, restore ? props : props1); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		el.css('overflow','hidden').css(el.from); // Shift

		// Animate
		if (scale == 'content' || scale == 'both') { // Scale the children
			vProps = vProps.concat(['marginTop','marginBottom']).concat(cProps); // Add margins/font-size
			hProps = hProps.concat(['marginLeft','marginRight']); // Add margins
			props2 = props.concat(vProps).concat(hProps); // Concat
			el.find("*[width]").each(function(){
				child = $(this);
				if (restore) $.effects.save(child, props2);
				var c_original = {height: child.height(), width: child.width()}; // Save original
				child.from = {height: c_original.height * factor.from.y, width: c_original.width * factor.from.x};
				child.to = {height: c_original.height * factor.to.y, width: c_original.width * factor.to.x};
				if (factor.from.y != factor.to.y) { // Vertical props scaling
					child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from);
					child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to);
				};
				if (factor.from.x != factor.to.x) { // Horizontal props scaling
					child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from);
					child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to);
				};
				child.css(child.from); // Shift children
				child.animate(child.to, o.duration, o.options.easing, function(){
					if (restore) $.effects.restore(child, props2); // Restore children
				}); // Animate children
			});
		};

		// Animate
		el.animate(el.to, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, restore ? props : props1); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Shake 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Shake
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.shake = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var direction = o.options.direction || 'left'; // Default direction
		var distance = o.options.distance || 20; // Default distance
		var times = o.options.times || 3; // Default # of times
		var speed = o.duration || o.options.duration || 140; // Default speed per shake

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';

		// Animation
		var animation = {}, animation1 = {}, animation2 = {};
		animation[ref] = (motion == 'pos' ? '-=' : '+=')  + distance;
		animation1[ref] = (motion == 'pos' ? '+=' : '-=')  + distance * 2;
		animation2[ref] = (motion == 'pos' ? '-=' : '+=')  + distance * 2;

		// Animate
		el.animate(animation, speed, o.options.easing);
		for (var i = 1; i < times; i++) { // Shakes
			el.animate(animation1, speed, o.options.easing).animate(animation2, speed, o.options.easing);
		};
		el.animate(animation1, speed, o.options.easing).
		animate(animation, speed / 2, o.options.easing, function(){ // Last shake
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
		});
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Slide 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Slide
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.slide = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var direction = o.options.direction || 'left'; // Default Direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true}));
		if (mode == 'show') el.css(ref, motion == 'pos' ? -distance : distance); // Shift

		// Animation
		var animation = {};
		animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Transfer 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.transfer = function(o) {
	return this.queue(function() {
		var elem = $(this),
			target = $(o.options.to),
			endPosition = target.offset(),
			animation = {
				top: endPosition.top,
				left: endPosition.left,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = elem.offset(),
			transfer = $('<div class="ui-effects-transfer"></div>')
				.appendTo(document.body)
				.addClass(o.options.className)
				.css({
					top: startPosition.top,
					left: startPosition.left,
					height: elem.innerHeight(),
					width: elem.innerWidth(),
					position: 'absolute'
				})
				.animate(animation, o.duration, o.options.easing, function() {
					transfer.remove();
					(o.callback && o.callback.apply(elem[0], arguments));
					elem.dequeue();
				});
	});
};

})(jQuery);




if(typeof jQuery=="undefined"){throw"Unable to load Shadowbox, jQuery library not found."}var Shadowbox={};Shadowbox.lib={getStyle:function(B,A){return jQuery(B).css(A)},setStyle:function(C,B,D){if(typeof B!="object"){var A={};A[B]=D;B=A}jQuery(C).css(B)},get:function(A){return(typeof A=="string")?document.getElementById(A):A},remove:function(A){jQuery(A).remove()},getTarget:function(A){return A.target},preventDefault:function(A){A=A.browserEvent||A;if(A.preventDefault){A.preventDefault()}else{A.returnValue=false}},addEvent:function(C,A,B){jQuery(C).bind(A,B)},removeEvent:function(C,A,B){jQuery(C).unbind(A,B)},animate:function(A,D,C,F){C=Math.round(C*1000);var E={};for(var B in D){for(var B in D){E[B]=String(D[B].to);if(B!="opacity"){E[B]+="px"}}}jQuery(A).animate(E,C,null,F)}};(function(A){A.fn.shadowbox=function(B){return this.each(function(){var E=A(this);var D=A.extend({},B||{},A.metadata?E.metadata():A.meta?E.data():{});var C=this.className||"";D.width=parseInt((C.match(/w:(\d+)/)||[])[1])||D.width;D.height=parseInt((C.match(/h:(\d+)/)||[])[1])||D.height;Shadowbox.setup(E,D)})}})(jQuery)



if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox, no base library adapter found."}(function(){var version="1.0";var options={assetURL:"",loadingImage:"images/loading.gif",animate:true,animSequence:"wh",flvPlayer:"flvplayer.swf",overlayColor:"#000",overlayOpacity:0.85,overlayBgImage:"images/overlay-85.png",listenOverlay:true,autoplayMovies:true,showMovieControls:true,resizeDuration:0.35,fadeDuration:0.35,displayNav:true,continuous:false,displayCounter:true,counterType:"default",viewportPadding:20,handleLgImages:"resize",initialHeight:160,initialWidth:320,enableKeys:true,keysClose:["c","q",27],keysNext:["n",39],keysPrev:["p",37],onOpen:null,onFinish:null,onChange:null,onClose:null,handleUnsupported:"link",skipSetup:false,text:{cancel:"Cancel",loading:"loading",close:'<span class="shortcut">C</span>lose',next:'<span class="shortcut">N</span>ext',prev:'<span class="shortcut">P</span>revious',errors:{single:'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',shared:'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',either:'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'}},errors:{fla:{name:"Flash",url:"http://www.adobe.com/products/flashplayer/"},qt:{name:"QuickTime",url:"http://www.apple.com/quicktime/download/"},wmp:{name:"Windows Media Player",url:"http://www.microsoft.com/windows/windowsmedia/"},f4m:{name:"Flip4Mac",url:"http://www.flip4mac.com/wmv_download.htm"}},skin:{main:'<div id="shadowbox_overlay"></div><div id="shadowbox_container"><div id="shadowbox"><div id="shadowbox_title"><div id="shadowbox_title_inner"></div></div><div id="shadowbox_body"><div id="shadowbox_body_inner"></div><div id="shadowbox_loading"></div></div><div id="shadowbox_toolbar"><div id="shadowbox_toolbar_inner"></div></div></div></div>',loading:'<img src="{0}" alt="{1}" /><span><a href="javascript:Shadowbox.close();">{2}</a></span>',counter:'<div id="shadowbox_counter">{0}</div>',close:'<div id="shadowbox_nav_close"><a href="javascript:Shadowbox.close();">{0}</a></div>',next:'<div id="shadowbox_nav_next"><a href="javascript:Shadowbox.next();">{0}</a></div>',prev:'<div id="shadowbox_nav_previous"><a href="javascript:Shadowbox.previous();">{0}</a></div>'},ext:{img:["png","jpg","jpeg","gif","bmp"],qt:["dv","mov","moov","movie","mp4"],wmp:["asf","wm","wmv"],qtwmp:["avi","mpg","mpeg"],iframe:["asp","aspx","cgi","cfm","htm","html","pl","php","php3","php4","php5","phtml","rb","rhtml","shtml","txt","vbs"]}};var default_options=null;var SL=Shadowbox.lib;var RE={resize:/(img|swf|flv)/,overlay:/(img|iframe|html|inline)/,swf:/\.swf\s*$/i,flv:/\.flv\s*$/i,domain:/:\/\/(.*?)[:\/]/,inline:/#(.+)$/,rel:/^(light|shadow)box/i,gallery:/^(light|shadow)box\[(.*?)\]/i,unsupported:/^unsupported-(\w+)/,param:/\s*([a-z_]*?)\s*=\s*(.+)\s*/,empty:/^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i};var cache=[];var current_gallery;var current;var optimal_height=options.initialHeight;var optimal_width=options.initialWidth;var current_height=0;var current_width=0;var preloader;var initialized=false;var activated=false;var drag;var draggable;var overlay_img_needed;var ua=navigator.userAgent.toLowerCase();var isStrict=document.compatMode=="CSS1Compat",isOpera=ua.indexOf("opera")>-1,isIE=ua.indexOf("msie")>-1,isIE7=ua.indexOf("msie 7")>-1,isBorderBox=isIE&&!isStrict,isSafari=(/webkit|khtml/).test(ua),isSafari3=isSafari&&!!(document.evaluate),isGecko=!isSafari&&ua.indexOf("gecko")>-1,isWindows=(ua.indexOf("windows")!=-1||ua.indexOf("win32")!=-1),isMac=(ua.indexOf("macintosh")!=-1||ua.indexOf("mac os x")!=-1),isLinux=(ua.indexOf("linux")!=-1);var absolute_pos=isIE&&!isIE7;var plugins=null;if(navigator.plugins&&navigator.plugins.length){var detectPlugin=function(plugin_name){var detected=false;for(var i=0,len=navigator.plugins.length;i<len;++i){if(navigator.plugins[i].name.indexOf(plugin_name)>-1){detected=true;break}}return detected};var f4m=detectPlugin("Flip4Mac");var plugins={fla:detectPlugin("Shockwave Flash"),qt:detectPlugin("QuickTime"),wmp:!f4m&&detectPlugin("Windows Media"),f4m:f4m}}else{var detectPlugin=function(plugin_name){var detected=false;try{var axo=new ActiveXObject(plugin_name);if(axo){detected=true}}catch(e){}return detected};var plugins={fla:detectPlugin("ShockwaveFlash.ShockwaveFlash"),qt:detectPlugin("QuickTime.QuickTime"),wmp:detectPlugin("wmplayer.ocx"),f4m:false}}var apply=function(o,e){for(var p in e){o[p]=e[p]}return o};var isLink=function(el){return typeof el.tagName=="string"&&(el.tagName.toUpperCase()=="A"||el.tagName.toUpperCase()=="AREA")};SL.getViewportHeight=function(){var height=window.innerHeight;var mode=document.compatMode;if((mode||isIE)&&!isOpera){height=isStrict?document.documentElement.clientHeight:document.body.clientHeight}return height};SL.getViewportWidth=function(){var width=window.innerWidth;var mode=document.compatMode;if(mode||isIE){width=isStrict?document.documentElement.clientWidth:document.body.clientWidth}return width};SL.getDocumentHeight=function(){var scrollHeight=isStrict?document.documentElement.scrollHeight:document.body.scrollHeight;return Math.max(scrollHeight,SL.getViewportHeight())};SL.getDocumentWidth=function(){var scrollWidth=isStrict?document.documentElement.scrollWidth:document.body.scrollWidth;return Math.max(scrollWidth,SL.getViewportWidth())};var clearOpacity=function(el){if(isIE){if(typeof el.style.filter=="string"&&(/alpha/i).test(el.style.filter)){el.style.filter=""}}else{el.style.opacity="";el.style["-moz-opacity"]="";el.style["-khtml-opacity"]=""}};var fadeIn=function(el,endingOpacity,duration,callback){if(options.animate){SL.setStyle(el,"opacity",0);el.style.visibility="visible";SL.animate(el,{opacity:{to:endingOpacity}},duration,function(){if(endingOpacity==1){clearOpacity(el)}if(typeof callback=="function"){callback()}})}else{if(endingOpacity==1){clearOpacity(el)}else{SL.setStyle(el,"opacity",endingOpacity)}el.style.visibility="visible";if(typeof callback=="function"){callback()}}};var fadeOut=function(el,duration,callback){var cb=function(){el.style.visibility="hidden";clearOpacity(el);if(typeof callback=="function"){callback()}};if(options.animate){SL.animate(el,{opacity:{to:0}},duration,cb)}else{cb()}};var appendHTML=function(el,html){el=SL.get(el);if(el.insertAdjacentHTML){el.insertAdjacentHTML("BeforeEnd",html);return el.lastChild}if(el.lastChild){var range=el.ownerDocument.createRange();range.setStartAfter(el.lastChild);var frag=range.createContextualFragment(html);el.appendChild(frag);return el.lastChild}else{el.innerHTML=html;return el.lastChild}};var overwriteHTML=function(el,html){el=SL.get(el);el.innerHTML=html;return el.firstChild};var getComputedHeight=function(el){var h=Math.max(el.offsetHeight,el.clientHeight);if(!h){h=parseInt(SL.getStyle(el,"height"),10)||0;if(!isBorderBox){h+=parseInt(SL.getStyle(el,"padding-top"),10)+parseInt(SL.getStyle(el,"padding-bottom"),10)+parseInt(SL.getStyle(el,"border-top-width"),10)+parseInt(SL.getStyle(el,"border-bottom-width"),10)}}return h};var getComputedWidth=function(el){var w=Math.max(el.offsetWidth,el.clientWidth);if(!w){w=parseInt(SL.getStyle(el,"width"),10)||0;if(!isBorderBox){w+=parseInt(SL.getStyle(el,"padding-left"),10)+parseInt(SL.getStyle(el,"padding-right"),10)+parseInt(SL.getStyle(el,"border-left-width"),10)+parseInt(SL.getStyle(el,"border-right-width"),10)}}return w};var getPlayerType=function(url){if(RE.img.test(url)){return"img"}var match=url.match(RE.domain);var this_domain=match?document.domain==match[1]:false;if(url.indexOf("#")>-1&&this_domain){return"inline"}var q_index=url.indexOf("?");if(q_index>-1){url=url.substring(0,q_index)}if(RE.swf.test(url)){return plugins.fla?"swf":"unsupported-swf"}if(RE.flv.test(url)){return plugins.fla?"flv":"unsupported-flv"}if(RE.qt.test(url)){return plugins.qt?"qt":"unsupported-qt"}if(RE.wmp.test(url)){if(plugins.wmp){return"wmp"}else{if(plugins.f4m){return"qt"}else{return isMac?(plugins.qt?"unsupported-f4m":"unsupported-qtf4m"):"unsupported-wmp"}}}else{if(RE.qtwmp.test(url)){if(plugins.qt){return"qt"}else{if(plugins.wmp){return"wmp"}else{return isMac?"unsupported-qt":"unsupported-qtwmp"}}}else{if(!this_domain||RE.iframe.test(url)){return"iframe"}}}return"unsupported"};var handleClick=function(ev){var link;if(isLink(this)){link=this}else{link=SL.getTarget(ev);while(!isLink(link)&&link.parentNode){link=link.parentNode}}Shadowbox.open(link);if(current_gallery.length){SL.preventDefault(ev)}};var setupGallery=function(obj){var copy=apply({},obj);if(!obj.gallery){current_gallery=[copy];current=0}else{current_gallery=[];var index,ci;for(var i=0,len=cache.length;i<len;++i){ci=cache[i];if(ci.gallery){if(ci.content==obj.content&&ci.gallery==obj.gallery&&ci.title==obj.title){index=current_gallery.length}if(ci.gallery==obj.gallery){current_gallery.push(apply({},ci))}}}if(index==null){current_gallery.unshift(copy);index=0}current=index}var match,r;for(var i=0,len=current_gallery.length;i<len;++i){r=false;if(current_gallery[i].type=="unsupported"){r=true}else{if(match=RE.unsupported.exec(current_gallery[i].type)){if(options.handleUnsupported=="link"){current_gallery[i].type="html";var m;switch(match[1]){case"qtwmp":m=String.format(options.text.errors.either,options.errors.qt.url,options.errors.qt.name,options.errors.wmp.url,options.errors.wmp.name);break;case"qtf4m":m=String.format(options.text.errors.shared,options.errors.qt.url,options.errors.qt.name,options.errors.f4m.url,options.errors.f4m.name);break;default:if(match[1]=="swf"||match[1]=="flv"){match[1]="fla"}m=String.format(options.text.errors.single,options.errors[match[1]].url,options.errors[match[1]].name)}current_gallery[i]=apply(current_gallery[i],{height:160,width:320,content:'<div class="shadowbox_message">'+m+"</div>"})}else{r=true}}else{if(current_gallery[i].type=="inline"){var match=RE.inline.exec(current_gallery[i].content);if(match){var el;if(el=SL.get(match[1])){current_gallery[i].content=el.innerHTML}else{throw"No element found with id "+match[1]}}else{throw"No element id found for inline content"}}}}if(r){current_gallery.splice(i,1);if(i<current){--current}--i}}};var buildBars=function(){var link=current_gallery[current];if(!link){return }var title_i=SL.get("shadowbox_title_inner");title_i.innerHTML=(link.title)?link.title:"";var tool_i=SL.get("shadowbox_toolbar_inner");tool_i.innerHTML="";if(options.displayNav){tool_i.innerHTML=String.format(options.skin.close,options.text.close);if(current_gallery.length>1){if(options.continuous){appendHTML(tool_i,String.format(options.skin.next,options.text.next));appendHTML(tool_i,String.format(options.skin.prev,options.text.prev))}else{if((current_gallery.length-1)>current){appendHTML(tool_i,String.format(options.skin.next,options.text.next))}if(current>0){appendHTML(tool_i,String.format(options.skin.prev,options.text.prev))}}}}if(current_gallery.length>1&&options.displayCounter){var counter="";if(options.counterType=="skip"){for(var i=0,len=current_gallery.length;i<len;++i){counter+='<a href="javascript:Shadowbox.change('+i+');"';if(i==current){counter+=' class="shadowbox_counter_current"'}counter+=">"+(i+1)+"</a>"}}else{counter=(current+1)+" of "+current_gallery.length}appendHTML(tool_i,String.format(options.skin.counter,counter))}};var hideBars=function(callback){var title_m=getComputedHeight(SL.get("shadowbox_title"));var tool_m=0-getComputedHeight(SL.get("shadowbox_toolbar"));var title_i=SL.get("shadowbox_title_inner");var tool_i=SL.get("shadowbox_toolbar_inner");if(options.animate&&callback){SL.animate(title_i,{marginTop:{to:title_m}},0.2);SL.animate(tool_i,{marginTop:{to:tool_m}},0.2,callback)}else{SL.setStyle(title_i,"marginTop",title_m+"px");SL.setStyle(tool_i,"marginTop",tool_m+"px")}};var showBars=function(callback){var title_i=SL.get("shadowbox_title_inner");if(options.animate){if(title_i.innerHTML!=""){SL.animate(title_i,{marginTop:{to:0}},0.35)}SL.animate(SL.get("shadowbox_toolbar_inner"),{marginTop:{to:0}},0.35,callback)}else{if(title_i.innerHTML!=""){SL.setStyle(title_i,"margin-top","0px")}SL.setStyle(SL.get("shadowbox_toolbar_inner"),"margin-top","0px");callback()}};var resetDrag=function(){drag={x:0,y:0,start_x:null,start_y:null}};var toggleDrag=function(on){if(on){resetDrag();var styles=["position:absolute","cursor:"+(isGecko?"-moz-grab":"move")];styles.push(isIE?"background-color:#fff;filter:alpha(opacity=0)":"background-color:transparent");appendHTML("shadowbox_body_inner",'<div id="shadowbox_drag_layer" style="'+styles.join(";")+'"></div>');SL.addEvent(SL.get("shadowbox_drag_layer"),"mousedown",listenDrag)}else{var d=SL.get("shadowbox_drag_layer");if(d){SL.removeEvent(d,"mousedown",listenDrag);SL.remove(d)}}};var listenDrag=function(ev){drag.start_x=ev.clientX;drag.start_y=ev.clientY;draggable=SL.get("shadowbox_content");SL.addEvent(document,"mousemove",positionDrag);SL.addEvent(document,"mouseup",unlistenDrag);if(isGecko){SL.setStyle(SL.get("shadowbox_drag_layer"),"cursor","-moz-grabbing")}};var unlistenDrag=function(){SL.removeEvent(document,"mousemove",positionDrag);SL.removeEvent(document,"mouseup",unlistenDrag);if(isGecko){SL.setStyle(SL.get("shadowbox_drag_layer"),"cursor","-moz-grab")}};var positionDrag=function(ev){var move_y=ev.clientY-drag.start_y;drag.start_y=drag.start_y+move_y;drag.y=Math.max(Math.min(0,drag.y+move_y),current_height-optimal_height);SL.setStyle(draggable,"top",drag.y+"px");var move_x=ev.clientX-drag.start_x;drag.start_x=drag.start_x+move_x;drag.x=Math.max(Math.min(0,drag.x+move_x),current_width-optimal_width);SL.setStyle(draggable,"left",drag.x+"px")};var loadContent=function(){var obj=current_gallery[current];if(!obj){return }buildBars();switch(obj.type){case"img":preloader=new Image();preloader.onload=function(){var h=obj.height?parseInt(obj.height,10):preloader.height;var w=obj.width?parseInt(obj.width,10):preloader.width;resizeContent(h,w,function(dims){showBars(function(){setContent({tag:"img",height:dims.i_height,width:dims.i_width,src:obj.content,style:"position:absolute"});if(dims.enableDrag&&options.handleLgImages=="drag"){toggleDrag(true);SL.setStyle(SL.get("shadowbox_drag_layer"),{height:dims.i_height+"px",width:dims.i_width+"px"})}finishContent()})});preloader.onload=function(){}};preloader.src=obj.content;break;case"swf":case"flv":case"qt":case"wmp":var markup=Shadowbox.movieMarkup(obj);resizeContent(markup.height,markup.width,function(){showBars(function(){setContent(markup);finishContent()})});break;case"iframe":var h=obj.height?parseInt(obj.height,10):SL.getViewportHeight();var w=obj.width?parseInt(obj.width,10):SL.getViewportWidth();var content={tag:"iframe",name:"shadowbox_content",height:"100%",width:"100%",frameborder:"0",marginwidth:"0",marginheight:"0",scrolling:"auto"};resizeContent(h,w,function(dims){showBars(function(){setContent(content);var win=(isIE)?SL.get("shadowbox_content").contentWindow:window.frames["shadowbox_content"];win.location=obj.content;finishContent()})});break;case"html":case"inline":var h=obj.height?parseInt(obj.height,10):SL.getViewportHeight();var w=obj.width?parseInt(obj.width,10):SL.getViewportWidth();var content={tag:"div",cls:"html",html:obj.content};resizeContent(h,w,function(){showBars(function(){setContent(content);finishContent()})});break;default:throw"Shadowbox cannot open content of type "+obj.type}if(current_gallery.length>0){var next=current_gallery[current+1];if(!next){next=current_gallery[0]}if(next.type=="img"){var preload_next=new Image();preload_next.src=next.href}var prev=current_gallery[current-1];if(!prev){prev=current_gallery[current_gallery.length-1]}if(prev.type=="img"){var preload_prev=new Image();preload_prev.src=prev.href}}};var setContent=function(obj){var id="shadowbox_content";var content=SL.get(id);if(content){switch(content.tagName.toUpperCase()){case"OBJECT":var link=current_gallery[(obj?current-1:current)];if(link.type=="wmp"&&isIE){try{shadowbox_content.controls.stop();shadowbox_content.URL="non-existent.wmv";window.shadowbox_content=function(){}}catch(e){}}else{if(link.type=="qt"&&isSafari){try{document.shadowbox_content.Stop()}catch(e){}content.innerHTML=""}}setTimeout(function(){SL.remove(content)},10);break;case"IFRAME":SL.remove(content);if(isGecko){delete window.frames[id]}break;default:SL.remove(content)}}if(obj){if(!obj.id){obj.id=id}return appendHTML("shadowbox_body_inner",Shadowbox.createHTML(obj))}return null};var finishContent=function(){var obj=current_gallery[current];if(!obj){return }hideLoading(function(){listenKeyboard(true);if(options.onFinish&&typeof options.onFinish=="function"){options.onFinish(obj)}})};var resizeContent=function(height,width,callback){optimal_height=height;optimal_width=width;var resizable=RE.resize.test(current_gallery[current].type);var dims=getDimensions(optimal_height,optimal_width,resizable);if(callback){var cb=function(){callback(dims)};switch(options.animSequence){case"hw":adjustHeight(dims.height,dims.top,true,function(){adjustWidth(dims.width,true,cb)});break;case"wh":adjustWidth(dims.width,true,function(){adjustHeight(dims.height,dims.top,true,cb)});break;default:adjustWidth(dims.width,true);adjustHeight(dims.height,dims.top,true,cb)}}else{adjustWidth(dims.width,false);adjustHeight(dims.height,dims.top,false);if(options.handleLgImages=="resize"&&resizable){var content=SL.get("shadowbox_content");if(content){content.height=dims.i_height;content.width=dims.i_width}}}};var getDimensions=function(o_height,o_width,resizable){if(typeof resizable=="undefined"){resizable=false}var height=o_height=parseInt(o_height);var width=o_width=parseInt(o_width);var shadowbox_b=SL.get("shadowbox_body");var view_height=SL.getViewportHeight();var extra_height=parseInt(SL.getStyle(shadowbox_b,"border-top-width"),10)+parseInt(SL.getStyle(shadowbox_b,"border-bottom-width"),10)+parseInt(SL.getStyle(shadowbox_b,"margin-top"),10)+parseInt(SL.getStyle(shadowbox_b,"margin-bottom"),10)+getComputedHeight(SL.get("shadowbox_title"))+getComputedHeight(SL.get("shadowbox_toolbar"))+(2*options.viewportPadding);if((height+extra_height)>=view_height){height=view_height-extra_height}var view_width=SL.getViewportWidth();var extra_body_width=parseInt(SL.getStyle(shadowbox_b,"border-left-width"),10)+parseInt(SL.getStyle(shadowbox_b,"border-right-width"),10)+parseInt(SL.getStyle(shadowbox_b,"margin-left"),10)+parseInt(SL.getStyle(shadowbox_b,"margin-right"),10);var extra_width=extra_body_width+(2*options.viewportPadding);if((width+extra_width)>=view_width){width=view_width-extra_width}var enableDrag=false;var i_height=o_height;var i_width=o_width;var handle=options.handleLgImages;if(resizable&&(handle=="resize"||handle=="drag")){var change_h=(o_height-height)/o_height;var change_w=(o_width-width)/o_width;if(handle=="resize"){if(change_h>change_w){width=Math.round((o_width/o_height)*height)}else{if(change_w>change_h){height=Math.round((o_height/o_width)*width)}}i_width=width;i_height=height}else{var link=current_gallery[current];if(link){enableDrag=link.type=="img"&&(change_h>0||change_w>0)}}}return{height:height,width:width+extra_body_width,i_height:i_height,i_width:i_width,top:((view_height-(height+extra_height))/2)+options.viewportPadding,enableDrag:enableDrag}};var centerVertically=function(){var shadowbox=SL.get("shadowbox");var scroll=document.documentElement.scrollTop;var s_top=scroll+Math.round((SL.getViewportHeight()-(shadowbox.offsetHeight||0))/2);SL.setStyle(shadowbox,"top",s_top+"px")};var adjustHeight=function(height,top,animate,callback){height=parseInt(height);current_height=height;var sbi=SL.get("shadowbox_body_inner");if(animate&&options.animate){SL.animate(sbi,{height:{to:height}},options.resizeDuration,callback)}else{SL.setStyle(sbi,"height",height+"px");if(typeof callback=="function"){callback()}}if(absolute_pos){centerVertically();SL.addEvent(window,"scroll",centerVertically);top+=document.documentElement.scrollTop}var shadowbox=SL.get("shadowbox");if(animate&&options.animate){SL.animate(shadowbox,{top:{to:top}},options.resizeDuration)}else{SL.setStyle(shadowbox,"top",top+"px")}};var adjustWidth=function(width,animate,callback){width=parseInt(width);current_width=width;var shadowbox=SL.get("shadowbox");if(animate&&options.animate){SL.animate(shadowbox,{width:{to:width}},options.resizeDuration,callback)}else{SL.setStyle(shadowbox,"width",width+"px");if(typeof callback=="function"){callback()}}};var listenKeyboard=function(on){if(!options.enableKeys){return }if(on){document.onkeydown=handleKey}else{document.onkeydown=""}};var assertKey=function(valid,key,code){return(valid.indexOf(key)!=-1||valid.indexOf(code)!=-1)};var handleKey=function(e){var code=e?e.which:event.keyCode;var key=String.fromCharCode(code).toLowerCase();if(assertKey(options.keysClose,key,code)){Shadowbox.close()}else{if(assertKey(options.keysPrev,key,code)){Shadowbox.previous()}else{if(assertKey(options.keysNext,key,code)){Shadowbox.next()}}}};var toggleTroubleElements=function(on){var vis=(on?"visible":"hidden");var selects=document.getElementsByTagName("select");for(i=0,len=selects.length;i<len;++i){selects[i].style.visibility=vis}var objects=document.getElementsByTagName("object");for(i=0,len=objects.length;i<len;++i){objects[i].style.visibility=vis}var embeds=document.getElementsByTagName("embed");for(i=0,len=embeds.length;i<len;++i){embeds[i].style.visibility=vis}};var showLoading=function(){var loading=SL.get("shadowbox_loading");overwriteHTML(loading,String.format(options.skin.loading,options.assetURL+options.loadingImage,options.text.loading,options.text.cancel));loading.style.visibility="visible"};var hideLoading=function(callback){var t=current_gallery[current].type;var anim=(t=="img"||t=="html");var loading=SL.get("shadowbox_loading");if(anim){fadeOut(loading,0.35,callback)}else{loading.style.visibility="hidden";callback()}};var resizeOverlay=function(){var overlay=SL.get("shadowbox_overlay");SL.setStyle(overlay,{height:"100%",width:"100%"});SL.setStyle(overlay,"height",SL.getDocumentHeight()+"px");if(!isSafari3){SL.setStyle(overlay,"width",SL.getDocumentWidth()+"px")}};var checkOverlayImgNeeded=function(){if(!(isGecko&&isMac)){return false}for(var i=0,len=current_gallery.length;i<len;++i){if(!RE.overlay.exec(current_gallery[i].type)){return true}}return false};var toggleOverlay=function(callback){var overlay=SL.get("shadowbox_overlay");if(overlay_img_needed==null){overlay_img_needed=checkOverlayImgNeeded()}if(callback){resizeOverlay();if(overlay_img_needed){SL.setStyle(overlay,{visibility:"visible",backgroundColor:"transparent",backgroundImage:"url("+options.assetURL+options.overlayBgImage+")",backgroundRepeat:"repeat",opacity:1});callback()}else{SL.setStyle(overlay,{visibility:"visible",backgroundColor:options.overlayColor,backgroundImage:"none"});fadeIn(overlay,options.overlayOpacity,options.fadeDuration,callback)}}else{if(overlay_img_needed){SL.setStyle(overlay,"visibility","hidden")}else{fadeOut(overlay,options.fadeDuration)}overlay_img_needed=null}};Shadowbox.init=function(opts){if(initialized){return }options=apply(options,opts||{});appendHTML(document.body,options.skin.main);RE.img=new RegExp(".("+options.ext.img.join("|")+")s*$","i");RE.qt=new RegExp(".("+options.ext.qt.join("|")+")s*$","i");RE.wmp=new RegExp(".("+options.ext.wmp.join("|")+")s*$","i");RE.qtwmp=new RegExp(".("+options.ext.qtwmp.join("|")+")s*$","i");RE.iframe=new RegExp(".("+options.ext.iframe.join("|")+")s*$","i");var id=null;var resize=function(){clearInterval(id);id=null;resizeOverlay();resizeContent(optimal_height,optimal_width)};SL.addEvent(window,"resize",function(){if(activated){if(id){clearInterval(id);id=null}if(!id){id=setInterval(resize,50)}}});if(options.listenOverlay){SL.addEvent(SL.get("shadowbox_overlay"),"click",Shadowbox.close)}if(absolute_pos){SL.setStyle(SL.get("shadowbox_container"),"position","absolute");SL.setStyle("shadowbox_body","zoom",1);SL.addEvent(SL.get("shadowbox_container"),"click",function(e){var target=SL.getTarget(e);if(target.id&&target.id=="shadowbox_container"){Shadowbox.close()}})}if(!options.skipSetup){Shadowbox.setup()}initialized=true};Shadowbox.setup=function(links,opts){if(!links){var links=[];var a=document.getElementsByTagName("a"),rel;for(var i=0,len=a.length;i<len;++i){rel=a[i].getAttribute("rel");if(rel&&RE.rel.test(rel)){links[links.length]=a[i]}}}else{if(!links.length){links=[links]}}var link;for(var i=0,len=links.length;i<len;++i){link=links[i];if(typeof link.shadowboxCacheKey=="undefined"){link.shadowboxCacheKey=cache.length;SL.addEvent(link,"click",handleClick)}cache[link.shadowboxCacheKey]=this.buildCacheObj(link,opts)}};Shadowbox.buildCacheObj=function(link,opts){var href=link.href;var o={el:link,title:link.getAttribute("title"),type:getPlayerType(href),options:apply({},opts||{}),content:href};var opt,l_opts=["title","type","height","width","gallery"];for(var i=0,len=l_opts.length;i<len;++i){opt=l_opts[i];if(typeof o.options[opt]!="undefined"){o[opt]=o.options[opt];delete o.options[opt]}}var rel=link.getAttribute("rel");if(rel){var match=rel.match(RE.gallery);if(match){o.gallery=escape(match[2])}var params=rel.split(";");for(var i=0,len=params.length;i<len;++i){match=params[i].match(RE.param);if(match){if(match[1]=="options"){eval("o.options = apply(o.options, "+match[2]+")")}else{o[match[1]]=match[2]}}}}return o};Shadowbox.applyOptions=function(opts){if(opts){default_options=apply({},options);options=apply(options,opts)}};Shadowbox.revertOptions=function(){if(default_options){options=default_options;default_options=null}};Shadowbox.open=function(obj,opts){if(activated){return }activated=true;if(isLink(obj)){if(typeof obj.shadowboxCacheKey=="undefined"||typeof cache[obj.shadowboxCacheKey]=="undefined"){obj=this.buildCacheObj(obj,opts)}else{obj=cache[obj.shadowboxCacheKey]}}this.revertOptions();if(obj.options||opts){this.applyOptions(apply(apply({},obj.options||{}),opts||{}))}setupGallery(obj);if(current_gallery.length){if(options.onOpen&&typeof options.onOpen=="function"){options.onOpen(obj)}SL.setStyle(SL.get("shadowbox"),"display","block");toggleTroubleElements(false);var dims=getDimensions(options.initialHeight,options.initialWidth);adjustHeight(dims.height,dims.top);adjustWidth(dims.width);hideBars(false);toggleOverlay(function(){SL.setStyle(SL.get("shadowbox"),"visibility","visible");showLoading();loadContent()})}};Shadowbox.change=function(num){if(!current_gallery){return }if(!current_gallery[num]){if(!options.continuous){return }else{num=(num<0)?(current_gallery.length-1):0}}current=num;toggleDrag(false);setContent(null);listenKeyboard(false);if(options.onChange&&typeof options.onChange=="function"){options.onChange(current_gallery[current])}showLoading();hideBars(loadContent)};Shadowbox.next=function(){return this.change(current+1)};Shadowbox.previous=function(){return this.change(current-1)};Shadowbox.close=function(){if(!activated){return }listenKeyboard(false);SL.setStyle(SL.get("shadowbox"),{display:"none",visibility:"hidden"});if(absolute_pos){SL.removeEvent(window,"scroll",centerVertically)}toggleDrag(false);setContent(null);if(preloader){preloader.onload=function(){};preloader=null}toggleOverlay(false);toggleTroubleElements(true);if(options.onClose&&typeof options.onClose=="function"){options.onClose(current_gallery[current])}activated=false};Shadowbox.clearCache=function(){for(var i=0,len=cache.length;i<len;++i){if(cache[i].el){SL.removeEvent(cache[i].el,"click",handleClick);delete cache[i].shadowboxCacheKey}}cache=[]};Shadowbox.movieMarkup=function(obj){var h=obj.height?parseInt(obj.height,10):300;var w=obj.width?parseInt(obj.width,10):300;var autoplay=options.autoplayMovies;var controls=options.showMovieControls;if(obj.options){if(obj.options.autoplayMovies!=null){autoplay=obj.options.autoplayMovies}if(obj.options.showMovieControls!=null){controls=obj.options.showMovieControls}}var markup={tag:"object",name:"shadowbox_content"};switch(obj.type){case"swf":var dims=getDimensions(h,w,true);h=dims.height;w=dims.width;markup.type="application/x-shockwave-flash";markup.data=obj.content;markup.children=[{tag:"param",name:"movie",value:obj.content}];break;case"flv":autoplay=autoplay?"true":"false";var showicons="false";var a=h/w;if(controls){showicons="true";h+=20}var dims=getDimensions(h,h/a,true);h=dims.height;w=(h-(controls?20:0))/a;var flashvars=["file="+obj.content,"height="+h,"width="+w,"autostart="+autoplay,"displayheight="+(h-(controls?20:0)),"showicons="+showicons,"backcolor=0x000000&amp;frontcolor=0xCCCCCC&amp;lightcolor=0x557722"];markup.type="application/x-shockwave-flash";markup.data=options.assetURL+options.flvPlayer;markup.children=[{tag:"param",name:"movie",value:options.assetURL+options.flvPlayer},{tag:"param",name:"flashvars",value:flashvars.join("&amp;")},{tag:"param",name:"allowfullscreen",value:"true"}];break;case"qt":autoplay=autoplay?"true":"false";if(controls){controls="true";h+=16}else{controls="false"}markup.children=[{tag:"param",name:"src",value:obj.content},{tag:"param",name:"scale",value:"aspect"},{tag:"param",name:"controller",value:controls},{tag:"param",name:"autoplay",value:autoplay}];if(isIE){markup.classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B";markup.codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"}else{markup.type="video/quicktime";markup.data=obj.content}break;case"wmp":autoplay=autoplay?1:0;markup.children=[{tag:"param",name:"autostart",value:autoplay}];if(isIE){if(controls){controls="full";h+=70}else{controls="none"}markup.classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6";markup.children[markup.children.length]={tag:"param",name:"url",value:obj.content};markup.children[markup.children.length]={tag:"param",name:"uimode",value:controls}}else{if(controls){controls=1;h+=45}else{controls=0}markup.type="video/x-ms-wmv";markup.data=obj.content;markup.children[markup.children.length]={tag:"param",name:"showcontrols",value:controls}}break}markup.height=h;markup.width=w;return markup};Shadowbox.createHTML=function(obj){var html="<"+obj.tag;for(var attr in obj){if(attr=="tag"||attr=="html"||attr=="children"){continue}if(attr=="cls"){html+=' class="'+obj["cls"]+'"'}else{html+=" "+attr+'="'+obj[attr]+'"'}}if(RE.empty.test(obj.tag)){html+="/>\n"}else{html+=">\n";var cn=obj.children;if(cn){for(var i=0,len=cn.length;i<len;++i){html+=this.createHTML(cn[i])}}if(obj.html){html+=obj.html}html+="</"+obj.tag+">\n"}return html};Shadowbox.getPlugins=function(){return plugins};Shadowbox.getOptions=function(){return options};Shadowbox.getCurrent=function(){return current_gallery[current]};Shadowbox.getVersion=function(){return version}})();Array.prototype.indexOf=Array.prototype.indexOf||function(C){for(var B=0,A=this.length;B<A;++B){if(this[B]==C){return B}}return -1};String.format=String.format||function(B){var A=Array.prototype.slice.call(arguments,1);return B.replace(/\{(\d+)\}/g,function(C,D){return A[D]})}



/*
 * jQuery corner plugin
 *
 * version 1.7 (1/26/2007)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/**
 * The corner() method provides a simple way of styling DOM elements.  
 *
 * corner() takes a single string argument:  $().corner("effect corners width")
 *
 *   effect:  The name of the effect to apply, such as round or bevel. 
 *            If you don't specify an effect, rounding is used.
 *
 *   corners: The corners can be one or more of top, bottom, tr, tl, br, or bl. 
 *            By default, all four corners are adorned. 
 *
 *   width:   The width specifies the width of the effect; in the case of rounded corners this 
 *            will be the radius of the width. 
 *            Specify this value using the px suffix such as 10px, and yes it must be pixels.
 *
 * For more details see: http://methvin.com/jquery/jq-corner.html
 * For a full demo see:  http://malsup.com/jquery/corner/
 *
 *
 * @example $('.adorn').corner();
 * @desc Create round, 10px corners 
 *
 * @example $('.adorn').corner("25px");
 * @desc Create round, 25px corners 
 *
 * @example $('.adorn').corner("notch bottom");
 * @desc Create notched, 10px corners on bottom only
 *
 * @example $('.adorn').corner("tr dog 25px");
 * @desc Create dogeared, 25px corner on the top-right corner only
 *
 * @example $('.adorn').corner("round 8px").parent().css('padding', '4px').corner("round 10px");
 * @desc Create a rounded border effect by styling both the element and its parent
 * 
 * @name corner
 * @type jQuery
 * @param String options Options which control the corner style
 * @cat Plugins/Corner
 * @return jQuery
 * @author Dave Methvin (dave.methvin@gmail.com)
 * @author Mike Alsup (malsup@gmail.com)
 */
jQuery.fn.corner = function(o) {
    function hex2(s) {
        var s = parseInt(s).toString(16);
        return ( s.length < 2 ) ? '0'+s : s;
    };
    function gpc(node) {
        for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode  ) {
            var v = jQuery.css(node,'backgroundColor');
            if ( v.indexOf('rgb') >= 0 ) { 
                rgb = v.match(/\d+/g); 
                return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
            }
            if ( v && v != 'transparent' )
                return v;
        }
        return '#ffffff';
    };
    function getW(i) {
        switch(fx) {
        case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
        case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
        case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
        case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
        case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
        case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
        case 'curl':   return Math.round(width*(Math.atan(i)));
        case 'tear':   return Math.round(width*(Math.cos(i)));
        case 'wicked': return Math.round(width*(Math.tan(i)));
        case 'long':   return Math.round(width*(Math.sqrt(i)));
        case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
        case 'dog':    return (i&1) ? (i+1) : width;
        case 'dog2':   return (i&2) ? (i+1) : width;
        case 'dog3':   return (i&3) ? (i+1) : width;
        case 'fray':   return (i%2)*width;
        case 'notch':  return width; 
        case 'bevel':  return i+1;
        }
    };
    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt(jQuery.css(this,'paddingTop'))||0,     R: parseInt(jQuery.css(this,'paddingRight'))||0,
            B: parseInt(jQuery.css(this,'paddingBottom'))||0,  L: parseInt(jQuery.css(this,'paddingLeft'))||0
        };

        if (jQuery.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = jQuery.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
            var d = document.createElement('div');
            var ds = d.style;

            bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

            if (bot && cssHeight != 'auto') {
                if (jQuery.css(this,'position') == 'static')
                    this.style.position = 'relative';
                ds.position = 'absolute';
                ds.bottom = ds.left = ds.padding = ds.margin = '0';
                if (jQuery.browser.msie)
                    ds.setExpression('width', 'this.parentNode.offsetWidth');
                else
                    ds.width = '100%';
            }
            else {
                ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                    (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
            }

            for (var i=0; i < width; i++) {
                var w = Math.max(0,getW(i));
                var e = strip.cloneNode(false);
                e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
            }
        }
    });
};




﻿/*!
 * jQuery blockUI plugin
 * Version 2.33 (29-MAR-2010)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
	alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
	return;
}

$.fn._fadeIn = $.fn.fadeIn;

var noOp = function() {};

// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
// retarded userAgent strings on Vista)
var mode = document.documentMode || 0;
var setExpr = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8);
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode;

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout, onClose) {
	var $m = $('<div class="growlUI"></div>');
	if (title) $m.append('<h1>'+title+'</h1>');
	if (message) $m.append('<h2>'+message+'</h2>');
	if (timeout == undefined) timeout = 3000;
	$.blockUI({
		message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
		timeout: timeout, showOverlay: false,
		onUnblock: onClose, 
		css: $.blockUI.defaults.growlCSS
	});
};

// plugin method for blocking element content
$.fn.block = function(opts) {
	return this.unblock({ fadeOut: 0 }).each(function() {
		if ($.css(this,'position') == 'static')
			this.style.position = 'relative';
		if ($.browser.msie)
			this.style.zoom = 1; // force 'hasLayout'
		install(this, opts);
	});
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
	return this.each(function() {
		remove(this, opts);
	});
};

$.blockUI.version = 2.33; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
	// message displayed when blocking (use null for no message)
	message:  '<h1>Please wait...</h1>',

	title: null,	  // title string; only used when theme == true
	draggable: true,  // only used when theme == true (requires jquery-ui.js to be loaded)
	
	theme: false, // set to true to use with jQuery UI themes
	
	// styles for the message when blocking; if you wish to disable
	// these and use an external stylesheet then do this in your code:
	// $.blockUI.defaults.css = {};
	css: {
		padding:	0,
		margin:		0,
		width:		'30%',
		top:		'40%',
		left:		'35%',
		textAlign:	'center',
		color:		'#000',
		border:		'3px solid #aaa',
		backgroundColor:'#fff',
		cursor:		'wait'
	},
	
	// minimal style set used when themes are used
	themedCSS: {
		width:	'30%',
		top:	'40%',
		left:	'35%'
	},

	// styles for the overlay
	overlayCSS:  {
		backgroundColor: '#000',
		opacity:	  	 0.6,
		cursor:		  	 'wait'
	},

	// styles applied when using $.growlUI
	growlCSS: {
		width:  	'350px',
		top:		'10px',
		left:   	'',
		right:  	'10px',
		border: 	'none',
		padding:	'5px',
		opacity:	0.6,
		cursor: 	'default',
		color:		'#fff',
		backgroundColor: '#000',
		'-webkit-border-radius': '10px',
		'-moz-border-radius':	 '10px',
		'border-radius': 		 '10px'
	},
	
	// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
	// (hat tip to Jorge H. N. de Vasconcelos)
	iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',

	// force usage of iframe in non-IE browsers (handy for blocking applets)
	forceIframe: false,

	// z-index for the blocking overlay
	baseZ: 1000,

	// set these to true to have the message automatically centered
	centerX: true, // <-- only effects element blocking (page block controlled via css above)
	centerY: true,

	// allow body element to be stetched in ie6; this makes blocking look better
	// on "short" pages.  disable if you wish to prevent changes to the body height
	allowBodyStretch: true,

	// enable if you want key and mouse events to be disabled for content that is blocked
	bindEvents: true,

	// be default blockUI will supress tab navigation from leaving blocking content
	// (if bindEvents is true)
	constrainTabKey: true,

	// fadeIn time in millis; set to 0 to disable fadeIn on block
	fadeIn:  200,

	// fadeOut time in millis; set to 0 to disable fadeOut on unblock
	fadeOut:  400,

	// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
	timeout: 0,

	// disable if you don't want to show the overlay
	showOverlay: true,

	// if true, focus will be placed in the first available input field when
	// page blocking
	focusInput: true,

	// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
	applyPlatformOpacityRules: true,
	
	// callback method invoked when fadeIn has completed and blocking message is visible
	onBlock: null,

	// callback method invoked when unblocking has completed; the callback is
	// passed the element that has been unblocked (which is the window object for page
	// blocks) and the options that were passed to the unblock call:
	//	 onUnblock(element, options)
	onUnblock: null,

	// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
	quirksmodeOffsetHack: 4
};

// private data and functions follow...

var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
	var full = (el == window);
	var msg = opts && opts.message !== undefined ? opts.message : undefined;
	opts = $.extend({}, $.blockUI.defaults, opts || {});
	opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
	var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
	var themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
	msg = msg === undefined ? opts.message : msg;

	// remove the current block (if there is one)
	if (full && pageBlock)
		remove(window, {fadeOut:0});

	// if an existing element is being used as the blocking content then we capture
	// its current place in the DOM (and current display style) so we can restore
	// it when we unblock
	if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
		var node = msg.jquery ? msg[0] : msg;
		var data = {};
		$(el).data('blockUI.history', data);
		data.el = node;
		data.parent = node.parentNode;
		data.display = node.style.display;
		data.position = node.style.position;
		if (data.parent)
			data.parent.removeChild(node);
	}

	var z = opts.baseZ;

	// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
	// layer1 is the iframe layer which is used to supress bleed through of underlying content
	// layer2 is the overlay layer which has opacity and a wait cursor (by default)
	// layer3 is the message content that is displayed while blocking

	var lyr1 = ($.browser.msie || opts.forceIframe) 
		? $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>')
		: $('<div class="blockUI" style="display:none"></div>');
	var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
	
	var lyr3, s;
	if (opts.theme && full) {
		s = '<div class="blockUI blockMsg blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:fixed">' +
				'<div class="ui-widget-header ui-dialog-titlebar blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
				'<div class="ui-widget-content ui-dialog-content"></div>' +
			'</div>';
	}
	else if (opts.theme) {
		s = '<div class="blockUI blockMsg blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:absolute">' +
				'<div class="ui-widget-header ui-dialog-titlebar blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
				'<div class="ui-widget-content ui-dialog-content"></div>' +
			'</div>';
	}
	else if (full) {
		s = '<div class="blockUI blockMsg blockPage" style="z-index:'+z+';display:none;position:fixed"></div>';
	}			
	else {
		s = '<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>';
	}
	lyr3 = $(s);

	// if we have a message, style it
	if (msg) {
		if (opts.theme) {
			lyr3.css(themedCSS);
			lyr3.addClass('ui-widget-content');
		}
		else 
			lyr3.css(css);
	}

	// style the overlay
	if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform)))
		lyr2.css(opts.overlayCSS);
	lyr2.css('position', full ? 'fixed' : 'absolute');

	// make iframe layer transparent in IE
	if ($.browser.msie || opts.forceIframe)
		lyr1.css('opacity',0.0);

	//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
	var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
	$.each(layers, function() {
		this.appendTo($par);
	});
	
	if (opts.theme && opts.draggable && $.fn.draggable) {
		lyr3.draggable({
			handle: '.ui-dialog-titlebar',
			cancel: 'li'
		});
	}

	// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
	var expr = setExpr && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
	if (ie6 || expr) {
		// give body 100% height
		if (full && opts.allowBodyStretch && $.boxModel)
			$('html,body').css('height','100%');

		// fix ie6 issue when blocked element has a border width
		if ((ie6 || !$.boxModel) && !full) {
			var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
			var fixT = t ? '(0 - '+t+')' : 0;
			var fixL = l ? '(0 - '+l+')' : 0;
		}

		// simulate fixed position
		$.each([lyr1,lyr2,lyr3], function(i,o) {
			var s = o[0].style;
			s.position = 'absolute';
			if (i < 2) {
				full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"')
					 : s.setExpression('height','this.parentNode.offsetHeight + "px"');
				full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
					 : s.setExpression('width','this.parentNode.offsetWidth + "px"');
				if (fixL) s.setExpression('left', fixL);
				if (fixT) s.setExpression('top', fixT);
			}
			else if (opts.centerY) {
				if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
				s.marginTop = 0;
			}
			else if (!opts.centerY && full) {
				var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0;
				var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
				s.setExpression('top',expression);
			}
		});
	}

	// show the message
	if (msg) {
		if (opts.theme)
			lyr3.find('.ui-widget-content').append(msg);
		else
			lyr3.append(msg);
		if (msg.jquery || msg.nodeType)
			$(msg).show();
	}

	if (($.browser.msie || opts.forceIframe) && opts.showOverlay)
		lyr1.show(); // opacity is zero
	if (opts.fadeIn) {
		var cb = opts.onBlock ? opts.onBlock : noOp;
		var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
		var cb2 = msg ? cb : noOp;
		if (opts.showOverlay)
			lyr2._fadeIn(opts.fadeIn, cb1);
		if (msg)
			lyr3._fadeIn(opts.fadeIn, cb2);
	}
	else {
		if (opts.showOverlay)
			lyr2.show();
		if (msg)
			lyr3.show();
		if (opts.onBlock)
			opts.onBlock();
	}

	// bind key and mouse events
	bind(1, el, opts);

	if (full) {
		pageBlock = lyr3[0];
		pageBlockEls = $(':input:enabled:visible',pageBlock);
		if (opts.focusInput)
			setTimeout(focus, 20);
	}
	else
		center(lyr3[0], opts.centerX, opts.centerY);

	if (opts.timeout) {
		// auto-unblock
		var to = setTimeout(function() {
			full ? $.unblockUI(opts) : $(el).unblock(opts);
		}, opts.timeout);
		$(el).data('blockUI.timeout', to);
	}
};

// remove the block
function remove(el, opts) {
	var full = (el == window);
	var $el = $(el);
	var data = $el.data('blockUI.history');
	var to = $el.data('blockUI.timeout');
	if (to) {
		clearTimeout(to);
		$el.removeData('blockUI.timeout');
	}
	opts = $.extend({}, $.blockUI.defaults, opts || {});
	bind(0, el, opts); // unbind events
	
	var els;
	if (full) // crazy selector to handle odd field errors in ie6/7
		els = $('body').children().filter('.blockUI').add('body > .blockUI');
	else
		els = $('.blockUI', el);

	if (full)
		pageBlock = pageBlockEls = null;

	if (opts.fadeOut) {
		els.fadeOut(opts.fadeOut);
		setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
	}
	else
		reset(els, data, opts, el);
};

// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
	els.each(function(i,o) {
		// remove via DOM calls so we don't lose event handlers
		if (this.parentNode)
			this.parentNode.removeChild(this);
	});

	if (data && data.el) {
		data.el.style.display = data.display;
		data.el.style.position = data.position;
		if (data.parent)
			data.parent.appendChild(data.el);
		$(el).removeData('blockUI.history');
	}

	if (typeof opts.onUnblock == 'function')
		opts.onUnblock(el,opts);
};

// bind/unbind the handler
function bind(b, el, opts) {
	var full = el == window, $el = $(el);

	// don't bother unbinding if there is nothing to unbind
	if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
		return;
	if (!full)
		$el.data('blockUI.isBlocked', b);

	// don't bind events when overlay is not in use or if bindEvents is false
	if (!opts.bindEvents || (b && !opts.showOverlay)) 
		return;

	// bind anchors and inputs for mouse and key events
	var events = 'mousedown mouseup keydown keypress';
	b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//	   var $e = $('a,:input');
//	   b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
	// allow tab navigation (conditionally)
	if (e.keyCode && e.keyCode == 9) {
		if (pageBlock && e.data.constrainTabKey) {
			var els = pageBlockEls;
			var fwd = !e.shiftKey && e.target == els[els.length-1];
			var back = e.shiftKey && e.target == els[0];
			if (fwd || back) {
				setTimeout(function(){focus(back)},10);
				return false;
			}
		}
	}
	// allow events within the message content
	if ($(e.target).parents('div.blockMsg').length > 0)
		return true;

	// allow events for content that is not being blocked
	return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
	if (!pageBlockEls)
		return;
	var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
	if (e)
		e.focus();
};

function center(el, x, y) {
	var p = el.parentNode, s = el.style;
	var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
	var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
	if (x) s.left = l > 0 ? (l+'px') : '0';
	if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) {
	return parseInt($.css(el,p))||0;
};

})(jQuery);




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

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

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



/*
 * jquery.qtip. The jQuery tooltip plugin
 *
 * Copyright (c) 2009 Craig Thompson
 * http://craigsworks.com
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Launch  : February 2009
 * Version : 1.0.0-rc3
 * Released: Tuesday 12th May, 2009 - 00:00
 * Debug: jquery.qtip.debug.js
 */
(function(f){f.fn.qtip=function(B,u){var y,t,A,s,x,w,v,z;if(typeof B=="string"){if(typeof f(this).data("qtip")!=="object"){f.fn.qtip.log.error.call(self,1,f.fn.qtip.constants.NO_TOOLTIP_PRESENT,false)}if(B=="api"){return f(this).data("qtip").interfaces[f(this).data("qtip").current]}else{if(B=="interfaces"){return f(this).data("qtip").interfaces}}}else{if(!B){B={}}if(typeof B.content!=="object"||(B.content.jquery&&B.content.length>0)){B.content={text:B.content}}if(typeof B.content.title!=="object"){B.content.title={text:B.content.title}}if(typeof B.position!=="object"){B.position={corner:B.position}}if(typeof B.position.corner!=="object"){B.position.corner={target:B.position.corner,tooltip:B.position.corner}}if(typeof B.show!=="object"){B.show={when:B.show}}if(typeof B.show.when!=="object"){B.show.when={event:B.show.when}}if(typeof B.show.effect!=="object"){B.show.effect={type:B.show.effect}}if(typeof B.hide!=="object"){B.hide={when:B.hide}}if(typeof B.hide.when!=="object"){B.hide.when={event:B.hide.when}}if(typeof B.hide.effect!=="object"){B.hide.effect={type:B.hide.effect}}if(typeof B.style!=="object"){B.style={name:B.style}}B.style=c(B.style);s=f.extend(true,{},f.fn.qtip.defaults,B);s.style=a.call({options:s},s.style);s.user=f.extend(true,{},B)}return f(this).each(function(){if(typeof B=="string"){w=B.toLowerCase();A=f(this).qtip("interfaces");if(typeof A=="object"){if(u===true&&w=="destroy"){while(A.length>0){A[A.length-1].destroy()}}else{if(u!==true){A=[f(this).qtip("api")]}for(y=0;y<A.length;y++){if(w=="destroy"){A[y].destroy()}else{if(A[y].status.rendered===true){if(w=="show"){A[y].show()}else{if(w=="hide"){A[y].hide()}else{if(w=="focus"){A[y].focus()}else{if(w=="disable"){A[y].disable(true)}else{if(w=="enable"){A[y].disable(false)}}}}}}}}}}}else{v=f.extend(true,{},s);v.hide.effect.length=s.hide.effect.length;v.show.effect.length=s.show.effect.length;if(v.position.container===false){v.position.container=f(document.body)}if(v.position.target===false){v.position.target=f(this)}if(v.show.when.target===false){v.show.when.target=f(this)}if(v.hide.when.target===false){v.hide.when.target=f(this)}t=f.fn.qtip.interfaces.length;for(y=0;y<t;y++){if(typeof f.fn.qtip.interfaces[y]=="undefined"){t=y;break}}x=new d(f(this),v,t);f.fn.qtip.interfaces[t]=x;if(typeof f(this).data("qtip")=="object"){if(typeof f(this).attr("qtip")==="undefined"){f(this).data("qtip").current=f(this).data("qtip").interfaces.length}f(this).data("qtip").interfaces.push(x)}else{f(this).data("qtip",{current:0,interfaces:[x]})}if(v.content.prerender===false&&v.show.when.event!==false&&v.show.ready!==true){v.show.when.target.bind(v.show.when.event+".qtip-"+t+"-create",{qtip:t},function(C){z=f.fn.qtip.interfaces[C.data.qtip];z.options.show.when.target.unbind(z.options.show.when.event+".qtip-"+C.data.qtip+"-create");z.cache.mouse={x:C.pageX,y:C.pageY};p.call(z);z.options.show.when.target.trigger(z.options.show.when.event)})}else{x.cache.mouse={x:v.show.when.target.offset().left,y:v.show.when.target.offset().top};p.call(x)}}})};function d(u,t,v){var s=this;s.id=v;s.options=t;s.status={animated:false,rendered:false,disabled:false,focused:false};s.elements={target:u.addClass(s.options.style.classes.target),tooltip:null,wrapper:null,content:null,contentWrapper:null,title:null,button:null,tip:null,bgiframe:null};s.cache={mouse:{},position:{},toggle:0};s.timers={};f.extend(s,s.options.api,{show:function(y){var x,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"show")}if(s.elements.tooltip.css("display")!=="none"){return s}s.elements.tooltip.stop(true,false);x=s.beforeShow.call(s,y);if(x===false){return s}function w(){if(s.options.position.type!=="static"){s.focus()}s.onShow.call(s,y);if(f.browser.msie){s.elements.tooltip.get(0).style.removeAttribute("filter")}}s.cache.toggle=1;if(s.options.position.type!=="static"){s.updatePosition(y,(s.options.show.effect.length>0))}if(typeof s.options.show.solo=="object"){z=f(s.options.show.solo)}else{if(s.options.show.solo===true){z=f("div.qtip").not(s.elements.tooltip)}}if(z){z.each(function(){if(f(this).qtip("api").status.rendered===true){f(this).qtip("api").hide()}})}if(typeof s.options.show.effect.type=="function"){s.options.show.effect.type.call(s.elements.tooltip,s.options.show.effect.length);s.elements.tooltip.queue(function(){w();f(this).dequeue()})}else{switch(s.options.show.effect.type.toLowerCase()){case"fade":s.elements.tooltip.fadeIn(s.options.show.effect.length,w);break;case"slide":s.elements.tooltip.slideDown(s.options.show.effect.length,function(){w();if(s.options.position.type!=="static"){s.updatePosition(y,true)}});break;case"grow":s.elements.tooltip.show(s.options.show.effect.length,w);break;default:s.elements.tooltip.show(null,w);break}s.elements.tooltip.addClass(s.options.style.classes.active)}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_SHOWN,"show")},hide:function(y){var x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"hide")}else{if(s.elements.tooltip.css("display")==="none"){return s}}clearTimeout(s.timers.show);s.elements.tooltip.stop(true,false);x=s.beforeHide.call(s,y);if(x===false){return s}function w(){s.onHide.call(s,y)}s.cache.toggle=0;if(typeof s.options.hide.effect.type=="function"){s.options.hide.effect.type.call(s.elements.tooltip,s.options.hide.effect.length);s.elements.tooltip.queue(function(){w();f(this).dequeue()})}else{switch(s.options.hide.effect.type.toLowerCase()){case"fade":s.elements.tooltip.fadeOut(s.options.hide.effect.length,w);break;case"slide":s.elements.tooltip.slideUp(s.options.hide.effect.length,w);break;case"grow":s.elements.tooltip.hide(s.options.hide.effect.length,w);break;default:s.elements.tooltip.hide(null,w);break}s.elements.tooltip.removeClass(s.options.style.classes.active)}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_HIDDEN,"hide")},updatePosition:function(w,x){var C,G,L,J,H,E,y,I,B,D,K,A,F,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updatePosition")}else{if(s.options.position.type=="static"){return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.CANNOT_POSITION_STATIC,"updatePosition")}}G={position:{left:0,top:0},dimensions:{height:0,width:0},corner:s.options.position.corner.target};L={position:s.getPosition(),dimensions:s.getDimensions(),corner:s.options.position.corner.tooltip};if(s.options.position.target!=="mouse"){if(s.options.position.target.get(0).nodeName.toLowerCase()=="area"){J=s.options.position.target.attr("coords").split(",");for(C=0;C<J.length;C++){J[C]=parseInt(J[C])}H=s.options.position.target.parent("map").attr("name");E=f('img[usemap="#'+H+'"]:first').offset();G.position={left:Math.floor(E.left+J[0]),top:Math.floor(E.top+J[1])};switch(s.options.position.target.attr("shape").toLowerCase()){case"rect":G.dimensions={width:Math.ceil(Math.abs(J[2]-J[0])),height:Math.ceil(Math.abs(J[3]-J[1]))};break;case"circle":G.dimensions={width:J[2]+1,height:J[2]+1};break;case"poly":G.dimensions={width:J[0],height:J[1]};for(C=0;C<J.length;C++){if(C%2==0){if(J[C]>G.dimensions.width){G.dimensions.width=J[C]}if(J[C]<J[0]){G.position.left=Math.floor(E.left+J[C])}}else{if(J[C]>G.dimensions.height){G.dimensions.height=J[C]}if(J[C]<J[1]){G.position.top=Math.floor(E.top+J[C])}}}G.dimensions.width=G.dimensions.width-(G.position.left-E.left);G.dimensions.height=G.dimensions.height-(G.position.top-E.top);break;default:return f.fn.qtip.log.error.call(s,4,f.fn.qtip.constants.INVALID_AREA_SHAPE,"updatePosition");break}G.dimensions.width-=2;G.dimensions.height-=2}else{if(s.options.position.target.add(document.body).length===1){G.position={left:f(document).scrollLeft(),top:f(document).scrollTop()};G.dimensions={height:f(window).height(),width:f(window).width()}}else{if(typeof s.options.position.target.attr("qtip")!=="undefined"){G.position=s.options.position.target.qtip("api").cache.position}else{G.position=s.options.position.target.offset()}G.dimensions={height:s.options.position.target.outerHeight(),width:s.options.position.target.outerWidth()}}}y=f.extend({},G.position);if(G.corner.search(/right/i)!==-1){y.left+=G.dimensions.width}if(G.corner.search(/bottom/i)!==-1){y.top+=G.dimensions.height}if(G.corner.search(/((top|bottom)Middle)|center/)!==-1){y.left+=(G.dimensions.width/2)}if(G.corner.search(/((left|right)Middle)|center/)!==-1){y.top+=(G.dimensions.height/2)}}else{G.position=y={left:s.cache.mouse.x,top:s.cache.mouse.y};G.dimensions={height:1,width:1}}if(L.corner.search(/right/i)!==-1){y.left-=L.dimensions.width}if(L.corner.search(/bottom/i)!==-1){y.top-=L.dimensions.height}if(L.corner.search(/((top|bottom)Middle)|center/)!==-1){y.left-=(L.dimensions.width/2)}if(L.corner.search(/((left|right)Middle)|center/)!==-1){y.top-=(L.dimensions.height/2)}I=(f.browser.msie)?1:0;B=(f.browser.msie&&parseInt(f.browser.version.charAt(0))===6)?1:0;if(s.options.style.border.radius>0){if(L.corner.search(/Left/)!==-1){y.left-=s.options.style.border.radius}else{if(L.corner.search(/Right/)!==-1){y.left+=s.options.style.border.radius}}if(L.corner.search(/Top/)!==-1){y.top-=s.options.style.border.radius}else{if(L.corner.search(/Bottom/)!==-1){y.top+=s.options.style.border.radius}}}if(I){if(L.corner.search(/top/)!==-1){y.top-=I}else{if(L.corner.search(/bottom/)!==-1){y.top+=I}}if(L.corner.search(/left/)!==-1){y.left-=I}else{if(L.corner.search(/right/)!==-1){y.left+=I}}if(L.corner.search(/leftMiddle|rightMiddle/)!==-1){y.top-=1}}if(s.options.position.adjust.screen===true){y=o.call(s,y,G,L)}if(s.options.position.target==="mouse"&&s.options.position.adjust.mouse===true){if(s.options.position.adjust.screen===true&&s.elements.tip){K=s.elements.tip.attr("rel")}else{K=s.options.position.corner.tooltip}y.left+=(K.search(/right/i)!==-1)?-6:6;y.top+=(K.search(/bottom/i)!==-1)?-6:6}if(!s.elements.bgiframe&&f.browser.msie&&parseInt(f.browser.version.charAt(0))==6){f("select, object").each(function(){A=f(this).offset();A.bottom=A.top+f(this).height();A.right=A.left+f(this).width();if(y.top+L.dimensions.height>=A.top&&y.left+L.dimensions.width>=A.left){k.call(s)}})}y.left+=s.options.position.adjust.x;y.top+=s.options.position.adjust.y;F=s.getPosition();if(y.left!=F.left||y.top!=F.top){z=s.beforePositionUpdate.call(s,w);if(z===false){return s}s.cache.position=y;if(x===true){s.status.animated=true;s.elements.tooltip.animate(y,200,"swing",function(){s.status.animated=false})}else{s.elements.tooltip.css(y)}s.onPositionUpdate.call(s,w);if(typeof w!=="undefined"&&w.type&&w.type!=="mousemove"){f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_POSITION_UPDATED,"updatePosition")}}return s},updateWidth:function(w){var x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateWidth")}else{if(w&&typeof w!=="number"){return f.fn.qtip.log.error.call(s,2,"newWidth must be of type number","updateWidth")}}x=s.elements.contentWrapper.siblings().add(s.elements.tip).add(s.elements.button);if(!w){if(typeof s.options.style.width.value=="number"){w=s.options.style.width.value}else{s.elements.tooltip.css({width:"auto"});x.hide();if(f.browser.msie){s.elements.wrapper.add(s.elements.contentWrapper.children()).css({zoom:"normal"})}w=s.getDimensions().width+1;if(!s.options.style.width.value){if(w>s.options.style.width.max){w=s.options.style.width.max}if(w<s.options.style.width.min){w=s.options.style.width.min}}}}if(w%2!==0){w-=1}s.elements.tooltip.width(w);x.show();if(s.options.style.border.radius){s.elements.tooltip.find(".qtip-betweenCorners").each(function(y){f(this).width(w-(s.options.style.border.radius*2))})}if(f.browser.msie){s.elements.wrapper.add(s.elements.contentWrapper.children()).css({zoom:"1"});s.elements.wrapper.width(w);if(s.elements.bgiframe){s.elements.bgiframe.width(w).height(s.getDimensions.height)}}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_WIDTH_UPDATED,"updateWidth")},updateStyle:function(w){var z,A,x,y,B;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateStyle")}else{if(typeof w!=="string"||!f.fn.qtip.styles[w]){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.STYLE_NOT_DEFINED,"updateStyle")}}s.options.style=a.call(s,f.fn.qtip.styles[w],s.options.user.style);s.elements.content.css(q(s.options.style));if(s.options.content.title.text!==false){s.elements.title.css(q(s.options.style.title,true))}s.elements.contentWrapper.css({borderColor:s.options.style.border.color});if(s.options.style.tip.corner!==false){if(f("<canvas>").get(0).getContext){z=s.elements.tooltip.find(".qtip-tip canvas:first");x=z.get(0).getContext("2d");x.clearRect(0,0,300,300);y=z.parent("div[rel]:first").attr("rel");B=b(y,s.options.style.tip.size.width,s.options.style.tip.size.height);h.call(s,z,B,s.options.style.tip.color||s.options.style.border.color)}else{if(f.browser.msie){z=s.elements.tooltip.find('.qtip-tip [nodeName="shape"]');z.attr("fillcolor",s.options.style.tip.color||s.options.style.border.color)}}}if(s.options.style.border.radius>0){s.elements.tooltip.find(".qtip-betweenCorners").css({backgroundColor:s.options.style.border.color});if(f("<canvas>").get(0).getContext){A=g(s.options.style.border.radius);s.elements.tooltip.find(".qtip-wrapper canvas").each(function(){x=f(this).get(0).getContext("2d");x.clearRect(0,0,300,300);y=f(this).parent("div[rel]:first").attr("rel");r.call(s,f(this),A[y],s.options.style.border.radius,s.options.style.border.color)})}else{if(f.browser.msie){s.elements.tooltip.find('.qtip-wrapper [nodeName="arc"]').each(function(){f(this).attr("fillcolor",s.options.style.border.color)})}}}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_STYLE_UPDATED,"updateStyle")},updateContent:function(A,y){var z,x,w;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateContent")}else{if(!A){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.NO_CONTENT_PROVIDED,"updateContent")}}z=s.beforeContentUpdate.call(s,A);if(typeof z=="string"){A=z}else{if(z===false){return}}if(f.browser.msie){s.elements.contentWrapper.children().css({zoom:"normal"})}if(A.jquery&&A.length>0){A.clone(true).appendTo(s.elements.content).show()}else{s.elements.content.html(A)}x=s.elements.content.find("img[complete=false]");if(x.length>0){w=0;x.each(function(C){f('<img src="'+f(this).attr("src")+'" />').load(function(){if(++w==x.length){B()}})})}else{B()}function B(){s.updateWidth();if(y!==false){if(s.options.position.type!=="static"){s.updatePosition(s.elements.tooltip.is(":visible"),true)}if(s.options.style.tip.corner!==false){n.call(s)}}}s.onContentUpdate.call(s);return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_CONTENT_UPDATED,"loadContent")},loadContent:function(w,z,A){var y;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"loadContent")}y=s.beforeContentLoad.call(s);if(y===false){return s}if(A=="post"){f.post(w,z,x)}else{f.get(w,z,x)}function x(B){s.onContentLoad.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_CONTENT_LOADED,"loadContent");s.updateContent(B)}return s},updateTitle:function(w){if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateTitle")}else{if(!w){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.NO_CONTENT_PROVIDED,"updateTitle")}}returned=s.beforeTitleUpdate.call(s);if(returned===false){return s}if(s.elements.button){s.elements.button=s.elements.button.clone(true)}s.elements.title.html(w);if(s.elements.button){s.elements.title.prepend(s.elements.button)}s.onTitleUpdate.call(s);return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_TITLE_UPDATED,"updateTitle")},focus:function(A){var y,x,w,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"focus")}else{if(s.options.position.type=="static"){return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.CANNOT_FOCUS_STATIC,"focus")}}y=parseInt(s.elements.tooltip.css("z-index"));x=6000+f("div.qtip[qtip]").length-1;if(!s.status.focused&&y!==x){z=s.beforeFocus.call(s,A);if(z===false){return s}f("div.qtip[qtip]").not(s.elements.tooltip).each(function(){if(f(this).qtip("api").status.rendered===true){w=parseInt(f(this).css("z-index"));if(typeof w=="number"&&w>-1){f(this).css({zIndex:parseInt(f(this).css("z-index"))-1})}f(this).qtip("api").status.focused=false}});s.elements.tooltip.css({zIndex:x});s.status.focused=true;s.onFocus.call(s,A);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_FOCUSED,"focus")}return s},disable:function(w){if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"disable")}if(w){if(!s.status.disabled){s.status.disabled=true;f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_DISABLED,"disable")}else{f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.TOOLTIP_ALREADY_DISABLED,"disable")}}else{if(s.status.disabled){s.status.disabled=false;f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_ENABLED,"disable")}else{f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.TOOLTIP_ALREADY_ENABLED,"disable")}}return s},destroy:function(){var w,x,y;x=s.beforeDestroy.call(s);if(x===false){return s}if(s.status.rendered){s.options.show.when.target.unbind("mousemove.qtip",s.updatePosition);s.options.show.when.target.unbind("mouseout.qtip",s.hide);s.options.show.when.target.unbind(s.options.show.when.event+".qtip");s.options.hide.when.target.unbind(s.options.hide.when.event+".qtip");s.elements.tooltip.unbind(s.options.hide.when.event+".qtip");s.elements.tooltip.unbind("mouseover.qtip",s.focus);s.elements.tooltip.remove()}else{s.options.show.when.target.unbind(s.options.show.when.event+".qtip-create")}if(typeof s.elements.target.data("qtip")=="object"){y=s.elements.target.data("qtip").interfaces;if(typeof y=="object"&&y.length>0){for(w=0;w<y.length-1;w++){if(y[w].id==s.id){y.splice(w,1)}}}}delete f.fn.qtip.interfaces[s.id];if(typeof y=="object"&&y.length>0){s.elements.target.data("qtip").current=y.length-1}else{s.elements.target.removeData("qtip")}s.onDestroy.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_DESTROYED,"destroy");return s.elements.target},getPosition:function(){var w,x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"getPosition")}w=(s.elements.tooltip.css("display")!=="none")?false:true;if(w){s.elements.tooltip.css({visiblity:"hidden"}).show()}x=s.elements.tooltip.offset();if(w){s.elements.tooltip.css({visiblity:"visible"}).hide()}return x},getDimensions:function(){var w,x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"getDimensions")}w=(!s.elements.tooltip.is(":visible"))?true:false;if(w){s.elements.tooltip.css({visiblity:"hidden"}).show()}x={height:s.elements.tooltip.outerHeight(),width:s.elements.tooltip.outerWidth()};if(w){s.elements.tooltip.css({visiblity:"visible"}).hide()}return x}})}function p(){var s,w,u,t,v,y,x;s=this;s.beforeRender.call(s);s.status.rendered=true;s.elements.tooltip='<div qtip="'+s.id+'" class="qtip '+(s.options.style.classes.tooltip||s.options.style)+'"style="display:none; -moz-border-radius:0; -webkit-border-radius:0; border-radius:0;position:'+s.options.position.type+';">  <div class="qtip-wrapper" style="position:relative; overflow:hidden; text-align:left;">    <div class="qtip-contentWrapper" style="overflow:hidden;">       <div class="qtip-content '+s.options.style.classes.content+'"></div></div></div></div>';s.elements.tooltip=f(s.elements.tooltip);s.elements.tooltip.appendTo(s.options.position.container);s.elements.tooltip.data("qtip",{current:0,interfaces:[s]});s.elements.wrapper=s.elements.tooltip.children("div:first");s.elements.contentWrapper=s.elements.wrapper.children("div:first").css({background:s.options.style.background});s.elements.content=s.elements.contentWrapper.children("div:first").css(q(s.options.style));if(f.browser.msie){s.elements.wrapper.add(s.elements.content).css({zoom:1})}if(s.options.hide.when.event=="unfocus"){s.elements.tooltip.attr("unfocus",true)}if(typeof s.options.style.width.value=="number"){s.updateWidth()}if(f("<canvas>").get(0).getContext||f.browser.msie){if(s.options.style.border.radius>0){m.call(s)}else{s.elements.contentWrapper.css({border:s.options.style.border.width+"px solid "+s.options.style.border.color})}if(s.options.style.tip.corner!==false){e.call(s)}}else{s.elements.contentWrapper.css({border:s.options.style.border.width+"px solid "+s.options.style.border.color});s.options.style.border.radius=0;s.options.style.tip.corner=false;f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.CANVAS_VML_NOT_SUPPORTED,"render")}if((typeof s.options.content.text=="string"&&s.options.content.text.length>0)||(s.options.content.text.jquery&&s.options.content.text.length>0)){u=s.options.content.text}else{if(typeof s.elements.target.attr("title")=="string"&&s.elements.target.attr("title").length>0){u=s.elements.target.attr("title").replace("\\n","<br />");s.elements.target.attr("title","")}else{if(typeof s.elements.target.attr("alt")=="string"&&s.elements.target.attr("alt").length>0){u=s.elements.target.attr("alt").replace("\\n","<br />");s.elements.target.attr("alt","")}else{u=" ";f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.NO_VALID_CONTENT,"render")}}}if(s.options.content.title.text!==false){j.call(s)}s.updateContent(u);l.call(s);if(s.options.show.ready===true){s.show()}if(s.options.content.url!==false){t=s.options.content.url;v=s.options.content.data;y=s.options.content.method||"get";s.loadContent(t,v,y)}s.onRender.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_RENDERED,"render")}function m(){var F,z,t,B,x,E,u,G,D,y,w,C,A,s,v;F=this;F.elements.wrapper.find(".qtip-borderBottom, .qtip-borderTop").remove();t=F.options.style.border.width;B=F.options.style.border.radius;x=F.options.style.border.color||F.options.style.tip.color;E=g(B);u={};for(z in E){u[z]='<div rel="'+z+'" style="'+((z.search(/Left/)!==-1)?"left":"right")+":0; position:absolute; height:"+B+"px; width:"+B+'px; overflow:hidden; line-height:0.1px; font-size:1px">';if(f("<canvas>").get(0).getContext){u[z]+='<canvas height="'+B+'" width="'+B+'" style="vertical-align: top"></canvas>'}else{if(f.browser.msie){G=B*2+3;u[z]+='<v:arc stroked="false" fillcolor="'+x+'" startangle="'+E[z][0]+'" endangle="'+E[z][1]+'" style="width:'+G+"px; height:"+G+"px; margin-top:"+((z.search(/bottom/)!==-1)?-2:-1)+"px; margin-left:"+((z.search(/Right/)!==-1)?E[z][2]-3.5:-1)+'px; vertical-align:top; display:inline-block; behavior:url(#default#VML)"></v:arc>'}}u[z]+="</div>"}D=F.getDimensions().width-(Math.max(t,B)*2);y='<div class="qtip-betweenCorners" style="height:'+B+"px; width:"+D+"px; overflow:hidden; background-color:"+x+'; line-height:0.1px; font-size:1px;">';w='<div class="qtip-borderTop" dir="ltr" style="height:'+B+"px; margin-left:"+B+'px; line-height:0.1px; font-size:1px; padding:0;">'+u.topLeft+u.topRight+y;F.elements.wrapper.prepend(w);C='<div class="qtip-borderBottom" dir="ltr" style="height:'+B+"px; margin-left:"+B+'px; line-height:0.1px; font-size:1px; padding:0;">'+u.bottomLeft+u.bottomRight+y;F.elements.wrapper.append(C);if(f("<canvas>").get(0).getContext){F.elements.wrapper.find("canvas").each(function(){A=E[f(this).parent("[rel]:first").attr("rel")];r.call(F,f(this),A,B,x)})}else{if(f.browser.msie){F.elements.tooltip.append('<v:image style="behavior:url(#default#VML);"></v:image>')}}s=Math.max(B,(B+(t-B)));v=Math.max(t-B,0);F.elements.contentWrapper.css({border:"0px solid "+x,borderWidth:v+"px "+s+"px"})}function r(u,w,s,t){var v=u.get(0).getContext("2d");v.fillStyle=t;v.beginPath();v.arc(w[0],w[1],s,0,Math.PI*2,false);v.fill()}function e(v){var t,s,x,u,w;t=this;if(t.elements.tip!==null){t.elements.tip.remove()}s=t.options.style.tip.color||t.options.style.border.color;if(t.options.style.tip.corner===false){return}else{if(!v){v=t.options.style.tip.corner}}x=b(v,t.options.style.tip.size.width,t.options.style.tip.size.height);t.elements.tip='<div class="'+t.options.style.classes.tip+'" dir="ltr" rel="'+v+'" style="position:absolute; height:'+t.options.style.tip.size.height+"px; width:"+t.options.style.tip.size.width+'px; margin:0 auto; line-height:0.1px; font-size:1px;">';if(f("<canvas>").get(0).getContext){t.elements.tip+='<canvas height="'+t.options.style.tip.size.height+'" width="'+t.options.style.tip.size.width+'"></canvas>'}else{if(f.browser.msie){u=t.options.style.tip.size.width+","+t.options.style.tip.size.height;w="m"+x[0][0]+","+x[0][1];w+=" l"+x[1][0]+","+x[1][1];w+=" "+x[2][0]+","+x[2][1];w+=" xe";t.elements.tip+='<v:shape fillcolor="'+s+'" stroked="false" filled="true" path="'+w+'" coordsize="'+u+'" style="width:'+t.options.style.tip.size.width+"px; height:"+t.options.style.tip.size.height+"px; line-height:0.1px; display:inline-block; behavior:url(#default#VML); vertical-align:"+((v.search(/top/)!==-1)?"bottom":"top")+'"></v:shape>';t.elements.tip+='<v:image style="behavior:url(#default#VML);"></v:image>';t.elements.contentWrapper.css("position","relative")}}t.elements.tooltip.prepend(t.elements.tip+"</div>");t.elements.tip=t.elements.tooltip.find("."+t.options.style.classes.tip).eq(0);if(f("<canvas>").get(0).getContext){h.call(t,t.elements.tip.find("canvas:first"),x,s)}if(v.search(/top/)!==-1&&f.browser.msie&&parseInt(f.browser.version.charAt(0))===6){t.elements.tip.css({marginTop:-4})}n.call(t,v)}function h(t,v,s){var u=t.get(0).getContext("2d");u.fillStyle=s;u.beginPath();u.moveTo(v[0][0],v[0][1]);u.lineTo(v[1][0],v[1][1]);u.lineTo(v[2][0],v[2][1]);u.fill()}function n(u){var t,w,s,x,v;t=this;if(t.options.style.tip.corner===false||!t.elements.tip){return}if(!u){u=t.elements.tip.attr("rel")}w=positionAdjust=(f.browser.msie)?1:0;t.elements.tip.css(u.match(/left|right|top|bottom/)[0],0);if(u.search(/top|bottom/)!==-1){if(f.browser.msie){if(parseInt(f.browser.version.charAt(0))===6){positionAdjust=(u.search(/top/)!==-1)?-3:1}else{positionAdjust=(u.search(/top/)!==-1)?1:2}}if(u.search(/Middle/)!==-1){t.elements.tip.css({left:"50%",marginLeft:-(t.options.style.tip.size.width/2)})}else{if(u.search(/Left/)!==-1){t.elements.tip.css({left:t.options.style.border.radius-w})}else{if(u.search(/Right/)!==-1){t.elements.tip.css({right:t.options.style.border.radius+w})}}}if(u.search(/top/)!==-1){t.elements.tip.css({top:-positionAdjust})}else{t.elements.tip.css({bottom:positionAdjust})}}else{if(u.search(/left|right/)!==-1){if(f.browser.msie){positionAdjust=(parseInt(f.browser.version.charAt(0))===6)?1:((u.search(/left/)!==-1)?1:2)}if(u.search(/Middle/)!==-1){t.elements.tip.css({top:"50%",marginTop:-(t.options.style.tip.size.height/2)})}else{if(u.search(/Top/)!==-1){t.elements.tip.css({top:t.options.style.border.radius-w})}else{if(u.search(/Bottom/)!==-1){t.elements.tip.css({bottom:t.options.style.border.radius+w})}}}if(u.search(/left/)!==-1){t.elements.tip.css({left:-positionAdjust})}else{t.elements.tip.css({right:positionAdjust})}}}s="padding-"+u.match(/left|right|top|bottom/)[0];x=t.options.style.tip.size[(s.search(/left|right/)!==-1)?"width":"height"];t.elements.tooltip.css("padding",0);t.elements.tooltip.css(s,x);if(f.browser.msie&&parseInt(f.browser.version.charAt(0))==6){v=parseInt(t.elements.tip.css("margin-top"))||0;v+=parseInt(t.elements.content.css("margin-top"))||0;t.elements.tip.css({marginTop:v})}}function j(){var s=this;if(s.elements.title!==null){s.elements.title.remove()}s.elements.title=f('<div class="'+s.options.style.classes.title+'">').css(q(s.options.style.title,true)).css({zoom:(f.browser.msie)?1:0}).prependTo(s.elements.contentWrapper);if(s.options.content.title.text){s.updateTitle.call(s,s.options.content.title.text)}if(s.options.content.title.button!==false&&typeof s.options.content.title.button=="string"){s.elements.button=f('<a class="'+s.options.style.classes.button+'" style="float:right; position: relative"></a>').css(q(s.options.style.button,true)).html(s.options.content.title.button).prependTo(s.elements.title).click(function(t){if(!s.status.disabled){s.hide(t)}})}}function l(){var t,v,u,s;t=this;v=t.options.show.when.target;u=t.options.hide.when.target;if(t.options.hide.fixed){u=u.add(t.elements.tooltip)}if(t.options.hide.when.event=="inactive"){s=["click","dblclick","mousedown","mouseup","mousemove","mouseout","mouseenter","mouseleave","mouseover"];function y(z){if(t.status.disabled===true){return}clearTimeout(t.timers.inactive);t.timers.inactive=setTimeout(function(){f(s).each(function(){u.unbind(this+".qtip-inactive");t.elements.content.unbind(this+".qtip-inactive")});t.hide(z)},t.options.hide.delay)}}else{if(t.options.hide.fixed===true){t.elements.tooltip.bind("mouseover.qtip",function(){if(t.status.disabled===true){return}clearTimeout(t.timers.hide)})}}function x(z){if(t.status.disabled===true){return}if(t.options.hide.when.event=="inactive"){f(s).each(function(){u.bind(this+".qtip-inactive",y);t.elements.content.bind(this+".qtip-inactive",y)});y()}clearTimeout(t.timers.show);clearTimeout(t.timers.hide);t.timers.show=setTimeout(function(){t.show(z)},t.options.show.delay)}function w(z){if(t.status.disabled===true){return}if(t.options.hide.fixed===true&&t.options.hide.when.event.search(/mouse(out|leave)/i)!==-1&&f(z.relatedTarget).parents("div.qtip[qtip]").length>0){z.stopPropagation();z.preventDefault();clearTimeout(t.timers.hide);return false}clearTimeout(t.timers.show);clearTimeout(t.timers.hide);t.elements.tooltip.stop(true,true);t.timers.hide=setTimeout(function(){t.hide(z)},t.options.hide.delay)}if((t.options.show.when.target.add(t.options.hide.when.target).length===1&&t.options.show.when.event==t.options.hide.when.event&&t.options.hide.when.event!=="inactive")||t.options.hide.when.event=="unfocus"){t.cache.toggle=0;v.bind(t.options.show.when.event+".qtip",function(z){if(t.cache.toggle==0){x(z)}else{w(z)}})}else{v.bind(t.options.show.when.event+".qtip",x);if(t.options.hide.when.event!=="inactive"){u.bind(t.options.hide.when.event+".qtip",w)}}if(t.options.position.type.search(/(fixed|absolute)/)!==-1){t.elements.tooltip.bind("mouseover.qtip",t.focus)}if(t.options.position.target==="mouse"&&t.options.position.type!=="static"){v.bind("mousemove.qtip",function(z){t.cache.mouse={x:z.pageX,y:z.pageY};if(t.status.disabled===false&&t.options.position.adjust.mouse===true&&t.options.position.type!=="static"&&t.elements.tooltip.css("display")!=="none"){t.updatePosition(z)}})}}function o(u,v,A){var z,s,x,y,t,w;z=this;if(A.corner=="center"){return v.position}s=f.extend({},u);y={x:false,y:false};t={left:(s.left<f.fn.qtip.cache.screen.scroll.left),right:(s.left+A.dimensions.width+2>=f.fn.qtip.cache.screen.width+f.fn.qtip.cache.screen.scroll.left),top:(s.top<f.fn.qtip.cache.screen.scroll.top),bottom:(s.top+A.dimensions.height+2>=f.fn.qtip.cache.screen.height+f.fn.qtip.cache.screen.scroll.top)};x={left:(t.left&&(A.corner.search(/right/i)!=-1||(A.corner.search(/right/i)==-1&&!t.right))),right:(t.right&&(A.corner.search(/left/i)!=-1||(A.corner.search(/left/i)==-1&&!t.left))),top:(t.top&&A.corner.search(/top/i)==-1),bottom:(t.bottom&&A.corner.search(/bottom/i)==-1)};if(x.left){if(z.options.position.target!=="mouse"){s.left=v.position.left+v.dimensions.width}else{s.left=z.cache.mouse.x}y.x="Left"}else{if(x.right){if(z.options.position.target!=="mouse"){s.left=v.position.left-A.dimensions.width}else{s.left=z.cache.mouse.x-A.dimensions.width}y.x="Right"}}if(x.top){if(z.options.position.target!=="mouse"){s.top=v.position.top+v.dimensions.height}else{s.top=z.cache.mouse.y}y.y="top"}else{if(x.bottom){if(z.options.position.target!=="mouse"){s.top=v.position.top-A.dimensions.height}else{s.top=z.cache.mouse.y-A.dimensions.height}y.y="bottom"}}if(s.left<0){s.left=u.left;y.x=false}if(s.top<0){s.top=u.top;y.y=false}if(z.options.style.tip.corner!==false){s.corner=new String(A.corner);if(y.x!==false){s.corner=s.corner.replace(/Left|Right|Middle/,y.x)}if(y.y!==false){s.corner=s.corner.replace(/top|bottom/,y.y)}if(s.corner!==z.elements.tip.attr("rel")){e.call(z,s.corner)}}return s}function q(u,t){var v,s;v=f.extend(true,{},u);for(s in v){if(t===true&&s.search(/(tip|classes)/i)!==-1){delete v[s]}else{if(!t&&s.search(/(width|border|tip|title|classes|user)/i)!==-1){delete v[s]}}}return v}function c(s){if(typeof s.tip!=="object"){s.tip={corner:s.tip}}if(typeof s.tip.size!=="object"){s.tip.size={width:s.tip.size,height:s.tip.size}}if(typeof s.border!=="object"){s.border={width:s.border}}if(typeof s.width!=="object"){s.width={value:s.width}}if(typeof s.width.max=="string"){s.width.max=parseInt(s.width.max.replace(/([0-9]+)/i,"$1"))}if(typeof s.width.min=="string"){s.width.min=parseInt(s.width.min.replace(/([0-9]+)/i,"$1"))}if(typeof s.tip.size.x=="number"){s.tip.size.width=s.tip.size.x;delete s.tip.size.x}if(typeof s.tip.size.y=="number"){s.tip.size.height=s.tip.size.y;delete s.tip.size.y}return s}function a(){var s,t,u,x,v,w;s=this;u=[true,{}];for(t=0;t<arguments.length;t++){u.push(arguments[t])}x=[f.extend.apply(f,u)];while(typeof x[0].name=="string"){x.unshift(c(f.fn.qtip.styles[x[0].name]))}x.unshift(true,{classes:{tooltip:"qtip-"+(arguments[0].name||"defaults")}},f.fn.qtip.styles.defaults);v=f.extend.apply(f,x);w=(f.browser.msie)?1:0;v.tip.size.width+=w;v.tip.size.height+=w;if(v.tip.size.width%2>0){v.tip.size.width+=1}if(v.tip.size.height%2>0){v.tip.size.height+=1}if(v.tip.corner===true){v.tip.corner=(s.options.position.corner.tooltip==="center")?false:s.options.position.corner.tooltip}return v}function b(v,u,t){var s={bottomRight:[[0,0],[u,t],[u,0]],bottomLeft:[[0,0],[u,0],[0,t]],topRight:[[0,t],[u,0],[u,t]],topLeft:[[0,0],[0,t],[u,t]],topMiddle:[[0,t],[u/2,0],[u,t]],bottomMiddle:[[0,0],[u,0],[u/2,t]],rightMiddle:[[0,0],[u,t/2],[0,t]],leftMiddle:[[u,0],[u,t],[0,t/2]]};s.leftTop=s.bottomRight;s.rightTop=s.bottomLeft;s.leftBottom=s.topRight;s.rightBottom=s.topLeft;return s[v]}function g(s){var t;if(f("<canvas>").get(0).getContext){t={topLeft:[s,s],topRight:[0,s],bottomLeft:[s,0],bottomRight:[0,0]}}else{if(f.browser.msie){t={topLeft:[-90,90,0],topRight:[-90,90,-s],bottomLeft:[90,270,0],bottomRight:[90,270,-s]}}}return t}function k(){var s,t,u;s=this;u=s.getDimensions();t='<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:false" style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=\'0\'); border: 1px solid red; height:'+u.height+"px; width:"+u.width+'px" />';s.elements.bgiframe=s.elements.wrapper.prepend(t).children(".qtip-bgiframe:first")}f(document).ready(function(){f.fn.qtip.cache={screen:{scroll:{left:f(window).scrollLeft(),top:f(window).scrollTop()},width:f(window).width(),height:f(window).height()}};var s;f(window).bind("resize scroll",function(t){clearTimeout(s);s=setTimeout(function(){if(t.type==="scroll"){f.fn.qtip.cache.screen.scroll={left:f(window).scrollLeft(),top:f(window).scrollTop()}}else{f.fn.qtip.cache.screen.width=f(window).width();f.fn.qtip.cache.screen.height=f(window).height()}for(i=0;i<f.fn.qtip.interfaces.length;i++){var u=f.fn.qtip.interfaces[i];if(u.status.rendered===true&&(u.options.position.type!=="static"||u.options.position.adjust.scroll&&t.type==="scroll"||u.options.position.adjust.resize&&t.type==="resize")){u.updatePosition(t,true)}}},100)});f(document).bind("mousedown.qtip",function(t){if(f(t.target).parents("div.qtip").length===0){f(".qtip[unfocus]").each(function(){var u=f(this).qtip("api");if(f(this).is(":visible")&&!u.status.disabled&&f(t.target).add(u.elements.target).length>1){u.hide(t)}})}})});f.fn.qtip.interfaces=[];f.fn.qtip.log={error:function(){return this}};f.fn.qtip.constants={};f.fn.qtip.defaults={content:{prerender:false,text:false,url:false,data:null,title:{text:false,button:false}},position:{target:false,corner:{target:"bottomRight",tooltip:"topLeft"},adjust:{x:0,y:0,mouse:true,screen:false,scroll:true,resize:true},type:"absolute",container:false},show:{when:{target:false,event:"mouseover"},effect:{type:"fade",length:100},delay:140,solo:false,ready:false},hide:{when:{target:false,event:"mouseout"},effect:{type:"fade",length:100},delay:0,fixed:false},api:{beforeRender:function(){},onRender:function(){},beforePositionUpdate:function(){},onPositionUpdate:function(){},beforeShow:function(){},onShow:function(){},beforeHide:function(){},onHide:function(){},beforeContentUpdate:function(){},onContentUpdate:function(){},beforeContentLoad:function(){},onContentLoad:function(){},beforeTitleUpdate:function(){},onTitleUpdate:function(){},beforeDestroy:function(){},onDestroy:function(){},beforeFocus:function(){},onFocus:function(){}}};f.fn.qtip.styles={defaults:{background:"white",color:"#111",overflow:"hidden",textAlign:"left",width:{min:0,max:250},padding:"5px 9px",border:{width:1,radius:0,color:"#d3d3d3"},tip:{corner:false,color:false,size:{width:13,height:13},opacity:1},title:{background:"#e1e1e1",fontWeight:"bold",padding:"7px 12px"},button:{cursor:"pointer"},classes:{target:"",tip:"qtip-tip",title:"qtip-title",button:"qtip-button",content:"qtip-content",active:"qtip-active"}},cream:{border:{width:3,radius:0,color:"#F9E98E"},title:{background:"#F0DE7D",color:"#A27D35"},background:"#FBF7AA",color:"#A27D35",classes:{tooltip:"qtip-cream"}},light:{border:{width:3,radius:0,color:"#E2E2E2"},title:{background:"#f1f1f1",color:"#454545"},background:"white",color:"#454545",classes:{tooltip:"qtip-light"}},dark:{border:{width:3,radius:0,color:"#303030"},title:{background:"#404040",color:"#f3f3f3"},background:"#505050",color:"#f3f3f3",classes:{tooltip:"qtip-dark"}},red:{border:{width:3,radius:0,color:"#CE6F6F"},title:{background:"#f28279",color:"#9C2F2F"},background:"#F79992",color:"#9C2F2F",classes:{tooltip:"qtip-red"}},green:{border:{width:3,radius:0,color:"#A9DB66"},title:{background:"#b9db8c",color:"#58792E"},background:"#CDE6AC",color:"#58792E",classes:{tooltip:"qtip-green"}},blue:{border:{width:3,radius:0,color:"#ADD9ED"},title:{background:"#D0E9F5",color:"#5E99BD"},background:"#E5F6FE",color:"#4D9FBF",classes:{tooltip:"qtip-blue"}}}})(jQuery);



//<!--
(function(jQuery) {
	jQuery.fn.pesquisador = function(options) {
	  var defaults = {
		imagemAguarde:'/ecp/midia/ajax-loader.gif',
		localAguarde:'.aguarde',
	    seletorAbas: '.abas',
	    seletorLista: '.lista',
	    seletorPaginacao: '.paginacao',
	    seletorFiltro: '.filtro',
	    mensagemNaoEncontrado:"Nenhum objeto encontrado.",
	    quantidadeResultados: 20,
	    formatadorResultado: function(item){
		    return "<span style='border:thin solid black'>"+item+"</span>";},
	    formatadorPagina:function(item){
			return jQuery(item).click(function(){alert("clicou em "+item);});},
		funcaoAoClicar:function(){},
	    camposPesquisa:{idEmp:0}
	  };
	  var opts = jQuery.extend(defaults, options);
	  opts.camposPesquisa.quantidadeRegistros=opts.quantidadeResultados;
	  var caixa;
	  if (!opts.urlRest){
		  alert("N�o tem a propriedade urlRest nas op��es");
		  return;
	  }
	  return this.each(function() {
	    var $this = jQuery(this);
	    caixa = $this;
	    pesquisar(1);
	    caixa.find("#"+opts.botaoDeAcao).click(function(){pesquisar(1)});
	  });
	  function criarAbas(){
		  caixa.find(opts.seletorAbas).children().each(function(i,obj){
			  	jQuery(obj).click(function(){
				  		pesquisa(1,jQuery(this).text().trim());
				  	});
			  });
	  }
	  function adicionarLista(data){
		caixa.find(opts.seletorLista).html("");
		if (data==undefined){
			caixa.find(opts.seletorLista).append(opts.mensagemNaoEncontrado);
		}else{
			var $results = jQuery.makeArray(jQuery(data));
			jQuery.each($results,function(i,obj){
				caixa.find(opts.seletorLista).append(
						jQuery(opts.formatadorResultado(obj)).data("dados",jQuery(obj)).click(opts.funcaoAoClicar));
			});
		}
	  }
	  function criarPaginas(total,paginaSelecionada){
		  caixa.find(opts.seletorPaginacao).html("");
		  for(var i = 1 ; i <= Math.ceil(total/opts.quantidadeResultados) && total > 0 && total > opts.quantidadeResultados ; i++){
			var $pag = jQuery(opts.formatadorPagina(i));
			if (i==paginaSelecionada)
				$pag.addClass("active");
			  caixa.find(opts.seletorPaginacao).append(
					$pag.click(function(){
				  			pesquisar(jQuery(this).text().trim());
					}));
		  }
	  }
	  function pesquisar(pagina,aba){
		if (pagina)
			opts.camposPesquisa.paramPagina=pagina;
		if (aba)
			opts.camposPesquisa.paramAba=aba;
		recuperarFiltros();
		aguardar(true)
		jQuery.getJSON(opts.urlRest,opts.camposPesquisa,function(data){
	    		if(eval("data."+opts.caminhoTotal)){
	    			criarPaginas(eval("data."+opts.caminhoTotal),pagina);
		    	}else{
				criarPaginas(0);
			}
		    	adicionarLista(eval("data."+opts.caminhoDados));
		    	aguardar(false);
		});
		criarAbas();
	  }
	  function aguardar(ligar){
		  if (ligar){
			  caixa.find(opts.localAguarde).html("<img src=\""+opts.imagemAguarde+"\" border=0/>")
		  }else{
			  caixa.find(opts.localAguarde).html("")
		  }
	  }
	  function recuperarFiltros(){
		jQuery(opts.filtros).each(function(){
			opts.camposPesquisa[this]=jQuery(caixa.find("#"+this)).val();
		});
	  }
}})(jQuery);
//-->



//jFontSizer - written by Jack Franklin (www.jackfranklin.co.uk) (jack [at] jackfranklin.co.uk) March 1st 2009. 
//VERSION 1.1 Released 3rd March 2009, with help from Larry Battle at blarry [at] bateru.com
//Released under the MIT License which you can find out more about here: http://en.wikipedia.org/wiki/MIT_License
//In short it means you may use, change, edit or distribute the code as you please but please leave these comments as they are. 

(function($) {
    $.fn.jFontSizer = function( userOptions ){
        options = $.extend({
			size: 10,
			sizemethod: "val", // /*can be: "+val", "pc",, "-pc", "val", "-val"*/
			type: "px" //can be "px", "em" (ONLY VALID FOR THE VAL METHOD)
		}, userOptions );
        return this.each(function(){
            var cursize = $(this).css($.browser.msie?"fontSize":"font-size");
            var change = options.size;
            var newSize = parseInt(cursize, 10);
            switch (options.sizemethod){
	            case "+val":
	                newSize += change;
	                break;
	            case "-val":
	                newSize -= change;
	                break;
	            case "pc":
	                change = 1 + (change / 100);
	                newSize *= change;
	                break;
	            case "-pc":
	                change = 1 - (change / 100);
	                newSize *= change;
	                break;
	            default:
	            	newSize = change;
            }
            $(this).css($.browser.msie?"fontSize":"font-size", newSize<0?0:newSize + options.type);
        });
    };
})(jQuery);



/**
* Styleswitch stylesheet switcher built on jQuery
* Under an Attribution, Share Alike License
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/

(function($)
{
	$(document).ready(function() {
		$('.styleswitch').click(function()
		{
			switchStylestyle(this.getAttribute("rel"));
			return false;
		});
		var c = readCookie('style');
		if (c) switchStylestyle(c);
	});

	function switchStylestyle(styleName)
	{
		$('link[@rel*=style][title]').each(function(i) 
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;
		});
		createCookie('style', styleName, 365);
	}
})(jQuery);
// cookie functions http://www.quirksmode.org/js/cookies.html
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);
}
// /cookie functions



/*
 * jQuery Media Plugin for converting elements into rich media content.
 *
 * Examples and documentation at: http://malsup.com/jquery/media/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @author: M. Alsup
 * @version: 0.92 (24-SEP-2009)
 * @requires jQuery v1.1.2 or later
 * $Id: jquery.media.js 2460 2007-07-23 02:53:15Z malsup $
 *
 * Supported Media Players:
 *	- Flash
 *	- Quicktime
 *	- Real Player
 *	- Silverlight
 *	- Windows Media Player
 *	- iframe
 *
 * Supported Media Formats:
 *	 Any types supported by the above players, such as:
 *	 Video: asf, avi, flv, mov, mpg, mpeg, mp4, qt, smil, swf, wmv, 3g2, 3gp
 *	 Audio: aif, aac, au, gsm, mid, midi, mov, mp3, m4a, snd, rm, wav, wma
 *	 Other: bmp, html, pdf, psd, qif, qtif, qti, tif, tiff, xaml
 *
 * Thanks to Mark Hicken and Brent Pedersen for helping me debug this on the Mac!
 * Thanks to Dan Rossi for numerous bug reports and code bits!
 * Thanks to Skye Giordano for several great suggestions!
 * Thanks to Richard Connamacher for excellent improvements to the non-IE behavior!
 */
;(function($) {

/**
 * Chainable method for converting elements into rich media.
 *
 * @param options
 * @param callback fn invoked for each matched element before conversion
 * @param callback fn invoked for each matched element after conversion
 */
$.fn.media = function(options, f1, f2) {
	if (options == 'undo') {
		return this.each(function() {
			var $this = $(this);
			var html = $this.data('media.origHTML');
			if (html)
				$this.replaceWith(html);
		});
	}
	
	return this.each(function() {
		if (typeof options == 'function') {
			f2 = f1;
			f1 = options;
			options = {};
		}
		var o = getSettings(this, options);
		// pre-conversion callback, passes original element and fully populated options
		if (typeof f1 == 'function') f1(this, o);

		var r = getTypesRegExp();
		var m = r.exec(o.src.toLowerCase()) || [''];

		o.type ? m[0] = o.type : m.shift();
		for (var i=0; i < m.length; i++) {
			fn = m[i].toLowerCase();
			if (isDigit(fn[0])) fn = 'fn' + fn; // fns can't begin with numbers
			if (!$.fn.media[fn])
				continue;  // unrecognized media type
			// normalize autoplay settings
			var player = $.fn.media[fn+'_player'];
			if (!o.params) o.params = {};
			if (player) {
				var num = player.autoplayAttr == 'autostart';
				o.params[player.autoplayAttr || 'autoplay'] = num ? (o.autoplay ? 1 : 0) : o.autoplay ? true : false;
			}
			var $div = $.fn.media[fn](this, o);

			$div.css('backgroundColor', o.bgColor).width(o.width);
			
			if (o.canUndo) {
				var $temp = $('<div></div>').append(this);
				$div.data('media.origHTML', $temp.html()); // store original markup
			}
			
			// post-conversion callback, passes original element, new div element and fully populated options
			if (typeof f2 == 'function') f2(this, $div[0], o, player.name);
			break;
		}
	});
};

/**
 * Non-chainable method for adding or changing file format / player mapping
 * @name mapFormat
 * @param String format File format extension (ie: mov, wav, mp3)
 * @param String player Player name to use for the format (one of: flash, quicktime, realplayer, winmedia, silverlight or iframe
 */
$.fn.media.mapFormat = function(format, player) {
	if (!format || !player || !$.fn.media.defaults.players[player]) return; // invalid
	format = format.toLowerCase();
	if (isDigit(format[0])) format = 'fn' + format;
	$.fn.media[format] = $.fn.media[player];
	$.fn.media[format+'_player'] = $.fn.media.defaults.players[player];
};

// global defautls; override as needed
$.fn.media.defaults = {
	standards:  false,      // use object tags only (no embeds for non-IE browsers)
	canUndo:    true,       // tells plugin to store the original markup so it can be reverted via: $(sel).mediaUndo()
	width:		400,
	height:		400,
	autoplay:	0,		   	// normalized cross-player setting
	bgColor:	'#ffffff', 	// background color
	params:		{ wmode: 'transparent'},	// added to object element as param elements; added to embed element as attrs
	attrs:		{},			// added to object and embed elements as attrs
	flvKeyName: 'file', 	// key used for object src param (thanks to Andrea Ercolino)
	flashvars:	{},			// added to flash content as flashvars param/attr
	flashVersion:	'7',	// required flash version
	expressInstaller: null,	// src for express installer

	// default flash video and mp3 player (@see: http://jeroenwijering.com/?item=Flash_Media_Player)
	flvPlayer:	 'mediaplayer.swf',
	mp3Player:	 'mediaplayer.swf',

	// @see http://msdn2.microsoft.com/en-us/library/bb412401.aspx
	silverlight: {
		inplaceInstallPrompt: 'true', // display in-place install prompt?
		isWindowless:		  'true', // windowless mode (false for wrapping markup)
		framerate:			  '24',	  // maximum framerate
		version:			  '0.9',  // Silverlight version
		onError:			  null,	  // onError callback
		onLoad:			      null,   // onLoad callback
		initParams:			  null,	  // object init params
		userContext:		  null	  // callback arg passed to the load callback
	}
};

// Media Players; think twice before overriding
$.fn.media.defaults.players = {
	flash: {
		name:		 'flash',
		title:		 'Flash',
		types:		 'flv,mp3,swf',
		mimetype:	 'application/x-shockwave-flash',
		pluginspage: 'http://www.adobe.com/go/getflashplayer',
		ieAttrs: {
			classid:  'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
			type:	  'application/x-oleobject',
			codebase: 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + $.fn.media.defaults.flashVersion
		}
	},
	quicktime: {
		name:		 'quicktime',
		title:		 'QuickTime',
		mimetype:	 'video/quicktime',
		pluginspage: 'http://www.apple.com/quicktime/download/',
		types:		 'aif,aiff,aac,au,bmp,gsm,mov,mid,midi,mpg,mpeg,mp4,m4a,psd,qt,qtif,qif,qti,snd,tif,tiff,wav,3g2,3gp',
		ieAttrs: {
			classid:  'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
			codebase: 'http://www.apple.com/qtactivex/qtplugin.cab'
		}
	},
	realplayer: {
		name:		  'real',
		title:		  'RealPlayer',
		types:		  'ra,ram,rm,rpm,rv,smi,smil',
		mimetype:	  'audio/x-pn-realaudio-plugin',
		pluginspage:  'http://www.real.com/player/',
		autoplayAttr: 'autostart',
		ieAttrs: {
			classid: 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'
		}
	},
	winmedia: {
		name:		  'winmedia',
		title:		  'Windows Media',
		types:		  'asx,asf,avi,wma,wmv',
		mimetype:	  $.browser.mozilla && isFirefoxWMPPluginInstalled() ? 'application/x-ms-wmp' : 'application/x-mplayer2',
		pluginspage:  'http://www.microsoft.com/Windows/MediaPlayer/',
		autoplayAttr: 'autostart',
		oUrl:		  'url',
		ieAttrs: {
			classid:  'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6',
			type:	  'application/x-oleobject'
		}
	},
	// special cases
	iframe: {
		name:  'iframe',
		types: 'html,pdf'
	},
	silverlight: {
		name:  'silverlight',
		types: 'xaml'
	}
};

//
//	everything below here is private
//


// detection script for FF WMP plugin (http://www.therossman.org/experiments/wmp_play.html)
// (hat tip to Mark Ross for this script)
function isFirefoxWMPPluginInstalled() {
	var plugs = navigator.plugins;
	for (i = 0; i < plugs.length; i++) {
		var plugin = plugs[i];
		if (plugin['filename'] == 'np-mswmp.dll')
			return true;
	}
	return false;
}

var counter = 1;

for (var player in $.fn.media.defaults.players) {
	var types = $.fn.media.defaults.players[player].types;
	$.each(types.split(','), function(i,o) {
		if (isDigit(o[0])) o = 'fn' + o;
		$.fn.media[o] = $.fn.media[player] = getGenerator(player);
		$.fn.media[o+'_player'] = $.fn.media.defaults.players[player];
	});
};

function getTypesRegExp() {
	var types = '';
	for (var player in $.fn.media.defaults.players) {
		if (types.length) types += ',';
		types += $.fn.media.defaults.players[player].types;
	};
	return new RegExp('\\.(' + types.replace(/,/ig,'|') + ')\\b');
};

function getGenerator(player) {
	return function(el, options) {
		return generate(el, options, player);
	};
};

function isDigit(c) {
	return '0123456789'.indexOf(c) > -1;
};

// flatten all possible options: global defaults, meta, option obj
function getSettings(el, options) {
	options = options || {};
	var $el = $(el);
	var cls = el.className || '';
	// support metadata plugin (v1.0 and v2.0)
	var meta = $.metadata ? $el.metadata() : $.meta ? $el.data() : {};
	meta = meta || {};
	var w = meta.width	 || parseInt(((cls.match(/w:(\d+)/)||[])[1]||0));
	var h = meta.height || parseInt(((cls.match(/h:(\d+)/)||[])[1]||0));

	if (w) meta.width	= w;
	if (h) meta.height = h;
	if (cls) meta.cls = cls;

	var a = $.fn.media.defaults;
	var b = options;
	var c = meta;

	var p = { params: { bgColor: options.bgColor || $.fn.media.defaults.bgColor } };
	var opts = $.extend({}, a, b, c);
	$.each(['attrs','params','flashvars','silverlight'], function(i,o) {
		opts[o] = $.extend({}, p[o] || {}, a[o] || {}, b[o] || {}, c[o] || {});
	});

	if (typeof opts.caption == 'undefined') opts.caption = $el.text();

	// make sure we have a source!
	opts.src = opts.src || $el.attr('href') || $el.attr('src') || 'unknown';
	return opts;
};

//
//	Flash Player
//

// generate flash using SWFObject library if possible
$.fn.media.swf = function(el, opts) {
	if (!window.SWFObject && !window.swfobject) {
		// roll our own
		if (opts.flashvars) {
			var a = [];
			for (var f in opts.flashvars)
				a.push(f + '=' + opts.flashvars[f]);
			if (!opts.params) opts.params = {};
			opts.params.flashvars = a.join('&');
		}
		return generate(el, opts, 'flash');
	}

	var id = el.id ? (' id="'+el.id+'"') : '';
	var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
	var $div = $('<div' + id + cls + '>');

	// swfobject v2+
	if (window.swfobject) {
		$(el).after($div).appendTo($div);
		if (!el.id) el.id = 'movie_player_' + counter++;

		// replace el with swfobject content
		swfobject.embedSWF(opts.src, el.id, opts.width, opts.height, opts.flashVersion,
			opts.expressInstaller, opts.flashvars, opts.params, opts.attrs);
	}
	// swfobject < v2
	else {
		$(el).after($div).remove();
		var so = new SWFObject(opts.src, 'movie_player_' + counter++, opts.width, opts.height, opts.flashVersion, opts.bgColor);
		if (opts.expressInstaller) so.useExpressInstall(opts.expressInstaller);

		for (var p in opts.params)
			if (p != 'bgColor') so.addParam(p, opts.params[p]);
		for (var f in opts.flashvars)
			so.addVariable(f, opts.flashvars[f]);
		so.write($div[0]);
	}

	if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
	return $div;
};

// map flv and mp3 files to the swf player by default
$.fn.media.flv = $.fn.media.mp3 = function(el, opts) {
	var src = opts.src;
	var player = /\.mp3\b/i.test(src) ? $.fn.media.defaults.mp3Player : $.fn.media.defaults.flvPlayer;
	var key = opts.flvKeyName;
	src = encodeURIComponent(src);
	opts.src = player;
	opts.src = opts.src + '?'+key+'=' + (src);
	var srcObj = {};
	srcObj[key] = src;
	opts.flashvars = $.extend({}, srcObj, opts.flashvars );
	return $.fn.media.swf(el, opts);
};

//
//	Silverlight
//
$.fn.media.xaml = function(el, opts) {
	if (!window.Sys || !window.Sys.Silverlight) {
		if ($.fn.media.xaml.warning) return;
		$.fn.media.xaml.warning = 1;
		alert('You must include the Silverlight.js script.');
		return;
	}

	var props = {
		width: opts.width,
		height: opts.height,
		background: opts.bgColor,
		inplaceInstallPrompt: opts.silverlight.inplaceInstallPrompt,
		isWindowless: opts.silverlight.isWindowless,
		framerate: opts.silverlight.framerate,
		version: opts.silverlight.version
	};
	var events = {
		onError: opts.silverlight.onError,
		onLoad: opts.silverlight.onLoad
	};

	var id1 = el.id ? (' id="'+el.id+'"') : '';
	var id2 = opts.id || 'AG' + counter++;
	// convert element to div
	var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
	var $div = $('<div' + id1 + cls + '>');
	$(el).after($div).remove();

	Sys.Silverlight.createObjectEx({
		source: opts.src,
		initParams: opts.silverlight.initParams,
		userContext: opts.silverlight.userContext,
		id: id2,
		parentElement: $div[0],
		properties: props,
		events: events
	});

	if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
	return $div;
};

//
// generate object/embed markup
//
function generate(el, opts, player) {
	var $el = $(el);
	var o = $.fn.media.defaults.players[player];

	if (player == 'iframe') {
		var o = $('<iframe' + ' width="' + opts.width + '" height="' + opts.height + '" >');
		o.attr('src', opts.src);
		o.css('backgroundColor', o.bgColor);
	}
	else if ($.browser.msie) {
		var a = ['<object width="' + opts.width + '" height="' + opts.height + '" '];
		for (var key in opts.attrs)
			a.push(key + '="'+opts.attrs[key]+'" ');
		for (var key in o.ieAttrs || {}) {
			var v = o.ieAttrs[key];
			if (key == 'codebase' && window.location.protocol == 'https:')
				v = v.replace('http','https');
			a.push(key + '="'+v+'" ');
		}
		a.push('></ob'+'ject'+'>');
		var p = ['<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">'];
		for (var key in opts.params)
			p.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
		var o = document.createElement(a.join(''));
		for (var i=0; i < p.length; i++)
			o.appendChild(document.createElement(p[i]));
	}
	else if (o.standards) {
		// Rewritten to be standards compliant by Richard Connamacher
		var a = ['<object type="' + o.mimetype +'" width="' + opts.width + '" height="' + opts.height +'"'];
		if (opts.src) a.push(' data="' + opts.src + '" ');
		a.push('>');
		a.push('<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">');
		for (var key in opts.params) {
			if (key == 'wmode' && player != 'flash') // FF3/Quicktime borks on wmode
				continue;
			a.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
		}
		// Alternate HTML
		a.push('<div><p><strong>'+o.title+' Required</strong></p><p>'+o.title+' is required to view this media. <a href="'+o.pluginspage+'">Download Here</a>.</p></div>');
		a.push('</ob'+'ject'+'>');
	}
	 else {
	        var a = ['<embed width="' + opts.width + '" height="' + opts.height + '" style="display:block"'];
	        if (opts.src) a.push(' src="' + opts.src + '" ');
	        for (var key in opts.attrs)
	            a.push(key + '="'+opts.attrs[key]+'" ');
	        for (var key in o.eAttrs || {})
	            a.push(key + '="'+o.eAttrs[key]+'" ');
	        for (var key in opts.params) {
	            if (key == 'wmode' && player != 'flash') // FF3/Quicktime borks on wmode
	            	continue;
	            a.push(key + '="'+opts.params[key]+'" ');
	        }
	        a.push('></em'+'bed'+'>');
	    }	
	// convert element to div
	var id = el.id ? (' id="'+el.id+'"') : '';
	var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
	var $div = $('<div' + id + cls + '>');
	$el.after($div).remove();
	($.browser.msie || player == 'iframe') ? $div.append(o) : $div.html(a.join(''));
	if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
	return $div;
};


})(jQuery);




/**
 * SWFObject v1.5: Flash Player detection and embed -
 * http://blog.deconcept.com/swfobject/
 * 
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
if (typeof deconcept == "undefined") {
	var deconcept = new Object();
}
if (typeof deconcept.util == "undefined") {
	deconcept.util = new Object();
}
if (typeof deconcept.SWFObjectUtil == "undefined") {
	deconcept.SWFObjectUtil = new Object();
}
deconcept.SWFObject = function(_1, id, w, h, _5, c, _7, _8, _9, _a) {
	if (!document.getElementById) {
		return;
	}
	this.DETECT_KEY = _a ? _a : "detectflash";
	this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();
	if (_1) {
		this.setAttribute("swf", _1);
	}
	if (id) {
		this.setAttribute("id", id);
	}
	if (w) {
		this.setAttribute("width", w);
	}
	if (h) {
		this.setAttribute("height", h);
	}
	if (_5) {
		this.setAttribute("version", new deconcept.PlayerVersion(_5.toString()
				.split(".")));
	}
	this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
	if (!window.opera && document.all && this.installedVer.major > 7) {
		deconcept.SWFObject.doPrepUnload = true;
	}
	if (c) {
		this.addParam("bgcolor", c);
	}
	var q = _7 ? _7 : "high";
	this.addParam("quality", q);
	this.setAttribute("useExpressInstall", false);
	this.setAttribute("doExpressInstall", false);
	var _c = (_8) ? _8 : window.location;
	this.setAttribute("xiRedirectUrl", _c);
	this.setAttribute("redirectUrl", "");
	if (_9) {
		this.setAttribute("redirectUrl", _9);
	}
};
deconcept.SWFObject.prototype = {
	useExpressInstall : function(_d) {
		this.xiSWFPath = !_d ? "expressinstall.swf" : _d;
		this.setAttribute("useExpressInstall", true);
	},
	setAttribute : function(_e, _f) {
		this.attributes[_e] = _f;
	},
	getAttribute : function(_10) {
		return this.attributes[_10];
	},
	addParam : function(_11, _12) {
		this.params[_11] = _12;
	},
	getParams : function() {
		return this.params;
	},
	addVariable : function(_13, _14) {
		this.variables[_13] = _14;
	},
	getVariable : function(_15) {
		return this.variables[_15];
	},
	getVariables : function() {
		return this.variables;
	},
	getVariablePairs : function() {
		var _16 = new Array();
		var key;
		var _18 = this.getVariables();
		for (key in _18) {
			_16[_16.length] = key + "=" + _18[key];
		}
		return _16;
	},
	getSWFHTML : function() {
		var _19 = "";
		if (navigator.plugins && navigator.mimeTypes
				&& navigator.mimeTypes.length) {
			if (this.getAttribute("doExpressInstall")) {
				this.addVariable("MMplayerType", "PlugIn");
				this.setAttribute("swf", this.xiSWFPath);
			}
			_19 = "<embed type=\"application/x-shockwave-flash\" src=\""
					+ this.getAttribute("swf") + "\" width=\""
					+ this.getAttribute("width") + "\" height=\""
					+ this.getAttribute("height") + "\" style=\""
					+ this.getAttribute("style") + "\"";
			_19 += " id=\"" + this.getAttribute("id") + "\" name=\""
					+ this.getAttribute("id") + "\" ";
			var _1a = this.getParams();
			for ( var key in _1a) {
				_19 += [ key ] + "=\"" + _1a[key] + "\" ";
			}
			var _1c = this.getVariablePairs().join("&");
			if (_1c.length > 0) {
				_19 += "flashvars=\"" + _1c + "\"";
			}
			_19 += "/>";
		} else {
			if (this.getAttribute("doExpressInstall")) {
				this.addVariable("MMplayerType", "ActiveX");
				this.setAttribute("swf", this.xiSWFPath);
			}
			_19 = "<object id=\""
					+ this.getAttribute("id")
					+ "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""
					+ this.getAttribute("width") + "\" height=\""
					+ this.getAttribute("height") + "\" style=\""
					+ this.getAttribute("style") + "\">";
			_19 += "<param name=\"movie\" value=\"" + this.getAttribute("swf")
					+ "\" />";
			var _1d = this.getParams();
			for ( var key in _1d) {
				_19 += "<param name=\"" + key + "\" value=\"" + _1d[key]
						+ "\" />";
			}
			var _1f = this.getVariablePairs().join("&");
			if (_1f.length > 0) {
				_19 += "<param name=\"flashvars\" value=\"" + _1f + "\" />";
			}
			_19 += "</object>";
		}
		return _19;
	},
	write : function(_20) {
		if (this.getAttribute("useExpressInstall")) {
			var _21 = new deconcept.PlayerVersion( [ 6, 0, 65 ]);
			if (this.installedVer.versionIsValid(_21)
					&& !this.installedVer.versionIsValid(this
							.getAttribute("version"))) {
				this.setAttribute("doExpressInstall", true);
				this.addVariable("MMredirectURL", escape(this
						.getAttribute("xiRedirectUrl")));
				document.title = document.title.slice(0, 47)
						+ " - Flash Player Installation";
				this.addVariable("MMdoctitle", document.title);
			}
		}
		if (this.skipDetect
				|| this.getAttribute("doExpressInstall")
				|| this.installedVer.versionIsValid(this
						.getAttribute("version"))) {
			var n = (typeof _20 == "string") ? document.getElementById(_20)
					: _20;
			n.innerHTML = this.getSWFHTML();
			return true;
		} else {
			if (this.getVariable("noFlashMessage")){
				var n = (typeof _20 == "string") ? document.getElementById(_20)
						: _20;
				n.innerHTML = "<div class=\"noFlashMessage\">"+this.getVariable("noFlashMessage")+"</div>";
				return true;
			} else
			if (this.getAttribute("redirectUrl") != "") {
				document.location.replace(this.getAttribute("redirectUrl"));
			}
		}
		return false;
	}
};
deconcept.SWFObjectUtil.getPlayerVersion = function() {
	var _23 = new deconcept.PlayerVersion( [ 0, 0, 0 ]);
	if (navigator.plugins && navigator.mimeTypes.length) {
		var x = navigator.plugins["Shockwave Flash"];
		if (x && x.description) {
			_23 = new deconcept.PlayerVersion(x.description.replace(
					/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".")
					.split("."));
		}
	} else {
		if (navigator.userAgent
				&& navigator.userAgent.indexOf("Windows CE") >= 0) {
			var axo = 1;
			var _26 = 3;
			while (axo) {
				try {
					_26++;
					axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."
							+ _26);
					_23 = new deconcept.PlayerVersion( [ _26, 0, 0 ]);
				} catch (e) {
					axo = null;
				}
			}
		} else {
			try {
				var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			} catch (e) {
				try {
					var axo = new ActiveXObject(
							"ShockwaveFlash.ShockwaveFlash.6");
					_23 = new deconcept.PlayerVersion( [ 6, 0, 21 ]);
					axo.AllowScriptAccess = "always";
				} catch (e) {
					if (_23.major == 6) {
						return _23;
					}
				}
				try {
					axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				} catch (e) {
				}
			}
			if (axo != null) {
				_23 = new deconcept.PlayerVersion(axo.GetVariable("$version")
						.split(" ")[1].split(","));
			}
		}
	}
	return _23;
};
deconcept.PlayerVersion = function(_29) {
	this.major = _29[0] != null ? parseInt(_29[0]) : 0;
	this.minor = _29[1] != null ? parseInt(_29[1]) : 0;
	this.rev = _29[2] != null ? parseInt(_29[2]) : 0;
};
deconcept.PlayerVersion.prototype.versionIsValid = function(fv) {
	if (this.major < fv.major) {
		return false;
	}
	if (this.major > fv.major) {
		return true;
	}
	if (this.minor < fv.minor) {
		return false;
	}
	if (this.minor > fv.minor) {
		return true;
	}
	if (this.rev < fv.rev) {
		return false;
	}
	return true;
};
deconcept.util = {
	getRequestParameter : function(_2b) {
		var q = document.location.search || document.location.hash;
		if (_2b == null) {
			return q;
		}
		if (q) {
			var _2d = q.substring(1).split("&");
			for ( var i = 0; i < _2d.length; i++) {
				if (_2d[i].substring(0, _2d[i].indexOf("=")) == _2b) {
					return _2d[i].substring((_2d[i].indexOf("=") + 1));
				}
			}
		}
		return "";
	}
};
deconcept.SWFObjectUtil.cleanupSWFs = function() {
	var _2f = document.getElementsByTagName("OBJECT");
	for ( var i = _2f.length - 1; i >= 0; i--) {
		_2f[i].style.display = "none";
		for ( var x in _2f[i]) {
			if (typeof _2f[i][x] == "function") {
				_2f[i][x] = function() {
				};
			}
		}
	}
};
if (deconcept.SWFObject.doPrepUnload) {
	if (!deconcept.unloadSet) {
		deconcept.SWFObjectUtil.prepUnload = function() {
			__flash_unloadHandler = function() {
			};
			__flash_savedUnloadHandler = function() {
			};
			window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
		};
		window
				.attachEvent("onbeforeunload",
						deconcept.SWFObjectUtil.prepUnload);
		deconcept.unloadSet = true;
	}
}
if (!document.getElementById && document.all) {
	document.getElementById = function(id) {
		return document.all[id];
	};
}
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject;
var SWFObject = deconcept.SWFObject;



/*
 * 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($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),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");this.tooltipText=this.title;$(this).removeAttr("title");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){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;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/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}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();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){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];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");}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()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);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);



/*
 * jquery.tools 1.1.2 - The missing UI library for the Web
 * 
 * [tools.tabs-1.0.4, tools.tooltip-1.1.2, tools.tooltip.slide-1.0.0, tools.tooltip.dynamic-1.0.1]
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 * 
 * -----
 * 
 * File generated: Thu Oct 08 19:47:18 GMT+00:00 2009
 */
(function(d){d.tools=d.tools||{};d.tools.tabs={version:"1.0.4",conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",api:false,rotate:false},addEffect:function(e,f){c[e]=f}};var c={"default":function(f,e){this.getPanes().hide().eq(f).show();e.call()},fade:function(g,e){var f=this.getConf(),j=f.fadeOutSpeed,h=this.getPanes();if(j){h.fadeOut(j)}else{h.hide()}h.eq(g).fadeIn(f.fadeInSpeed,e)},slide:function(f,e){this.getPanes().slideUp(200);this.getPanes().eq(f).slideDown(400,e)},ajax:function(f,e){this.getPanes().eq(0).load(this.getTabs().eq(f).attr("href"),e)}};var b;d.tools.tabs.addEffect("horizontal",function(f,e){if(!b){b=this.getPanes().eq(0).width()}this.getCurrentPane().animate({width:0},function(){d(this).hide()});this.getPanes().eq(f).animate({width:b},function(){d(this).show();e.call()})});function a(g,h,f){var e=this,j=d(this),i;d.each(f,function(k,l){if(d.isFunction(l)){j.bind(k,l)}});d.extend(this,{click:function(k,n){var o=e.getCurrentPane();var l=g.eq(k);if(typeof k=="string"&&k.replace("#","")){l=g.filter("[href*="+k.replace("#","")+"]");k=Math.max(g.index(l),0)}if(f.rotate){var m=g.length-1;if(k<0){return e.click(m,n)}if(k>m){return e.click(0,n)}}if(!l.length){if(i>=0){return e}k=f.initialIndex;l=g.eq(k)}if(k===i){return e}n=n||d.Event();n.type="onBeforeClick";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}c[f.effect].call(e,k,function(){n.type="onClick";j.trigger(n,[k])});n.type="onStart";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}i=k;g.removeClass(f.current);l.addClass(f.current);return e},getConf:function(){return f},getTabs:function(){return g},getPanes:function(){return h},getCurrentPane:function(){return h.eq(i)},getCurrentTab:function(){return g.eq(i)},getIndex:function(){return i},next:function(){return e.click(i+1)},prev:function(){return e.click(i-1)},bind:function(k,l){j.bind(k,l);return e},onBeforeClick:function(k){return this.bind("onBeforeClick",k)},onClick:function(k){return this.bind("onClick",k)},unbind:function(k){j.unbind(k);return e}});g.each(function(k){d(this).bind(f.event,function(l){e.click(k,l);return false})});if(location.hash){e.click(location.hash)}else{if(f.initialIndex===0||f.initialIndex>0){e.click(f.initialIndex)}}h.find("a[href^=#]").click(function(k){e.click(d(this).attr("href"),k)})}d.fn.tabs=function(i,f){var g=this.eq(typeof f=="number"?f:0).data("tabs");if(g){return g}if(d.isFunction(f)){f={onBeforeClick:f}}var h=d.extend({},d.tools.tabs.conf),e=this.length;f=d.extend(h,f);this.each(function(l){var j=d(this);var k=j.find(f.tabs);if(!k.length){k=j.children()}var m=i.jquery?i:j.children(i);if(!m.length){m=e==1?d(i):j.parent().find(i)}g=new a(k,m,f);j.data("tabs",g)});return f.api?g:this}})(jQuery);
//(function(c){var d=[];c.tools=c.tools||{};c.tools.tooltip={version:"1.1.2",conf:{effect:"toggle",fadeOutSpeed:"fast",tip:null,predelay:0,delay:30,opacity:1,lazy:undefined,position:["top","center"],offset:[0,0],cancelDefault:true,relative:false,oneInstance:true,events:{def:"mouseover,mouseout",input:"focus,blur",widget:"focus mouseover,blur mouseout",tooltip:"mouseover,mouseout"},api:false},addEffect:function(e,g,f){b[e]=[g,f]}};var b={toggle:[function(e){var f=this.getConf(),g=this.getTip(),h=f.opacity;if(h<1){g.css({opacity:h})}g.show();e.call()},function(e){this.getTip().hide();e.call()}],fade:[function(e){this.getTip().fadeIn(this.getConf().fadeInSpeed,e)},function(e){this.getTip().fadeOut(this.getConf().fadeOutSpeed,e)}]};function a(f,g){var p=this,k=c(this);f.data("tooltip",p);var l=f.next();if(g.tip){l=c(g.tip);if(l.length>1){l=f.nextAll(g.tip).eq(0);if(!l.length){l=f.parent().nextAll(g.tip).eq(0)}}}function o(u){var t=g.relative?f.position().top:f.offset().top,s=g.relative?f.position().left:f.offset().left,v=g.position[0];t-=l.outerHeight()-g.offset[0];s+=f.outerWidth()+g.offset[1];var q=l.outerHeight()+f.outerHeight();if(v=="center"){t+=q/2}if(v=="bottom"){t+=q}v=g.position[1];var r=l.outerWidth()+f.outerWidth();if(v=="center"){s-=r/2}if(v=="left"){s-=r}return{top:t,left:s}}var i=f.is(":input"),e=i&&f.is(":checkbox, :radio, select, :button"),h=f.attr("type"),n=g.events[h]||g.events[i?(e?"widget":"input"):"def"];n=n.split(/,\s*/);if(n.length!=2){throw"Tooltip: bad events configuration for "+h}f.bind(n[0],function(r){if(g.oneInstance){c.each(d,function(){this.hide()})}var q=l.data("trigger");if(q&&q[0]!=this){l.hide().stop(true,true)}r.target=this;p.show(r);n=g.events.tooltip.split(/,\s*/);l.bind(n[0],function(){p.show(r)});if(n[1]){l.bind(n[1],function(){p.hide(r)})}});f.bind(n[1],function(q){p.hide(q)});if(!c.browser.msie&&!i&&!g.predelay){f.mousemove(function(){if(!p.isShown()){f.triggerHandler("mouseover")}})}if(g.opacity<1){l.css("opacity",g.opacity)}var m=0,j=f.attr("title");if(j&&g.cancelDefault){f.removeAttr("title");f.data("title",j)}c.extend(p,{show:function(r){if(r){f=c(r.target)}clearTimeout(l.data("timer"));if(l.is(":animated")||l.is(":visible")){return p}function q(){l.data("trigger",f);var t=o(r);if(g.tip&&j){l.html(f.data("title"))}r=r||c.Event();r.type="onBeforeShow";k.trigger(r,[t]);if(r.isDefaultPrevented()){return p}t=o(r);l.css({position:"absolute",top:t.top,left:t.left});var s=b[g.effect];if(!s){throw'Nonexistent effect "'+g.effect+'"'}s[0].call(p,function(){r.type="onShow";k.trigger(r)})}if(g.predelay){clearTimeout(m);m=setTimeout(q,g.predelay)}else{q()}return p},hide:function(r){clearTimeout(l.data("timer"));clearTimeout(m);if(!l.is(":visible")){return}function q(){r=r||c.Event();r.type="onBeforeHide";k.trigger(r);if(r.isDefaultPrevented()){return}b[g.effect][1].call(p,function(){r.type="onHide";k.trigger(r)})}if(g.delay&&r){l.data("timer",setTimeout(q,g.delay))}else{q()}return p},isShown:function(){return l.is(":visible, :animated")},getConf:function(){return g},getTip:function(){return l},getTrigger:function(){return f},bind:function(q,r){k.bind(q,r);return p},onHide:function(q){return this.bind("onHide",q)},onBeforeShow:function(q){return this.bind("onBeforeShow",q)},onShow:function(q){return this.bind("onShow",q)},onBeforeHide:function(q){return this.bind("onBeforeHide",q)},unbind:function(q){k.unbind(q);return p}});c.each(g,function(q,r){if(c.isFunction(r)){p.bind(q,r)}})}c.prototype.tooltip=function(e){var f=this.eq(typeof e=="number"?e:0).data("tooltip");if(f){return f}var g=c.extend(true,{},c.tools.tooltip.conf);if(c.isFunction(e)){e={onBeforeShow:e}}else{if(typeof e=="string"){e={tip:e}}}e=c.extend(true,g,e);if(typeof e.position=="string"){e.position=e.position.split(/,?\s/)}if(e.lazy!==false&&(e.lazy===true||this.length>20)){this.one("mouseover",function(h){f=new a(c(this),e);f.show(h);d.push(f)})}else{this.each(function(){f=new a(c(this),e);d.push(f)})}return e.api?f:this}})(jQuery);
//(function(b){var a=b.tools.tooltip;a.effects=a.effects||{};a.effects.slide={version:"1.0.0"};b.extend(a.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!b.browser.msie});var c={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};b.tools.tooltip.addEffect("slide",function(d){var f=this.getConf(),g=this.getTip(),h=f.slideFade?{opacity:f.opacity}:{},e=c[f.direction]||c.up;h[e[1]]=e[0]+"="+f.slideOffset;if(f.slideFade){g.css({opacity:0})}g.show().animate(h,f.slideInSpeed,d)},function(e){var g=this.getConf(),i=g.slideOffset,h=g.slideFade?{opacity:0}:{},f=c[g.direction]||c.up;var d=""+f[0];if(g.bounce){d=d=="+"?"-":"+"}h[f[1]]=d+"="+i;this.getTip().animate(h,g.slideOutSpeed,function(){b(this).hide();e.call()})})})(jQuery);
//(function(d){var c=d.tools.tooltip;c.plugins=c.plugins||{};c.plugins.dynamic={version:"1.0.1",conf:{api:false,classNames:"top right bottom left"}};function b(h){var e=d(window);var g=e.width()+e.scrollLeft();var f=e.height()+e.scrollTop();return[h.offset().top<=e.scrollTop(),g<=h.offset().left+h.width(),f<=h.offset().top+h.height(),e.scrollLeft()>=h.offset().left]}function a(f){var e=f.length;while(e--){if(f[e]){return false}}return true}d.fn.dynamic=function(g){var h=d.extend({},c.plugins.dynamic.conf),f;if(typeof g=="number"){g={speed:g}}g=d.extend(h,g);var e=g.classNames.split(/\s/),i;this.each(function(){if(d(this).tooltip().jquery){throw"Lazy feature not supported by dynamic plugin. set lazy: false for tooltip"}var j=d(this).tooltip().onBeforeShow(function(n,o){var m=this.getTip(),l=this.getConf();if(!i){i=[l.position[0],l.position[1],l.offset[0],l.offset[1],d.extend({},l)]}d.extend(l,i[4]);l.position=[i[0],i[1]];l.offset=[i[2],i[3]];m.css({visibility:"hidden",position:"absolute",top:o.top,left:o.left}).show();var k=b(m);if(!a(k)){if(k[2]){d.extend(l,g.top);l.position[0]="top";m.addClass(e[0])}if(k[3]){d.extend(l,g.right);l.position[1]="right";m.addClass(e[1])}if(k[0]){d.extend(l,g.bottom);l.position[0]="bottom";m.addClass(e[2])}if(k[1]){d.extend(l,g.left);l.position[1]="left";m.addClass(e[3])}if(k[0]||k[2]){l.offset[0]*=-1}if(k[1]||k[3]){l.offset[1]*=-1}}m.css({visibility:"visible"}).hide()});j.onShow(function(){var l=this.getConf(),k=this.getTip();l.position=[i[0],i[1]];l.offset=[i[2],i[3]]});j.onHide(function(){var k=this.getTip();k.removeClass(g.classNames)});f=j});return g.api?f:this}})(jQuery);




/*
 * Copyright (c) 2009 Simo Kinnunen.
 * Licensed under the MIT license.
 *
 * @version 1.09
 */
var Cufon=(function(){var m=function(){return m.replace.apply(null,arguments)};var x=m.DOM={ready:(function(){var C=false,E={loaded:1,complete:1};var B=[],D=function(){if(C){return}C=true;for(var F;F=B.shift();F()){}};if(document.addEventListener){document.addEventListener("DOMContentLoaded",D,false);window.addEventListener("pageshow",D,false)}if(!window.opera&&document.readyState){(function(){E[document.readyState]?D():setTimeout(arguments.callee,10)})()}if(document.readyState&&document.createStyleSheet){(function(){try{document.body.doScroll("left");D()}catch(F){setTimeout(arguments.callee,1)}})()}q(window,"load",D);return function(F){if(!arguments.length){D()}else{C?F():B.push(F)}}})(),root:function(){return document.documentElement||document.body}};var n=m.CSS={Size:function(C,B){this.value=parseFloat(C);this.unit=String(C).match(/[a-z%]*$/)[0]||"px";this.convert=function(D){return D/B*this.value};this.convertFrom=function(D){return D/this.value*B};this.toString=function(){return this.value+this.unit}},addClass:function(C,B){var D=C.className;C.className=D+(D&&" ")+B;return C},color:j(function(C){var B={};B.color=C.replace(/^rgba\((.*?),\s*([\d.]+)\)/,function(E,D,F){B.opacity=parseFloat(F);return"rgb("+D+")"});return B}),fontStretch:j(function(B){if(typeof B=="number"){return B}if(/%$/.test(B)){return parseFloat(B)/100}return{"ultra-condensed":0.5,"extra-condensed":0.625,condensed:0.75,"semi-condensed":0.875,"semi-expanded":1.125,expanded:1.25,"extra-expanded":1.5,"ultra-expanded":2}[B]||1}),getStyle:function(C){var B=document.defaultView;if(B&&B.getComputedStyle){return new a(B.getComputedStyle(C,null))}if(C.currentStyle){return new a(C.currentStyle)}return new a(C.style)},gradient:j(function(F){var G={id:F,type:F.match(/^-([a-z]+)-gradient\(/)[1],stops:[]},C=F.substr(F.indexOf("(")).match(/([\d.]+=)?(#[a-f0-9]+|[a-z]+\(.*?\)|[a-z]+)/ig);for(var E=0,B=C.length,D;E<B;++E){D=C[E].split("=",2).reverse();G.stops.push([D[1]||E/(B-1),D[0]])}return G}),quotedList:j(function(E){var D=[],C=/\s*((["'])([\s\S]*?[^\\])\2|[^,]+)\s*/g,B;while(B=C.exec(E)){D.push(B[3]||B[1])}return D}),recognizesMedia:j(function(G){var E=document.createElement("style"),D,C,B;E.type="text/css";E.media=G;try{E.appendChild(document.createTextNode("/**/"))}catch(F){}C=g("head")[0];C.insertBefore(E,C.firstChild);D=(E.sheet||E.styleSheet);B=D&&!D.disabled;C.removeChild(E);return B}),removeClass:function(D,C){var B=RegExp("(?:^|\\s+)"+C+"(?=\\s|$)","g");D.className=D.className.replace(B,"");return D},supports:function(D,C){var B=document.createElement("span").style;if(B[D]===undefined){return false}B[D]=C;return B[D]===C},textAlign:function(E,D,B,C){if(D.get("textAlign")=="right"){if(B>0){E=" "+E}}else{if(B<C-1){E+=" "}}return E},textShadow:j(function(F){if(F=="none"){return null}var E=[],G={},B,C=0;var D=/(#[a-f0-9]+|[a-z]+\(.*?\)|[a-z]+)|(-?[\d.]+[a-z%]*)|,/ig;while(B=D.exec(F)){if(B[0]==","){E.push(G);G={};C=0}else{if(B[1]){G.color=B[1]}else{G[["offX","offY","blur"][C++]]=B[2]}}}E.push(G);return E}),textTransform:(function(){var B={uppercase:function(C){return C.toUpperCase()},lowercase:function(C){return C.toLowerCase()},capitalize:function(C){return C.replace(/\b./g,function(D){return D.toUpperCase()})}};return function(E,D){var C=B[D.get("textTransform")];return C?C(E):E}})(),whiteSpace:(function(){var D={inline:1,"inline-block":1,"run-in":1};var C=/^\s+/,B=/\s+$/;return function(H,F,G,E){if(E){if(E.nodeName.toLowerCase()=="br"){H=H.replace(C,"")}}if(D[F.get("display")]){return H}if(!G.previousSibling){H=H.replace(C,"")}if(!G.nextSibling){H=H.replace(B,"")}return H}})()};n.ready=(function(){var B=!n.recognizesMedia("all"),E=false;var D=[],H=function(){B=true;for(var K;K=D.shift();K()){}};var I=g("link"),J=g("style");function C(K){return K.disabled||G(K.sheet,K.media||"screen")}function G(M,P){if(!n.recognizesMedia(P||"all")){return true}if(!M||M.disabled){return false}try{var Q=M.cssRules,O;if(Q){search:for(var L=0,K=Q.length;O=Q[L],L<K;++L){switch(O.type){case 2:break;case 3:if(!G(O.styleSheet,O.media.mediaText)){return false}break;default:break search}}}}catch(N){}return true}function F(){if(document.createStyleSheet){return true}var L,K;for(K=0;L=I[K];++K){if(L.rel.toLowerCase()=="stylesheet"&&!C(L)){return false}}for(K=0;L=J[K];++K){if(!C(L)){return false}}return true}x.ready(function(){if(!E){E=n.getStyle(document.body).isUsable()}if(B||(E&&F())){H()}else{setTimeout(arguments.callee,10)}});return function(K){if(B){K()}else{D.push(K)}}})();function s(D){var C=this.face=D.face,B={"\u0020":1,"\u00a0":1,"\u3000":1};this.glyphs=D.glyphs;this.w=D.w;this.baseSize=parseInt(C["units-per-em"],10);this.family=C["font-family"].toLowerCase();this.weight=C["font-weight"];this.style=C["font-style"]||"normal";this.viewBox=(function(){var F=C.bbox.split(/\s+/);var E={minX:parseInt(F[0],10),minY:parseInt(F[1],10),maxX:parseInt(F[2],10),maxY:parseInt(F[3],10)};E.width=E.maxX-E.minX;E.height=E.maxY-E.minY;E.toString=function(){return[this.minX,this.minY,this.width,this.height].join(" ")};return E})();this.ascent=-parseInt(C.ascent,10);this.descent=-parseInt(C.descent,10);this.height=-this.ascent+this.descent;this.spacing=function(L,N,E){var O=this.glyphs,M,K,G,P=[],F=0,J=-1,I=-1,H;while(H=L[++J]){M=O[H]||this.missingGlyph;if(!M){continue}if(K){F-=G=K[H]||0;P[I]-=G}F+=P[++I]=~~(M.w||this.w)+N+(B[H]?E:0);K=M.k}P.total=F;return P}}function f(){var C={},B={oblique:"italic",italic:"oblique"};this.add=function(D){(C[D.style]||(C[D.style]={}))[D.weight]=D};this.get=function(H,I){var G=C[H]||C[B[H]]||C.normal||C.italic||C.oblique;if(!G){return null}I={normal:400,bold:700}[I]||parseInt(I,10);if(G[I]){return G[I]}var E={1:1,99:0}[I%100],K=[],F,D;if(E===undefined){E=I>400}if(I==500){I=400}for(var J in G){if(!k(G,J)){continue}J=parseInt(J,10);if(!F||J<F){F=J}if(!D||J>D){D=J}K.push(J)}if(I<F){I=F}if(I>D){I=D}K.sort(function(M,L){return(E?(M>=I&&L>=I)?M<L:M>L:(M<=I&&L<=I)?M>L:M<L)?-1:1});return G[K[0]]}}function r(){function D(F,G){if(F.contains){return F.contains(G)}return F.compareDocumentPosition(G)&16}function B(G){var F=G.relatedTarget;if(!F||D(this,F)){return}C(this,G.type=="mouseover")}function E(F){C(this,F.type=="mouseenter")}function C(F,G){setTimeout(function(){var H=d.get(F).options;m.replace(F,G?h(H,H.hover):H,true)},10)}this.attach=function(F){if(F.onmouseenter===undefined){q(F,"mouseover",B);q(F,"mouseout",B)}else{q(F,"mouseenter",E);q(F,"mouseleave",E)}}}function u(){var C=[],D={};function B(H){var E=[],G;for(var F=0;G=H[F];++F){E[F]=C[D[G]]}return E}this.add=function(F,E){D[F]=C.push(E)-1};this.repeat=function(){var E=arguments.length?B(arguments):C,F;for(var G=0;F=E[G++];){m.replace(F[0],F[1],true)}}}function A(){var D={},B=0;function C(E){return E.cufid||(E.cufid=++B)}this.get=function(E){var F=C(E);return D[F]||(D[F]={})}}function a(B){var D={},C={};this.extend=function(E){for(var F in E){if(k(E,F)){D[F]=E[F]}}return this};this.get=function(E){return D[E]!=undefined?D[E]:B[E]};this.getSize=function(F,E){return C[F]||(C[F]=new n.Size(this.get(F),E))};this.isUsable=function(){return !!B}}function q(C,B,D){if(C.addEventListener){C.addEventListener(B,D,false)}else{if(C.attachEvent){C.attachEvent("on"+B,function(){return D.call(C,window.event)})}}}function v(C,B){var D=d.get(C);if(D.options){return C}if(B.hover&&B.hoverables[C.nodeName.toLowerCase()]){b.attach(C)}D.options=B;return C}function j(B){var C={};return function(D){if(!k(C,D)){C[D]=B.apply(null,arguments)}return C[D]}}function c(F,E){var B=n.quotedList(E.get("fontFamily").toLowerCase()),D;for(var C=0;D=B[C];++C){if(i[D]){return i[D].get(E.get("fontStyle"),E.get("fontWeight"))}}return null}function g(B){return document.getElementsByTagName(B)}function k(C,B){return C.hasOwnProperty(B)}function h(){var C={},B,F;for(var E=0,D=arguments.length;B=arguments[E],E<D;++E){for(F in B){if(k(B,F)){C[F]=B[F]}}}return C}function o(E,M,C,N,F,D){var K=document.createDocumentFragment(),H;if(M===""){return K}var L=N.separate;var I=M.split(p[L]),B=(L=="words");if(B&&t){if(/^\s/.test(M)){I.unshift("")}if(/\s$/.test(M)){I.push("")}}for(var J=0,G=I.length;J<G;++J){H=z[N.engine](E,B?n.textAlign(I[J],C,J,G):I[J],C,N,F,D,J<G-1);if(H){K.appendChild(H)}}return K}function l(D,M){var C=D.nodeName.toLowerCase();if(M.ignore[C]){return}var E=!M.textless[C];var B=n.getStyle(v(D,M)).extend(M);var F=c(D,B),G,K,I,H,L,J;if(!F){return}for(G=D.firstChild;G;G=I){K=G.nodeType;I=G.nextSibling;if(E&&K==3){if(H){H.appendData(G.data);D.removeChild(G)}else{H=G}if(I){continue}}if(H){D.replaceChild(o(F,n.whiteSpace(H.data,B,H,J),B,M,G,D),H);H=null}if(K==1){if(G.firstChild){if(G.nodeName.toLowerCase()=="cufon"){z[M.engine](F,null,B,M,G,D)}else{arguments.callee(G,M)}}J=G}}}var t=" ".split(/\s+/).length==0;var d=new A();var b=new r();var y=new u();var e=false;var z={},i={},w={autoDetect:false,engine:null,forceHitArea:false,hover:false,hoverables:{a:true},ignore:{applet:1,canvas:1,col:1,colgroup:1,head:1,iframe:1,map:1,optgroup:1,option:1,script:1,select:1,style:1,textarea:1,title:1,pre:1},printable:true,selector:(window.Sizzle||(window.jQuery&&function(B){return jQuery(B)})||(window.dojo&&dojo.query)||(window.Ext&&Ext.query)||(window.YAHOO&&YAHOO.util&&YAHOO.util.Selector&&YAHOO.util.Selector.query)||(window.$$&&function(B){return $$(B)})||(window.$&&function(B){return $(B)})||(document.querySelectorAll&&function(B){return document.querySelectorAll(B)})||g),separate:"words",textless:{dl:1,html:1,ol:1,table:1,tbody:1,thead:1,tfoot:1,tr:1,ul:1},textShadow:"none"};var p={words:/\s/.test("\u00a0")?/[^\S\u00a0]+/:/\s+/,characters:"",none:/^/};m.now=function(){x.ready();return m};m.refresh=function(){y.repeat.apply(y,arguments);return m};m.registerEngine=function(C,B){if(!B){return m}z[C]=B;return m.set("engine",C)};m.registerFont=function(D){if(!D){return m}var B=new s(D),C=B.family;if(!i[C]){i[C]=new f()}i[C].add(B);return m.set("fontFamily",'"'+C+'"')};m.replace=function(D,C,B){C=h(w,C);if(!C.engine){return m}if(!e){n.addClass(x.root(),"cufon-active cufon-loading");n.ready(function(){n.addClass(n.removeClass(x.root(),"cufon-loading"),"cufon-ready")});e=true}if(C.hover){C.forceHitArea=true}if(C.autoDetect){delete C.fontFamily}if(typeof C.textShadow=="string"){C.textShadow=n.textShadow(C.textShadow)}if(typeof C.color=="string"&&/^-/.test(C.color)){C.textGradient=n.gradient(C.color)}else{delete C.textGradient}if(!B){y.add(D,arguments)}if(D.nodeType||typeof D=="string"){D=[D]}n.ready(function(){for(var F=0,E=D.length;F<E;++F){var G=D[F];if(typeof G=="string"){m.replace(C.selector(G),C,true)}else{l(G,C)}}});return m};m.set=function(B,C){w[B]=C;return m};return m})();Cufon.registerEngine("canvas",(function(){var b=document.createElement("canvas");if(!b||!b.getContext||!b.getContext.apply){return}b=null;var a=Cufon.CSS.supports("display","inline-block");var e=!a&&(document.compatMode=="BackCompat"||/frameset|transitional/i.test(document.doctype.publicId));var f=document.createElement("style");f.type="text/css";f.appendChild(document.createTextNode(("cufon{text-indent:0;}@media screen,projection{cufon{display:inline;display:inline-block;position:relative;vertical-align:middle;"+(e?"":"font-size:1px;line-height:1px;")+"}cufon cufontext{display:-moz-inline-box;display:inline-block;width:0;height:0;overflow:hidden;text-indent:-10000in;}"+(a?"cufon canvas{position:relative;}":"cufon canvas{position:absolute;}")+"}@media print{cufon{padding:0;}cufon canvas{display:none;}}").replace(/;/g,"!important;")));document.getElementsByTagName("head")[0].appendChild(f);function d(p,h){var n=0,m=0;var g=[],o=/([mrvxe])([^a-z]*)/g,k;generate:for(var j=0;k=o.exec(p);++j){var l=k[2].split(",");switch(k[1]){case"v":g[j]={m:"bezierCurveTo",a:[n+~~l[0],m+~~l[1],n+~~l[2],m+~~l[3],n+=~~l[4],m+=~~l[5]]};break;case"r":g[j]={m:"lineTo",a:[n+=~~l[0],m+=~~l[1]]};break;case"m":g[j]={m:"moveTo",a:[n=~~l[0],m=~~l[1]]};break;case"x":g[j]={m:"closePath"};break;case"e":break generate}h[g[j].m].apply(h,g[j].a)}return g}function c(m,k){for(var j=0,h=m.length;j<h;++j){var g=m[j];k[g.m].apply(k,g.a)}}return function(V,w,P,t,C,W){var k=(w===null);if(k){w=C.getAttribute("alt")}var A=V.viewBox;var m=P.getSize("fontSize",V.baseSize);var B=0,O=0,N=0,u=0;var z=t.textShadow,L=[];if(z){for(var U=z.length;U--;){var F=z[U];var K=m.convertFrom(parseFloat(F.offX));var I=m.convertFrom(parseFloat(F.offY));L[U]=[K,I];if(I<B){B=I}if(K>O){O=K}if(I>N){N=I}if(K<u){u=K}}}var Z=Cufon.CSS.textTransform(w,P).split("");var E=V.spacing(Z,~~m.convertFrom(parseFloat(P.get("letterSpacing"))||0),~~m.convertFrom(parseFloat(P.get("wordSpacing"))||0));if(!E.length){return null}var h=E.total;O+=A.width-E[E.length-1];u+=A.minX;var s,n;if(k){s=C;n=C.firstChild}else{s=document.createElement("cufon");s.className="cufon cufon-canvas";s.setAttribute("alt",w);n=document.createElement("canvas");s.appendChild(n);if(t.printable){var S=document.createElement("cufontext");S.appendChild(document.createTextNode(w));s.appendChild(S)}}var aa=s.style;var H=n.style;var j=m.convert(A.height);var Y=Math.ceil(j);var M=Y/j;var G=M*Cufon.CSS.fontStretch(P.get("fontStretch"));var J=h*G;var Q=Math.ceil(m.convert(J+O-u));var o=Math.ceil(m.convert(A.height-B+N));n.width=Q;n.height=o;H.width=Q+"px";H.height=o+"px";B+=A.minY;H.top=Math.round(m.convert(B-V.ascent))+"px";H.left=Math.round(m.convert(u))+"px";var r=Math.max(Math.ceil(m.convert(J)),0)+"px";if(a){aa.width=r;aa.height=m.convert(V.height)+"px"}else{aa.paddingLeft=r;aa.paddingBottom=(m.convert(V.height)-1)+"px"}var X=n.getContext("2d"),D=j/A.height;X.scale(D,D*M);X.translate(-u,-B);X.save();function T(){var x=V.glyphs,ab,l=-1,g=-1,y;X.scale(G,1);while(y=Z[++l]){var ab=x[Z[l]]||V.missingGlyph;if(!ab){continue}if(ab.d){X.beginPath();if(ab.code){c(ab.code,X)}else{ab.code=d("m"+ab.d,X)}X.fill()}X.translate(E[++g],0)}X.restore()}if(z){for(var U=z.length;U--;){var F=z[U];X.save();X.fillStyle=F.color;X.translate.apply(X,L[U]);T()}}var q=t.textGradient;if(q){var v=q.stops,p=X.createLinearGradient(0,A.minY,0,A.maxY);for(var U=0,R=v.length;U<R;++U){p.addColorStop.apply(p,v[U])}X.fillStyle=p}else{X.fillStyle=P.get("color")}T();return s}})());Cufon.registerEngine("vml",(function(){var e=document.namespaces;if(!e){return}e.add("cvml","urn:schemas-microsoft-com:vml");e=null;var b=document.createElement("cvml:shape");b.style.behavior="url(#default#VML)";if(!b.coordsize){return}b=null;var h=(document.documentMode||0)<8;document.write(('<style type="text/css">cufoncanvas{text-indent:0;}@media screen{cvml\\:shape,cvml\\:rect,cvml\\:fill,cvml\\:shadow{behavior:url(#default#VML);display:block;antialias:true;position:absolute;}cufoncanvas{position:absolute;text-align:left;}cufon{display:inline-block;position:relative;vertical-align:'+(h?"middle":"text-bottom")+";}cufon cufontext{position:absolute;left:-10000in;font-size:1px;}a cufon{cursor:pointer}}@media print{cufon cufoncanvas{display:none;}}</style>").replace(/;/g,"!important;"));function c(i,j){return a(i,/(?:em|ex|%)$|^[a-z-]+$/i.test(j)?"1em":j)}function a(l,m){if(m==="0"){return 0}if(/px$/i.test(m)){return parseFloat(m)}var k=l.style.left,j=l.runtimeStyle.left;l.runtimeStyle.left=l.currentStyle.left;l.style.left=m.replace("%","em");var i=l.style.pixelLeft;l.style.left=k;l.runtimeStyle.left=j;return i}function f(l,k,j,n){var i="computed"+n,m=k[i];if(isNaN(m)){m=k.get(n);k[i]=m=(m=="normal")?0:~~j.convertFrom(a(l,m))}return m}var g={};function d(p){var q=p.id;if(!g[q]){var n=p.stops,o=document.createElement("cvml:fill"),i=[];o.type="gradient";o.angle=180;o.focus="0";o.method="sigma";o.color=n[0][1];for(var m=1,l=n.length-1;m<l;++m){i.push(n[m][0]*100+"% "+n[m][1])}o.colors=i.join(",");o.color2=n[l][1];g[q]=o}return g[q]}return function(ac,G,Y,C,K,ad,W){var n=(G===null);if(n){G=K.alt}var I=ac.viewBox;var p=Y.computedFontSize||(Y.computedFontSize=new Cufon.CSS.Size(c(ad,Y.get("fontSize"))+"px",ac.baseSize));var y,q;if(n){y=K;q=K.firstChild}else{y=document.createElement("cufon");y.className="cufon cufon-vml";y.alt=G;q=document.createElement("cufoncanvas");y.appendChild(q);if(C.printable){var Z=document.createElement("cufontext");Z.appendChild(document.createTextNode(G));y.appendChild(Z)}if(!W){y.appendChild(document.createElement("cvml:shape"))}}var ai=y.style;var R=q.style;var l=p.convert(I.height),af=Math.ceil(l);var V=af/l;var P=V*Cufon.CSS.fontStretch(Y.get("fontStretch"));var U=I.minX,T=I.minY;R.height=af;R.top=Math.round(p.convert(T-ac.ascent));R.left=Math.round(p.convert(U));ai.height=p.convert(ac.height)+"px";var F=Y.get("color");var ag=Cufon.CSS.textTransform(G,Y).split("");var L=ac.spacing(ag,f(ad,Y,p,"letterSpacing"),f(ad,Y,p,"wordSpacing"));if(!L.length){return null}var k=L.total;var x=-U+k+(I.width-L[L.length-1]);var ah=p.convert(x*P),X=Math.round(ah);var O=x+","+I.height,m;var J="r"+O+"ns";var u=C.textGradient&&d(C.textGradient);var o=ac.glyphs,S=0;var H=C.textShadow;var ab=-1,aa=0,w;while(w=ag[++ab]){var D=o[ag[ab]]||ac.missingGlyph,v;if(!D){continue}if(n){v=q.childNodes[aa];while(v.firstChild){v.removeChild(v.firstChild)}}else{v=document.createElement("cvml:shape");q.appendChild(v)}v.stroked="f";v.coordsize=O;v.coordorigin=m=(U-S)+","+T;v.path=(D.d?"m"+D.d+"xe":"")+"m"+m+J;v.fillcolor=F;if(u){v.appendChild(u.cloneNode(false))}var ae=v.style;ae.width=X;ae.height=af;if(H){var s=H[0],r=H[1];var B=Cufon.CSS.color(s.color),z;var N=document.createElement("cvml:shadow");N.on="t";N.color=B.color;N.offset=s.offX+","+s.offY;if(r){z=Cufon.CSS.color(r.color);N.type="double";N.color2=z.color;N.offset2=r.offX+","+r.offY}N.opacity=B.opacity||(z&&z.opacity)||1;v.appendChild(N)}S+=L[aa++]}var M=v.nextSibling,t,A;if(C.forceHitArea){if(!M){M=document.createElement("cvml:rect");M.stroked="f";M.className="cufon-vml-cover";t=document.createElement("cvml:fill");t.opacity=0;M.appendChild(t);q.appendChild(M)}A=M.style;A.width=X;A.height=af}else{if(M){q.removeChild(M)}}ai.width=Math.max(Math.ceil(p.convert(k*P)),0);if(h){var Q=Y.computedYAdjust;if(Q===undefined){var E=Y.get("lineHeight");if(E=="normal"){E="1em"}else{if(!isNaN(E)){E+="em"}}Y.computedYAdjust=Q=0.5*(a(ad,E)-parseFloat(ai.height))}if(Q){ai.marginTop=Math.ceil(Q)+"px";ai.marginBottom=Q+"px"}}return y}})());



/*!
 * The following copyright notice may not be removed under any circumstances.
 * 
 * Copyright:
 * 1991 Erik Spiekermann, published by Fontshop International for the FontFont
 * library.
 */
Cufon.registerFont({"w":533,"face":{"font-family":"Meta","font-weight":700,"font-stretch":"normal","units-per-em":"1000","panose-1":"2 0 8 3 0 0 0 0 0 0","ascent":"800","descent":"-200","x-height":"11","bbox":"-190 -942 1180.04 224","underline-thickness":"20","underline-position":"-142","stemh":"98","stemv":"133","unicode-range":"U+0020-U+FB02"},"glyphs":{" ":{"w":225},"!":{"d":"226,-710r-28,489r-102,0r-30,-466xm230,-70v0,46,-38,83,-84,83v-45,0,-81,-37,-81,-83v0,-46,37,-83,83,-83v45,0,82,37,82,83","w":295},"\"":{"d":"423,-426r-126,0r0,-282r126,0r0,282xm191,-426r-126,0r0,-282r126,0r0,282","w":488},"#":{"d":"532,-417r-96,0r-17,126r84,0r0,90r-96,0r-28,201r-97,0r28,-201r-99,0r-28,201r-97,0r28,-201r-84,0r0,-90r96,0r17,-126r-84,0r0,-90r96,0r28,-201r97,0r-28,201r99,0r28,-201r97,0r-28,201r84,0r0,90xm339,-417r-99,0r-17,126r99,0","w":562},"$":{"d":"554,-219v0,128,-95,217,-243,232r0,81r-86,0r0,-81v-67,-6,-137,-28,-195,-61r52,-109v65,34,121,56,191,56v80,0,122,-33,122,-95v0,-72,-100,-94,-168,-111v-107,-28,-166,-81,-166,-194v0,-115,83,-198,209,-213r0,-72r86,0r0,73v70,7,136,31,186,67r-66,100v-63,-38,-110,-53,-162,-53v-57,0,-97,33,-97,80v0,63,105,77,161,93v114,33,176,104,176,207","w":584},"%":{"d":"638,-336v102,0,173,66,172,172v-1,109,-61,174,-172,174v-103,0,-169,-67,-169,-172v0,-104,67,-174,169,-174xm199,-705v102,0,173,66,172,172v-1,109,-61,174,-172,174v-103,0,-169,-67,-169,-172v0,-104,67,-174,169,-174xm650,-695r-364,695r-95,0r364,-695r95,0xm139,-534v0,65,7,100,61,100v42,0,60,-30,60,-101v0,-63,-11,-96,-62,-96v-49,0,-59,40,-59,97xm578,-165v0,65,7,100,61,100v42,0,60,-30,60,-101v0,-63,-11,-96,-62,-96v-49,0,-59,40,-59,97","w":840},"&":{"d":"165,-348v-59,-45,-81,-69,-81,-150v0,-99,82,-168,200,-168v163,0,258,139,169,254v-18,23,-53,43,-97,67r116,110v9,-29,9,-49,9,-105r112,0v0,78,-9,141,-32,192r149,148r-186,0r-42,-42v-45,38,-103,56,-191,56v-160,0,-251,-69,-251,-189v0,-78,41,-134,125,-173xm400,-118r-163,-157v-36,22,-54,52,-54,92v0,63,41,99,112,99v48,0,83,-11,105,-34xm347,-506v0,-39,-26,-67,-62,-67v-38,0,-64,26,-64,65v0,28,23,59,60,96v43,-22,66,-55,66,-94","w":705},"\u2019":{"d":"224,-591v0,86,-57,159,-141,180r-53,-55v59,-16,104,-58,46,-89v-71,-39,-36,-156,48,-156v58,0,100,50,100,120","w":259},"(":{"d":"330,-702v-114,73,-157,189,-154,378v2,111,12,249,55,318v27,44,50,69,101,97r-35,78v-179,-63,-257,-233,-257,-491v0,-242,89,-385,255,-459","w":312},")":{"d":"15,-782v178,63,255,230,255,489v0,245,-88,387,-256,461r-34,-79v115,-72,157,-192,155,-380v-1,-110,-11,-247,-54,-316v-28,-44,-50,-69,-101,-97","w":310},"*":{"d":"451,-518r-131,42r83,114r-83,61r-84,-115r-81,110r-81,-61r84,-109r-133,-46r32,-95r131,47r0,-138r102,0r0,138r131,-43","w":476},"+":{"d":"588,-240r-211,0r0,211r-126,0r0,-211r-211,0r0,-126r211,0r0,-211r126,0r0,211r211,0r0,126","w":628},",":{"d":"234,-36v0,87,-57,160,-141,181r-53,-56v61,-14,103,-58,46,-89v-72,-39,-35,-156,48,-156v58,0,100,50,100,120","w":284},"-":{"d":"280,-216r-240,0r0,-116r240,0r0,116","w":320},".":{"d":"226,-73v0,49,-40,89,-88,89v-49,0,-88,-40,-88,-89v0,-48,39,-87,87,-87v49,0,89,39,89,87","w":276},"\/":{"d":"396,-764r-268,918r-88,0r268,-918r88,0","w":436},"0":{"d":"515,-256v0,161,-97,268,-238,268v-146,0,-237,-105,-237,-266v0,-161,97,-268,238,-268v146,0,237,105,237,266xm368,-253v0,-141,-39,-171,-90,-171v-68,0,-91,66,-91,167v0,141,39,171,90,171v68,0,91,-66,91,-167","w":555},"1":{"d":"388,0r-317,0r0,-109r108,0r0,-259v-37,23,-76,43,-120,58r-34,-72r193,-140r90,0r0,413r80,0r0,109","w":423},"2":{"d":"506,-112r-29,112r-417,0r0,-122v35,-18,44,-18,103,-52v138,-78,173,-123,173,-169v0,-44,-33,-67,-80,-67v-43,0,-80,18,-136,64r-80,-83v72,-64,149,-99,252,-99v119,0,195,66,195,164v0,147,-155,197,-257,257v78,-9,187,-4,276,-5","w":556},"3":{"d":"482,-349v0,70,-41,128,-103,147v75,25,119,82,119,152v0,160,-210,260,-435,229r-32,-93v147,30,310,-35,310,-147v0,-88,-88,-93,-188,-87r0,-112v83,12,180,2,180,-75v0,-43,-27,-75,-85,-75v-67,0,-118,31,-148,56r-70,-85v57,-45,145,-83,236,-84v125,0,216,74,216,174","w":538},"4":{"d":"442,-203v1,27,-1,74,-3,89r74,-1r0,115r-76,-2v9,38,4,126,5,177r-127,16r2,-194v-89,7,-202,1,-297,3r0,-91r193,-427r138,0r-144,324v-6,13,-32,68,-45,81v48,-5,108,-2,158,-1v-4,-68,12,-168,17,-242r105,-24r0,177"},"5":{"d":"460,-70v0,170,-183,284,-391,247r-29,-99v130,43,280,-15,275,-132v-6,-126,-137,-122,-255,-78r32,-380r341,0r-20,114r-196,0r-14,139v144,-27,257,61,257,189","w":510},"6":{"d":"530,-214v0,129,-102,228,-234,228v-146,0,-251,-117,-251,-282v0,-257,199,-380,395,-451r29,96v-102,33,-213,91,-260,231v27,-22,64,-33,107,-33v121,0,214,92,214,211xm389,-212v0,-115,-112,-129,-195,-72v-2,12,-3,37,-3,60v0,85,37,135,99,135v60,0,99,-48,99,-123","w":575},"7":{"d":"467,-512r-22,117v-40,60,-153,233,-210,419v-5,17,-11,40,-29,139r-147,37v56,-241,142,-431,253,-595v-89,10,-196,1,-292,4r30,-121r417,0","w":487},"8":{"d":"400,-355v72,24,155,75,155,172v0,124,-117,203,-268,203v-139,0,-247,-72,-247,-192v0,-75,48,-144,118,-169v-50,-17,-99,-82,-99,-151v0,-110,97,-185,240,-185v135,0,230,72,230,174v0,68,-51,127,-129,148xm302,-79v98,0,137,-112,64,-158v-26,-17,-66,-35,-113,-51v-42,24,-64,61,-64,106v0,63,44,103,113,103xm380,-507v0,-46,-32,-72,-91,-72v-55,0,-92,30,-92,75v0,45,58,78,102,95v34,-17,81,-45,81,-98","w":595},"9":{"d":"521,-256v0,134,-53,246,-164,338v-61,51,-141,98,-212,123r-73,-82v108,-28,234,-130,264,-214v-149,66,-296,-50,-296,-204v0,-135,102,-234,242,-234v149,0,239,103,239,273xm376,-292v0,-84,-37,-134,-97,-134v-57,0,-94,50,-94,127v0,112,116,158,181,82v7,-24,10,-46,10,-75","w":561},":":{"d":"233,-68v0,47,-39,84,-87,84v-47,0,-86,-37,-86,-84v0,-49,39,-90,87,-89v48,1,86,40,86,89xm234,-368v0,48,-39,86,-87,86v-47,0,-85,-38,-85,-85v0,-48,38,-88,85,-88v48,0,87,39,87,87","w":294},";":{"d":"254,-35v0,85,-59,160,-142,180r-52,-56v56,-14,102,-58,48,-87v-76,-41,-39,-158,46,-158v58,0,100,51,100,121xm241,-369v0,47,-38,86,-85,86v-48,0,-87,-38,-87,-85v0,-48,37,-88,84,-88v48,0,88,39,88,87","w":314},"<":{"d":"366,-78r-105,90r-241,-311r241,-311r105,92r-168,219","w":406},"=":{"d":"588,-336r-548,0r0,-126r548,0r0,126xm588,-144r-548,0r0,-126r548,0r0,126","w":628},">":{"d":"386,-299r-241,311r-105,-90r168,-221r-168,-219r105,-92","w":406},"?":{"d":"419,-538v0,92,-57,127,-92,152v-72,51,-82,91,-75,165r-115,0v-24,-94,0,-160,83,-218v28,-20,66,-40,66,-81v0,-49,-38,-69,-82,-69v-56,0,-90,32,-108,46r-61,-86v25,-26,91,-76,194,-76v102,0,190,62,190,167xm291,-70v0,46,-38,83,-84,83v-45,0,-81,-37,-81,-83v0,-46,37,-83,83,-83v45,0,82,37,82,83","w":474},"@":{"d":"851,-276v0,176,-104,295,-227,295v-100,0,-111,-46,-115,-92v-35,42,-91,80,-150,80v-81,0,-131,-51,-131,-150v0,-166,103,-315,284,-315v49,0,99,18,142,41v-27,89,-44,179,-63,269v-17,77,-9,90,36,90v61,0,106,-90,106,-218v0,-158,-111,-264,-279,-264v-159,0,-295,152,-295,339v0,241,210,337,421,267r18,85v-277,92,-558,-55,-558,-352v0,-235,174,-429,414,-429v223,0,397,142,397,354xm539,-372v-136,-39,-201,112,-201,233v0,40,12,63,42,63v41,0,105,-45,122,-125","w":891},"A":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0","w":582},"B":{"d":"533,-521v0,76,-43,134,-111,152v86,25,138,84,138,175v0,96,-60,191,-182,192r-308,2r0,-695r235,0v139,-6,228,61,228,174xm301,-114v69,4,101,-38,101,-97v0,-61,-35,-91,-105,-91r-87,0r0,188r91,0xm291,-417v73,5,87,-26,96,-80v-5,-52,-29,-79,-98,-79r-81,0r0,159r83,0","w":600},"C":{"d":"355,-599v-117,0,-157,98,-157,239v0,95,8,148,29,186v48,90,169,105,253,33r64,88v-55,45,-114,65,-193,65v-193,0,-311,-149,-311,-345v0,-219,127,-376,313,-377v69,0,138,22,176,55r-63,95v-35,-26,-72,-39,-111,-39","w":564},"D":{"d":"483,-622v113,104,128,389,25,518v-67,84,-131,104,-269,104r-169,0r0,-695r140,0v128,0,202,8,273,73xm421,-332v-1,-136,-17,-250,-145,-253r-64,0r0,471r75,0v92,0,134,-71,134,-218","w":618},"E":{"d":"475,0r-405,0r0,-695r396,0r-18,114r-238,0r0,161r199,0r0,114r-197,0r0,186r263,0r0,120","w":495},"F":{"d":"447,-695r-16,113r-221,0r0,159r177,0r0,114r-177,0r0,309r-140,0r0,-695r377,0","w":437},"G":{"d":"197,-334v1,155,31,237,161,237v31,0,56,-5,79,-17r0,-158r-106,0r-18,-114r269,0r0,332v-71,42,-149,62,-231,62v-197,2,-311,-145,-311,-349v0,-210,109,-365,314,-365v84,0,160,27,221,80r-74,87v-45,-37,-92,-54,-145,-54v-135,0,-160,110,-159,259","w":642},"H":{"d":"551,0r-142,0r0,-310r-200,0r0,310r-139,0r0,-695r139,0r0,270r200,0r0,-270r142,0r0,695","w":621},"I":{"d":"216,0r-146,0r0,-695r146,0r0,695","w":286},"J":{"d":"-20,92v74,-58,95,-68,95,-212r0,-575r142,0r0,560v0,90,-3,108,-10,136v-20,85,-99,139,-162,163","w":287},"K":{"d":"608,0r-184,0r-211,-363r0,363r-143,0r0,-695r143,0r0,317r198,-317r172,0r-222,322","w":588},"L":{"d":"462,-116r-25,116r-367,0r0,-695r143,0r0,579r249,0","w":467},"M":{"d":"768,0r-137,0r-26,-371v-3,-44,-5,-79,-5,-116v-37,168,-92,325,-136,487r-119,0r-99,-365v-9,-34,-21,-83,-28,-123v0,41,-2,82,-5,125r-24,363r-139,0r65,-695r179,0r91,348v13,50,18,74,24,110v30,-156,81,-307,119,-458r178,0","w":818},"N":{"d":"553,0r-146,0r-119,-266v-39,-87,-81,-185,-94,-228v5,57,6,139,7,197r4,297r-135,0r0,-695r155,0v66,144,166,325,209,475v-15,-154,-11,-312,-14,-475r133,0r0,695","w":623},"O":{"d":"40,-345v0,-205,96,-359,301,-359v185,0,299,135,299,353v0,210,-87,356,-294,362v-208,6,-306,-160,-306,-356xm196,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251","w":680},"P":{"d":"546,-481v0,92,-47,162,-120,202v-35,19,-138,24,-216,23r0,256r-140,0r0,-695v119,1,331,-10,376,34v65,36,100,100,100,180xm283,-370v88,3,110,-32,110,-108v0,-65,-35,-104,-94,-104r-89,0r0,212r73,0","w":566},"Q":{"d":"503,-32v47,19,88,63,148,64v30,0,62,-5,62,-5r-37,91v0,0,-20,12,-62,12v-54,0,-102,-32,-128,-49v-33,-22,-87,-53,-141,-70v-206,8,-305,-161,-305,-356v0,-206,96,-359,301,-359v185,0,299,135,299,353v0,151,-54,264,-137,319xm196,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251","w":680},"R":{"d":"574,0r-165,0v-44,-71,-155,-292,-180,-284v-7,-3,-13,-5,-22,-6r0,290r-137,0r0,-695r259,0v123,0,204,82,204,204v0,104,-69,190,-155,192v60,44,184,287,196,299xm254,-395v99,2,127,-19,132,-93v7,-93,-80,-99,-179,-95r0,188r47,0","w":584},"S":{"d":"554,-219v0,141,-114,234,-287,234v-79,0,-167,-23,-237,-63r52,-109v65,34,121,56,191,56v80,0,122,-33,122,-95v0,-72,-100,-94,-168,-111v-107,-28,-166,-81,-166,-194v0,-127,102,-215,249,-215v85,0,171,26,232,70r-66,100v-63,-38,-110,-53,-162,-53v-57,0,-97,33,-97,80v0,63,105,77,161,93v114,33,176,104,176,207","w":584},"T":{"d":"511,-695r-23,116r-166,0r0,579r-142,0r0,-579r-170,0r0,-116r501,0","w":491},"U":{"d":"318,-107v85,0,108,-44,108,-143r0,-445r142,0r0,468v0,66,-1,79,-11,109v-18,55,-86,131,-236,131v-106,0,-184,-32,-223,-93v-23,-36,-30,-64,-30,-131r0,-484r143,0r0,457v-3,98,27,131,107,131","w":636},"V":{"d":"585,-695r-242,700r-127,0r-236,-700r153,0r115,362v10,31,21,70,32,121v43,-171,106,-321,158,-483r147,0","w":565},"W":{"d":"832,-695r-168,701r-153,0r-62,-283v-20,-90,-31,-178,-33,-200v-10,92,-66,364,-91,483r-159,0r-166,-701r148,0r60,274v28,130,37,229,37,229v10,-114,68,-373,98,-503r153,0r64,311v13,65,30,184,30,184v14,-125,65,-361,95,-495r147,0","w":832},"X":{"d":"577,0r-169,0r-125,-245r-124,245r-174,0r218,-372r-188,-323r171,0r94,187r95,-187r167,0r-181,314","w":562},"Y":{"d":"559,-695r-222,409r0,286r-146,0r0,-286r-216,-409r168,0r89,190v18,38,27,63,35,89v8,-20,22,-54,37,-87r90,-192r165,0","w":534},"Z":{"d":"500,-114r-36,114r-434,0r0,-98r256,-423v19,-32,43,-63,43,-63v-63,8,-205,4,-285,5r31,-116r416,0r0,101r-258,435v-15,25,-36,49,-36,49v78,-7,212,-3,303,-4","w":530},"[":{"d":"280,156r-210,0r0,-888r210,0r0,90r-90,0r0,708r90,0r0,90","w":300},"\\":{"d":"423,18r-113,35r-300,-779r114,-35","w":433},"]":{"d":"230,156r-210,0r0,-90r90,0r0,-708r-90,0r0,-90r210,0r0,888","w":300},"^":{"d":"551,-343r-142,0r-111,-238r-112,238r-141,0r180,-365r146,0","w":596},"_":{"d":"500,125r-500,0r0,-50r500,0r0,50","w":500},"\u2018":{"d":"229,-661v-61,13,-103,59,-46,89v72,38,35,156,-48,156v-58,0,-100,-51,-100,-120v0,-87,57,-160,141,-181","w":259},"a":{"d":"46,-451v53,-34,145,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,56,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-31,33,-71,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32","w":512},"b":{"d":"512,-265v0,147,-69,275,-207,275v-50,0,-85,-15,-114,-47v-4,18,-5,23,-14,37r-120,0v10,-23,13,-38,13,-109r0,-474v0,-63,-2,-97,-9,-126r137,-32v8,80,7,174,2,257v26,-28,62,-41,109,-41v125,0,203,100,203,260xm280,-104v77,0,77,-60,80,-158v3,-92,-15,-152,-79,-152v-35,0,-59,22,-76,41r0,236v18,16,39,33,75,33","w":552},"c":{"d":"188,-248v3,103,13,149,86,158v32,4,70,-21,100,-49r61,81v-43,45,-95,70,-172,70v-141,0,-223,-98,-223,-264v0,-173,81,-275,232,-275v64,0,111,22,149,59r-65,88v-90,-80,-173,-42,-168,132","w":455},"d":{"d":"498,0r-120,0v-4,-8,-6,-16,-8,-30v-33,29,-72,43,-118,43v-130,0,-212,-101,-212,-260v0,-160,89,-270,219,-270v37,0,66,9,91,29v-7,-66,-3,-175,-4,-252r133,21r0,532v0,126,10,167,19,187xm348,-133r0,-244v-87,-71,-159,-29,-159,131v0,110,23,146,93,146v25,0,53,-17,66,-33","w":549},"e":{"d":"265,-523v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-59,48,-121,71,-193,71v-147,0,-242,-104,-242,-265v0,-161,79,-272,225,-272xm342,-312v2,-69,-17,-112,-75,-113v-52,-1,-81,41,-80,113r155,0","w":506},"f":{"d":"354,-709r-43,83v-54,-32,-111,-21,-111,41r0,73r130,0r-34,92r-95,0r0,420r-131,0r0,-420r-46,0r0,-92r49,0v-24,-131,28,-229,160,-229v44,0,80,9,121,32","w":304},"g":{"d":"260,-521v42,0,115,23,155,24v37,0,75,-16,106,-44r56,85v-36,35,-75,43,-129,35v84,111,-21,254,-179,235v-34,16,-53,28,-53,42v0,7,8,12,22,12v94,0,185,2,227,47v28,30,44,63,44,109v0,123,-121,172,-243,172v-127,0,-278,-67,-224,-198r124,0v-21,59,13,96,90,96v60,0,115,-19,117,-69v4,-102,-215,-41,-274,-78v-24,-9,-39,-32,-39,-67v0,-33,10,-64,94,-86v-74,-19,-110,-66,-110,-142v0,-105,85,-173,216,-173xm340,-347v0,-48,-30,-76,-81,-76v-51,0,-80,28,-80,76v0,52,32,73,79,73v53,0,82,-26,82,-73","w":553},"h":{"d":"349,-526v105,0,146,53,146,168r0,358r-131,0r0,-344v3,-114,-110,-66,-158,-23r0,367r-136,0r0,-592v0,-48,-4,-96,-10,-117r137,-32v12,65,10,189,7,270v35,-33,93,-55,145,-55","w":565},"i":{"d":"204,0r-134,0r0,-503r134,-21r0,524xm220,-653v0,46,-37,83,-83,83v-45,0,-82,-37,-82,-83v0,-46,38,-83,84,-83v45,0,81,37,81,83","w":274},"j":{"d":"5,146v45,-42,65,-65,65,-156r0,-481r133,-32r0,509v0,97,-20,136,-38,159v-24,31,-58,56,-104,75xm221,-655v0,46,-38,84,-84,84v-46,0,-82,-37,-82,-82v0,-46,37,-84,83,-84v45,0,83,37,83,82","w":273},"k":{"d":"204,0r-134,0r0,-577v0,-45,-1,-80,-9,-133r135,-33v18,218,4,506,8,743xm537,0r-158,0r-172,-290r131,-222r161,0r-163,214","w":517},"l":{"d":"281,-2v-73,30,-178,11,-199,-56v-8,-27,-12,-42,-12,-115r0,-382v0,-67,-2,-108,-7,-154r137,-31v15,142,7,369,7,532v0,88,1,100,9,114v8,13,24,17,42,12","w":281},"m":{"d":"584,-521v96,0,139,39,139,157r0,364r-130,0r0,-338v0,-61,-7,-73,-42,-73v-25,0,-60,17,-89,43r0,368r-127,0r0,-333v0,-64,-9,-79,-46,-79v-25,0,-59,13,-88,39r0,373r-131,0r0,-357v0,-74,-5,-106,-19,-131r121,-33v9,14,13,26,18,52v67,-74,203,-67,249,15v47,-48,89,-67,145,-67","w":793},"n":{"d":"341,-521v85,3,133,49,133,147r0,374r-132,0r0,-333v4,-120,-86,-74,-138,-29r0,362r-134,0r0,-371v0,-44,-6,-86,-18,-120r119,-34v12,21,19,43,19,64v38,-29,90,-62,151,-60","w":544},"o":{"d":"265,-522v143,1,233,107,233,264v0,88,-20,148,-64,198v-39,44,-90,71,-169,71v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166"},"p":{"d":"512,-270v0,110,-20,164,-71,223v-55,62,-168,75,-244,31v5,63,1,136,2,202r-129,34r0,-592v0,-67,-1,-86,-8,-129r119,-21v5,18,8,32,9,48v42,-52,164,-63,227,-17v53,39,95,103,95,221xm366,-257v0,-87,-2,-156,-77,-156v-33,0,-65,14,-89,39r0,249v18,15,47,30,74,30v66,0,92,-45,92,-162","w":552},"q":{"d":"40,-248v0,-167,77,-277,212,-277v53,0,109,24,120,52v1,-18,3,-25,10,-40r111,0v-9,39,-12,90,-12,151r0,550r-127,34r0,-194v0,-20,1,-41,3,-52v-27,24,-62,36,-102,36v-154,0,-215,-124,-215,-260xm354,-137r0,-241v-19,-20,-47,-35,-77,-35v-81,0,-90,85,-90,148v0,66,0,167,90,167v30,0,61,-20,77,-39","w":551},"r":{"d":"362,-513r-37,118v-47,-23,-87,-6,-121,33r0,362r-134,0v-5,-155,15,-375,-19,-492r120,-32v12,21,19,44,21,73v38,-51,98,-94,170,-62","w":347},"s":{"d":"423,-249v83,126,-24,265,-191,265v-63,0,-132,-20,-207,-59r48,-98v41,25,112,58,170,58v38,0,68,-25,68,-58v0,-54,-84,-63,-139,-74v-69,-13,-123,-62,-123,-144v0,-100,79,-167,198,-167v82,0,136,25,183,48r-44,90v-51,-26,-88,-37,-126,-37v-39,0,-65,20,-65,50v0,44,83,56,126,68v63,17,86,34,102,58","w":481},"t":{"d":"326,-11v-121,48,-256,26,-256,-131r0,-278r-51,0r0,-92r51,0v0,-50,0,-83,5,-121r136,-34v-5,47,-8,103,-8,155r120,0r-34,92r-86,0r0,257v-4,90,41,92,106,72","w":341},"u":{"d":"197,-196v1,77,2,108,58,108v33,0,73,-24,83,-49r0,-360r128,-27r0,391v0,34,11,69,31,93r-95,54v-17,-12,-31,-29,-40,-50v-33,32,-81,49,-135,49v-115,0,-162,-49,-162,-185r0,-328r132,-25r0,329","w":536},"v":{"d":"474,-512r-187,512r-111,0r-186,-504r137,-17r74,231v11,34,26,90,33,123v17,-106,69,-242,100,-345r140,0","w":464},"w":{"d":"699,-512r-146,512r-123,0r-46,-176v-16,-60,-29,-116,-37,-175v-18,111,-57,242,-82,351r-125,0r-140,-503r133,-15r42,197v13,59,29,159,29,159v2,-40,62,-278,85,-350r126,0r41,169v23,95,38,181,38,181v9,-81,46,-257,67,-350r138,0","w":699},"x":{"d":"256,-368v0,-2,50,-117,69,-144r158,0r-152,236r184,276r-170,0r-54,-94v-9,-16,-36,-69,-40,-76v-8,28,-68,129,-94,170r-172,0r189,-273r-142,-215r139,-39v47,78,56,96,85,159","w":500},"y":{"d":"502,-512r-186,520v-55,156,-86,186,-222,216r-46,-88v81,-19,125,-60,150,-136r-34,0r-169,-504r137,-16r89,299v8,30,25,99,27,106v21,-132,77,-274,113,-397r141,0","w":497},"z":{"d":"439,-93r-32,93r-377,0r0,-83r241,-335r-221,0r0,-94r380,0r0,92r-226,327r235,0","w":469},"{":{"d":"362,156v-135,5,-234,5,-234,-146r0,-172v0,-62,-83,-69,-108,-69r0,-114v25,0,108,-7,108,-69r0,-173v1,-150,99,-150,234,-145r0,114r-49,0v-61,0,-65,37,-65,64r0,161v1,96,-62,96,-100,106v42,3,100,10,100,103r0,162v0,27,4,64,65,64r49,0r0,114","w":382},"|":{"d":"196,208r-126,0r0,-964r126,0r0,964","w":266},"}":{"d":"362,-231v-28,0,-108,7,-108,69r0,173v-1,150,-99,150,-234,145r0,-114r49,0v61,0,65,-37,65,-64r0,-161v-1,-96,62,-96,100,-106v-42,-3,-100,-10,-100,-103r0,-162v0,-27,-4,-64,-65,-64r-49,0r0,-114v135,-5,234,-7,234,146r0,172v0,62,80,69,108,69r0,114","w":382},"~":{"d":"170,-400v66,0,155,68,213,68v40,0,65,-37,88,-68r36,108v-22,42,-58,86,-125,86v-66,0,-155,-68,-213,-68v-40,0,-65,37,-88,68r-36,-108v22,-42,58,-86,125,-86","w":552},"\u00a1":{"d":"229,178r-160,23r28,-489r102,0xm230,-439v0,46,-37,83,-83,83v-45,0,-82,-37,-82,-83v0,-46,38,-83,84,-83v45,0,81,37,81,83","w":295},"\u00a2":{"d":"188,-248v3,103,13,149,86,158v32,4,70,-21,100,-49r61,81v-35,37,-70,55,-124,66r0,103r-94,0r0,-103v-112,-19,-177,-113,-177,-260v0,-154,62,-237,177,-268r0,-97r94,0r0,96v50,5,76,23,110,53r-65,88v-90,-80,-173,-42,-168,132","w":455},"\u00a3":{"d":"593,-652r-100,107v-27,-27,-64,-43,-91,-43v-109,0,-121,78,-116,174r156,0r0,102r-156,0r0,198r253,0r0,114r-499,0r0,-114r96,0r0,-198r-96,0r0,-102r96,0r0,-71v0,-119,86,-235,248,-235v75,0,154,18,209,68","w":583},"\u2044":{"d":"446,-764r-528,918r-108,0r528,-918r108,0","w":256},"\u00a5":{"d":"571,-695r-153,280r103,0r0,103r-158,0r-14,26r0,50r172,0r0,103r-172,0r0,133r-146,0r0,-133r-169,0r0,-103r169,0r0,-50r-14,-26r-155,0r0,-103r101,0r-148,-280r168,0r89,190v18,38,27,63,35,89v8,-20,22,-54,37,-87r90,-192r165,0","w":558},"\u0192":{"d":"108,-512v-5,-133,39,-229,164,-229v42,0,83,16,108,32r-41,83v-51,-34,-104,-19,-108,41r-5,73r118,0r-32,94r-90,0r-27,384v-12,167,-39,183,-145,254r-62,-91v63,-49,79,-66,84,-139r27,-408r-43,0r0,-94r52,0","w":312},"\u00a7":{"d":"548,-281v0,55,-36,106,-84,130v35,28,55,73,55,119v0,131,-138,183,-246,183v-99,0,-188,-30,-233,-126r128,-63v12,48,64,69,109,69v32,0,80,-11,80,-52v0,-94,-301,-79,-301,-272v0,-67,32,-114,87,-148v-39,-26,-63,-67,-63,-115v0,-117,115,-170,215,-170v85,0,183,25,224,109r-126,72v-14,-38,-52,-61,-92,-61v-32,0,-65,17,-65,53v0,98,312,90,312,272xm410,-253v0,-38,-35,-58,-65,-72r-116,-55v-23,13,-35,33,-35,59v0,48,43,65,80,82r102,47v22,-13,34,-35,34,-61","w":588},"\u00a4":{"d":"301,-216v25,119,172,161,269,75r34,108v-48,30,-84,45,-163,45v-154,0,-263,-98,-297,-228r-114,0r0,-98r100,0r2,-77r-102,0r0,-98r122,0v38,-129,157,-221,291,-221v69,0,115,17,146,35r-33,115v-89,-76,-233,-31,-252,71r193,0r0,98r-208,0r0,77r208,0r0,98r-196,0","w":624},"'":{"d":"191,-426r-126,0r0,-282r126,0r0,282","w":256},"\u201c":{"d":"229,-662v-61,14,-103,58,-46,89v72,39,35,156,-49,156v-57,0,-99,-50,-99,-120v0,-87,57,-160,141,-181xm454,-662v-59,14,-103,58,-45,89v71,39,35,156,-49,156v-58,0,-99,-50,-99,-120v0,-87,57,-160,140,-181","w":484},"\u00ab":{"d":"517,-76r-91,61r-159,-234r159,-234r91,61r-116,173xm275,-76r-91,61r-159,-234r159,-234r91,61r-116,173","w":542},"\u2039":{"d":"275,-76r-91,61r-159,-234r159,-234r91,61r-116,173","w":300},"\u203a":{"d":"275,-249r-159,234r-91,-61r116,-173r-116,-173r91,-61","w":300},"\ufb01":{"d":"506,0r-134,0r0,-418r-171,0r0,418r-131,0r0,-418r-46,0r0,-94r49,0v-22,-131,27,-229,160,-229v44,0,88,11,111,24r-43,83v-47,-20,-101,-8,-101,49r0,73r306,0r0,512xm522,-653v0,46,-37,83,-83,83v-45,0,-82,-37,-82,-83v0,-46,38,-83,84,-83v45,0,81,37,81,83","w":576},"\ufb02":{"d":"341,-717r-43,83v-47,-20,-101,-8,-101,49r0,73r123,0r-34,94r-85,0r0,418r-131,0r0,-418r-46,0r0,-94r46,0v-22,-131,27,-229,160,-229v44,0,88,11,111,24xm580,-2v-73,30,-178,11,-199,-56v-8,-27,-12,-42,-12,-115r0,-382v0,-67,-2,-108,-7,-154r137,-31v15,142,7,369,7,532v0,88,1,100,9,114v7,13,25,17,42,12","w":580},"\u2013":{"d":"527,-223r-487,0r0,-103r487,0r0,103","w":567},"\u2020":{"d":"464,-545r-23,121r-139,0r0,424r-132,0r0,-424r-150,0r0,-121r150,0r0,-150r132,0r0,150r162,0","w":484},"\u2021":{"d":"476,-545r-23,121r-139,0r0,153r150,0r0,121r-150,0r0,150r-132,0r0,-150r-162,0r23,-121r139,0r0,-153r-150,0r0,-121r150,0r0,-150r132,0r0,150r162,0","w":496},"\u00b7":{"d":"218,-273v0,48,-40,88,-90,88v-49,0,-88,-40,-88,-89v0,-49,40,-90,90,-90v49,0,88,41,88,91","w":258},"\u00b6":{"d":"522,126r-90,0r0,-762r-107,0r0,762r-90,0r0,-464v-130,0,-215,-77,-215,-182v0,-134,94,-188,233,-188r269,0r0,834","w":592},"\u2022":{"d":"414,-354v0,98,-79,177,-177,177v-98,0,-177,-79,-177,-177v0,-98,79,-177,177,-177v98,0,177,79,177,177","w":474},"\u201a":{"d":"224,-36v0,87,-57,160,-141,181r-53,-56v61,-14,103,-58,46,-89v-72,-39,-35,-156,48,-156v58,0,100,50,100,120","w":259},"\u201e":{"d":"450,-36v0,87,-57,160,-141,181r-53,-56v59,-14,102,-58,46,-89v-71,-39,-36,-156,48,-156v58,0,100,50,100,120xm224,-36v0,87,-57,160,-141,181r-53,-56v61,-14,103,-58,46,-89v-72,-39,-35,-156,48,-156v58,0,100,50,100,120","w":485},"\u201d":{"d":"224,-591v0,86,-57,159,-141,180r-53,-55v59,-16,104,-58,46,-89v-71,-39,-36,-156,48,-156v58,0,100,50,100,120xm449,-591v0,86,-56,159,-140,180r-53,-55v59,-15,102,-58,46,-89v-71,-39,-36,-156,48,-156v58,0,99,50,99,120","w":484},"\u00bb":{"d":"517,-249r-159,234r-91,-61r116,-173r-116,-173r91,-61xm275,-249r-159,234r-91,-61r116,-173r-116,-173r91,-61","w":542},"\u2026":{"d":"726,-73v0,49,-40,89,-88,89v-49,0,-88,-40,-88,-89v0,-48,39,-87,87,-87v49,0,89,39,89,87xm226,-73v0,49,-40,89,-88,89v-49,0,-88,-40,-88,-89v0,-48,39,-87,87,-87v49,0,89,39,89,87xm476,-73v0,49,-40,89,-88,89v-49,0,-88,-40,-88,-89v0,-48,39,-87,87,-87v49,0,89,39,89,87","w":776},"\u2030":{"d":"638,-336v103,-1,174,67,172,172v-2,108,-61,174,-172,174v-103,0,-169,-67,-169,-172v0,-104,67,-174,169,-174xm1008,-336v102,0,174,65,172,172v-2,108,-61,174,-172,174v-103,0,-169,-67,-169,-172v0,-104,67,-174,169,-174xm199,-705v105,0,173,69,172,172v-1,109,-61,174,-172,174v-103,0,-169,-67,-169,-172v0,-104,67,-174,169,-174xm650,-695r-364,695r-95,0r364,-695r95,0xm139,-534v0,66,7,100,61,100v42,0,60,-30,60,-101v0,-62,-11,-96,-62,-96v-49,0,-59,40,-59,97xm948,-165v0,66,7,100,61,100v42,0,60,-30,60,-101v0,-62,-11,-96,-62,-96v-49,0,-59,40,-59,97xm578,-165v0,66,7,100,61,100v42,0,60,-30,60,-101v0,-62,-11,-96,-62,-96v-49,0,-59,40,-59,97","w":1210},"\u00bf":{"d":"439,120v-25,26,-91,76,-194,76v-102,0,-190,-62,-190,-167v0,-92,57,-127,92,-152v72,-51,82,-91,75,-165r115,0v24,94,0,160,-83,218v-28,20,-66,40,-66,81v0,49,38,69,82,69v56,0,90,-32,108,-46xm348,-439v0,46,-37,83,-83,83v-45,0,-82,-37,-82,-83v0,-46,38,-83,84,-83v45,0,81,37,81,83","w":474},"`":{"d":"295,-631r-41,74r-224,-100r58,-104","w":325},"\u00b4":{"d":"295,-657r-224,100r-41,-74r207,-130","w":325},"\u02c6":{"d":"384,-625r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":404},"\u02dc":{"d":"384,-639v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30","w":404},"\u00af":{"d":"334,-666r-314,0r0,-78r314,0r0,78","w":354},"\u02d8":{"d":"361,-693v-13,19,-93,115,-170,115v-78,0,-157,-96,-171,-115r36,-44v18,17,76,65,139,65v54,0,119,-52,135,-65","w":381},"\u02d9":{"d":"185,-653v0,46,-37,83,-83,83v-45,0,-82,-37,-82,-83v0,-46,38,-83,84,-83v45,0,81,37,81,83","w":205},"\u00a8":{"d":"414,-635v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm203,-635v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":464},"\u02da":{"d":"230,-659v0,58,-48,106,-106,106v-57,0,-104,-48,-104,-106v0,-58,49,-106,106,-106v57,0,104,48,104,106xm175,-659v0,-28,-22,-51,-49,-51v-29,0,-52,23,-52,51v0,28,23,51,50,51v28,0,51,-23,51,-51","w":250},"\u00b8":{"d":"246,111v0,49,-39,88,-109,88v-30,0,-67,-13,-87,-24r30,-63v19,12,71,26,77,-3v5,-22,-36,-23,-52,-14r-13,-20r24,-87r72,6r-14,38v51,5,72,40,72,79","w":296},"\u02dd":{"d":"214,-741r-116,217r-78,-34r83,-229xm441,-723r-147,196r-72,-46r117,-213","w":461},"\u02db":{"d":"246,175v-20,11,-57,24,-87,24v-70,0,-109,-39,-109,-88v0,-72,57,-125,73,-137r71,40v-24,23,-54,51,-54,87v0,40,55,24,76,11","w":296},"\u02c7":{"d":"384,-689r-180,135r-184,-135r45,-73r139,76r135,-76","w":404},"\u2014":{"d":"753,-223r-713,0r0,-103r713,0r0,103","w":793},"\u00c6":{"d":"829,0r-409,0r0,-165r-191,0r-93,165r-156,0r414,-695r422,0r-18,114r-238,0r0,161r199,0r0,114r-197,0r0,186r267,0r0,120xm420,-442v0,-41,4,-79,5,-81v-5,9,-105,197,-131,242r126,0r0,-161","w":849},"\u00aa":{"d":"218,-772v92,5,130,32,130,136v0,80,-26,181,34,214r-48,62v-24,-10,-50,-27,-59,-47v-29,30,-49,42,-101,42v-85,0,-132,-44,-132,-120v0,-97,78,-137,207,-132v1,-45,-2,-72,-45,-72v-32,0,-70,15,-111,43r-43,-72v41,-25,109,-57,168,-54xm395,-231r-365,0r0,-78r365,0r0,78xm248,-548v-69,-1,-100,11,-99,59v1,59,68,63,97,24","w":425},"\u0141":{"d":"462,-116r-25,116r-367,0r0,-294r-56,18r0,-92r56,-18r0,-309r143,0r0,262r148,-48r0,92r-148,48r0,225r249,0","w":467},"\u00d8":{"d":"40,-345v0,-206,96,-359,301,-359v55,0,104,12,145,35r61,-99r73,41r-68,110v57,61,88,152,88,266v0,210,-87,362,-294,362v-63,0,-113,-11,-155,-34r-67,111r-73,-41r76,-125v-60,-73,-87,-165,-87,-267xm339,-596v-162,-2,-153,235,-131,385r215,-354v-20,-18,-47,-31,-84,-31xm479,-347v0,-54,-4,-97,-11,-131r-216,355v26,18,56,27,89,27v97,0,138,-74,138,-251","w":680},"\u0152":{"d":"816,0r-408,0v-147,0,-202,-9,-273,-72v-113,-101,-127,-385,-25,-514v44,-56,104,-90,169,-100v139,-21,362,-5,524,-9r-18,114r-237,0r0,161r198,0r0,114r-198,0r0,186r268,0r0,120xm207,-362v1,136,18,250,145,253v33,0,64,-10,64,-10r0,-447v0,0,-38,-10,-75,-10v-92,0,-134,67,-134,214","w":836},"\u00ba":{"d":"209,-764v109,0,177,79,175,198v-2,120,-57,201,-175,201v-104,0,-172,-78,-172,-198v0,-121,69,-201,172,-201xm395,-231r-365,0r0,-78r365,0r0,78xm151,-566v1,73,8,123,61,123v42,0,59,-38,59,-124v0,-74,-5,-111,-60,-117v-51,6,-60,52,-60,118","w":425},"\u00e6":{"d":"521,-522v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-100,89,-279,101,-364,3v-43,49,-78,72,-156,72v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58r-57,-96v49,-32,147,-72,223,-72v55,0,100,23,130,47v28,-26,73,-46,122,-46xm309,-224v-92,-1,-132,15,-131,78v2,80,91,83,130,31xm598,-311v2,-69,-17,-112,-75,-113v-52,-1,-81,41,-80,113r155,0","w":762},"\u0131":{"d":"204,0r-134,0r0,-503r134,-21r0,524","w":274},"\u0142":{"d":"281,-2v-73,30,-179,11,-199,-56v-18,-32,-10,-161,-12,-228r-40,13r0,-92r40,-13r0,-177v0,-67,-2,-108,-7,-154r137,-31v11,64,6,225,7,315r54,-18r0,92r-54,18v2,59,-6,226,9,239v8,13,24,17,42,12","w":281},"\u00f8":{"d":"430,-454v94,85,83,303,4,394v-54,63,-181,93,-272,48r-58,96r-62,-35r62,-103v-44,-47,-69,-115,-69,-200v0,-204,162,-321,339,-244r59,-96r62,35xm352,-259v0,-23,-1,-48,-3,-60r-131,215v87,50,137,-5,134,-155xm267,-423v-92,2,-86,134,-80,233r130,-214v-13,-12,-30,-19,-50,-19"},"\u0153":{"d":"561,-522v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-97,86,-259,97,-354,14v-37,33,-84,53,-152,53v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268v61,0,110,17,150,53v39,-36,86,-53,146,-53xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166xm638,-311v1,-75,-16,-113,-75,-113v-51,0,-80,40,-80,113r155,0","w":802},"\u00df":{"d":"90,-512v-14,-135,77,-213,209,-213v133,0,217,64,217,165v0,68,-52,115,-106,144v-23,12,-16,31,11,43v63,28,83,39,109,67v30,31,42,68,42,113v0,147,-149,240,-303,194r30,-92v70,19,126,-21,126,-97v0,-109,-147,-94,-147,-202v0,-82,88,-77,88,-152v0,-52,-23,-80,-68,-80v-60,0,-72,47,-72,129r0,390v0,50,-14,90,-20,103r-136,0v30,-91,18,-281,20,-408r-82,0r0,-104r82,0","w":602},"\u0178":{"d":"559,-695r-222,409r0,286r-146,0r0,-286r-216,-409r168,0r89,190v18,38,27,63,35,89v8,-20,22,-54,37,-87r90,-192r165,0xm446,-795v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm235,-795v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":534},"\u2122":{"d":"960,-296r-108,0r0,-268r-2,0r-98,268r-70,0r-98,-268r-2,0r0,268r-108,0r0,-412r145,0r98,268r98,-268r145,0r0,412xm386,-612r-119,0r0,316r-108,0r0,-316r-119,0r0,-96r346,0r0,96","w":1020},"\u017e":{"d":"439,-93r-32,93r-377,0r0,-83r241,-335r-221,0r0,-94r380,0r0,92r-226,327r235,0xm420,-689r-180,135r-184,-135r45,-73r139,76r135,-76","w":469},"\u017d":{"d":"500,-114r-36,114r-434,0r0,-98r256,-423v19,-32,43,-63,43,-63v-63,8,-205,4,-285,5r31,-116r416,0r0,101r-258,435v-15,25,-36,49,-36,49v78,-7,212,-3,303,-4xm445,-869r-180,135r-184,-135r45,-73r139,76r135,-76","w":530},"\u0161":{"d":"423,-249v83,126,-24,265,-191,265v-63,0,-132,-20,-207,-59r48,-98v41,25,112,58,170,58v38,0,68,-25,68,-58v0,-54,-84,-63,-139,-74v-69,-13,-123,-62,-123,-144v0,-100,79,-167,198,-167v82,0,136,25,183,48r-44,90v-51,-26,-88,-37,-126,-37v-39,0,-65,20,-65,50v0,44,83,56,126,68v63,17,86,34,102,58xm417,-689r-180,135r-184,-135r45,-73r139,76r135,-76","w":481},"\u0160":{"d":"554,-219v0,141,-114,234,-287,234v-79,0,-167,-23,-237,-63r52,-109v65,34,121,56,191,56v80,0,122,-33,122,-95v0,-72,-100,-94,-168,-111v-107,-28,-166,-81,-166,-194v0,-127,102,-215,249,-215v85,0,171,26,232,70r-66,100v-63,-38,-110,-53,-162,-53v-57,0,-97,33,-97,80v0,63,105,77,161,93v114,33,176,104,176,207xm481,-869r-180,135r-184,-135r45,-73r139,76r135,-76","w":584},"\u00ff":{"d":"502,-512r-186,520v-55,156,-86,186,-222,216r-46,-88v81,-19,125,-60,150,-136r-34,0r-169,-504r137,-16r89,299v8,30,25,99,27,106v21,-132,77,-274,113,-397r141,0xm443,-635v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm232,-635v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":497},"\u00fe":{"d":"508,-265v0,147,-69,275,-207,275v-50,0,-82,-15,-106,-39r0,215r-129,34r0,-803v0,-63,-2,-97,-9,-126r137,-32v8,80,7,174,2,257v26,-28,62,-41,109,-41v125,0,203,100,203,260xm276,-104v77,0,77,-60,80,-158v3,-92,-15,-152,-79,-152v-35,0,-59,22,-76,41r0,236v18,16,39,33,75,33","w":548},"\u00fd":{"d":"502,-512r-186,520v-55,156,-86,186,-222,216r-46,-88v81,-19,125,-60,150,-136r-34,0r-169,-504r137,-16r89,299v9,31,27,106,27,106v21,-131,77,-274,113,-397r141,0xm416,-657r-224,100r-41,-74r207,-130","w":497},"\u00fc":{"d":"197,-196v1,77,2,108,58,108v33,0,73,-24,83,-49r0,-360r128,-27r0,391v0,34,11,69,31,93r-95,54v-17,-12,-31,-29,-40,-50v-33,32,-81,49,-135,49v-115,0,-162,-49,-162,-185r0,-328r132,-25r0,329xm450,-635v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm234,-635v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":536},"\u00fb":{"d":"197,-196v1,77,2,108,58,108v33,0,73,-24,83,-49r0,-360r128,-27r0,391v0,34,11,69,31,93r-95,54v-17,-12,-31,-29,-40,-50v-33,32,-81,49,-135,49v-115,0,-162,-49,-162,-185r0,-328r132,-25r0,329xm451,-625r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":536},"\u00fa":{"d":"197,-196v1,77,2,108,58,108v33,0,73,-24,83,-49r0,-360r128,-27r0,391v0,34,11,69,31,93r-95,54v-17,-12,-31,-29,-40,-50v-33,32,-81,49,-135,49v-115,0,-162,-49,-162,-185r0,-328r132,-25r0,329xm425,-657r-224,100r-41,-74r207,-130","w":536},"\u00f9":{"d":"197,-196v1,77,2,108,58,108v33,0,73,-24,83,-49r0,-360r128,-27r0,391v0,34,11,69,31,93r-95,54v-17,-12,-31,-29,-40,-50v-33,32,-81,49,-135,49v-115,0,-162,-49,-162,-185r0,-328r132,-25r0,329xm390,-631r-41,74r-224,-100r58,-104","w":536},"\u00f7":{"d":"545,-214r-505,0r0,-105r505,0r0,105xm377,-68v0,47,-39,84,-87,84v-47,0,-86,-37,-86,-84v0,-49,39,-90,87,-89v48,1,86,40,86,89xm378,-467v0,48,-39,86,-87,86v-47,0,-85,-38,-85,-85v0,-48,38,-88,85,-88v48,0,87,39,87,87","w":585},"\u00f6":{"d":"265,-522v143,1,233,107,233,264v0,88,-20,148,-64,198v-39,44,-90,71,-169,71v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166xm448,-635v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm237,-635v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77"},"\u00f5":{"d":"265,-522v143,1,233,107,233,264v0,88,-20,148,-64,198v-39,44,-90,71,-169,71v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166xm447,-639v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30"},"\u00f4":{"d":"265,-522v143,1,233,107,233,264v0,88,-20,148,-64,198v-39,44,-90,71,-169,71v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166xm449,-625r-45,73r-139,-76r-135,76r-45,-73r180,-135"},"\u00f3":{"d":"265,-522v143,1,233,107,233,264v0,88,-20,148,-64,198v-39,44,-90,71,-169,71v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166xm412,-657r-224,100r-41,-74r207,-130"},"\u00f2":{"d":"265,-522v143,1,233,107,233,264v0,88,-20,148,-64,198v-39,44,-90,71,-169,71v-139,0,-230,-104,-230,-265v0,-161,92,-268,230,-268xm184,-257v0,100,9,171,85,171v58,0,83,-52,83,-173v0,-103,-8,-155,-85,-164v-72,6,-83,75,-83,166xm358,-631r-41,74r-224,-100r58,-104"},"\u00f1":{"d":"341,-521v85,3,133,49,133,147r0,374r-132,0r0,-333v4,-120,-86,-74,-138,-29r0,362r-134,0r0,-371v0,-44,-6,-86,-18,-120r119,-34v12,21,19,43,19,64v38,-29,90,-62,151,-60xm452,-639v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30","w":544},"\u00f0":{"d":"293,-605v107,71,193,220,193,364v0,167,-97,253,-225,253v-126,0,-221,-85,-221,-226v0,-145,111,-228,264,-206v-25,-34,-57,-67,-92,-93r-41,47r-81,-36r48,-54v-39,-18,-87,-32,-142,-38r80,-95v43,5,93,18,142,41r31,-36r81,36xm267,-97v79,0,97,-115,80,-201v-19,-12,-41,-19,-89,-19v-52,0,-83,37,-83,105v0,68,34,115,92,115","w":526},"\u00ef":{"d":"204,0r-134,0r0,-503r134,-21r0,524xm319,-635v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm108,-635v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":274},"\u00ee":{"d":"204,0r-134,0r0,-503r134,-21r0,524xm319,-625r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":274},"\u00ed":{"d":"204,0r-134,0r0,-503r134,-21r0,524xm298,-657r-224,100r-41,-74r207,-130","w":274},"\u00ec":{"d":"204,0r-134,0r0,-503r134,-21r0,524xm245,-631r-41,74r-224,-100r58,-104","w":274},"\u00eb":{"d":"265,-523v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-59,48,-121,71,-193,71v-147,0,-242,-104,-242,-265v0,-161,79,-272,225,-272xm448,-635v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm237,-635v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77xm342,-312v2,-69,-17,-112,-75,-113v-52,-1,-81,41,-80,113r155,0","w":506},"\u00ea":{"d":"265,-523v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-59,48,-121,71,-193,71v-147,0,-242,-104,-242,-265v0,-161,79,-272,225,-272xm448,-625r-45,73r-139,-76r-135,76r-45,-73r180,-135xm342,-312v2,-69,-17,-112,-75,-113v-52,-1,-81,41,-80,113r155,0","w":506},"\u00e9":{"d":"265,-523v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-59,48,-121,71,-193,71v-147,0,-242,-104,-242,-265v0,-161,79,-272,225,-272xm411,-657r-224,100r-41,-74r207,-130xm342,-312v2,-69,-17,-112,-75,-113v-52,-1,-81,41,-80,113r155,0","w":506},"\u00e8":{"d":"265,-523v167,0,223,121,216,309r-296,0v-1,81,38,128,108,128v46,0,89,-17,130,-51r52,80v-59,48,-121,71,-193,71v-147,0,-242,-104,-242,-265v0,-161,79,-272,225,-272xm360,-631r-41,74r-224,-100r58,-104xm342,-312v2,-69,-17,-112,-75,-113v-52,-1,-81,41,-80,113r155,0","w":506},"\u00e7":{"d":"188,-248v3,103,13,149,86,158v32,4,70,-21,100,-49r61,81v-41,43,-91,68,-164,70r-7,20v51,5,72,40,72,79v0,49,-39,88,-109,88v-30,0,-67,-13,-87,-24r30,-63v19,12,71,26,77,-3v5,-23,-36,-21,-52,-14r-13,-20r19,-70v-103,-25,-161,-117,-161,-257v0,-173,81,-275,232,-275v63,0,111,22,149,59r-65,88v-90,-80,-173,-42,-168,132","w":455},"\u00e5":{"d":"46,-451v53,-34,145,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,54,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-31,33,-71,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm361,-659v0,58,-48,106,-106,106v-57,0,-104,-48,-104,-106v0,-58,49,-106,106,-106v57,0,104,48,104,106xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32xm306,-659v0,-28,-22,-51,-49,-51v-29,0,-52,23,-52,51v0,28,23,51,50,51v28,0,51,-23,51,-51","w":512},"\u00e4":{"d":"46,-451v58,-37,142,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,54,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-37,39,-67,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm434,-635v0,44,-36,80,-80,80v-44,0,-79,-36,-79,-80v0,-44,36,-80,81,-80v43,0,78,36,78,80xm223,-635v0,44,-36,80,-80,80v-43,0,-79,-36,-79,-80v0,-44,37,-80,81,-80v43,0,78,36,78,80xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32","w":512},"\u00e3":{"d":"46,-451v53,-34,145,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,54,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-31,33,-71,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm436,-639v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32","w":512},"\u00e2":{"d":"46,-451v53,-34,145,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,54,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-31,33,-71,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm432,-625r-45,73r-139,-76r-135,76r-45,-73r180,-135xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32","w":512},"\u00e1":{"d":"46,-451v53,-34,145,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,54,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-31,33,-71,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm407,-657r-224,100r-41,-74r207,-130xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32","w":512},"\u00e0":{"d":"46,-451v50,-32,147,-72,223,-72v86,0,146,32,165,89v19,55,6,186,6,264v0,54,3,80,48,114r-71,82v-31,-13,-59,-36,-72,-62v-30,33,-72,55,-134,55v-114,0,-176,-58,-176,-160v0,-129,107,-184,276,-175v1,-60,-3,-97,-60,-97v-43,0,-93,21,-148,58xm376,-631r-41,74r-224,-100r58,-104xm309,-224v-92,-1,-131,15,-131,78v0,79,90,84,129,32","w":512},"\u00de":{"d":"546,-371v0,92,-47,162,-120,202v-35,19,-138,24,-216,23r0,146r-140,0r0,-695r140,0r0,110v106,-2,207,7,236,34v65,36,100,100,100,180xm283,-260v88,3,110,-32,110,-108v0,-65,-35,-104,-94,-104r-89,0r0,212r73,0","w":566},"\u00dd":{"d":"559,-695r-222,409r0,286r-146,0r0,-286r-216,-409r168,0r89,190v18,38,27,63,35,89v8,-20,22,-54,37,-87r90,-192r165,0xm425,-817r-224,100r-41,-74r207,-130","w":534},"\u00dc":{"d":"318,-107v85,0,108,-44,108,-143r0,-445r142,0r0,468v0,66,-1,79,-11,109v-18,55,-86,131,-236,131v-106,0,-184,-32,-223,-93v-23,-36,-30,-64,-30,-131r0,-484r143,0r0,457v-3,98,27,131,107,131xm499,-795v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm289,-795v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":636},"\u00db":{"d":"318,-107v85,0,108,-44,108,-143r0,-445r142,0r0,468v0,66,-1,79,-11,109v-18,55,-86,131,-236,131v-106,0,-184,-32,-223,-93v-23,-36,-30,-64,-30,-131r0,-484r143,0r0,457v-3,98,27,131,107,131xm505,-785r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":636},"\u00da":{"d":"318,-107v85,0,108,-44,108,-143r0,-445r142,0r0,468v0,66,-1,79,-11,109v-18,55,-86,131,-236,131v-106,0,-184,-32,-223,-93v-23,-36,-30,-64,-30,-131r0,-484r143,0r0,457v-3,98,27,131,107,131xm482,-817r-224,100r-41,-74r207,-130","w":636},"\u00d9":{"d":"318,-107v85,0,108,-44,108,-143r0,-445r142,0r0,468v0,66,-1,79,-11,109v-18,55,-86,131,-236,131v-106,0,-184,-32,-223,-93v-23,-36,-30,-64,-30,-131r0,-484r143,0r0,457v-3,98,27,131,107,131xm433,-791r-41,74r-224,-100r58,-104","w":636},"\u00d7":{"d":"546,-154r-89,89r-149,-149r-149,149r-89,-89r149,-149r-149,-149r89,-89r149,149r149,-149r89,89r-149,149","w":616},"\u00d6":{"d":"40,-345v0,-205,96,-359,301,-359v185,0,299,135,299,353v0,210,-87,356,-294,362v-208,6,-306,-160,-306,-356xm196,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251xm522,-795v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm311,-795v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":680},"\u00d5":{"d":"34,-345v0,-205,96,-359,301,-359v185,0,299,135,299,353v0,210,-87,356,-294,362v-208,6,-306,-160,-306,-356xm190,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251xm516,-799v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30","w":668},"\u00d4":{"d":"40,-345v0,-205,96,-359,301,-359v185,0,299,135,299,353v0,210,-87,356,-294,362v-208,6,-306,-160,-306,-356xm196,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251xm525,-785r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":680},"\u00d3":{"d":"40,-345v0,-205,96,-359,301,-359v185,0,299,135,299,353v0,210,-87,356,-294,362v-208,6,-306,-160,-306,-356xm196,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251xm481,-817r-224,100r-41,-74r207,-130","w":680},"\u00d2":{"d":"40,-345v0,-205,96,-359,301,-359v185,0,299,135,299,353v0,210,-87,356,-294,362v-208,6,-306,-160,-306,-356xm196,-345v0,166,18,249,145,249v97,0,138,-74,138,-251v0,-71,-6,-122,-18,-161v-11,-35,-48,-88,-122,-88v-120,0,-143,112,-143,251xm457,-791r-41,74r-224,-100r58,-104","w":680},"\u00d1":{"d":"553,0r-146,0r-119,-266v-39,-87,-81,-185,-94,-228v5,57,6,139,7,197r4,297r-135,0r0,-695r155,0v66,144,166,325,209,475v-15,-154,-11,-312,-14,-475r133,0r0,695xm487,-799v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30","w":623},"\u00d0":{"d":"483,-622v113,104,128,389,25,518v-67,84,-131,104,-269,104r-169,0r0,-306r-76,0r0,-89r76,0r0,-300r140,0v128,0,202,8,273,73xm421,-332v-1,-136,-17,-250,-145,-253r-64,0r0,190r107,0r-24,89r-83,0r0,192r75,0v92,0,134,-71,134,-218","w":618},"\u00cf":{"d":"216,0r-146,0r0,-695r146,0r0,695xm325,-795v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm114,-795v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":286},"\u00ce":{"d":"216,0r-146,0r0,-695r146,0r0,695xm325,-785r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":286},"\u00cd":{"d":"216,0r-146,0r0,-695r146,0r0,695xm295,-817r-224,100r-41,-74r207,-130","w":286},"\u00cc":{"d":"216,0r-146,0r0,-695r146,0r0,695xm260,-791r-41,74r-224,-100r58,-104","w":286},"\u00cb":{"d":"475,0r-405,0r0,-695r396,0r-18,114r-238,0r0,161r199,0r0,114r-197,0r0,186r263,0r0,120xm450,-795v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm239,-795v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77","w":495},"\u00ca":{"d":"475,0r-405,0r0,-695r396,0r-18,114r-238,0r0,161r199,0r0,114r-197,0r0,186r263,0r0,120xm448,-785r-45,73r-139,-76r-135,76r-45,-73r180,-135","w":495},"\u00c9":{"d":"475,0r-405,0r0,-695r396,0r-18,114r-238,0r0,161r199,0r0,114r-197,0r0,186r263,0r0,120xm400,-817r-224,100r-41,-74r207,-130","w":495},"\u00c8":{"d":"475,0r-405,0r0,-695r396,0r-18,114r-238,0r0,161r199,0r0,114r-197,0r0,186r263,0r0,120xm376,-791r-41,74r-224,-100r58,-104","w":495},"\u00c7":{"d":"355,-599v-117,0,-157,98,-157,239v0,95,7,148,29,186v52,89,161,107,253,33r64,88v-59,48,-120,67,-210,65r-7,20v51,5,72,40,72,79v0,49,-39,88,-109,88v-30,0,-67,-13,-87,-24r30,-63v19,12,71,26,77,-3v5,-23,-36,-21,-52,-14r-13,-20r20,-73v-136,-34,-225,-166,-225,-335v0,-219,127,-376,313,-377v69,0,138,22,176,55r-63,95v-35,-26,-72,-39,-111,-39","w":564},"\u00c5":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm400,-819v0,58,-48,106,-106,106v-57,0,-104,-48,-104,-106v0,-58,49,-106,106,-106v57,0,104,48,104,106xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0xm345,-819v0,-28,-22,-51,-49,-51v-29,0,-52,23,-52,51v0,28,23,51,50,51v28,0,51,-23,51,-51","w":582},"\u00c4":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm478,-795v0,42,-35,77,-77,77v-42,0,-76,-35,-76,-77v0,-42,35,-77,78,-77v41,0,75,35,75,77xm266,-795v0,42,-35,77,-77,77v-41,0,-76,-35,-76,-77v0,-42,36,-77,78,-77v41,0,75,35,75,77xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0","w":582},"\u00c3":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm469,-799v-30,39,-65,58,-124,58v-61,0,-73,-34,-131,-34v-27,0,-51,11,-68,29r-41,-75v28,-35,68,-58,124,-58v59,0,73,34,131,34v28,0,51,-11,68,-30xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0","w":582},"\u00c2":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm472,-785r-45,73r-139,-76r-135,76r-45,-73r180,-135xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0","w":582},"\u00c1":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm447,-817r-224,100r-41,-74r207,-130xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0","w":582},"\u00c0":{"d":"590,0r-150,0r-49,-165r-204,0r-49,165r-146,0r228,-697r151,0xm412,-791r-41,74r-224,-100r58,-104xm357,-281v-9,-21,-54,-202,-66,-263r-33,134v-13,50,-22,83,-37,129r136,0","w":582},"\u03bc":{"d":"202,-196v1,77,2,108,58,108v33,0,73,-24,83,-49r0,-360r128,-27r0,391v0,34,11,69,31,93r-95,54v-17,-12,-31,-29,-40,-50v-39,36,-116,69,-170,35v4,55,1,127,2,187r-129,34r0,-720r132,-25r0,329","w":541},"\u00b1":{"d":"463,-283r-150,0r0,143r-123,0r0,-143r-150,0r0,-113r150,0r0,-137r123,0r0,137r150,0r0,113xm461,0r-419,0r0,-113r419,0r0,113","w":503},"\u00b0":{"d":"199,-705v101,0,174,65,172,172v-2,108,-61,174,-172,174v-103,0,-169,-67,-169,-172v0,-104,67,-174,169,-174xm139,-534v0,66,7,100,61,100v42,0,60,-30,60,-101v0,-63,-11,-96,-62,-96v-49,0,-59,40,-59,97","w":401},"\u00ae":{"d":"784,-354v0,205,-167,372,-372,372v-205,0,-372,-167,-372,-372v0,-205,167,-372,372,-372v205,0,372,167,372,372xm682,-354v0,-155,-121,-282,-270,-282v-149,0,-270,127,-270,282v0,155,121,282,270,282v149,0,270,-127,270,-282xm580,-171r-115,0v-18,-29,-25,-39,-40,-65v-36,-61,-46,-79,-54,-86r0,151r-97,0r0,-382r153,0v75,0,123,47,123,117v0,57,-38,99,-88,104v47,17,107,151,118,161xm447,-435v3,-38,-35,-41,-76,-39r0,77v41,2,82,-3,76,-38","w":824},"\u00ac":{"d":"481,-58r-123,0r0,-140r-318,0r0,-109r441,0r0,249","w":521},"\u00a9":{"d":"784,-354v0,205,-167,372,-372,372v-205,0,-372,-167,-372,-372v0,-205,167,-372,372,-372v205,0,372,167,372,372xm682,-354v0,-155,-121,-282,-270,-282v-149,0,-270,127,-270,282v0,155,121,282,270,282v149,0,270,-127,270,-282xm540,-198v-122,99,-304,20,-304,-148v0,-120,71,-207,183,-207v41,0,82,13,112,38r-46,66v-73,-53,-140,-23,-140,89v0,131,78,156,146,100","w":824},"\u00a6":{"d":"196,-342r-126,0r0,-414r126,0r0,414xm196,208r-126,0r0,-414r126,0r0,414","w":266},"\u2212":{"d":"527,-223r-487,0r0,-103r487,0r0,103","w":567},"\u00b3":{"d":"336,-386v0,103,-140,161,-279,140r-27,-74v91,24,195,-12,191,-72v-3,-55,-64,-38,-112,-41r0,-81v42,9,108,5,108,-35v0,-19,-11,-33,-41,-33v-37,0,-66,16,-91,36r-54,-64v46,-34,95,-56,155,-56v78,0,140,45,140,109v0,36,-17,64,-47,84v36,18,57,49,57,87","w":366},"\u00b2":{"d":"46,-317v44,-40,165,-154,165,-211v0,-34,-16,-42,-39,-42v-22,0,-45,10,-86,42r-56,-63v52,-44,100,-65,165,-65v77,0,127,49,127,119v0,77,-90,155,-146,205r168,-1r-23,83r-275,0r0,-67","w":374},"\u00b9":{"d":"284,-250r-215,0r0,-81r64,0r0,-208v-21,11,-45,24,-75,34r-28,-56r134,-89r68,0r0,319r52,0r0,81","w":314},"\u00be":{"d":"817,-764r-528,918r-108,0r528,-918r108,0xm895,-315r-1,160v14,-2,29,-1,44,-1r0,85v-15,0,-31,1,-44,-1v2,26,0,58,1,86r-96,11r1,-96r-178,0r0,-63r109,-267r105,0r-84,207v-6,14,-13,27,-19,38r69,0v0,-50,6,-91,11,-141xm336,-386v0,103,-140,161,-279,140r-27,-74v91,24,195,-12,191,-72v-3,-55,-64,-38,-112,-41r0,-81v42,9,108,5,108,-35v0,-19,-11,-33,-41,-33v-37,0,-66,16,-91,36r-54,-64v46,-34,95,-56,155,-56v78,0,140,45,140,109v0,36,-17,64,-47,84v36,18,57,49,57,87","w":968},"\u00bd":{"d":"744,-764r-528,918r-108,0r528,-918r108,0xm586,-67v44,-40,165,-154,165,-211v0,-34,-16,-42,-39,-42v-22,0,-45,10,-86,42r-56,-63v52,-44,100,-65,165,-65v77,0,127,49,127,119v0,77,-90,155,-146,205r168,-1r-23,83r-275,0r0,-67xm284,-250r-215,0r0,-81r64,0r0,-208v-21,11,-45,24,-75,34r-28,-56r134,-89r68,0r0,319r52,0r0,81","w":914},"\u00bc":{"d":"765,-764r-528,918r-108,0r528,-918r108,0xm843,-315r-1,160v14,-2,29,-1,44,-1r0,85v-15,0,-31,1,-44,-1v2,26,0,58,1,86r-96,11r1,-96r-178,0r0,-63r109,-267r105,0r-84,207v-6,14,-13,27,-19,38r69,0v0,-50,6,-91,11,-141xm284,-250r-215,0r0,-81r64,0r0,-208v-21,11,-45,24,-75,34r-28,-56r134,-89r68,0r0,319r52,0r0,81","w":916},"\u00a0":{"w":225},"\u20ac":{"d":"301,-216v25,119,172,161,269,75r34,108v-48,30,-84,45,-163,45v-154,0,-263,-98,-297,-228r-114,0r0,-98r100,0r2,-77r-102,0r0,-98r122,0v38,-129,157,-221,291,-221v69,0,115,17,146,35r-33,115v-89,-76,-233,-31,-252,71r193,0r0,98r-208,0r0,77r208,0r0,98r-196,0","w":624}}});




/* Tipografia */
	Cufon.replace('.n1', { textShadow: '#A62523 1px 1px' });
	Cufon.replace('.titulo');
	Cufon.replace('.pagina-atual', { textShadow: '#DAD9D8 0 2px',color: '-linear-gradient(#B4B4B4, 0.60=#9E9E9E, 0.60=#909090, #909090)' });
	
	/* Slides */
	$(function(){ $('#slide').cycle({ fx:'fade', speed:500, timeout:5000, pager:'#slide-control' }); });
	
	/* Tabs */
	$(function() { $("div.destaques").tabs("div.destaque", { effect: 'fade' }); });
	//$(function() { $("div.tab-servicos").tabs("div.tab-content"); });

	/* Tips */
	$(function(){ 
		$('.tip').ToolTip({ className: 'tip-red', position: 'top' });
		$('ul.servicos a').ToolTip({ className: 'tip-servicos', position: 'top' });
		$('ul.servicosEmpresa a').ToolTip({ className: 'tip-servicos', position: 'top' });
		$('ul.servicosEstado a').ToolTip({ className: 'tip-servicos', position: 'top' });
	});
	
	/* Autocomplete */
	//$(function() { $(".ac").focus().autocomplete(busca); });
	
	/* Banners */
	$(function() { 
		$('div.banners').parent("div.portlet-content").css('width','135px');
	});

	
	function fecharSubMenu(){
		$(".sub-ativo").removeClass("sub-ativo").css("display","none");
		$(".ativo").removeClass("ativo");
	}

	function abrirSubMenu(seta){
		seta.addClass("ativo");
		var submenu = seta.next(".subcategoria");
		$(submenu).css("display","block").addClass("sub-ativo");
	}

function esconderSetaSubMenu(){
	$("ul.subcategoria").prev().css("display","block");
}

function configSubMenu(){
	/* SUB-MENU */
	var timeoutTempo = 2000;
	var timeoutSubMenu;
	$(".submenu")
	.click(function(){
		fecharSubMenu();
		abrirSubMenu($(this))
	})
	.mouseover(function(){
		clearTimeout(timeoutSubMenu);
	})
	.mouseout(function(){
		timeoutSubMenu = setTimeout("fecharSubMenu()", timeoutTempo);
	});

	$(".subcategoria")
	.click(function(){
		fecharSubMenu();
		abrirSubMenu($(this))
	})
	.mouseover(function(){
		clearTimeout(timeoutSubMenu);
	})
	.mouseout(function(){
		timeoutSubMenu = setTimeout("fecharSubMenu()", timeoutTempo);
	});

}

var selControleTab = "span#controle-tab"; 
function iniciarTabulacao(){
	proxTabindex = 0;
}

function controlarTabulacao(){
	
	if(jQuery.browser.msie){
		jQuery(selControleTab).attr("tabindex", 1);
	}else{
		jQuery(selControleTab).attr("tabindex", 0);
	}

	jQuery("body").mousedown(function(){
		iniciarTabulacao();
	});	
	jQuery("div.topo").mousedown(function(){
		iniciarTabulacao();
	});

	jQuery("*").keypress(function(evt){
		executarTabulacao(evt);
	});	
	
}

var proxTabindex = 0;
function executarTabulacao(evt){
	if(proxTabindex == 0){
		var code = evt.keyCode ? evt.keyCode : evt.which;
		if(code == 9){
			jQuery("#irmenu").focus();
			evt.preventDefault();
			proxTabindex = 1;
		}
	}
}

function tabulacoes(){

	//Foca o logo do portal para que a primeira tabula��o funcione
	jQuery("<span id='controle-tab'>controle-tab</span>").insertBefore("#irmenu");
	iniciarTabulacao();
	controlarTabulacao();

	$(".campo_pesquisa").attr("tabindex",11);
	$(".btn_pesquisa").attr("tabindex",12);
//	$("#busca_avancada>a").attr("tabindex",12);
//	$(".rss").attr("tabindex",13);
//	$(".oquee").attr("tabindex",14);
//	$(".enviar-mail").attr("tabindex",15);
//	$("li.redes-sociais > a").attr("tabindex",16);
//	$(".duvidas").attr("tabindex",17);
	$("a.inicial").attr("tabindex",14);
	$("li.conheca a").attr("tabindex",15);
	$("li.invista a").attr("tabindex",16);
	$("li.governo a").attr("tabindex",17);
	$("li.cidadao a").attr("tabindex",18);
	$(".empresa.n1.sub").attr("tabindex",19);
	$(".empresa.n1.sub ~ul a").attr("tabindex",20);
	$(".estado.n1.sub").attr("tabindex",21);
	$(".estado.n1.sub ~ul a").attr("tabindex",22);
	$("li.acesso a").attr("tabindex",23);
//	$(".logo").attr("tabindex",26);	

	$("ul.dropdown>li").mouseenter(function(){
		if($.browser.msie) $("div.conteudo,#DIV_CAMINHO_NAVEGACAO").css("z-index","-1");
	}).mouseleave(function(){
		if($.browser.msie) $("div.conteudo,#DIV_CAMINHO_NAVEGACAO").css("z-index","0");
	});
	$(".conheca").focus(function(){
		$('.conheca ul').css('display', 'block');
		$('.invista ul').css('display', 'none');
	});
	$(".invista").focus(function(){
		$('.invista ul').css('display', 'block');
		$('.conheca ul').css('display', 'none');
		$('.governo ul').css('display', 'none');
	});
	$(".governo").focus(function(){
		$('.invista ul').css('display', 'none');
		$('.governo ul').css('display', 'block');
		$('li>a.cidadao~ul').css('display', 'none');
	});
	
	$("li>a.cidadao").focus(function(){
		$('li>a.cidadao~ul').css('display', 'block');
		$('.governo ul').css('display', 'none');
		$('li>a.empresa~ul').css('display', 'none');
	});
	$("li>a.empresa").focus(function(){
		$('li>a.cidadao~ul').css('display', 'none');
		$('li>a.empresa~ul').css('display', 'block');
		$('li>a.estado~ul').css('display', 'none');
	});
	$("li>a.estado").focus(function(){
		$('li>a.empresa~ul').css('display', 'none');
		$('li>a.estado~ul').css('display', 'block');
		$('.acesso ul').css('display', 'none');
	});
	$(".acesso").focus(function(){
		$('li>a.estado~ul').css('display', 'none');
		$('.acesso ul').css('display', 'block');
	});
	
	$(".logo").focus(function(){
		$('.acesso ul').css('display', 'none');
	});
	
}

/* ABAS DOS SERVICOS MAIS ACESSADOS DA HOME */
function servicoEstado(){

	$("div.servicos-acessados div.tab-content.cidadao").css("display","none");
	$("div.servicos-acessados div.tab-content.empresa").css("display","none");
	$("div.servicos-acessados div.tab-content.estado").css("display","block");
	$("div.tab-servicos a").removeClass("current");
	$("div.tab-servicos a.estado").addClass("current");
}

function servicoEmpresa(){

$("div.servicos-acessados div.tab-content.cidadao").css("display","none");
$("div.servicos-acessados div.tab-content.empresa").css("display","block");
$("div.servicos-acessados div.tab-content.estado").css("display","none");
$("div.tab-servicos a").removeClass("current");
$("div.tab-servicos a.empresa").addClass("current");
}

function servicoCidadao(){

$("div.servicos-acessados div.tab-content.cidadao").css("display","block");
$("div.servicos-acessados div.tab-content.empresa").css("display","none");
$("div.servicos-acessados div.tab-content.estado").css("display","none");
$("div.tab-servicos a").removeClass("current");
$("div.tab-servicos a.cidadao").addClass("current");
}


/* TECLAS DE ATALHO */
function teclasAtalho(){
	

		shortcut.add("alt+shift+0",function() {
			$("#irmenu").focus();
		});
		shortcut.add("alt+shift+1",function() {
			$("#irconteudo").focus();
			jQuery(document).attr("location", jQuery("#irconteudo").attr("href"));
		});
		shortcut.add("alt+shift+2",function() {
			$(".aumentar-fonte").focus();
			$(".aumentar-fonte").click();
		});
		shortcut.add("alt+shift+3",function() {
			$(".diminuir-fonte").focus();
			$(".diminuir-fonte").click();
		});
		shortcut.add("alt+shift+4",function() {
			$(".maior-contraste").focus();
			$(".maior-contraste").click();
		});
		shortcut.add("alt+shift+5",function() {
			$(".menor-contraste").focus();
			$(".menor-contraste").click();
		});
		shortcut.add("alt+shift+6",function() {
			$("#irajuda").focus();
			jQuery(document).attr("location", jQuery("#irajuda").attr("href"))
		});
		shortcut.add("alt+shift+7",function() {
			$("#irmapasite").focus();
			jQuery(document).attr("location", jQuery("#irmapasite").attr("href"))
		}); 
		shortcut.add("alt+shift+8",function() {
			$("a.duvidas").focus();
			jQuery(document).attr("location", jQuery(".duvidas").attr("href"))
		});
		shortcut.add("alt+shift+9",function() {
			$(".campo_pesquisa").focus();
		});

}


/* ALTERNA BANNERS DE UTILIDADES*/
function alternaBanner(){
	try{
		var url = window.location.pathname;
		var banner = "";
		if(url.indexOf("mapa-do-site")!=-1){
		    banner = "banner_mapadosite";
	    }else if(url.indexOf("ajuda")!=-1){
	    	banner = "banner_ajuda";	    	
	    }else if(url.indexOf("aspectos-legais-e-responsabilidades")!=-1){
	    	banner = "banner_aspectos";
	    } else if(url.indexOf("fale-conosco")!=-1){
	    	banner = "banner_faleconosco";   	
	    } else if(url.indexOf("duvidas-frequentes")!=-1){
	    	banner = "banner_faq"; 
	    } else if(url.indexOf("acessibilidade")!=-1){
	    	banner = "banner_acessibilidade";	
	    } else if(url.indexOf("rss")!=-1){
	    	banner = "banner_rss";	
	    }

		
		$("#banner_mapadosite").hide();
		$("#banner_ajuda").hide();
		$("#banner_faleconosco").hide();
		$("#banner_acessibilidade").hide();
		$("#banner_faq").hide();
		$("#banner_rss").hide();
		$('#'+banner).show();
	}
	catch(err){
	}
}

function escondePortlet(){
	$("div.portlet-content:empty").hide();
}

function mostraNoticia(){
	try{
		var url = window.location.pathname;
	//MOSTRA NOTICIA SOMENTE QD TIVER NO TEMPLATE DE EVENTOS.
			if(url.indexOf("5200")!=-1){
				$(".prt-noticia-view-lista").show();	
			} 
		}
		catch(err){
		}	
}

function funcionamentoMapa(){
	$('ul#mapa-unidades a').ToolTip({ className: 'tip-unidades', position: 'top' });
	$('#tooltipURL').css('display','none');
	
	$('ul#mapa-unidades li.und-bh').hover(
		  function(){
		    $('li.und-bh ul').css('display', 'block');
		  }, 
		  function(){
		     $('li.und-bh ul').css('display', 'none');
		  }
		
	);
	// AJUSTES DO HOVER PARA IE6
	$('ul#mapa-unidades li').hover(
		function(){
			$(this).addClass('unidades-hover');
		},
		function(){
			$(this).removeClass('unidades-hover');
		}
	);	
	//AJUSTES DE Z-INDEX IE6/IE7
	var zIndexNumber = 1000;
	$('ul#mapa-unidades li').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
}

function ordenarTaxonomiaNivel1(seletor) {
	var mylist = $(seletor);
	var listitems = mylist.children('li').get();
	listitems.sort(function(a, b) {
	   var compA = $(a).attr('class').toUpperCase();
	   var compB = $(b).attr('class').toUpperCase();
	   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
	})
	$.each(listitems, function(idx, itm) { mylist.append(itm); });
}

function ordenarLista(lista, atributo) {
	atributo = typeof atributo == "undefined" ? "class" : atributo; 
	var itens = lista.split(",");
	for(i = 0; i < itens.length; i++){
		if(itens[i] != ""){
			jqSort.ordenar(itens[i]+' li',atributo);
		}
	}
}

var indextab = 20;
function configuraCssPortalParaTransitional(){
	jQuery("a").each(function(){
		if(jQuery(this).attr("class") != "logo"){
			if(typeof jQuery(this).attr("tabindex") == "undefined" ||
					  jQuery(this).attr("tabindex") == -1 ||
					  jQuery(this).attr("tabindex") == 0){
				jQuery(this).attr("tabindex", indextab++);
			}
		}else{
			if($.browser.msie){
				jQuery(this).attr("tabindex", 1);
			}else{
				jQuery(this).attr("tabindex", 0);
			}
		}
	});
}

$(document).ready(function(){
	tabulacoes();
	configSubMenu();
	esconderSetaSubMenu();
	alternaBanner();
	teclasAtalho();
	mostraNoticia();
	escondePortlet();
	funcionamentoMapa();
});






/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target;
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code).toLowerCase();
			
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown

			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
			
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}



/*
 * jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */;(function($){$.fn.extend({autocomplete:function(urlOrData,options){var isUrl=typeof urlOrData=="string";options=$.extend({},$.Autocompleter.defaults,{url:isUrl?urlOrData:null,data:isUrl?null:urlOrData,delay:isUrl?$.Autocompleter.defaults.delay:10,max:options&&!options.scroll?10:150},options);options.highlight=options.highlight||function(value){return value;};options.formatMatch=options.formatMatch||options.formatItem;return this.each(function(){new $.Autocompleter(this,options);});},result:function(handler){return this.bind("result",handler);},search:function(handler){return this.trigger("search",[handler]);},flushCache:function(){return this.trigger("flushCache");},setOptions:function(options){return this.trigger("setOptions",[options]);},unautocomplete:function(){return this.trigger("unautocomplete");}});$.Autocompleter=function(input,options){var KEY={UP:38,DOWN:40,DEL:46,TAB:9,RETURN:13,ESC:27,COMMA:188,PAGEUP:33,PAGEDOWN:34,BACKSPACE:8};var $input=$(input).attr("autocomplete","off").addClass(options.inputClass);var timeout;var previousValue="";var cache=$.Autocompleter.Cache(options);var hasFocus=0;var lastKeyPressCode;var config={mouseDownOnSelect:false};var select=$.Autocompleter.Select(options,input,selectCurrent,config);var blockSubmit;$.browser.opera&&$(input.form).bind("submit.autocomplete",function(){if(blockSubmit){blockSubmit=false;return false;}});$input.bind(($.browser.opera?"keypress":"keydown")+".autocomplete",function(event){hasFocus=1;lastKeyPressCode=event.keyCode;switch(event.keyCode){case KEY.UP:event.preventDefault();if(select.visible()){select.prev();}else{onChange(0,true);}break;case KEY.DOWN:event.preventDefault();if(select.visible()){select.next();}else{onChange(0,true);}break;case KEY.PAGEUP:event.preventDefault();if(select.visible()){select.pageUp();}else{onChange(0,true);}break;case KEY.PAGEDOWN:event.preventDefault();if(select.visible()){select.pageDown();}else{onChange(0,true);}break;case options.multiple&&$.trim(options.multipleSeparator)==","&&KEY.COMMA:case KEY.TAB:case KEY.RETURN:if(selectCurrent()){event.preventDefault();blockSubmit=true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout=setTimeout(onChange,options.delay);break;}}).focus(function(){hasFocus++;}).blur(function(){hasFocus=0;if(!config.mouseDownOnSelect){hideResults();}}).click(function(){if(hasFocus++>1&&!select.visible()){onChange(0,true);}}).bind("search",function(){var fn=(arguments.length>1)?arguments[1]:null;function findValueCallback(q,data){var result;if(data&&data.length){for(var i=0;i<data.length;i++){if(data[i].result.toLowerCase()==q.toLowerCase()){result=data[i];break;}}}if(typeof fn=="function")fn(result);else $input.trigger("result",result&&[result.data,result.value]);}$.each(trimWords($input.val()),function(i,value){request(value,findValueCallback,findValueCallback);});}).bind("flushCache",function(){cache.flush();}).bind("setOptions",function(){$.extend(options,arguments[1]);if("data"in arguments[1])cache.populate();}).bind("unautocomplete",function(){select.unbind();$input.unbind();$(input.form).unbind(".autocomplete");});function selectCurrent(){var selected=select.selected();if(!selected)return false;var v=selected.result;previousValue=v;if(options.multiple){var words=trimWords($input.val());if(words.length>1){var seperator=options.multipleSeparator.length;var cursorAt=$(input).selection().start;var wordAt,progress=0;$.each(words,function(i,word){progress+=word.length;if(cursorAt<=progress){wordAt=i;return false;}progress+=seperator;});words[wordAt]=v;v=words.join(options.multipleSeparator);}v+=options.multipleSeparator;}$input.val(v);hideResultsNow();$input.trigger("result",[selected.data,selected.value]);return true;}function onChange(crap,skipPrevCheck){if(lastKeyPressCode==KEY.DEL){select.hide();return;}var currentValue=$input.val();if(!skipPrevCheck&&currentValue==previousValue)return;previousValue=currentValue;currentValue=lastWord(currentValue);if(currentValue.length>=options.minChars){$input.addClass(options.loadingClass);if(!options.matchCase)currentValue=currentValue.toLowerCase();request(currentValue,receiveData,hideResultsNow);}else{stopLoading();select.hide();}};function trimWords(value){if(!value)return[""];if(!options.multiple)return[$.trim(value)];return $.map(value.split(options.multipleSeparator),function(word){return $.trim(value).length?$.trim(word):null;});}function lastWord(value){if(!options.multiple)return value;var words=trimWords(value);if(words.length==1)return words[0];var cursorAt=$(input).selection().start;if(cursorAt==value.length){words=trimWords(value)}else{words=trimWords(value.replace(value.substring(cursorAt),""));}return words[words.length-1];}function autoFill(q,sValue){if(options.autoFill&&(lastWord($input.val()).toLowerCase()==q.toLowerCase())&&lastKeyPressCode!=KEY.BACKSPACE){$input.val($input.val()+sValue.substring(lastWord(previousValue).length));$(input).selection(previousValue.length,previousValue.length+sValue.length);}};function hideResults(){clearTimeout(timeout);timeout=setTimeout(hideResultsNow,200);};function hideResultsNow(){var wasVisible=select.visible();select.hide();clearTimeout(timeout);stopLoading();if(options.mustMatch){$input.search(function(result){if(!result){if(options.multiple){var words=trimWords($input.val()).slice(0,-1);$input.val(words.join(options.multipleSeparator)+(words.length?options.multipleSeparator:""));}else{$input.val("");$input.trigger("result",null);}}});}};function receiveData(q,data){if(data&&data.length&&hasFocus){stopLoading();select.display(data,q);autoFill(q,data[0].value);select.show();}else{hideResultsNow();}};function request(term,success,failure){if(!options.matchCase)term=term.toLowerCase();var data=cache.load(term);if(data&&data.length){success(term,data);}else if((typeof options.url=="string")&&(options.url.length>0)){var extraParams={timestamp:+new Date()};$.each(options.extraParams,function(key,param){extraParams[key]=typeof param=="function"?param():param;});$.ajax({mode:"abort",port:"autocomplete"+input.name,dataType:options.dataType,url:options.url,data:$.extend({q:lastWord(term),limit:options.max},extraParams),success:function(data){var parsed=options.parse&&options.parse(data)||parse(data);cache.add(term,parsed);success(term,parsed);}});}else{select.emptyList();failure(term);}};function parse(data){var parsed=[];var rows=data.split("\n");for(var i=0;i<rows.length;i++){var row=$.trim(rows[i]);if(row){row=row.split("|");parsed[parsed.length]={data:row,value:row[0],result:options.formatResult&&options.formatResult(row,row[0])||row[0]};}}return parsed;};function stopLoading(){$input.removeClass(options.loadingClass);};};$.Autocompleter.defaults={inputClass:"ac_input",resultsClass:"ac_results",loadingClass:"ac_loading",minChars:1,delay:400,matchCase:false,matchSubset:true,matchContains:false,cacheLength:10,max:100,mustMatch:false,extraParams:{},selectFirst:true,formatItem:function(row){return row[0];},formatMatch:null,autoFill:false,width:0,multiple:false,multipleSeparator:", ",highlight:function(value,term){return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)("+term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")+")(?![^<>]*>)(?![^&;]+;)","gi"),"<strong>$1</strong>");},scroll:true,scrollHeight:180};$.Autocompleter.Cache=function(options){var data={};var length=0;function matchSubset(s,sub){if(!options.matchCase)s=s.toLowerCase();var i=s.indexOf(sub);if(options.matchContains=="word"){i=s.toLowerCase().search("\\b"+sub.toLowerCase());}if(i==-1)return false;return i==0||options.matchContains;};function add(q,value){if(length>options.cacheLength){flush();}if(!data[q]){length++;}data[q]=value;}function populate(){if(!options.data)return false;var stMatchSets={},nullData=0;if(!options.url)options.cacheLength=1;stMatchSets[""]=[];for(var i=0,ol=options.data.length;i<ol;i++){var rawValue=options.data[i];rawValue=(typeof rawValue=="string")?[rawValue]:rawValue;var value=options.formatMatch(rawValue,i+1,options.data.length);if(value===false)continue;var firstChar=value.charAt(0).toLowerCase();if(!stMatchSets[firstChar])stMatchSets[firstChar]=[];var row={value:value,data:rawValue,result:options.formatResult&&options.formatResult(rawValue)||value};stMatchSets[firstChar].push(row);if(nullData++<options.max){stMatchSets[""].push(row);}};$.each(stMatchSets,function(i,value){options.cacheLength++;add(i,value);});}setTimeout(populate,25);function flush(){data={};length=0;}return{flush:flush,add:add,populate:populate,load:function(q){if(!options.cacheLength||!length)return null;if(!options.url&&options.matchContains){var csub=[];for(var k in data){if(k.length>0){var c=data[k];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub.push(x);}});}}return csub;}else
if(data[q]){return data[q];}else
if(options.matchSubset){for(var i=q.length-1;i>=options.minChars;i--){var c=data[q.substr(0,i)];if(c){var csub=[];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub[csub.length]=x;}});return csub;}}}return null;}};};$.Autocompleter.Select=function(options,input,select,config){var CLASSES={ACTIVE:"ac_over"};var listItems,active=-1,data,term="",needsInit=true,element,list;function init(){if(!needsInit)return;element=$("<div/>").hide().addClass(options.resultsClass).css("position","absolute").appendTo(document.body);list=$("<ul/>").appendTo(element).mouseover(function(event){if(target(event).nodeName&&target(event).nodeName.toUpperCase()=='LI'){active=$("li",list).removeClass(CLASSES.ACTIVE).index(target(event));$(target(event)).addClass(CLASSES.ACTIVE);}}).click(function(event){$(target(event)).addClass(CLASSES.ACTIVE);select();input.focus();return false;}).mousedown(function(){config.mouseDownOnSelect=true;}).mouseup(function(){config.mouseDownOnSelect=false;});if(options.width>0)element.css("width",options.width);needsInit=false;}function target(event){var element=event.target;while(element&&element.tagName!="LI")element=element.parentNode;if(!element)return[];return element;}function moveSelect(step){listItems.slice(active,active+1).removeClass(CLASSES.ACTIVE);movePosition(step);var activeItem=listItems.slice(active,active+1).addClass(CLASSES.ACTIVE);if(options.scroll){var offset=0;listItems.slice(0,active).each(function(){offset+=this.offsetHeight;});if((offset+activeItem[0].offsetHeight-list.scrollTop())>list[0].clientHeight){list.scrollTop(offset+activeItem[0].offsetHeight-list.innerHeight());}else if(offset<list.scrollTop()){list.scrollTop(offset);}}};function movePosition(step){active+=step;if(active<0){active=listItems.size()-1;}else if(active>=listItems.size()){active=0;}}function limitNumberOfItems(available){return options.max&&options.max<available?options.max:available;}function fillList(){list.empty();var max=limitNumberOfItems(data.length);for(var i=0;i<max;i++){if(!data[i])continue;var formatted=options.formatItem(data[i].data,i+1,max,data[i].value,term);if(formatted===false)continue;var li=$("<li/>").html(options.highlight(formatted,term)).addClass(i%2==0?"ac_even":"ac_odd").appendTo(list)[0];$.data(li,"ac_data",data[i]);}listItems=list.find("li");if(options.selectFirst){listItems.slice(0,1).addClass(CLASSES.ACTIVE);active=0;}if($.fn.bgiframe)list.bgiframe();}return{display:function(d,q){init();data=d;term=q;fillList();},next:function(){moveSelect(1);},prev:function(){moveSelect(-1);},pageUp:function(){if(active!=0&&active-8<0){moveSelect(-active);}else{moveSelect(-8);}},pageDown:function(){if(active!=listItems.size()-1&&active+8>listItems.size()){moveSelect(listItems.size()-1-active);}else{moveSelect(8);}},hide:function(){element&&element.hide();listItems&&listItems.removeClass(CLASSES.ACTIVE);active=-1;},visible:function(){return element&&element.is(":visible");},current:function(){return this.visible()&&(listItems.filter("."+CLASSES.ACTIVE)[0]||options.selectFirst&&listItems[0]);},show:function(){var offset=$(input).offset();element.css({width:typeof options.width=="string"||options.width>0?options.width:$(input).width(),top:offset.top+input.offsetHeight,left:offset.left}).show();if(options.scroll){list.scrollTop(0);list.css({maxHeight:options.scrollHeight,overflow:'auto'});if($.browser.msie&&typeof document.body.style.maxHeight==="undefined"){var listHeight=0;listItems.each(function(){listHeight+=this.offsetHeight;});var scrollbarsVisible=listHeight>options.scrollHeight;list.css('height',scrollbarsVisible?options.scrollHeight:listHeight);if(!scrollbarsVisible){listItems.width(list.width()-parseInt(listItems.css("padding-left"))-parseInt(listItems.css("padding-right")));}}}},selected:function(){var selected=listItems&&listItems.filter("."+CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);return selected&&selected.length&&$.data(selected[0],"ac_data");},emptyList:function(){list&&list.empty();},unbind:function(){element&&element.remove();}};};$.fn.selection=function(start,end){if(start!==undefined){return this.each(function(){if(this.createTextRange){var selRange=this.createTextRange();if(end===undefined||start==end){selRange.move("character",start);selRange.select();}else{selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}}else if(this.setSelectionRange){this.setSelectionRange(start,end);}else if(this.selectionStart){this.selectionStart=start;this.selectionEnd=end;}});}var field=this[0];if(field.createTextRange){var range=document.selection.createRange(),orig=field.value,teststring="<->",textLength=range.text.length;range.text=teststring;var caretAt=field.value.indexOf(teststring);field.value=orig;this.selection(caretAt,caretAt+textLength);return{start:caretAt,end:caretAt+textLength}}else if(field.selectionStart!==undefined){return{start:field.selectionStart,end:field.selectionEnd}}};})(jQuery);



/*
 * jquery.tools 1.1.2 - The missing UI library for the Web
 * 
 * [tools.tabs-1.0.4]
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 * 
 * -----
 * 
 * File generated: Wed Oct 07 11:06:47 GMT+00:00 2009
 */
(function(d){d.tools=d.tools||{};d.tools.tabs={version:"1.0.4",conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",api:false,rotate:false},addEffect:function(e,f){c[e]=f}};var c={"default":function(f,e){this.getPanes().hide().eq(f).show();e.call()},fade:function(g,e){var f=this.getConf(),j=f.fadeOutSpeed,h=this.getPanes();if(j){h.fadeOut(j)}else{h.hide()}h.eq(g).fadeIn(f.fadeInSpeed,e)},slide:function(f,e){this.getPanes().slideUp(200);this.getPanes().eq(f).slideDown(400,e)},ajax:function(f,e){this.getPanes().eq(0).load(this.getTabs().eq(f).attr("href"),e)}};var b;d.tools.tabs.addEffect("horizontal",function(f,e){if(!b){b=this.getPanes().eq(0).width()}this.getCurrentPane().animate({width:0},function(){d(this).hide()});this.getPanes().eq(f).animate({width:b},function(){d(this).show();e.call()})});function a(g,h,f){var e=this,j=d(this),i;d.each(f,function(k,l){if(d.isFunction(l)){j.bind(k,l)}});d.extend(this,{click:function(k,n){var o=e.getCurrentPane();var l=g.eq(k);if(typeof k=="string"&&k.replace("#","")){l=g.filter("[href*="+k.replace("#","")+"]");k=Math.max(g.index(l),0)}if(f.rotate){var m=g.length-1;if(k<0){return e.click(m,n)}if(k>m){return e.click(0,n)}}if(!l.length){if(i>=0){return e}k=f.initialIndex;l=g.eq(k)}if(k===i){return e}n=n||d.Event();n.type="onBeforeClick";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}c[f.effect].call(e,k,function(){n.type="onClick";j.trigger(n,[k])});n.type="onStart";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}i=k;g.removeClass(f.current);l.addClass(f.current);return e},getConf:function(){return f},getTabs:function(){return g},getPanes:function(){return h},getCurrentPane:function(){return h.eq(i)},getCurrentTab:function(){return g.eq(i)},getIndex:function(){return i},next:function(){return e.click(i+1)},prev:function(){return e.click(i-1)},bind:function(k,l){j.bind(k,l);return e},onBeforeClick:function(k){return this.bind("onBeforeClick",k)},onClick:function(k){return this.bind("onClick",k)},unbind:function(k){j.unbind(k);return e}});g.each(function(k){d(this).bind(f.event,function(l){e.click(k,l);return false})});if(location.hash){e.click(location.hash)}else{if(f.initialIndex===0||f.initialIndex>0){e.click(f.initialIndex)}}h.find("a[href^=#]").click(function(k){e.click(d(this).attr("href"),k)})}d.fn.tabs=function(i,f){var g=this.eq(typeof f=="number"?f:0).data("tabs");if(g){return g}if(d.isFunction(f)){f={onBeforeClick:f}}var h=d.extend({},d.tools.tabs.conf),e=this.length;f=d.extend(h,f);this.each(function(l){var j=d(this);var k=j.find(f.tabs);if(!k.length){k=j.children()}var m=i.jquery?i:j.children(i);if(!m.length){m=e==1?d(i):j.parent().find(i)}g=new a(k,m,f);j.data("tabs",g)});return f.api?g:this}})(jQuery);




/*
* Copyright (C) 2009 Joel Sutherland
* Licenced under the MIT license
* http://www.newmediacampaigns.com/page/jcaption-a-jquery-plugin-for-simple-image-captions
*/
(function($){$.fn.jcaption=function(settings){settings=$.extend({wrapperElement:'div',wrapperClass:'caption',captionElement:'p',imageAttr:'alt',requireText:true,copyStyle:false,removeStyle:true,removeAlign:true,copyAlignmentToClass:false,copyFloatToClass:true,autoWidth:true,animate:false,show:{opacity:'show'},showDuration:200,hide:{opacity:'hide'},hideDuration:200},settings);$(this).each(function(){$(this).bind('load',function(){if($(this).data('loaded'))return false;$(this).data('loaded',true);var image=$(this);if(image.attr(settings.imageAttr).length>0||!settings.requireText){image.wrap("<"+settings.wrapperElement+" class='"+settings.wrapperClass+"'></"+settings.wrapperElement+">");var imageFloat=image.css('float')
var imageStyle=image.attr('style');if(settings.removeStyle)image.removeAttr('style');var imageAlign=image.attr('align');if(settings.removeAlign)image.removeAttr('align');var div=$(this).parent().append('<'+settings.captionElement+'>'+image.attr(settings.imageAttr)+'</'+settings.captionElement+'>');if(settings.animate){$(this).next().hide();$(this).parent().hover(function(){$(this).find('p').animate(settings.show,settings.showDuration);},function(){$(this).find('p').animate(settings.hide,settings.hideDuration);});}
if(settings.copyStyle)div.attr('style',imageStyle);if(settings.copyAlignmentToClass)div.addClass(imageAlign);if(settings.copyFloatToClass)div.addClass(imageFloat);if(settings.autoWidth)div.width(image.width());}});if(this.complete||this.naturalWidth>0){$(this).trigger('load');}});}})(jQuery);



/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();



/*
 * jQuery Easing v1.1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php
 *
 * Uses the built in easing capabilities added in jQuery 1.1
 * to offer multiple easing options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

jQuery.extend(jQuery.easing, {
	easein: function(x, t, b, c, d) {
		return c*(t/=d)*t + b; // in
	},
	easeinout: function(x, t, b, c, d) {
		if (t < d/2) return 2*c*t*t/(d*d) + b;
		var ts = t - d/2;
		return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;		
	},
	easeout: function(x, t, b, c, d) {
		return -c*t*t/(d*d) + 2*c*t/d + b;
	},
	expoin: function(x, t, b, c, d) {
		var flip = 1;
		if (c < 0) {
			flip *= -1;
			c *= -1;
		}
		return flip * (Math.exp(Math.log(c)/d * t)) + b;		
	},
	expoout: function(x, t, b, c, d) {
		var flip = 1;
		if (c < 0) {
			flip *= -1;
			c *= -1;
		}
		return flip * (-Math.exp(-Math.log(c)/d * (t-d)) + c + 1) + b;
	},
	expoinout: function(x, t, b, c, d) {
		var flip = 1;
		if (c < 0) {
			flip *= -1;
			c *= -1;
		}
		if (t < d/2) return flip * (Math.exp(Math.log(c/2)/(d/2) * t)) + b;
		return flip * (-Math.exp(-2*Math.log(c/2)/d * (t-d)) + c + 1) + b;
	},
	bouncein: function(x, t, b, c, d) {
		return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + b;
	},
	bounceout: function(x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	bounceinout: function(x, t, b, c, d) {
		if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b;
	},
	elasin: function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	elasout: function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	elasinout: function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	backin: function(x, t, b, c, d) {
		var s=1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	backout: function(x, t, b, c, d) {
		var s=1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	backinout: function(x, t, b, c, d) {
		var s=1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	}
});



/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and 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.
 *
 * $LastChangedDate: 2007-10-06 20:11:15 +0200 (Sa, 06 Okt 2007) $
 * $Rev: 3581 $
 *
 * Version: @VERSION
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return num( this, name.toLowerCase() )
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, '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) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

})(jQuery);



/*
 * jQuery UI Accordion 1.6
 * 
 * Copyright (c) 2007 Jörn Zaefferer
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * 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.accordion.js 4876 2008-03-08 11:49:04Z joern.zaefferer $
 *
 */

;(function($) {
	
// If the UI scope is not available, add it
$.ui = $.ui || {};

$.fn.extend({
	accordion: function(options, data) {
		var args = Array.prototype.slice.call(arguments, 1);

		return this.each(function() {
			if (typeof options == "string") {
				var accordion = $.data(this, "ui-accordion");
				accordion[options].apply(accordion, args);
			// INIT with optional options
			} else if (!$(this).is(".ui-accordion"))
				$.data(this, "ui-accordion", new $.ui.accordion(this, options));
		});
	},
	// deprecated, use accordion("activate", index) instead
	activate: function(index) {
		return this.accordion("activate", index);
	}
});

$.ui.accordion = function(container, options) {
	
	// setup configuration
	this.options = options = $.extend({}, $.ui.accordion.defaults, options);
	this.element = container;
	
	$(container).addClass("ui-accordion");
	
	if ( options.navigation ) {
		var current = $(container).find("a").filter(options.navigationFilter);
		if ( current.length ) {
			if ( current.filter(options.header).length ) {
				options.active = current;
			} else {
				options.active = current.parent().parent().prev();
				current.addClass("current");
			}
		}
	}
	
	// calculate active if not specified, using the first header
	options.headers = $(container).find(options.header);
	options.active = findActive(options.headers, options.active);

	if ( options.fillSpace ) {
		var maxHeight = $(container).parent().height();
		options.headers.each(function() {
			maxHeight -= $(this).outerHeight();
		});
		var maxPadding = 0;
		options.headers.next().each(function() {
			maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
		}).height(maxHeight - maxPadding);
	} else if ( options.autoheight ) {
		var maxHeight = 0;
		options.headers.next().each(function() {
			maxHeight = Math.max(maxHeight, $(this).outerHeight());
		}).height(maxHeight);
	}

	options.headers
		.not(options.active || "")
		.next()
		.hide();
	options.active.parent().andSelf().addClass(options.selectedClass);
	
	if (options.event)
		$(container).bind((options.event) + ".ui-accordion", clickHandler);
};

$.ui.accordion.prototype = {
	activate: function(index) {
		// call clickHandler with custom event
		clickHandler.call(this.element, {
			target: findActive( this.options.headers, index )[0]
		});
	},
	
	enable: function() {
		this.options.disabled = false;
	},
	disable: function() {
		this.options.disabled = true;
	},
	destroy: function() {
		this.options.headers.next().css("display", "");
		if ( this.options.fillSpace || this.options.autoheight ) {
			this.options.headers.next().css("height", "");
		}
		$.removeData(this.element, "ui-accordion");
		$(this.element).removeClass("ui-accordion").unbind(".ui-accordion");
	}
}

function scopeCallback(callback, scope) {
	return function() {
		return callback.apply(scope, arguments);
	};
}

function completed(cancel) {
	// if removed while animated data can be empty
	if (!$.data(this, "ui-accordion"))
		return;
	var instance = $.data(this, "ui-accordion");
	var options = instance.options;
	options.running = cancel ? 0 : --options.running;
	if ( options.running )
		return;
	if ( options.clearStyle ) {
		options.toShow.add(options.toHide).css({
			height: "",
			overflow: ""
		});
	}
	$(this).triggerHandler("change.ui-accordion", [options.data], options.change);
}

function toggle(toShow, toHide, data, clickedActive, down) {
	var options = $.data(this, "ui-accordion").options;
	options.toShow = toShow;
	options.toHide = toHide;
	options.data = data;
	var complete = scopeCallback(completed, this);
	
	// count elements to animate
	options.running = toHide.size() == 0 ? toShow.size() : toHide.size();
	
	if ( options.animated ) {
		if ( !options.alwaysOpen && clickedActive ) {
			$.ui.accordion.animations[options.animated]({
				toShow: jQuery([]),
				toHide: toHide,
				complete: complete,
				down: down,
				autoheight: options.autoheight
			});
		} else {
			$.ui.accordion.animations[options.animated]({
				toShow: toShow,
				toHide: toHide,
				complete: complete,
				down: down,
				autoheight: options.autoheight
			});
		}
	} else {
		if ( !options.alwaysOpen && clickedActive ) {
			toShow.toggle();
		} else {
			toHide.hide();
			toShow.show();
		}
		complete(true);
	}
}

function clickHandler(event) {
	var options = $.data(this, "ui-accordion").options;
	if (options.disabled)
		return false;
	
	// called only when using activate(false) to close all parts programmatically
	if ( !event.target && !options.alwaysOpen ) {
		options.active.parent().andSelf().toggleClass(options.selectedClass);
		var toHide = options.active.next(),
			data = {
				instance: this,
				options: options,
				newHeader: jQuery([]),
				oldHeader: options.active,
				newContent: jQuery([]),
				oldContent: toHide
			},
			toShow = options.active = $([]);
		toggle.call(this, toShow, toHide, data );
		return false;
	}
	// get the click target
	var clicked = $(event.target);
	
	// due to the event delegation model, we have to check if one
	// of the parent elements is our actual header, and find that
	if ( clicked.parents(options.header).length )
		while ( !clicked.is(options.header) )
			clicked = clicked.parent();
	
	var clickedActive = clicked[0] == options.active[0];
	
	// if animations are still active, or the active header is the target, ignore click
	if (options.running || (options.alwaysOpen && clickedActive))
		return false;
	if (!clicked.is(options.header))
		return;

	// switch classes
	options.active.parent().andSelf().toggleClass(options.selectedClass);
	if ( !clickedActive ) {
		clicked.parent().andSelf().addClass(options.selectedClass);
	}

	// find elements to show and hide
	var toShow = clicked.next(),
		toHide = options.active.next(),
		//data = [clicked, options.active, toShow, toHide],
		data = {
			instance: this,
			options: options,
			newHeader: clicked,
			oldHeader: options.active,
			newContent: toShow,
			oldContent: toHide
		},
		down = options.headers.index( options.active[0] ) > options.headers.index( clicked[0] );
	
	options.active = clickedActive ? $([]) : clicked;
	toggle.call(this, toShow, toHide, data, clickedActive, down );

	return false;
};

function findActive(headers, selector) {
	return selector != undefined
		? typeof selector == "number"
			? headers.filter(":eq(" + selector + ")")
			: headers.not(headers.not(selector))
		: selector === false
			? $([])
			: headers.filter(":eq(0)");
}

$.extend($.ui.accordion, {
	defaults: {
		selectedClass: "selected",
		alwaysOpen: true,
		animated: 'slide',
		event: "click",
		header: "a",
		autoheight: false,
		running: 0,
		navigationFilter: function() {
			return this.href.toLowerCase() == location.href.toLowerCase();
		}
	},
	animations: {
		slide: function(options, additions) {
			options = $.extend({
				easing: "swing",
				duration: 300
			}, options, additions);
			if ( !options.toHide.size() ) {
				options.toShow.animate({height: "show"}, options);
				return;
			}
			var hideHeight = options.toHide.height(),
				showHeight = options.toShow.height(),
				difference = showHeight / hideHeight;
			options.toShow.css({ height: 0, overflow: 'hidden' }).show();
			options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{
				step: function(now) {
					var current = (hideHeight - now) * difference;
					if ($.browser.msie || $.browser.opera) {
						current = Math.ceil(current);
					}
					options.toShow.height( current );
				},
				duration: options.duration,
				easing: options.easing,
				complete: function() {
					if ( !options.autoheight ) {
						options.toShow.css("height", "auto");
					}
					options.complete();
				}
			});
		},
		bounceslide: function(options) {
			this.slide(options, {
				easing: options.down ? "bounceout" : "swing",
				duration: options.down ? 1000 : 200
			});
		},
		easeslide: function(options) {
			this.slide(options, {
				easing: "easeinout",
				duration: 700
			})
		}
	}
});

})(jQuery);



