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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) )
			return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector );

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

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

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

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

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

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

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

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

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

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

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

		return this;
	},

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

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		var ret = -1;

		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem && elem.jquery ? elem[0] : elem
		, this );
	},

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

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

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

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

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

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

		var ret = "";

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

		return ret;
	},

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

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

					return elem;
				})
				.append(this);

		return this;
	},

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Return the cloned set
		return ret;
	},

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

			jQuery.multiFilter( selector, this ) );
	},

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

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

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

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

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

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

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

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

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

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

						if ( option.selected ) {
							// Get the specifc value for the option
							value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;

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

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

					return values;

				// Everything else, we just grab the value
				} else
					return (this[0].value || "").replace(/\r/g, "");

			}

			return undefined;
		}

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

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

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

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

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

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

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

	html: function( value ) {
		return value == undefined ?
			(this[0] ?
				this[0].innerHTML :
				null) :
			this.empty().append( value );
	},

	replaceWith: function( value ) {
		return this.after( value ).remove();
	},

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

	slice: function() {
		return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
	},

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

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

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

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

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

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

	removeData: function( key ){
		return this.each(function(){
			jQuery.removeData( this, key );
		});
	},

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

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

				if ( reverse )
					elems.reverse();
			}

			var obj = this;

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

			var scripts = jQuery( [] );

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

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

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

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

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

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

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

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

function now(){
	return +new Date;
}

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

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

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

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

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

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

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

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

			}

	// Return the modified object
	return target;
};

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

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

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

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

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

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

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

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

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

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

	cache: {},

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

		var id = elem[ expando ];

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

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

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

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

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

		var id = elem[ expando ];

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

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

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

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

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

			// Completely remove the data cache
			delete jQuery.cache[ id ];
		}
	},

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

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

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

		return object;
	},

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

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

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

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

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

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

		callback.call( elem );

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

	css: function( elem, name, force ) {
		if ( name == "width" || name == "height" ) {
			var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];

			function getWH() {
				val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
				var padding = 0, border = 0;
				jQuery.each( which, function() {
					padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
					border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
				});
				val -= Math.round(padding + border);
			}

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

			return Math.max(0, val);
		}

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

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

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

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

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

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

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

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

		else if ( defaultView.getComputedStyle ) {

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

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

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

			if ( computedStyle && !color( elem ) )
				ret = computedStyle.getPropertyValue( name );

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

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

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

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

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

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

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

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

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

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

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

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

		return ret;
	},

	clean: function( elems, context ) {
		var ret = [];
		context = context || document;
		// !context.createElement fails in IE with an error but returns typeof 'object'
		if (typeof context.createElement == 'undefined')
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

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

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

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

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

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

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

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

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

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

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

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

					[ 0, "", "" ];

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

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

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

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

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

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

					// IE completely kills leading whitespace when innerHTML is used
					if ( /^\s/.test( elem ) )
						div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );

				}

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

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

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

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

		});

		return ret;
	},

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

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

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

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

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

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

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

					elem[ name ] = value;
				}

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

				return elem[ name ];
			}

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

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

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

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

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

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

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

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

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

		if ( set )
			elem[ name ] = value;

		return elem[ name ];
	},

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

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

		if( array != null ){
			var i = array.length;
			//the window, strings and functions also have 'length'
			if( i == null || array.split || array.setInterval || array.call )
				ret[0] = array;
			else
				while( i )
					ret[--i] = array[i];
		}

		return ret;
	},

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

		return -1;
	},

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

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

		return first;
	},

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

		try {

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

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

		} catch( e ) {
			ret = array;
		}

		return ret;
	},

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

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

		return ret;
	},

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

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

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

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

var userAgent = navigator.userAgent.toLowerCase();

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

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

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

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

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

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

		return this.pushStack( jQuery.unique( ret ) );
	};
});

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

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

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

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

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

	toggleClass: function( classNames ) {
		jQuery.className[ jQuery.className.has( this, classNames ) ? "remove" : "add" ]( this, classNames );
	},

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

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

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

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

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

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

			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] :

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

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

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

// Helper function used by the dimensions and offset modules
function num(elem, prop) {
	return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
		"(?:[\\w*_-]|\\\\.)" :
		"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
	quickChild = new RegExp("^>\\s*(" + chars + "+)"),
	quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
	quickClass = new RegExp("^([#.]?)(" + chars + "*)");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return cur;
	},

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

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

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

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

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

			t = jQuery.trim(t);

			var foundToken = false,

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

				m = re.exec(t);

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

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

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

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

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

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

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

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

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

					ret = r;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

							r = tmp;
						}

						ret = r;
					}

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

			}

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

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

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

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

		return done;
	},

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

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

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

			var p = jQuery.parse, m;

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

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

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

			if ( !m )
				break;

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

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

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

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

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

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

				r = tmp;

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

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

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

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

						merge[id] = true;
					}

					var add = false;

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

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

				r = tmp;

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

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

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

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

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

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

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

		return cur;
	},

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

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

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

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

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

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

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

			// Create unique handler function, wrapped around original handler
			handler = this.proxy( fn, function() {
				// Pass arguments and context to original handler
				return fn.apply(this, arguments);
			});

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

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

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		jQuery.each(types.split(/\s+/), function(index, type) {
			// Namespaced event handlers
			var parts = type.split(".");
			type = parts[0];
			handler.type = parts[1];

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

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

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

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

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

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

	guid: 1,
	global: {},

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

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

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

				// Handle multiple events seperated by a space
				// jQuery(...).unbind("mouseover mouseout", fn);
				jQuery.each(types.split(/\s+/), function(index, type){
					// Namespaced event handlers
					var parts = type.split(".");
					type = parts[0];

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

						// remove all handlers for the given type
						else
							for ( handler in events[type] )
								// Handle the removal of namespaced events
								if ( !parts[1] || events[type][handler].type == parts[1] )
									delete events[type][handler];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			this.triggered = false;
		}

		return val;
	},

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

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

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

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

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

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

				ret = handler.apply( this, arguments );

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

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

		return val;
	},

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

		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = { originalEvent: originalEvent };
		var props = "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");
		for ( var i=props.length; i; i-- )
			event[ props[i] ] = originalEvent[ props[i] ];

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

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

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

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

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

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

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

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

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

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

		return event;
	},

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

	special: {
		ready: {
			setup: function() {
				// Make sure the ready event is setup
				bindReady();
				return;
			},

			teardown: function() { return; }
		},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return this;
	}
});

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

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

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

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

var readyBound = false;

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

	// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
	if ( document.addEventListener && !jQuery.browser.opera)
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", jQuery.ready, false );

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

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

	if ( jQuery.browser.safari ) {
		var numStyles;
		(function(){
			if (jQuery.isReady) return;
			if ( document.readyState != "loaded" && document.readyState != "complete" ) {
				setTimeout( arguments.callee, 0 );
				return;
			}
			if ( numStyles === undefined )
				numStyles = jQuery("style, link[rel=stylesheet]").length;
			if ( document.styleSheets.length != numStyles ) {
				setTimeout( arguments.callee, 0 );
				return;
			}
			// and execute any waiting functions
			jQuery.ready();
		})();
	}

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

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

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

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

// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery(window).bind("unload", function() {
	jQuery("*").add(document).unbind();
});
jQuery.fn.extend({
	// Keep a copy of the old load
	_load: jQuery.fn.load,

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

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

		callback = callback || function(){};

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

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

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

		var self = this;

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

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

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

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

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

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

var jsc = now();

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

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

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

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

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

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

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

	ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		timeout: 0,
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		data: null,
		username: null,
		password: null,
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	},

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

	ajax: function( s ) {
		// Extend the settings, but re-extend 's' so that it can be
		// checked again later (in the test suite, specifically)
		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
		var jsonp, jsre = /=\?(&|$)/g, status, data,
			type = s.type.toUpperCase();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			head.appendChild(script);

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

		var requestDone = false;

		// Create the request object; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
		var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

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

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

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

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

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

		// Allow custom headers/mimetypes
		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
			// cleanup active request counter
			s.global && jQuery.active--;
			// close opended socket
			xhr.abort();
			return false;
		}

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

		// Wait for a response to come back
		var onreadystatechange = function(isTimeout){
			// The transfer is complete and the data is available, or the request timed out
			if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;
				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}

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

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

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

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

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

				// Fire the complete handlers
				complete();

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

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

			// Timeout checker
			if ( s.timeout > 0 )
				setTimeout(function(){
					// Check to see if the request is still happening
					if ( xhr ) {
						// Cancel the request
						xhr.abort();

						if( !requestDone )
							onreadystatechange( "timeout" );
					}
				}, s.timeout);
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";
			
		// Allow a pre-filtering function to sanitize the response
		if( filter )
			data = filter( data, type );

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

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

		return data;
	},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return this[ optall.queue === false ? "each" : "queue" ](function(){
			if ( this.nodeType != 1)
				return false;

			var opt = jQuery.extend({}, optall), p,
				hidden = jQuery(this).is(":hidden"), self = this;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return this;
	}

});

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

		type = type || "fx";

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

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

	}
	return q;
};

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

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

		q.shift();

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

jQuery.extend({

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

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

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

		return opt;
	},

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

	timers: [],
	timerId: null,

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

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

});

jQuery.fx.prototype = {

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

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

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

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

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

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

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

		t.elem = this.elem;

		jQuery.timers.push(t);

		if ( jQuery.timerId == null ) {
			jQuery.timerId = setInterval(function(){
				var timers = jQuery.timers;

				for ( var i = 0; i < timers.length; i++ )
					if ( !timers[i]() )
						timers.splice(i--, 1);

				if ( !timers.length ) {
					clearInterval( jQuery.timerId );
					jQuery.timerId = null;
				}
			}, 13);
		}
	},

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

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

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

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

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

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

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

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

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

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

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

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

				// Hide the element if the "hide" operation was done
				if ( this.options.hide )
					this.elem.style.display = "none";

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

			if ( done )
				// Execute the complete function
				this.options.complete.call( this.elem );

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

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

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

		return true;
	}

};

jQuery.extend( jQuery.fx, {
	speeds:{
		slow: 600,
 		fast: 200,
 		// Default speed
 		def: 400
	},
	step: {
		scrollLeft: function(fx){
			fx.elem.scrollLeft = fx.now;
		},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return results;
};


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

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

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

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

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

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

		return results;
	},

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


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

		return val != undefined ?

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

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

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

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

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

});})();


//forms plugin
/*
 * jQuery Form Plugin
 * version: 2.12 (06/07/2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
(function($) {

/*
    Usage Note:  
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });
        
    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.  
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting 
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
   }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data)
            a.push( { name: n, value: options.data[n] } );
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].call(this, data, status, $form);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        
        if ($(':input[@name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        
        var opts = $.extend({}, $.ajaxSettings, options);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

        var cbInvoked = 0;
        var timedOut = 0;
        var operaHack = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }
        
        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                
                if ((!doc || (opts.dataType != 'xml' && !doc.body)) && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */ 
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var $form = this.form;
            $form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    $form.clk_x = e.offsetX;
                    $form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    $form.clk_x = e.pageX - offset.left;
                    $form.clk_y = e.pageY - offset.top;
                } else {
                    $form.clk_x = e.pageX - this.offsetLeft;
                    $form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.select = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').select(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};


})(jQuery);

//scrollTo plugin
(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'y',
		duration:1
	};

	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	$.fn.scrollable = function(){
		return this.map(function(){
			var win = this.parentWindow || this.defaultView,
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		duration = duration || settings.speed || settings.duration;
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(targ) ){
						targ = both( targ );
						break;
					}
					targ = $(targ,this);
				case 'object':
					if( targ.is || targ.style )
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height',
					dim = Dim.toLowerCase();

				if( toff ){
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						attr[key] += targ[dim]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				if( /^\d+$/.test(attr[key]) )
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				if( !i && settings.queue ){
					if( old != attr[key] )
						animate( settings.onAfterFirst );
					delete attr[key];
				}
			});			
			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;
				
				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

jQuery.fn.bgIframe = jQuery.fn.bgiframe = function() {
    // This is only for IE6
    if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function') ) return this;
    var html = '<iframe class="bgiframe" src="javascript:;" tabindex="-1" '
    		    +'style="display:block; position:absolute; '
			+'top: expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)  || 0) * -1) + \'px\'); '
			+'left:expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth) || 0) * -1) + \'px\'); ' 
			+'z-index:-1; filter:Alpha(Opacity=\'0\'); '
			+'width:expression(this.parentNode.offsetWidth + \'px\'); '
			+'height:expression(this.parentNode.offsetHeight + \'px\')"/>';
    return this.each(function() {
	if ( !jQuery('iframe.bgiframe', this)[0] )
	    this.insertBefore( document.createElement(html), this.firstChild );
    });
};

/**
 * jQuery.Preload
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/12/2008
 *
 * @projectDescription Multifunctional preloader
 * @author Ariel Flesler
 * @version 1.0.7
 *
 * @id jQuery.preload
 * @param {String, jQuery, Array< String, <a>, <link>, <img> >} original Collection of sources to preload
 * @param {Object} settings Hash of settings.
 *
 * @id jQuery.fn.preload
 * @param {Object} settings Hash of settings.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example Link Mode:
 *	$.preload( '#images a' );
 *
 * @example Rollover Mode:
 *	$.preload( '#images img', {
 *		find:/\.(gif|jpg)/,
 *		replace:'_over.$1'
 *	});
 *
 * @example Src Mode:
 *	$.preload( [ 'red', 'blue', 'yellow' ], {
 *		base:'images/colors/',
 *		ext:'.jpg'
 *	});
 *
 * @example Placeholder Mode:
 *	$.preload( '#images img', {
 *		placeholder:'placeholder.jpg',
 *		notFound:'notfound.jpg'
 *	});
 *
 * @example Placeholder+Rollover Mode(High res):
 *	$.preload( '#images img', {
 *		placeholder:true,
 *		find:/\.(gif|jpg)/,
 *		replace:'_high.$1'
 *	});
 */
(function( $ ){

	var $preload = $.preload = function( original, settings ){
		if( original.split )//selector
			original = $(original);

		settings = $.extend( {}, $preload.defaults, settings );
		var sources = $.map( original, function( source ){
			if( !source ) 
				return;//skip
			if( source.split )//URL Mode
				return settings.base + source + settings.ext;
			var url = source.src || source.href;//save the original source
			if( typeof settings.placeholder == 'string' && source.src )//Placeholder Mode, if it's an image, set it.
				source.src = settings.placeholder;
			if( url && settings.find )//Rollover mode
				url = url.replace( settings.find, settings.replace );
			return url || null;//skip if empty string
		});

		var data = {
			loaded:0,//how many were loaded successfully
			failed:0,//how many urls failed
			next:0,//which one's the next image to load (index)
			done:0,//how many urls were tried
			//found:false,//whether the last one was successful
			total:sources.length//how many images are being preloaded overall
		};
		
		if( !data.total )//nothing to preload
			return finish();
		
		var imgs = '<img/>',//ensure one
			thres = settings.threshold;//save a copy
		
		while( --thres > 0 )//it could be oddly negative
			imgs += '<img/>';
		imgs = $(imgs).load(handler).error(handler).bind('abort',handler).each(fetch);
		
		function handler( e ){
			data.found = e.type == 'load';
			data.image = this.src;
			var orig = data.original = original[this.index];
			data[data.found?'loaded':'failed']++;
			data.done++;
			if( settings.placeholder && orig.src )//special case when on placeholder mode
				orig.src = data.found ? data.image : settings.notFound || orig.src;
			if( settings.onComplete )
				settings.onComplete( data );
			if( data.done < data.total )//let's continue
				fetch( 0, this );
			else{//we are finished
				if( imgs.unbind )//sometimes IE gets here before finishing line 84
					imgs.unbind('load').unbind('error').unbind('abort');//cleanup
				imgs = null;
				finish();
			}
		};
		function fetch( i, img, retry ){
			if( $.browser.msie && data.next && data.next % $preload.gap == 0 && !retry ){//IE problem, can't preload more than 15
				setTimeout(function(){ fetch( i, img, true ); }, 0);
				return false;
			}
			if( data.next == data.total ) return false;//no more to fetch
			img.index = data.next;//save it, we'll need it.
			img.src = sources[data.next++];
			if( settings.onRequest ){
				data.image = img.src;
				data.original = original[data.next-1];
				settings.onRequest( data );
			}
		};
		function finish(){
			if( settings.onFinish )
				settings.onFinish( data );
		};
	};

	// each time we load this amount and it's IE, we must rest for a while, make it lower if you get stack overflow.
	$preload.gap = 14; 

	$preload.defaults = {
		threshold:2,//how many images to load simultaneously
		base:'',//URL mode: a base url can be specified, it is prepended to all string urls
		ext:'',//URL mode:same as base, but it's appended after the original url.
		replace:''//Rollover mode: replacement (can be left empty)
		/*
		find:null,//Rollover mode: a string or regex for the replacement
		notFound:''//Placeholder Mode: Optional url of an image to use when the original wasn't found
		placeholder:'',//Placeholder Mode: url of an image to set while loading
		onRequest:function( data ){ ... },//callback called every time a new url is requested
		onComplete:function( data ){ ... },//callback called every time a response is received(successful or not)
		onFinish:function( data ){ ... }//callback called after all the images were loaded(or failed)
		*/
	};

	$.fn.preload = function( settings ){
		$preload( this, settings );
		return this;
	};

})( jQuery );
//!!!!



function _uGetOffset(obj){
	if(!obj) return { 'left' : 0, 'top' : 0 };
	var left_offset = obj.offsetLeft;
	var top_offset = obj.offsetTop;
	if(!left_offset && !top_offset && obj.offsetParent==null) {
	left_offset=parseInt(obj.style.left);
	top_offset=parseInt(obj.style.top);
	} else
	while ((obj = obj.offsetParent) != null)
	{
		left_offset += obj.offsetLeft;
		top_offset += obj.offsetTop;
	}

	return { 'left' : left_offset, 'top' : top_offset };
}


function _uMenu(id,par,group) {
    this.init(id,par,group);
}
_uMenu.get=function(id) {
    var o=$('#'+id)[0];
    if(o) return o._umenu;
    return null;
}
_uMenu.show=function(id,par,tp,mid,dy,dx) {
    var o=_uMenu.get(id);
    if(o)o.show_menu(par,tp,mid,dy,dx);
};
_uMenu.hide=function(id,c) {
    var o=_uMenu.get(id);
    if(o) if(!c)o.hide_menu();else o.hide_child();
};
_uMenu.hideAll=function(e) {
//    if (e.which!=1 && e.type == 'click')return;
    var gr;
    with(_uMenu.prototype) {
	for (gr in have_active) {
	    if(have_active[gr] && !donothide[gr]) {
		for (var i in all_menus[gr]) _uMenu.hide(i);
    	    have_active[gr]='';
	    }
	donothide[gr]=false;
	}
    }
};
_uMenu.showOver=function (id,par,tp,mid,dy,dx) {
    var o=_uMenu.get(id);
    if(o) {
	var gr=o.group;
        with(_uMenu.prototype) {
	    if(timerid2[gr]) clearTimeout(timerid2[gr]);
	    if (have_active[gr].length>0 && have_active[gr].indexOf(","+id+",")==-1)
		o.show_menu(par,tp,mid,dy,dx);
	}
    }
};
_uMenu.schedule_hidechild=function(id) {
    var o=_uMenu.get(id);
    if(o) {
	var gr=o.group;
        with(_uMenu.prototype) {
    	if(timerid2[gr]) clearTimeout(timerid2[gr]);
	    timerid2[gr]=setTimeout("_uMenu.hide('"+id+"',1);_uMenu.prototype.timerid2['"+gr+"']=0;",800);
	}
    }
}

_uMenu.prototype={
    donothide: [], //group is first key
    all_menus: [], //group is first key
    have_active: [], //group is first key
    timerid: [], //group is first key
    timerid2: [], //group is first key
    global_set: false,
    init: function (id,par,group){
		this.id=id;
        this.obj=$('#'+id)[0];
        if(!this.obj) return;
        this.obj._umenu=this;
        if(!par) par=id;
        this.parentid=par;
        if(!group) group='def';
        this.group=group;
        this.obj.style.display = 'none';
        $(this.obj).bind("click",this,function(e) {e.data.donothide[e.data.group]=true;});
	if(this.all_menus[group]==undefined) this.all_menus[group]=[];
	if(this.have_active[group]==undefined) this.have_active[group]='';
	this.all_menus[group][id]=this;
	if(!this.global_set) {
	    $(document).bind("click",_uMenu.hideAll);
	    $(window).bind("resize",_uMenu.hideAll);
	    _uMenu.prototype.global_set=true;	
	}
    },
    show_menu: function (par,tp,mid,dy,dx) { 
        var ddX=0;
        var ddY=0;
        if(this.timerid2[this.group]) clearTimeout(this.timerid2[this.group]);
        if(this.have_active[this.group].indexOf(","+this.id+",")>=0) {
                this.hide_menu();
                return;
        }
        if(!dy)dy=0;
        if(!dx)dx=0;
        if(mid){
                ddX=$('#'+mid)[0].offsetLeft;
                ddY=$('#'+mid)[0].offsetTop;
        }
        this.allmenus_hidenp();
        if(!par) par=this.obj.parentNode; else par=$('#'+par)[0];
        var pos=_uGetOffset(par);
        pos['left']+=dx-ddX;
        pos['top']+=dy-ddY;
        if(tp=='r') pos['left']+=par.offsetWidth-4;
    	    else pos['top']+=par.offsetHeight+1; //tp=='d'
        var ww=$(window).width();
        with(this.obj.style) {
    	left=pos['left']+'px';
    	top=pos['top']+'px';
    	display='';
    	visibility='visible';
        };
        try { if(pos['left']+this.obj.offsetWidth>ww) {
                pos['left']=ww-this.obj.offsetWidth-5;
                this.obj.style.left=pos['left']+'px';
                }
        } catch(e) {}
        if(!this.have_active[this.group]) this.have_active[this.group]='';
        this.have_active[this.group]+=','+this.id+',';
        if(this.timerid[this.group]) clearTimeout(this.timerid[this.group]);
        this.donothide[this.group]=true;
        this.timerid[this.group]=setTimeout("with(_uMenu.prototype){donothide['"+this.group+"']=false;timerid['"+this.group+"']=null;};",100);
    },
    allmenus_hidenp: function () {
        var parents={};
        var id=this.id;
        while(this.all_menus[this.group][id] && this.all_menus[this.group][id].parentid!=id && id) {parents[this.all_menus[this.group][id].parentid]=1;id=this.all_menus[this.group][id].parentid;}
        for (var i in this.all_menus[this.group]) {
                if(parents[i]==1) continue;
                this.all_menus[this.group][i].hide_menu();
        }
    },
    hide_menu: function () {
      with(this) {
        hide_child();
        var x=have_active[group].indexOf(","+id+",");
        if(x>=0) have_active[group]=have_active[group].substring(0,x);
        obj.style.display = 'none';
        obj.style.visibility = 'hidden';
      }
    },
    hide_child: function () {
      with(this) {
        for (var i in all_menus[group]) if(all_menus[group][i].parentid==id && i!=id) all_menus[group][i].hide_menu();
      }
    }
};


/*
Each menu item can be in form:
1.  'string' - just string with default action onitem (if it's defined) or without action. in last case item has not hover hightlight by default
2.  'sep' - separator
3.  ['label',action,props]
	def props is {hl:0} if action is not defined
	action can be:
	3.1 'a' - tells that item has <a> tag and item action is to follow href in that tag
	3.2 function - action(item_index,menuobj,id,item_opts,event). if null then global onitem is used. default this parameter is thispar from menu props
	3.3 array - submenu
	props:
		{
		action - 'a' or function if second element was array for creating submenu (to add action to item opening submenu)
		id - item string id which will be sent to action or onitem func in addition to index
		hl  - hover highlight. can be used to overwrite menu property
		thispar - this parameter for action
		mark - if menu has marks enabled specifies the state of mark (false - hidden, true - visible)
		marktext - if mark is visible (mark is true) then specifies html content for mark element (e.g. img tag). can be specified as array (object). then mark true values are used as index to this array. menu.props.withmarks is the default value of this field
		onldown - action for left mouse down
		onrdown - action for right mouse down
		pos - override default pos properties for submenu
		opts - override default properties for submenu
		}
*/

function _uMENU(name,pos,opts,elems,noinit) {
	this.constructor=_uMENU;
	this.name=name;
	this.pos=$.extend({
		pos: null,
		alignObj: null,
		align: 'd',
//r(R) - to the right from object + dx, top edge from object + dy ; R will change horiz pos to l-rules if goes out screen
//l(L) - to the left from object + dx, top edge from object + dy ; L will change horiz pos to r-rules if goes out screen
//d(D) - left (right from rtl) edge from object+dx, to the down from object + dy ; D will change vert pos to u-rules if goes out screen
//u(U) - left (right from rtl) edge from object+dx, to the up from object + dy ; U will change vert pos to d-rules or horiz pos to l-rules if goes out screen
		parent: null,
		dx:0,
		dy:0,
		childdy:0,
		childdx:0
	},pos || {});
	this.props=$.extend({
		parentnode: null, //inherited by child menus
		design: _uMENU.defdesign || 'std',
		hidden: opts.statical && elems && elems.length>0 ? 0 : 1,
		shadow: 1,
		addclass: '', //add this class to class of top menu html object
		withmarks: null, //if true (some object specified) then items of this menu can have marks to the left (u-menumarks is added to top menu object). value of this field is the default marktext
		highlight: 1, //whether hovered items must be highlighted by adding class u-menuitemhl
		statical: opts.horiz ? 1 : 0, //do not hide menu on mouse clicks
		hidetimer: 0, //time in ms to hide menu if no item was hovered
		horiz: 0, //whether menu is horizontal
		noabs: 0, //do not use position:absolute for menu
		width: 0, //0 - width is calculated by content, auto - width is just not assigned (for noabs=1), X - specified value
		onshow: null, //(menuobj,menuidx) called just before menu is shown (can be used to set marks)
		onhide: null,
		ondestroy: null,
		onitem: null, //inherited by child menus, reaction to item click
		onldown: null, //inherited by child menus, reaction to item left mouse down
		onrdown: null, //inherited by child menus, reaction to item right mouse down
		thispar: null, //'this' param for handlers; inherited by child menus
		wnd:null, //inherited by child menus
		rtl:0 //inherited by child menus
	},opts || {});
	this.state={visible:false,init:false,destroyed:false};
    this.design=this.props.design && _uMENU.designs[this.props.design] ? _uMENU.designs[this.props.design] : _uMENU.designs['std'];
    this.idx=_uMENU.nextidx++;
    _uMENU.all[this.idx]=this;
   	if(!this.pos.parent) this.zpos=_uMENU.defz;
   		else this.zpos=this.pos.parent.zpos+5;
    this.xpos=this.ypos=0;
	this.width=10;
	this.height=10;	
	this.elems=[];
	this.add_elems=elems && elems.length>0 ? [elems] : [];
	this.del_elems=[];
	this.pend_show=null;
	this.appendtimer=null;
	this.decor={w:0,h:0};
	this.frame=null;
	this.childtimer=null;
	this.sh=null;
	this.have_active=null;
	this.hidetimer=null;

	var t=document.createElement("div");
	t.id="_umenu"+this.idx;
	if(!this.props.parentnode) $($("body")[0]).prepend(t);
		else this.props.parentnode.appendChild(t);

	this.top=t;
    $(t).addClass("x-unselectable").css({visibility:'hidden',display:'block'});
    var m=document.createElement("div");
    t.appendChild(m);
    this.menu=m;

	if(
//	!this.props.horiz || 
	!this.props.noabs) {
    	$(t).css({position:'absolute',zIndex:this.zpos});
	    if($.browser.msie && parseFloat($.browser.version)<7){
		    var html = '<iframe tabindex="-1" '
    		    +'style="display:block; position:absolute; '
			+'filter:Alpha(Opacity=\'0\'); '
			+'width:'+this.width+'px'
			+'height:'+this.height+'px;border:0"/>';

	    	this.frame=document.createElement(html);
			t.appendChild(this.frame);
	    }
	    if(this.props.shadow && !this.props.horiz && (!$.browser.msie || $.browser.version>6)) {
			this.shadow_init();
			this._resizeSh();
	    }
    	$(m).css({position:"absolute",zIndex:2,left:0});
	}
   	$(m).css("width","50px").bind("mousedown",this,_uMENU._onmenumousedown);

    this.parts=this.design.menu_init(m,this.props.horiz ? 10 : 50,this.props,this.pos.parent);
	if(!_uMENU.globalset) {
		_uMENU.globalset=true;
	    $(document).bind("mousedown",_uMENU.hideallmenus);
	    $(window).bind("resize",_uMENU.hideallmenus);
	}
	this.toinit=[]; //submenus which require init1()
	this.tocalcsize=[]; //submenus which require calcsize()
	this.createsubmenus();

	if(!this.props.hidden) this.show();
	if(!noinit)setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.init1();",10);
}


_uMENU.all=[];
_uMENU.nextidx=0;
_uMENU.lastz=0;
_uMENU.defz=20050;
_uMENU.defdesign='std';
_uMENU.globalset=false;
_uMENU.ignoreclick=null;

_uMENU.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};

_uMENU.designs={
    std: {
	sh_sz: [4,2], //design specific shadow config

	shadow_init: function(top) {
	    var sh=[];
	    for(var i=0;i<3;i++) {
		sh[i]=document.createElement("div");
		top.appendChild(sh[i]);
		$(sh[i]).attr("class","x-sh").css("position","absolute").css("z-index",1);
	    }
	    $(sh[0]).addClass("xsl").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px",top:"0px"}).html('<div class="xstl"><div class="xsml"></div></div>');
	    $(sh[1]).addClass("xsr").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",top:"0px"}).html('<div class="xstr"><div class="xsmr"></div></div>');
	    $(sh[2]).addClass("xsb").css({height:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px"}).html('<div class="xsbl"><div class="xsbr"><div class="xsbc"></div></div></div>');
	    return sh;
	},
	shadow_resize: function(sh,w,h) {
	    $(sh[0]).css({height:(h-this.sh_sz[1])+"px"});
	    $(sh[1]).css({height:(h-this.sh_sz[1])+"px",left:(w-this.sh_sz[1])+"px"});
	    $(sh[2]).css({width:(w+this.sh_sz[0]*2)+"px",top:(h-this.sh_sz[1])+"px"});
	},
	shadow_hide: function(sh) {
	    $(sh[0]).add(sh[1]).add(sh[2]).hide();
	},
	shadow_show: function(sh) {
	    $(sh[0]).add(sh[1]).add(sh[2]).show();
	},
	menu_init: function(menu,inith,props,parent) {
	    var p={};
		if(!props.horiz) {
			$(menu).attr("class","u-menu"+(props.addclass ? ' '+String(props.addclass): '')+(props.withmarks ? ' u-menumarks': ''));
			if($.browser.msie) $(menu).css("overflow","hidden");
		    $(menu).html(
(parent && parent.props.horiz ? '' : '<div class="xw-tl"><div class="xw-tr"><div class="xw-tc xw-tsps"></div></div></div>')
+ '<div class="xw-ml"><div class="xw-mr"><div class="xw-mc"><div class="u-menubody">'
+ '<div class="u-menucont" style="overflow:visible;height:'+inith+'px"></div></div></div></div></div>'
+ '<div class="xw-bl"><div class="xw-br"><div class="xw-bc"><div class="xw-footer"></div></div></div></div>'
		    );
//		    p.upper=$(menu).find(".xw-tl")[0];
//		    p.center=$(wnd).find(".xw-ml")[0];
//	    	$(wnd).find(".xw-mc").bind("mousedown",function(e){e.stopPropagation();});
		} else {
			$(menu).attr("class","u-menuh"+(props.addclass ? ' '+String(props.addclass): '')+(props.withmarks ? ' u-menumarks': '')).css("overflow","hidden");
			$(menu).html('<div class="u-menubody"><div class="u-menucont" style="overflow:hidden;height:'+inith+'px"></div></div>');
		}
	    p.content=$(menu).find(".u-menucont")[0];
		p.elems=[];
		p.marks=[];
		$(menu).find("div,span").andSelf().attr("unselectable","on");
	    return p;
	},
	append_item: function(o,el,hl) {
		var i=o.elems.length,a,txt,act=null,mark,actl,actr;
		act=el[1] || el[2].action || o.props.onitem;
		actl=el[2].onldown || o.props.onldown;
		actr=el[2].onrdown || o.props.onrdown;
		txt=el[0];
		if(el[2].hl!=undefined) hl=el[2].hl;
		if(o.props.withmarks && txt!='sep' && el[2].mark!=undefined) { //if we have to add u-menumark object
			txt='<div class="u-menumark"></div>'+txt;
			mark=1;
		}
		if(act && (act=='a' || el[2].action=='a')) {
			a=document.createElement('a');
			$(a).css('display','block');
		} else a=document.createElement('div');
		if(!o.props.horiz) {
			if(txt=='sep') {
				a.className='u-menuvsep';
			} else {
				a.className='u-menuvitem';
				if(!act || act.constructor!=_uMENU) {
					$(a).html(txt);
					if(hl) $(a).bind("mouseover",{hl:hl,item:-1,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:-1,obj:o},_uMENU._onitemmouseout);
					if(act) $(a).bind("click",{act:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) $(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				} else {
//					$(a).addClass('u-menuvitemparent').html('<div class="u-menuarrow" style="float:right"></div>'+txt);
//					$(a).addClass('u-menuvitemparent').html('<table align="center" style="text-align:left;padding:0;margin:0;botder:0" cellspacing="0" cellpadding="0"><tr><td style="white-space:nowrap">'+txt+'</td><td><div class="u-menuarrow"></div></td></tr></table>');
					$(a).addClass('u-menuvitemparent').html('<div class="u-menuarrow"></div>'+txt);
					$(a).bind("mouseover",{hl:hl,item:i,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:i,obj:o},_uMENU._onitemmouseout);
					$(a).bind("mousedown",{child:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(el[2].action) $(a).bind("click",{act:el[2].action,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) $(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				}
			}
		} else { //horiz
			$(a).css("float","left"); 
			if(txt=='sep') {
				a.className='u-menuhsep';
			} else {
				a.className='u-menuhitem';
				if(!act || act.constructor!=_uMENU) {
					$(a).html(txt);
					if(hl) $(a).bind("mouseover",{hl:hl,item:i,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:i,obj:o},_uMENU._onitemmouseout);
					if(act) $(a).bind("click",{act:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) $(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				} else {
					$(a).addClass('u-menuhitemparent').html(txt);
					$(a).bind("mouseover",{hl:hl,item:i,obj:o},_uMENU._onitemmouseover).bind("mouseout",{hl:hl,item:i,obj:o},_uMENU._onitemmouseout);
					$(a).bind("mousedown",{child:act,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(el[2].action) $(a).bind("click",{act:el[2].action,obj:o,item:i,itemobj:el},_uMENU._onitemclick);
					if(actl || actr) $(a).bind("mousedown",{actl:actl,actr:actr,obj:o,item:i,itemobj:el},_uMENU._onitemmousedown);
				}
			}
		}
		if(hl) $(a).find("*").andSelf().filter('[nodeType=1]').attr("unselectable","on");
		o.elems[i]=el;
		o.parts.elems[i]=a;
		if(mark) o.parts.marks[i]=$(a).find('.u-menumark')[0];
		if(o.props.horiz && (o.props.rtl || window._rtl))
			o.parts.content.insertBefore(a,o.parts.content.firstChild);
			else
			o.parts.content.appendChild(a);
	},
	calc_size: function(o) {
		var w=0,h=0,hm=0,prevm=0;
		if(!o.props.horiz) {
			for(var i=0;i<o.parts.elems.length;i++) {
				w=Math.max(w,Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth));
				hm+=Math.max(prevm,parseInt('0'+$(o.parts.elems[i]).css('margin-top')));
				prevm=parseInt('0'+$(o.parts.elems[i]).css('margin-bottom'));
				h+=o.parts.elems[i].offsetHeight;
			}
			h+=hm+prevm;
		} else {  //horiz
			for(var i=0;i<o.parts.elems.length;i++) {
				w+=Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth);
				h=Math.max(h,o.parts.elems[i].offsetHeight);
			}
		}
		return {w:w,h:h};
	},
	_onitemmouseover: function(e) {
		$(this).addClass("u-menuitemhl");
	},
	_onitemmouseout: function(e) {
		$(this).removeClass("u-menuitemhl");
	}
    }	
};
_uMENU._onitemmouseover=function(e) {
		var d=e.data;
		if(d.hl) d.obj.design._onitemmouseover.apply(this,[e]);
		if(d.obj.hidetimer) clearTimeout(d.obj.hidetimer); d.obj.hidetimer=null;
		if(d.item>=0)if(!d.obj.props.horiz || d.obj.have_active)d.obj.schedule_childopen(d.item);
};
_uMENU._onitemmouseout=function(e) {
		var d=e.data;
		if(d.hl) d.obj.design._onitemmouseout.apply(this,[e]);
		d.obj.reset_childopen();
};
_uMENU._onitemclick=function(e) {
		var d=e.data,act=d.itemobj[1] || d.itemobj[2].action || d.obj.props.onitem;
		if(!d.child && act) {
			if(!d.obj.props.statical)d.obj.hide(true);else d.obj.hidechildren();
			if(act.constructor==Function) {
				act.apply(d.itemobj[2].thispar || d.obj.props.thispar,[d.item,d.obj,d.itemobj[2].id,d.itemobj[2],e]);
			} 
			else if(act=='a') {
				var l=null;
			    if(this==e.target || e.target.tagName.toLowerCase()!='a') {
					if(this!=e.target) { //check that we do not have tag-A parent
						var c1=$(e.target).find('*').andSelf(),c2=$(this).find('*').not(c1);
						if(c2.filter("A").length==0) l=$(this).find("a")[0];
							else l=null;
					} else l=$(this).find("a")[0];
					if(l) {
						this.target=l.target;
						this.href=l.href;
						if(l.onclick) return l.onclick();
					}
				}
				if(!l){
					this.removeAttribute('href');
				}
			}
			return;
		}
		if(!d.child) return;
		_uMENU.ignoreclick=d.child;
		d.obj.reset_childopen();
		d.obj.hidechildren(d.child);
		if(d.child.state.visible) d.child.hide();
			else d.obj.childopen(d.item,d.itemobj[2]);
};
_uMENU._onitemmousedown=function(e) {
		var d=e.data,actl=d.actl || d.obj.props.onldown,actr=d.actr || d.obj.props.onrdown;
		if(e.which==1 && e.ctrlKey) e.which=3;
		if(e.which==1 && actl) {
			_uWnd.globalmousedown();
			actl.apply(d.itemobj[2].thispar || d.obj.props.thispar,[d.item,d.obj,d.itemobj[2].id,d.itemobj[2],e]);
			e.stopPropagation();
		} else if(e.which==3 && actr) {
			actr.apply(d.itemobj[2].thispar || d.obj.props.thispar,[d.item,d.obj,d.itemobj[2].id,d.itemobj[2],e]);
			_uWnd.globalmousedown();
			e.preventDefault();
			e.stopPropagation();
		}
};
//hides all non-statical menus which are visible except for 'exc' and its parents
_uMENU.hideallmenus=function() { //optional exception
	var i,m,ig;
loop:
	for(i=0;i<_uMENU.all.length;i++) {
		m=_uMENU.all[i];
		if(!m || !m.state.visible || m.props.statical) continue;
		ig=_uMENU.ignoreclick;
		while(ig) {
			if(ig==m) continue loop;
			ig=ig.pos.parent;
		}
		m.hide();
	}
	if(_uMENU.ignoreclick)setTimeout("_uMENU.ignoreclick=null;",10);
};
_uMENU._onmenumousedown=function(e) {
	if(!_uMENU.ignoreclick)_uMENU.ignoreclick=e.data;
//	e.stopPropagation();
};
_uMENU.prototype={
	shadow_init:function() {
    	this.sh=this.design.shadow_init(this.top);
	},
	_resizeSh:function() {
	    if(this.sh)this.design.shadow_resize(this.sh,this.width,this.height);
	},
	moveTo:function(x,y) {
		with(this) {
			$(top).css("left",x+'px').css("top",y+'px');
		    xpos=x;
    		ypos=y;
  		}
	},
	resizeTo:function(w,h) {
		with(this) {
			if(props.width==0) $(menu).css("width",w+'px');
				else if(props.width!='auto') $(menu).css("width",props.width);
				else $(menu).css("width",'auto');
			if(props.horiz) {
				$(menu).css("height",h+'px');
	    		$(parts.content).css("width",(w-decor.w)+'px').css("height",(h-decor.h)+'px');
			} else {
//			    $(menu).css("width",w+'px');//.css("height",h+'px');
    			$(parts.content).css("width",(w-decor.w)+'px');//.css("height",(h-decor.h)+'px');
			}
//   		$(parts.upper).css("width",w+'px');
//    		$(parts.upper.firstChild.firstChild).css("width",w+'px');
		    if(frame) $(frame).css("width",w+'px').css("height",h+'px');
		    width=w;
		    height=h;
		    _resizeSh();
		}
	},
	init1: function(nocalcsize) {
		with(this) {
    		decor.w=50-parts.content.offsetWidth;
    		decor.h=menu.offsetHeight-(props.horiz ? 10 : 50);
			state.init=true;
//alert('in init of '+this.idx);
			_initsubmenus();
			if(add_elems)appendItems(null,0,nocalcsize); 
				else {
				if(pend_show)show(pend_show);
//				if(oninit && props.wnd)oninit.apply(props.wnd);
				}
  		}
	},
	show: function(pos) {
		if(this.state.destroyed) return;
		if(!this.state.init){this.pend_show=pos || {};return;}
		this.pend_show=null;
		this.pos=$.extend(this.pos,pos || {});
	    if(!this.pos.parent) this.zpos=_uMENU.defz;
    		else this.zpos=this.pos.parent.zpos+5;
		$(this.top).css("z-index",this.zpos);
		if(this.pos.pos || this.pos.alignObj) {
			var a,pos,ow,oh;
//			this.moveTo(this.pos.pos.x,this.pos.pos.y);
			if(this.pos.alignObj) {
				a=this.pos.alignObj;
				pos=$(a).offset();
				ow=a.offsetWidth;
				oh=a.offsetHeight;
			} else {
				pos={left:this.pos.pos.x,top:this.pos.pos.y};
				ow=oh=0;
			}
		        var ppos,x,y,
		        	d=_uWnd.getdims(),ww=d.clientW,wh=d.clientH,wl=d.clientLeft,wt=d.clientTop,
		        	al=this.pos.align || 'd';
				if(this.props.wnd && this.props.wnd.desktop) {
					d=this.props.wnd.desktop;
					ww=d.width;
					wh=d.height;
					wl=0;
					wt=0;
				}
				if(this.props.rtl || window._rtl) x=pos.left+ow+this.pos.dx-this.width;
					else
					x=pos.left+this.pos.dx;
				y=pos.top+this.pos.dy;

				if(al=='r' || al=='R') x=pos.left+ow+this.pos.dx;
					else if(al=='l' || al=='L') x=pos.left-this.width+this.pos.dx;
					else if(al=='d' || al=='D') y=pos.top+oh+this.pos.dy;
					else if(al=='u' || al=='U') y=pos.top-this.height+this.pos.dy;
				if(x-wl+this.width>ww-3-this.design.sh_sz[0] || x-wl<1)
					if(al=='R' || al=='U') x=pos.left-this.width-this.pos.dx;
						else if(al=='L') x=pos.left+ow-this.pos.dx;
				if(x-wl+this.width>ww-3) x=ww-3-this.design.sh_sz[0]-this.width+wl;
				if(x-wl<1) x=1+wl;

				if(y-wt+this.height>wh-3-this.design.sh_sz[1] || y-wt<1)
					if(al=='D') y=pos.top-this.height-this.pos.dy;
						else if(al=='U') y=pos.top+oh-this.pos.dy;
				if(y-wt+this.height>wh-3) y=wh-3-this.design.sh_sz[1]-this.height+wt;
				if(y-wt<1) y=1+wt;

		        if(this.props.parentnode){
		        	ppos=$(this.props.parentnode).offset();
		        	x-=ppos.left;
		        	y-=ppos.top;
		        }
        		this.moveTo(x,y);
			}
    	if(this.props.onshow) this.props.onshow.apply(this.props.thispar,[this,this.idx]);
		//check marks
		if(this.props.withmarks) {
			for(var i=0;i<this.elems.length;i++) {
				var c=this.elems[i];
				if(c && c[2] && this.parts.marks[i]) {
					if(!c[2].mark) this.parts.marks[i].style.display='none';
						else {
							var m=c[2].marktext || this.props.withmarks;
							if(typeof m=='object' && m.constructr!=String) m=m[c[2].mark];
							this.parts.marks[i].innerHTML=String(m);
							this.parts.marks[i].style.display='block';
						}
				}
			}
		}

		$(this.top).show();
		this.state.visible=true;
		if(this.pos.parent) this.pos.parent.have_active=this;
		if(this.props.hidetimer>0) this.hidetimer=setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.hide();",this.props.hidetimer);
	},
	hidechildren: function(except) {
		if(this.state.destroyed) return;
		var e=this.elems;
		for(var i=0;i<e.length;i++)
			if(e[i] && e[i].constructor==Array && e[i][1] && e[i][1].constructor==_uMENU) if(e[i][1]!=except) e[i][1].hide();
	},
	hide: function(withpar) {
		if(this.state.destroyed) return;
		if(!this.state.visible) return;
		$(this.top).hide();
		this.state.visible=false;
		if(this.hidetimer) clearTimeout(this.hidetimer); this.hidetimer=null;

		this.pend_show=null;
		this.hidechildren();
		if(this.pos.parent && this.pos.parent.have_active==this) this.pos.parent.have_active=null;
    	if(this.props.onhide) this.props.onhide.apply(this.props.thispar,[this,this.idx]);

		if(withpar) { //hide all non-statical parents
			var p=this.pos.parent;
			while(p && !p.props.statical && p!=this) {p.hide(false);p=p.pos.parent;}
		} 
	},
	childopen: function(i) {
		if(this.state.destroyed) return;
		if(this.childtimer) clearTimeout(this.childtimer);
		this.childtimer=null;
		var h=this.parts.elems[i];
		var c=this.elems[i];
		if(!c) return;
		c=c[1];
		if(!c || c.constructor!=_uMENU) {
			if(this.props.horiz) {this.hidechildren(c);this.have_active=this;}
			return;
		}
		this.hidechildren(c);
		c.show({dx:(this.props.horiz ? 0 : -3 * (this.props.rtl || window._rtl ? -1 : 1)),alignObj:h,align:(this.props.horiz ? 'D' : (this.props.rtl || window._rtl ? 'L' : 'R')),parent:this});
	},
	schedule_childopen: function(i) {
		if(this.state.destroyed) return;
		if(this.childtimer) clearTimeout(this.childtimer);
		this.childtimer=setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.childopen("+i+");",100);
	},
	reset_childopen: function() {
		if(this.childtimer) clearTimeout(this.childtimer);
	},
	_initsubmenus: function() {
	  with(this) {
		for(var i=0;i<toinit.length;i++) {toinit[i].init1(true);tocalcsize[tocalcsize.length]=toinit[i];}
		toinit.length=0;
	  }
	},
	_calcsizesubmenus: function() {
	  with(this) {
		for(var i=0;i<tocalcsize.length;i++) tocalcsize[i]._setsize();
		tocalcsize.length=0;
	  }
	},
	createsubmenus: function() {
		var i,was=false;
		for(i=0;i<this.add_elems.length;i++) {
			var el=this.add_elems[i];
			var n=el.length;
			for(var j=0;j<n;j++) {
				if(el[j] && el[j].constructor==Array && el[j][1] && el[j][1].constructor==Array) { //create submenu
					var o={},pos,opts,s;
					if(el[j][2] && (typeof el[j][2])=='object') o=el[j][2];
						else if((typeof el[j][2])=='number') o={hl:el[j][2]};
						else if((typeof el[j][2])=='string') o={id:el[j][2]};
					el[j][2]=o;
					pos=$.extend({
						parent:this,
						dx:this.props.horiz ? this.pos.childdx : 0,
						dy:this.props.horiz ? this.pos.childdy : 0
						},o.pos || {});
					opts=$.extend({
						shadow:this.props.shadow,
						rtl:this.props.rtl ? 1 : 0,
						parentnode:this.props.wnd ? this.props.wnd.top : this.props.parentnode,
						wnd:this.props.wnd,
						onitem: this.props.onitem,
						thispar: this.props.thispar
						},o.opts || {});
					s=new _uMENU('',pos,opts,el[j][1],true);
					el[j][1]=s;
					this.toinit[this.toinit.length]=s;
					was=true;
				}
			}
		}
		return was;
	},
	indexById: function(id) { //find index by string id
		id=String(id);
		for(var i=0;i<this.elems.length;i++)
			if(this.elems[i][2].id==id) return i;
		return -1;
	},
	removeItems: function(idx,nodestroy,norecalc) {
		var i,p,e;
		if(idx==undefined || idx==null) { //remove all
			idx=[];
			for(i=0;i<this.elems.length;i++)idx[i]=this.elems.length-1-i;
		} else if(idx.constructor!=Array) idx=[idx];
		for(i=0;i<idx.length;i++)
			if(idx[i]==undefined || idx[i]==null || idx[i].constructor!=Number) idx[i]=this.indexById(idx[i]);
		idx.sort(function(a,b){return b-a;});
		p=-1;
		for(i=0;i<idx.length;i++) {
			if(idx[i]==p || idx[i]<0 || idx[i]>=this.elems.length) continue;
			e=this.elems[idx[i]];
			if(!nodestroy && e && e.constructor==Array && e[1] && e[1].constructor==_uMENU) e[1].destroy();
			this.elems.splice(idx[i],1);
			this.parts.elems[idx[i]].parentNode.removeChild(this.parts.elems[idx[i]]);
			this.parts.elems.splice(idx[i],1);
			p=idx[i];
		}
		if(!norecalc) this.appendItems(null,0);
	},	
	appendItems: function(el,idx,nocalcsize) {
		if(this.state.destroyed) return;
		if(el && el.constructor==Array && el.length>0)this.add_elems[this.add_elems.length]=el;
		if(!this.state.init)return;
//alert('in appendItems of '+this.idx);
		if(this.createsubmenus()) { //
			setTimeout("var m=_uMENU.all["+this.idx+"];if(m){m._initsubmenus();m.appendItems(null,0,"+nocalcsize+");}",10);
			return;
		}

		if(this.appendtimer)clearTimeout(this.appendtimer);
		this.appendtimer=null;
   		$(this.top).css("visibility",'hidden').css("display",'block');
		if(this.props.horiz) {
			if(!this.props.noabs) $(this.menu).css("width","2100px").css("height","auto");
				else $(this.menu).css("width",this.props.width==0 ? "auto" : this.props.width=='auto' ? 'auto' : this.props.width+"px");
   			$(this.parts.content).css("width","2000px").css("height","auto");
   		} else {
	   		$(this.menu).css("width","auto").css("height","auto");
   			$(this.parts.content).css("width",$.browser.msie ? "50px" : "auto").css("height","auto");
   		}
		var i;
		for(i=0;i<this.add_elems.length;i++) {
			el=this.add_elems[i];
			var n=el.length;
			for(var j=0;j<n;j++) {
				if(!el[j] || el[j].constructor!=Array) el[j]=[''+el[j]];
				var o={};
				if(el[j][2] && (typeof el[j][2])=='object') o=el[j][2];
					else if((typeof el[j][2])=='number') o={hl:el[j][2]};
					else if((typeof el[j][2])=='string') o={id:el[j][2]};
				el[j][2]=o;
				this.design.append_item(this,el[j],this.props.highlight);
			}
		}
		this.add_elems.splice(0,i);
//		if(onfinish && this.props.wnd)this.onsetsize=onfinish;
		if(!nocalcsize)this.appendtimer=setTimeout("var m=_uMENU.all["+this.idx+"];if(m){m.appendtimer=null;m._setsize();}",10);
	},
	_setsize: function() {
		var d=this.design.calc_size(this);
		this.resizeTo(d.w+this.decor.w,d.h+this.decor.h);

//alert('in setsize of '+this.idx);
		this._calcsizesubmenus();

   		$(this.top).css("display",'none').css("visibility",'visible');
		if(this.pend_show || this.state.visible)this.show(this.pend_show);
//	alert('setsize');
		if(this.onsetsize) {
			var a=this.onsetsize;
			this.onsetsize=null;
			if(this.props.wnd)a.apply(this.props.wnd);
		}
	},
	destroy: function() {
		if(this.state.destroyed) return;
	    this.top.parentNode.removeChild(this.top);
	    _uMENU.all[this.idx]=null;
	    this.state.destroyed=true;
    	if(this.props.ondestroy) this.props.ondestroy.apply(this.props.thispar,[this,this.idx]);
	}
};
//vals - [[val1,icon1,issel1,text11,text12,...],[val2,icon2,issel2,text21,text22,...]] 
//cols - number of text columns (0 if valX is used as displayed text), place for icons is reserved always
function _uComboBox(name,inputId,opts,cols,vals) {
	this.constructor=_uComboBox;
	this.name=name;
	this.obj=document.getElementById(inputId);
	if(!this.obj) return null;
	this.props=$.extend({
//		parentnode: null, //parent node for drop-down list
		design: 'std',
		readonly: false,
		noicons: -1,
		deficon: null,
//		width: 'auto',
//		height: 'auto',
		maxlistheight: 'auto',
		colwidth: null,
//		hidden: 0,
//		onshow: null,
//		onhide: null,
//		ondestroy: null,
		onchange: null,
//		wnd:null,
		rtl:0
	},opts || {});
	this.textvals=cols > 0 ? cols : 0;
	this.tablecols=cols<=0 ? 1 : cols;
	this.colwidth=this.props.colwidth || [];
	this.destroyed=false;
    this.design=this.props.design && _uComboBox.designs[this.props.design] ? _uComboBox.designs[this.props.design] : _uComboBox.designs['std'];
    this.idx=_uComboBox.nextidx++;
    _uComboBox.all[this.idx]=this;
//    if(this.props.width=='auto') {
//    	this.width=this.obj.offsetWidth || parseInt(this.obj.style.width);
//    	if(!this.width>0) this.width=100;
//    } else this.width=this.props.width;
//    if(this.props.height=='auto') {
//    	this.height=this.obj.offsetHeight || parseInt(this.obj.style.height);
//    	if(!this.height>0) this.height=100;
//    } else this.height=this.props.height;
//	this.zpos=this.props.wnd ? 5 : _uComboBox.defz;
	this.data=vals || [];
	var defIdx=-1;
	for(var i=0;i<this.data.length;i++) if(this.data[i][2]) {defIdx=i;break;}
	this.userInput=this.prevInput=this.obj.value; 
	if(this.props.readonly) {
		this.obj.readOnly=true;
		this.valobj=$('<input type="hidden" name="'+this.obj.name+'" value="">')[0];
		this.obj.removeAttribute('name');
		if(this.obj.form) this.obj.form.appendChild(this.valobj);
		if(defIdx<0 || defIdx>=this.data.length) defIdx=0;
	} else {
		this.obj.readOnly=false;
		this.valobj=this.obj; //object which holds form value
		if(defIdx<0 || defIdx>=this.data.length) defIdx=-1;
	}
	this.selected=this.userIdx=defIdx;
	this.changetimer=null;


	this.haveicons=this.props.noicons>0;
	if(this.props.noicons<0) for(var i=0;i<this.data.length;i++) if(this.data[i][1]) {this.haveicons=true;break;}


	this.frame=null;
	this.opened=false;
	this.updated=true;
	this.showtimer=null;
	this.blurtimer=null;
	this.cancelblur=false;
//	var c=document.createElement("div");
//	c.id="_ucombo"+this.idx;
//	this.obj.parentNode.insertBefore(c,this.obj);
	this.combo=null;

	var t=document.createElement("div");
	t.id="_ucombolist"+this.idx;
//	this.combo.appendChild(t);
//	if(!this.props.parentnode) $($("body")[0]).prepend(t);
//		else this.props.parentnode.appendChild(t);
	this.toplist=t;

   	$(t).css({position:'absolute',zIndex:5,display:'none'});//zIndex:this.zpos,
    if($.browser.msie && parseFloat($.browser.version)<7){
		    var html = '<iframe tabindex="-1" '
    		    +'style="display:block; position:absolute; '
			+'filter:Alpha(Opacity=\'0\'); '
			+'width:1px;height:1px;border:0"/>';

	    	this.frame=document.createElement(html);
			t.appendChild(this.frame);
	}

    this.parts=this.design.combo_init(this);

    $(this.obj).attr("autocomplete", "off")
	.bind("focus",this,_uComboBox._onobjfocus)
	.bind("blur",this,_uComboBox._onobjblur)
	.bind("beforedeactivate",this,_uComboBox._onobjdeact)
	.bind("keydown",this,function(e) {return e.data.onkeydown(e);})
	.bind("keyup",this,function(e) {return e.data.onkeyup(e);});

	$(this.combo).bind("mousedown",this,_uComboBox._oncombomousedown);
	$(this.toplist).bind("mousedown",this,_uComboBox._onlistmousedown);
    for(var i=0;i<this.data.length;i++) this.appendItem(this.data[i]);
	if(!_uComboBox.globalset) {
		_uComboBox.globalset=true;
	    $(document).bind("mousedown",_uComboBox.hideall);
	    $(window).bind("resize",_uComboBox.hideall);
	}
	if(defIdx>=0) this.select(defIdx,false,true);
//	setTimeout("var m=_uComboBox.all["+this.idx+"];if(m)m.showlist();",10);
//	this.showlist();
//	if(!this.props.hidden) this.show();
//	if(!noinit)setTimeout("var m=_uMENU.all["+this.idx+"];if(m)m.init1();",10);
}


_uComboBox.all=[];
_uComboBox.nextidx=0;
_uComboBox.defz=20015;
_uComboBox.globalset=false;
_uComboBox.ignoreclick=null;

_uComboBox.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uComboBox.hideall=function() {
    var a=_uComboBox.all;
    for(var i=0;i<a.length;i++) if(a[i] && !a[i].destroyed && _uComboBox.ignoreclick!=a[i]) a[i].hidelist();
	if(_uComboBox.ignoreclick)setTimeout("_uComboBox.ignoreclick=null;",10);
};
_uComboBox.designs={
    std: {
	combo_init: function(o) {
	    var p={};
		o.combo=$('<table id="_ucombo'+o.idx+'" style="position:relative" cellspacing="0" cellpadding="0" border="0" class="x-unselectable u-combo" align="left">'
				+'<tr><td class="u-comboeditcell"></td><td class="u-combobutcell"><div class="u-combobut"></td></tr>'
				+'</table>')[0];
		o.obj.parentNode.insertBefore(o.combo,o.obj);
		o.obj.parentNode.insertBefore(o.toplist,o.obj);
//		$(o.combo).attr("class","x-unselectable u-combo").css({position:'relative'}).prepend('<img border="0" class="u-combobut" src="http://src.ucoz.net/img/1px.gif">');
		p.editcell=$(o.combo).find(".u-comboeditcell")[0];
		p.button=$(o.combo).find(".u-combobut")[0];
		p.butcell=$(o.combo).find(".u-combobutcell")[0];
		p.editcell.appendChild(o.obj);
		$(o.obj).attr("class","x-selectable u-comboedit"+(o.haveicons ? " u-comboeditimg" : "")+" "+$(o.obj).attr("class"));
//		if($.browser.msie) $(o.obj).css({marginTop:'-1px',marginBottom:'-1px'});

	    $(o.toplist).append('<div class="u-combolist"><div style="zoom:1"><table border="0" cellspacing="0" class="x-unselectable u-combocont" width="100%"></table></div></div>');
		p.list=$(o.toplist).find(".u-combolist")[0];
		p.content=$(o.toplist).find(".u-combocont")[0];

		if(!o.props.readonly) $(p.button).bind("mousedown",o,_uComboBox._onbutclick);
			else {
				$(o.obj).bind("mousedown",function(e){e.preventDefault();return 0;});
			}
		$(p.button).bind("mouseover",o.design._onbutmouseover).bind("mouseout",o.design._onbutmouseout);

		p.items=[];
		$(o.toplist).find("div,span,table").andSelf().attr("unselectable","on");
	    return p;
	},
	append_item: function(o,el) {
		var row,cell,t=o.parts.content,i=t.rows.length,txt;
		row=o.parts.items[i]=t.insertRow(i);
		$(row).attr("class","u-comborow").bind("mouseover",{item:i,obj:o},_uComboBox._onitemmouseover).bind("mouseout",{item:i,obj:o},_uComboBox._onitemmouseout)
			.bind("click",{obj:o,item:i},_uComboBox._onitemclick);
		for(var j=0;j<o.tablecols;j++) {
			cell=row.insertCell(j);
			txt= j+3<o.data[i].length ? o.data[i][j+3] : (j==0 ? o.data[i][0] : '&nbsp;');
			if(j==0 && o.data[i][1]) txt='<img class="u-comborowicon" border="0" src="'+o.data[i][1]+'">'+txt;
			$(cell).attr("class","u-combocell"+j).html(txt);
			if(o.colwidth[j]) $(cell).attr("width",o.colwidth[j]);
		}
		$(row).find("*").andSelf().attr("unselectable","on");
	},
	calc_size: function(o) {
		var w=0,h=0;
		if(!o.props.horiz) {
			for(var i=0;i<o.parts.elems.length;i++) {
				w=Math.max(w,Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth));
				h+=o.parts.elems[i].offsetHeight;
			}
		} else {  //horiz
			for(var i=0;i<o.parts.elems.length;i++) {
				w+=Math.max(o.parts.elems[i].offsetWidth,o.parts.elems[i].scrollWidth);
				h=Math.max(h,o.parts.elems[i].offsetHeight);
			}
		}
		return {w:w,h:h};
	},
	_onitemmouseover: function(e) {
		$(this).addClass("u-comborowhl");
	},
	_onitemmouseout: function(e) {
		$(this).removeClass("u-comborowhl");
	},
	_onbutmouseover: function() {
		$(this).addClass("u-combobuthl");
	},
	_onbutmouseout: function() {
		$(this).removeClass("u-combobuthl");
	},
	_onlistopen: function(o) {
		$(o.combo).addClass("u-comboopen");
	},
	_onlisthide: function(o) {
		$(o.combo).removeClass("u-comboopen");
	},
	_onfocus: function(o,e) {
		$(o.combo).addClass("u-combofocus");
	},
	_onblur: function(o,e) {
		$(o.combo).removeClass("u-combofocus");
	},
	_select: function(o,i) {
		$(o.parts.items[i]).addClass("u-comborowsel");
	},
	_deselect: function(o,i) {
		$(o.parts.items[i]).removeClass("u-comborowsel");
	},
	seticon: function(o,icon) {
		if(icon) $(o.obj).css("background-image","url("+icon+")");
			else $(o.obj).css("background-image",o.props.deficon ? "url("+o.props.deficon+")" : "none")
	}
    }	
};

_uComboBox._onitemmouseover=function(e) {
		var d=e.data;
		d.obj.design._onitemmouseover.apply(this,[e]);
};
_uComboBox._onitemmouseout=function(e) {
		var d=e.data;
		d.obj.design._onitemmouseout.apply(this,[e]);
};
_uComboBox._onitemclick=function(e) {
		var d=e.data;
		d.obj.select(d.item);
		d.obj.hidelist();
		d.obj.obj.focus();
		e.stopPropagation();
		e.preventDefault();
};
_uComboBox._onbutclick=function(e) {
		var o=e.data;
//		_uWnd.globalmousedown();
		if(o.opened) o.hidelist(); else o.showlist();
//		_uComboBox.ignoreclick=e.data;
		o.obj.focus();
		if($.browser.msie && !e.data.cancelblur) {
			e.data.cancelblur=true;
			setTimeout("var c=_uComboBox.all["+e.data.idx+"];if(c)c.cancelblur=false;",10);
		}
//		e.stopPropagation();
		e.preventDefault();
};
_uComboBox._onlistmousedown=function(e) {
	_uComboBox.ignoreclick=e.data;
	e.data.obj.focus();
	if($.browser.msie && !e.data.cancelblur) {
		e.data.cancelblur=true;
		setTimeout("var c=_uComboBox.all["+e.data.idx+"];if(c)c.cancelblur=false;",10);
	}
//	e.stopPropagation();
	e.preventDefault();
};
_uComboBox._oncombomousedown=function(e) {
	_uComboBox.ignoreclick=e.data;
	if(e.which!=1) return;
	var o=e.data;
	if(o.props.readonly) if(o.opened) o.hidelist(); else o.showlist();
	o.obj.focus();
	if($.browser.msie && !o.cancelblur) {
		o.cancelblur=true;
		setTimeout("var c=_uComboBox.all["+o.idx+"];if(c)c.cancelblur=false;",10);
	}
//	e.stopPropagation();
	if(e.target!=o.obj) e.preventDefault();
};
_uComboBox._onobjfocus=function(e) {
	var o=e.data;
	if(o.blurtimer) clearTimeout(o.blurtimer);
	o.blurtimer=null;
	o.design._onfocus(o,e);
};
_uComboBox._onobjblur=function(e) {
	e.data.onblur();
};
_uComboBox._onobjdeact=function(e) {
	var o=e.data;
	if(o.cancelblur) e.preventDefault();
};

_uComboBox.isUpKey=function (code) {
    return code==38 || code == 63232;
};
_uComboBox.isDownKey=function (code) {
    return code==40 || code == 63233;
};

_uComboBox.prototype={
	_setvalue: function(i) {
	  with(this) {
		if(i>=0 && i<data.length) {
			valobj.value=prevInput=data[i][0];
			if(props.readonly) obj.value=data[i].length>3 ? data[i][3] : data[i][0];
			if(haveicons) design.seticon(this,data[i][1]);
		} else {
			if(props.readonly) {valobj.value='';obj.value=userInput;}
				else {valobj.value=prevInput=userInput;}
			if(haveicons) this.design.seticon(this,null);
		}
	  }
	},
	_selectitem: function(i) {
	  with(this) {
		if(selected>=0 && selected<data.length) {
			design._deselect(this,selected);
			selected=-1;
		}
		if(i>=0 && i<data.length) {
			design._select(this,i);
			selected=i;
		}
	  }
	},
	setvalue: function (v) {
	  with(this) {
	  	var ch=false;
		if(changetimer) clearTimeout(changetimer);
		if(props.readonly) return;
		if(valobj.value!=v) ch=true;
		valobj.value=prevInput=userInput=v;
		if(selected!=-1) ch=true;
		_selectitem(-1);
		userIdx=-1;
		if(haveicons) this.design.seticon(this,null);
		if(props.onchange && ch) props.onchange.apply(this,[selected,v]);
	  }
	},
	select: function (i,soft) { //
	  with(this) {
		var ch=false;
		if(changetimer) clearTimeout(changetimer);
		changetimer=null;
	  	_selectitem(i);
		_setvalue(selected);
		if(!soft) {
			if(selected!=userIdx) ch=true;
			userIdx=selected;
			if(props.onchange && ch) props.onchange.apply(this,[selected,valobj.value]);
		}
	  }
	},
	onblur: function (e) {
		if(this.blurtimer) clearTimeout(this.blurtimer);
		this.blurtimer=setTimeout("var c=_uComboBox.all["+this.idx+"];if(c)c._onblur2();",10);
	}, 
	_onblur2: function (e) {
		this.blurtimer=null;
		this.design._onblur(this,e);
	}, 
	onkeydown: function (e) {
	  var i;
	  with(this) {
    	var c=e.keyCode;
    	if(c==27 && opened) {
			select(userIdx,true);
			hidelist();
			return false;
    	}
    	if(data.length==0) return;
	    if(c==13) {
	    	select(selected);
			hidelist();
			obj.focus();
			e.preventDefault();
			e.stopPropagation();
			return false;
	    }
		if(c==9) {
			if(changetimer) select(selected);
			return;
		}
	    if(_uComboBox.isDownKey(c) || _uComboBox.isUpKey(c)) {
			i=selected+(_uComboBox.isDownKey(c) ? 1 : -1);
			if(props.readonly) {
	    		if(i>=data.length) i=0;
					else if(i<0) i=data.length-1;
			} else {
    			if(i>=data.length) i=-1;
					else if(i<-1) i=data.length-1;
			}
			select(i,true); //select clears changetimer
			if(!opened) changetimer=setTimeout("var c=_uComboBox.all["+this.idx+"];if(c)c.select("+i+");",500);
			return false;
    	}
  	  }
	},
	onkeyup: function (e) {
  	  with(this) {
    	if(props.readonly || obj.value==prevInput) return;
		if(changetimer) clearTimeout(changetimer);
    	prevInput=userInput=obj.value;
		_selectitem(-1);
		userIdx=-1;
		if(haveicons) this.design.seticon(this,null);
		if(props.onchange) props.onchange.apply(this,[-1,obj.value]);
  	  }
	},
	appendItem: function(elem) { //0 - id, 1 - optional icon, 2... - text labels
		this.design.append_item(this,elem);
		this.updated=true;
	},
	hidelist: function() {
	    this.toplist.style.display='none';
	    this.opened=false;
		this.design._onlisthide(this);
	},
	showlist: function () {
    	var w=this.combo.offsetWidth;
		$(this.toplist).css({left:this.combo.offsetLeft+'px',top:this.combo.offsetTop+this.combo.offsetHeight+'px',width:w+'px'});
	    if(this.frame) $(this.frame).css({width:w+'px'});
		if(this.updated) {
			$(this.parts.list).css({height:'auto',overflow:'hidden'});
			$(this.toplist).css({visibility:'hidden'}).css({display:'block'});
			if(this.showtimer) clearTimeout(this.showtimer);
			this.showtimer=setTimeout("var c=_uComboBox.all["+this.idx+"];if(c)c._showlist();",10);
		} else {
		    this.toplist.style.display='block';
		}
		this.design._onlistopen(this);
		this.opened=true;
	    this.updated=false;
	},
	_showlist:function(){
		this.showtimer=null;
		var o=this.parts.list,h,maxh,pos,d=_uWnd.getdims();
		h=Math.max(o.scrollHeight,o.offsetHeight);
		pos=$(this.toplist).offset();
		if(this.props.maxlistheight>0) maxh=Math.max(50,Math.min(this.props.maxlistheight,d.clientH-pos.top));
			else maxh=Math.max(50,d.clientH-pos.top);
		if(h>maxh) {
			$(this.parts.list).css({height:maxh+'px',overflow:'auto'});
			h=maxh;
		}
	    if(this.frame) $(this.frame).css({height:h+'px'});

		$(this.toplist).css({visibility:'visible'});
	}
};

//vals in form:
//{'word1':[['word11',col2],['word12',col2]],'word2':[['word21',col2],['word22',col2]]}

//function _uSuggestList(editId,cachegroup,tblClass,normalclass,highclass,minlength,url,vals) {
function _uSuggestList(name,inputId,opts,vals) { //inputId can be ID or object
	this.constructor=_uSuggestList;
	this.name=name;
	this.obj=typeof inputId=='string' ? document.getElementById(inputId) : inputId;
	if(!this.obj) return null;
	this.props=$.extend({
		design: 'std',
		maxlistheight: 'auto',
		colwidth: null,
		cachegroup: 'def',
		minlen: 2,
		url: null,
		separator: null
//		hidden: 0,
//		onshow: null,
//		onhide: null,
//		ondestroy: null,
//		onchange: null,
//		wnd:null,
//		rtl:0
	},opts || {});
	this.colwidth=this.props.colwidth || [];
//	this.destroyed=false;
    this.design=this.props.design && _uSuggestList.designs[this.props.design] ? _uSuggestList.designs[this.props.design] : _uSuggestList.designs['std'];
    this.idx=_uSuggestList.nextidx++;
    _uSuggestList.all[this.idx]=this;
    this.cacheGroup=this.props.cachegroup;
    if(!this.queryCache[this.cacheGroup]) this.queryCache[this.cacheGroup]=[];
    if(vals) this.queryCache[this.cacheGroup]=vals;

    this.visible=true;
    this.hlIndex=-1; //highlighted item
    this.hlRow=null; //highlighted row
    this.blockMouseOver=false;

    this.userInput=this.obj.value; //saved value
    this.previousInput=this.obj.value; //to track changes
    this.resultInput=""; //value for which we have result if result is not empty
    this.requestedInput=""; //to track value which will be requested remotely
    this.ignoreInput=""; //value which must be ignored
	this.sep_pos=-1;

    this.remoteReqTimer=null;
    this.hideTimer=null;
    this.AJAXretries=0;
    this.AJAXTimer=null;


	this.frame=null;


	var t=document.createElement("div");
	t.id="_usuggest"+this.idx;
	this.top=t;
	
	var wnd;
	if(wnd=_uWnd.findparent(this.obj)) {
		this.parent=wnd.top;
		this.parent.appendChild(t);
	} else {
		this.parent=this.obj.parentNode;
		this.parent.insertBefore(t,this.obj);

	}

   	$(t).css({position:'absolute',zIndex:5,display:'none',zoom:1});//zIndex:this.zpos,
    if(0 && $.browser.msie && parseFloat($.browser.version)<7){
		    var html = '<iframe tabindex="-1" '
    		    +'style="display:block; position:absolute;'
			+'filter:Alpha(Opacity=\'100\'); '
			+'width:1px;height:20px;border:0"/>';

	    	this.frame=document.createElement(html);
			t.appendChild(this.frame);
	}

    this.parts=this.design.suggest_init(this);

    $(this.obj).attr("autocomplete", "off").css("position","relative")
//	.bind("focus",this,_uComboBox._onobjfocus)
	.bind("blur",this,function(e) {return e.data.onblur(e);})
//	.bind("beforedeactivate",this,_uComboBox._onobjdeact)
	.bind("keydown",this,function(e) {return e.data.onkeydown(e);})
	.bind("keyup",this,function(e) {return e.data.onkeyup(e);});

//	$(this.combo).bind("mousedown",this,_uComboBox._oncombomousedown);
//	$(this.toplist).bind("mousedown",this,_uComboBox._onlistmousedown);
	if(!_uSuggestList.globalset) {
		_uSuggestList.globalset=true;
	    $(document).bind("mousedown",_uSuggestList.hideall);
	    $(window).bind("resize",_uSuggestList.hideall);
	}


    this.hide();
//    $(window).bind("resize",this,function(e) {return e.data.positionResult();});

    //attach event to parent form
    if(this.obj.form) {
	$(this.obj.form).bind("submit."+this.idx,this,function(e) {return e.data.onsubmitform(e);});
    }
}

_uSuggestList.all=[];
_uSuggestList.nextidx=0;
_uSuggestList.defz=20015;
_uSuggestList.globalset=false;
_uSuggestList.ignoreclick=null;

_uSuggestList.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uSuggestList.hideall=function() {
    var a=_uSuggestList.all;
    for(var i=0;i<a.length;i++) if(a[i] && !a[i].destroyed && _uSuggestList.ignoreclick!=a[i]) a[i].hide();
	if(_uSuggestList.ignoreclick)setTimeout("_uSuggestList.ignoreclick=null;",10);
};

_uSuggestList.designs={
	std: {
	suggest_init: function(o) {
	    var p={};
		$(o.obj).attr("class","x-selectable u-suggedit "+$(o.obj).attr("class"));
//		if($.browser.msie) $(o.obj).css({marginTop:'-1px',marginBottom:'-1px'});

	    $(o.top).append('<div class="u-sugglist" style="zoom:1"><div style="zoom:1"><table border="0" cellspacing="0" class="x-unselectable u-suggcont" width="100%"></table></div></div>');
		p.list=$(o.top).find(".u-sugglist")[0];
		p.content=$(o.top).find(".u-suggcont")[0];
//		p.items=[];
		$(o.top).find("div,span,table").andSelf().attr("unselectable","on");
	    return p;

		},
	append_row: function(o,item,cols,key) {
		var row=o.parts.content.insertRow(-1);
		$(row).bind("mousedown",o,o._onrowmousedown)
	      .bind("mousemove",o,o._onrowmousemove)
	      .bind("mouseover",o,o._onrowmouseover).addClass('u-suggrow').attr("usuggeststr",item[0]);
		var v=String(item[0]);
	    if(v.toLowerCase().substr(0,key.length)==key.toLowerCase()) v='<span class="u-suggmark">'+v.substr(0,key.length)+'</span>'+v.substr(key.length);
		for(var j=0;j<cols;j++) {
		    $(row).append("<td unselectable='on' class='u-suggcell"+j+"'>"+(j==0?v:item[j])+"</td>");
		}
	},
//	_onlistopen: function(o) {
//		$(o.combo).addClass("u-comboopen");
//	},
//	_onlisthide: function(o) {
//		$(o.combo).removeClass("u-comboopen");
//	}
	_select: function(o,row) {
		$(row).addClass("u-suggrowhl");
	},
	_deselect: function(o,row) {
		$(row).removeClass("u-suggrowhl");
	}

	}

};

_uSuggestList.prototype = {
queryCache: [],
onsubmitform: function (e) {
    if(this.visible) {
	if(this.resultInput!="") this.obj.value=this.userInput;
	this.hide();
    }
},
hide: function () {
  with(this) {
    top.style.display='none';
	visible=false;
	if(hlRow) design._deselect(this,hlRow);
	hlRow=null;
	hlIndex=-1;
  }
},
show: function () {
  with(this) {
    if(!visible && numItems()>0) {
	   	var w=obj.offsetWidth,x,y,off,offp;
	   	off=$(obj).offset();
	   	offp=$(parent).offset();
		$(top).css({left:off.left-offp.left+'px',top:off.top-offp.top+obj.offsetHeight+'px',width:w+'px'});
	    if(frame) $(frame).css({width:w+'px'});
	    top.style.display='block';
		visible=true;
		blockMouseOver=true;
    }
  }
},
numItems: function () {
    return this.parts.content ? this.parts.content.rows.length : 0;
},
onblur: function (e) {
  with(this) {
    if(visible) {
	if(hlIndex>=0) obj.value=userInput;
	hide();
    }
  }
}, 
onkeydown: function (e) {
  with(this) {
    var c=e.keyCode;
    if(c==27 && visible) {
	if(resultInput!="") _setvalue_sep(userInput);
	hide();
	return false;
    }
    if(resultInput=="") return;
    if(c==13 && hlIndex>=0 && visible) {
	previousInput=obj.value;
	userInput=_getvalue_sep();
	resetRequest(userInput);
	hide();
	if(userInput != resultInput) clearResult();
	obj.focus();
	e.preventDefault();
	e.stopPropagation();
	return false;
    }
    if(isDownKey(c)) {
	moveSelection(hlIndex+1);
	return false;
    }
    if(isUpKey(c)) {
	moveSelection(hlIndex-1);
	return false;
    }
  }
},
onkeyup: function (e) {
  with(this) {
    if(ignoreInput!="" && _getvalue_sep()==ignoreInput) return;
    if(obj.value==previousInput) return;
    ignoreInput=resultInput="";
    previousInput=obj.value;
    userInput=_getvalue_sep();
    if(hideTimer) clearTimeout(hideTimer);
    hideTimer=setTimeout("var c=_uSuggestList.all["+idx+"];if(c)c.clearResult(true);",2000);
	
    procRequest(userInput);
  }
},
_setvalue_sep: function(v) {
	with(this){
		if(sep_pos>=0) obj.value=obj.value.substr(0,sep_pos)+props.separator+' '+v;
			else obj.value=v;
	}
},
_getvalue_sep: function() {
  with(this){
  	if(props.separator) sep_pos=obj.value.lastIndexOf(props.separator);
	if(sep_pos>=0) {
		var t=obj.value.substr(sep_pos+props.separator.length);
	    t=t.replace(/^\s+/,"");
	    return t;
	} else return obj.value;
  }
},
moveSelection: function (newi) {
  with(this) {
    if(resultInput=="" && ignoreInput!="" && _getvalue_sep()==ignoreInput) {
	procRequest(_getvalue_sep(),true);
	return;
    }
    if(!visible && resultInput.length>0 && resultInput==_getvalue_sep()) {
	show();
	return;
    }
    if(!visible) return;
    if(hlRow) design._deselect(this,hlRow);
    hlRow=null;
    var cnt=numItems();
    if(newi>=cnt) newi=-1;
	else if(newi<-1) newi=cnt-1;
    if(newi==-1) {
	hlIndex=-1;
	_setvalue_sep(userInput);
	obj.focus();
	return;
    }
    hlIndex=newi;
    hlRow=parts.content.rows[newi];
    design._select(this,hlRow);
    ignoreInput=$(hlRow).attr("usuggeststr");
    _setvalue_sep(ignoreInput);
  }
},	
isUpKey: function (code) {
    return code==38 || code == 63232;
},
isDownKey: function (code) {
    return code==40 || code == 63233;
},
resetRequest: function(txt) {
  with(this) {
    if(remoteReqTimer && requestedInput==txt) return;
    clearTimeout(remoteReqTimer); 	remoteReqTimer=null;
    requestedInput=txt;
    clearTimeout(AJAXTimer); AJAXTimer=null;
    try{if(AJAXObj) AJAXObj.abort(); AJAXObj=null;}catch(e){};
  }
},
procRequest: function (txt,nopause) {
  with(this) {
    resetRequest(txt);

    if(txt.length<props.minlen) {
	clearResult(true);
	return;
    }
    if(queryCache[cacheGroup][txt]) {
	setResult(txt,queryCache[cacheGroup][txt]);
	return;
    }
    AJAXretries=0;
    if(!props.url) return;
    if(nopause) remoteRequest();
	else remoteReqTimer=setTimeout("var c=_uSuggestList.all["+this.idx+"];if(c)c.remoteRequest();",350);
  }
},
remoteRequest: function () {
  with(this) {
    clearTimeout(remoteReqTimer);
    remoteReqTimer=null;
    try{if(AJAXObj) AJAXObj.abort(); AJAXObj=null;}catch(e){};

    if(AJAXretries>1) return;
    clearTimeout(AJAXTimer);
    AJAXTimer=setTimeout("var c=_uSuggestList.all["+this.idx+"];if(c){c.AJAXretries++;c.remoteRequest();}",12000);

    AJAXObj=$.ajax({
	type: "GET",
	dataType: "text",
	cache: false,
	url: props.url,
	data: {tag:requestedInput},
	success: new Function("resp","status","var c=_uSuggestList.all["+this.idx+"];if(c)c.parseRequest(resp,status);"),
	timeout: 10000
    });
  }
},
parseRequest: function (resp,status) {
    clearTimeout(this.AJAXTimer);
    this.AJAXTimer=null;
    this.AJAXretries=0;
    var res=[];
    try {
	res=eval("res="+resp);
    } catch(e) {}
    this.AJAXObj=req=null;
    if(!res || res.length<2 || res[1]<1 || res[1]>10) {
	this.clearResult();
	return;
    }
    var n=res[1],idx=0;
    var data=[];
    for(var i=2;i<res.length;i+=n,idx++) {
	data[idx]=[];
	for(var j=0;j<n;j++) {
	    data[idx][j]=res[i+j];
	}
    }
    this.queryCache[this.cacheGroup][res[0]]=data;
    if(res[0]==this.requestedInput) this.setResult(res[0],this.queryCache[this.cacheGroup][res[0]]);
},
_onrowmousemove: function(e) {
    return e.data.onrowmousemove(e);
},
_onrowmouseover: function(e) {
    return e.data.onrowmouseover(e);
},
_onrowmousedown: function(e) {
    return e.data.onrowmousedown(e);
},
onrowmousemove: function(e) {
    if(this.blockMouseOver) { //mouseOver is disable right after showing results
	this.blockMouseOver=false;
	this.onrowmouseover(e);
    }
},
onrowmouseover: function(e) {
  with(this) {
    if(blockMouseOver) return;
    if(hlRow) design._deselect(this,hlRow);
    hlRow=null;
    hlIndex=-1;
    for(var i=0;i<parts.content.rows.length;i++) {
	if(parts.content.rows[i]==e.target || jQuery.inArray(e.target,$(parts.content.rows[i]).contents())>=0) {
	    hlIndex=i;
	    hlRow=parts.content.rows[i];
	    design._select(this,hlRow);
	    break;
	}
    }
  }
},
onrowmousedown: function(e) {
  with(this) {
    if(numItems()<=0 || !hlIndex<0 || !hlRow) return;
    ignoreInput=userInput=$(hlRow).attr("usuggeststr");
    _setvalue_sep(userInput);
    previousInput=obj.value;
    resetRequest(userInput);
    hide();
    if(userInput != resultInput) clearResult();
    obj.focus();
  }
},

setResult: function (phrase,table) { //array of arrays
  with(this) {
    if(hideTimer) clearTimeout(hideTimer);
    hideTimer=null;
    clearResult();
    hlIndex=-1;
    hlRow=null;
    resultInput=phrase;
    var cnt=table.length;
    if(cnt<=0) {hide();return;}	
    var cols=table[0].length; //determine num cols by first item
    for(var i=0;i<cnt;i++) {
	    design.append_row(this,table[i],cols,phrase);
    }
    show();
  }
},
clearResult: function (hide) {
  with(this) {
    if(hide) hide();
    resultInput="";
    hlRow=null;
    hlIndex=-1;
    while(parts.content.rows.length > 0)parts.content.deleteRow(-1);
  }
}
};

function _uDraggable(obj,onmove,oninitdrag,onstartdrag,onstopdrag) {
	this.par=obj;
	this.x=this.y=this.w=this.h=this.m=0;
	this.moved=false;
	this.active=false;
	this.onmove=onmove || _uDraggable.dummy;
	this.oninitdrag=oninitdrag || _uDraggable.dummy;
	this.onstartdrag=onstartdrag || _uDraggable.dummy;
	this.onstopdrag=onstopdrag || _uDraggable.dummy;
    if(!_uDraggable.globalset) {
		_uDraggable.globalset=true;
		$(document).bind("mouseup",_uDraggable.onmouseup);
		$(document).bind("mousemove",_uDraggable.onmousemove);
//		if($.browser.msie)$(document).bind("mouseout",function(e) {if(!e.relatedTarget && !e.toElement)_uWnd._dragging=null});
	}
}
_uDraggable.dummy=function(){};
_uDraggable.obj=null;
_uDraggable.clkX=0;
_uDraggable.clkY=0;
_uDraggable.scrL=0;
_uDraggable.scrT=0;
_uDraggable.globalset=false;
_uDraggable.onmousemove=function(e) {
  with(_uDraggable) {
    var o=obj;
    if(!o) return;
	if(e.which!=1) {o.stop();obj=null;return;}
	e.stopPropagation();
	e.preventDefault();
    var d=_uWnd.getdims();
	o.event=e;
	if(!o.moved && (e.clientX!=clkX || e.clientY!=clkY)) {o.onstartdrag.apply(o.par,[o.x,o.y,o.w,o.h,o.m]);o.moved=true;}

	o.onmove.apply(o.par,[e.clientX-clkX-(scrL-d.clientLeft),e.clientY-clkY-(scrT-d.clientTop),o.x,o.y,o.w,o.h,o.m]);
	o.event=null;
	return false;
  }
};
_uDraggable.onmouseup=function(e) {
    if(e.which!=1) return;
  with(_uDraggable) {
    var o=obj;
    if(!o) return;
  	if(o.moved)onmousemove(e);
	o.event=e;
  	o.stop();
  	o.event=null;
  	obj=null;
  }
};
_uDraggable.prototype={
	start: function(e,x,y,w,h,m) {
		var r=_uDraggable;
		if(r.obj) r.obj.onstopdrag.apply(r.obj.par);
		this.x=x;
		this.y=y;
		this.w=w;
		this.h=h;
		this.m=m;
		this.active=true;
		this.moved=false;
		r.obj=this;
	    var d=_uWnd.getdims();
	    r.clkX=e.clientX;
	    r.clkY=e.clientY;
	    r.scrL=d.clientLeft;
	    r.scrT=d.clientTop;
	    this.oninitdrag.apply(this.par,[x,y,w,h,m]);
//window.dump("drag start\n");

	},
	stop: function() {
		var r=_uDraggable;
		if(r.obj==this) r.obj=null;
		if(this.active) {
			this.onstopdrag.apply(this.par,[this.x,this.y,this.w,this.h,this.m]);
			this.active=false;
//window.dump("drag stop \n");
		}
	}

};

function _uTabCtrl (name,ntabs,opts,titles,datas,topts) {
	this.constructor=_uTabCtrl;
	this.name=name;
	this.ntabs=ntabs;

	this.props=$.extend({
		parentnode: null, //if null, then just append child
		wnd:null, //use wnd as parent node. window must be created
		app:opts && opts.wnd && opts.wnd.app || null, //parent app and 'this' for all handlers
		width: 'auto', //outer width
		height: 'auto', //outer height
		min_height: 50, //content height
		active_tab: -1, //if 'auto' then check current url for active tab
		close: 0, //default availability of close button
		design: 'std',
		noinit: false,
		markload: '<div align="left"><div class="myWinLoad"></div></div>', //default mark load text
		emptycontent: '', //content when no active tabs
		
					
		onload: null, //(tabctrl,idx,tabid) after tab content is loaded (reloaded)for the first time (called before onshow)
		onshow: null, //(tabctrl,idx,tabid) after tab content is loaded into DOM
		onhide: null, //(tabctrl,idx,tabid) when tab looses active state (if tab was closed then this event is called after onbeforeclose if closing was allowed)
		onbeforechange: null, //(tabctrl,idx,tabid) before tab is changed to idx. if false, than ignore click
		onchange: null, //(tabctrl,idx,tabid) after tab is changed to idx. if false, than do not load tab contents
		onbeforeclose: null, //(tabctrl,idx,tabid) before tab is closed. if false, than ignore close
		onclose: null, //(idx,tabid) after tab is closed. 
		ondestroy: null, //(tabctrl,name)
		onresize: null, //(cont_width,cont_height,tabctrl,name)
		rtl:0
	},opts || {});

	this.app=this.props.app;
	this.state={init:false,destroyed:false};
    this.design=this.props.design && _uTabCtrl.designs[this.props.design] ? _uTabCtrl.designs[this.props.design] : _uTabCtrl.designs['std'];
    this.idx=_uTabCtrl.nextidx++;
    _uTabCtrl.all[this.idx]=this;
	this.width=parseInt(this.props.width) || 0; //outer width
	this.height=parseInt(this.props.height) || 0;	//outer height
	this.data=[]; 
	this.pend_show=null;
	this.decor={cdw:0,cdh:0,pdw:0,pdh:0,ph:0}; //
	this.maxid=0;
	this.wnd=null;

	this.active_tab=this.props.active_tab;
	this.scrollpos={tabswidth:0,havewidth:0,pos:null};

	for(var i=0;i<ntabs;i++) {
		var opt=(topts && topts[i]) || {};
		var id=opt.id || '';
		if(!id || id.length==0) id='_tc'+this.idx+'tb'+(this.maxid++);
		this.data[i]={
			id:id,
			title:(titles && titles[i]) || '.',
			dat:(datas && datas[i]) || '',
			cont:null,
			markloadcont:null,
			obj:null,
			ishidden: opt.hidden,
			clbut:null,
			link:null,
			href:opt.href,
			target:opt.target,
			label:null,
			close:opt.close==undefined ? this.props.close : opt.close,
			icon:opt.icon,
			markload:opt.markload,
			firstload:0,
			onload:opt.onload==undefined ? this.props.onload : opt.onload,
			onshow:opt.onshow==undefined ? this.props.onshow : opt.onshow,
			onhide:opt.onhide==undefined ? this.props.onhide : opt.onhide,
			onbeforechange:opt.onbeforechange==undefined ? this.props.onbeforechange : opt.onbeforechange,
			onchange:opt.onchange==undefined ? this.props.onchange : opt.onchange,
			onbeforeclose:opt.onbeforeclose==undefined ? this.props.onbeforeclose : opt.onbeforeclose,
			onclose:opt.onclose==undefined ? this.props.onclose : opt.onclose
			};
	}

	if(!_uTabCtrl.globalset) {
		_uTabCtrl.globalset=true;
//	    $(document).bind("mousedown",_uMENU.hideallmenus);
//	    $(window).bind("resize",_uMENU.hideallmenus);
	}
	this.butdown=new _uDraggable(this,null,null,null,function(but,tab){this.design._onbuttonup(this,but,tab);});

	if(!this.props.noinit)this.init();
}


_uTabCtrl.all=[];
_uTabCtrl.nextidx=0;
_uTabCtrl.globalset=false;

_uTabCtrl.getbyname=function(name) {
    var a=this.all;
    for(var i=0;i<a.length;i++) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uTabCtrl.closeTab=function(name,idx) {
    var w=this.getbyname(name);
    if(w) w.closeTab(idx);
}
_uTabCtrl.content=function(name,idx,c) {
    var w=this.getbyname(name);
    if(w)w.content(idx,c);
}
_uTabCtrl.setTitle=function(name,idx,t) {
    var w=this.getbyname(name);
    if(w)w.setTitle(idx,t);
}

_uTabCtrl.designs={
    std: {
//    tab_height:'25px',
	tabctrl_init: function(o) {
	    var p={};
		$(o.top).attr('class',"x-unselectable u-tabc").html(
 '<div class="u-tabc-p"><div class="u-tabc-listp"><div class="u-tabc-list"></div><div class="u-tabc-pbot"></div></div><div class="u-tabc-scrbut"><div class="u-tabc-tabl"><div class="u-tabc-label"><div class="u-tabc-scrl"></div><div class="u-tabc-scrr"></div></div></div></div></div>'
+'<div class="u-tabc-body"><div class="u-tabc-content" style="height:'+o.props.min_height+'px">'+o.props.emptycontent+'</div></div>'
			);
	    p.pane=$(o.top).find(".u-tabc-p")[0];
	    p.panebot=$(o.top).find(".u-tabc-pbot")[0];
	    p.listp=$(o.top).find(".u-tabc-listp")[0];
	    p.list=$(o.top).find(".u-tabc-list")[0];
	    p.scrbut=$(o.top).find(".u-tabc-scrbut")[0];
	    p.scrl=$(o.top).find(".u-tabc-scrl")[0];
	    p.scrr=$(o.top).find(".u-tabc-scrr")[0];
	    p.body=$(o.top).find(".u-tabc-body")[0];
	    p.emptycontent=p.content=$(o.top).find(".u-tabc-content")[0];
		$(o.top).find("div,span").andSelf().attr("unselectable","on");
		$(p.scrl).bind("click mousedown mouseover mouseout",{obj:o,but:0},_uTabCtrl._onscrbutevent);
		$(p.scrr).bind("click mousedown mouseover mouseout",{obj:o,but:1},_uTabCtrl._onscrbutevent);

	    return p;
	},
	remove_item: function(o,idx) {
		o.parts.list.removeChild(o.data[idx].obj);
	},
	set_title: function(o,idx) {
		$(o.data[idx].label).html(
			(o.data[idx].icon ? '<img class="u-tabc-icon" border="0" src="'+o.data[idx].icon+'">' : ($.browser.msie && $.browser.version<8 ? '<img class="u-tabc-spacer" src="/img/1px.gif" width="1" height="1" border="0">' : ''))
			+o.data[idx].title
		);
	},
	insert_item: function(o,idx) {
		var a=document.createElement('div');
		$(a).attr('class','u-tabc-tab'+(o.data[idx].close ? ' u-tabc-wcl':'')).html(
(o.data[idx].href ?
'<a '+(o.data[idx].target ? 'target="'+o.data[idx].target+'" ':'')+'href="'+o.data[idx].href+'" class="u-tabc-tabl" style="display:block">' :
'<div class="u-tabc-tabl">' )
			+(o.data[idx].close ? '<div class="u-tabc-closebut"></div>' : '')
			+'<div class="u-tabc-tabr"><div class="u-tabc-label">'
			+(o.data[idx].icon ? '<img class="u-tabc-icon" border="0" src="'+o.data[idx].icon+'">' : ($.browser.msie && $.browser.version<8 ? '<img class="u-tabc-spacer" src="/img/1px.gif" width="1" height="1" border="0">' : ''))
			+o.data[idx].title
			+'</div></div>'+(o.data[idx].href ? '</a>' : '</div>')
		);
		o.data[idx].obj=a;
		o.data[idx].label=$(a).find(".u-tabc-label")[0];
		o.data[idx].link=$(a).find(".u-tabc-tabl")[0];
	    if(o.data[idx].close) {
	    	o.data[idx].clbut=$(a).find(".u-tabc-closebut")[0];
			$(o.data[idx].clbut).bind("mouseover",this._onclbutmouseover).bind("mouseout",this._onclbutmouseout).bind("click",{obj:o,tab:o.data[idx]},_uTabCtrl._onclbutclick).bind("mousedown",{obj:o,tab:o.data[idx]},_uTabCtrl._onclbutdown);
	    }
		$(o.data[idx].link).bind("mouseover",this._ontabmouseover).bind("mouseout",this._ontabmouseout).bind("mousedown",{obj:o,tab:o.data[idx]},_uTabCtrl._ontabclick);
		$(a).find("div,span,a,img").andSelf().attr("unselectable","on");
		if(o.data[idx].ishidden) a.style.display='none';

		var nc=o.parts.list.childNodes.length;
//		if(o.props.rtl || window._rtl)
//			o.parts.list.insertBefore(a,nc-idx>=nc ? null : o.parts.list.childNodes[nc-idx]);
//		else
			o.parts.list.insertBefore(a,idx>=nc ? null : o.parts.list.childNodes[idx]);
	},
	_ontabmouseover: function(e) {
		$(this.parentNode).addClass("u-tabc-tab-over");
	},
	_ontabmouseout: function(e) {
		$(this.parentNode).removeClass("u-tabc-tab-over");
	},
	_onclbutmouseover: function(e) {
		$(this).addClass("u-tabc-closebut-over");
	},
	_onclbutmouseout: function(e) {
		$(this).removeClass("u-tabc-closebut-over");
	},
	_onclbutmousedown: function(b,v) {
		if(v) $(b).addClass("u-tabc-closebut-down");
			else $(b).removeClass("u-tabc-closebut-down");
	},
	_ontabactivate: function(o,idx) {
		$(o.data[idx].obj).addClass("u-tabc-tab-act");
	},
	_ontabdeactivate: function(o,idx) {
		$(o.data[idx].obj).removeClass("u-tabc-tab-act");
	},
	_onscrbutactivate: function(o,but,v) { //0-left else right
		if(v) $(!but ? o.parts.scrl : o.parts.scrr).removeClass("u-tabc-scr-dis");
			else $(!but ? o.parts.scrl : o.parts.scrr).addClass("u-tabc-scr-dis");
	},
	_onscrbutover: function(o,but,v) { //0-left else right
		var b=!but ? o.parts.scrl : o.parts.scrr;
		if(v) $(b).addClass("u-tabc-scr-over");
			else $(b).removeClass("u-tabc-scr-over");
	},
	_onscrbutdown: function(o,but,v) { //0-left else right
		var b=!but ? o.parts.scrl : o.parts.scrr;
		if(v) $(b).addClass("u-tabc-scr-down");
			else $(b).removeClass("u-tabc-scr-down");
	},
	_onbuttonup: function(o,but,tab) { //0-left scroll,1-right scroll,2-tab close
		if(but<2) this._onscrbutdown(o,but,0);
			else this._onclbutmousedown(tab.clbut,0);
	}
    }	
};
_uTabCtrl._onclbutdown=function(e) {
		if(e.which==1) {
			e.stopPropagation();
			e.data.obj.design._onclbutmousedown(e.data.tab.clbut,1);
			e.data.obj.butdown.start(e,2,e.data.tab);
		}
		_uWnd.globalmousedown();
};
_uTabCtrl._onscrbutevent=function(e) {
		var o=e.data.obj,but=e.data.but;
		if(e.type=='click' && e.which==1) o.scrollTabPane(but ? 40 : -40);
			else if(e.type=='mouseover') o.design._onscrbutover(o,but,1);
			else if(e.type=='mouseout') o.design._onscrbutover(o,but,0);
			else if(e.type=='mousedown' && e.which==1) {
				o.design._onscrbutdown(o,but,1);
				o.butdown.start(e,but);
			}
};
_uTabCtrl._onclbutclick=function(e) {
		var d=e.data,o=d.obj;
		for(var i=0;i<o.data.length;i++) 
			if(o.data[i]==d.tab) {
				if(typeof o.data[i].onbeforeclose == 'function') if(!o.data[i].onbeforeclose.call(o.app,o,i,o.data[i].id)) break;
				o.closeTab(i);
				break;
			}
		e.preventDefault();
		e.stopPropagation();
};
_uTabCtrl._ontabclick=function(e) {
		var d=e.data,o=d.obj;
		e.preventDefault();
		for(var i=0;i<o.data.length;i++)
			if(o.data[i]==e.data.tab) {
				if(i==o.active_tab) return;
				if(typeof o.data[i].onbeforechange == 'function') if(!o.data[i].onbeforechange.call(o.app,o,i,o.data[i].id)) break;
				o.activateTab(i);
				break;
			}
};

_uTabCtrl.prototype={
	init: function(noinit) {
		var t=document.createElement("div");
		t.id="_utabctrl"+this.idx;
		if(this.props.parentnode) this.props.parentnode.appendChild(t);
			else if(this.props.wnd) {
				var ww=this.props.wnd.parts.wndcont;
				while(ww.firstChild) ww.removeChild(ww.firstChild);
				ww.appendChild(t);
				this.wnd=this.props.wnd;
				this.wnd.tabctrl=this;
				this.wnd.state.loaded=true;
				}
			else $($("body")[0]).append(t);

		this.top=t;
	    $(t).css({visibility:'hidden',display:'block'});
		if(this.width>0) $(t).css('width',this.width+'px');
//		if(this.height>0) $(t).css('height',this.height+'px');

	    this.parts=this.design.tabctrl_init(this);
	    this.parts.markloadcont=null;
		this.show();
		if(!noinit)setTimeout("var m=_uTabCtrl.all["+this.idx+"];if(m)m.init1();",10);
	},
	init1: function(noresize) { //noresize used internally by windows
//calculate decor
		var p=this.parts,d=this.decor;
		if(!(this.width>0)) this.width=this.top.offsetWidth;
		if(!(this.height>0)) this.height=this.top.offsetHeight;
		d.cdw=this.top.offsetWidth-p.content.offsetWidth;
		d.cdh=this.top.offsetHeight-p.content.offsetHeight;
		d.pdw=this.top.offsetWidth-p.listp.offsetWidth;
		if(!this.props.wnd && !noresize) {
			$(this.top).css('height',this.height+'px');
			$(p.content).css({width:(this.top.offsetWidth-d.cdw)+'px',height:(this.top.offsetHeight-d.cdh)+'px'});
			$(p.listp).css({width:(this.top.offsetWidth-d.pdw)+'px'});
		}

		$(p.listp).css({overflow:'hidden'});
		$(p.panebot).css('width','4000px');
		$(p.list).css('width','4000px');
		for(var i=0;i<this.ntabs;i++)
			this.design.insert_item(this,i);
		if(this.props.wnd)
			this.resizeTo(this.props.wnd.width-this.props.wnd.decor.w,this.props.wnd.height-this.props.wnd.decor.h);
		var at=this.active_tab;
		this.active_tab=-1;
		if(at=='auto')
			if(this.name && this.name.length>0 && self.location.hash.length>1) {
				var u=self.location.hash.substr(1).split(';');
				var s='T_'+this.name+'=';
				for(var ui=0;ui<u.length;ui++)
					if(u[ui].length>s.length && u[ui].substr(0,s.length)==s) {
						var tb=this.idxbyid(u[ui].substr(s.length));
						if(tb>=0 && tb<this.data.length) {at=tb;break;}
					}
			} else at=-1;
	    $(this.top).css("display",'block').css("visibility",'visible');
	    if(at==-1 && this.data.length>0) at=0;
	    if(at>=0 && at<this.ntabs) {
			for(var i=0;i<this.ntabs;i++) {
				var j=(at+i)%this.ntabs;
				if(!this.data[j].ishidden && (!this.data[j].onbeforechange || !!this.data[j].onbeforechange(this,j,this.data[j].id))) {
					this.activateTab(j,true);
					break;
				}
			}
		} else this.activateTab(-1,true);

	    $(this.top).css("display",'none').css("visibility",'visible');
		this.state.init=true;
	    if(pend_show) this.show(pend_show[0]);
	    if(this.props.wnd) this.props.wnd.onexternalload(); //activate autosize 
	},
	scrollTabPane: function(dx) { //>0 - right
		var pos=this.scrollpos.pos+=dx;
		var w=this.scrollpos.tabswidth,havew=this.scrollpos.havewidth;
		if(w<havew) {
			this.design._onscrbutactivate(this,0,0);
			this.design._onscrbutactivate(this,1,0);
			if((this.props.rtl || window._rtl) && this.data.length>0) {
				pos=this.data[this.data.length-1].obj.offsetLeft+havew-w;
			} else pos=0;
			this.scrollpos.pos=pos;
			this.parts.listp.scrollLeft=pos;
		} else {
			if(this.props.rtl || window._rtl) {
				var ol=this.data[this.data.length-1].obj.offsetLeft;
				if(pos<ol) pos=ol;
					else if(pos>ol+w-havew) pos=ol+w-havew;
			} else if(pos<0) pos=0;
					else if(pos>w-havew) pos=w-havew;
			this.scrollpos.pos=pos;
			this.parts.listp.scrollLeft=pos;
			if(pos>0) this.design._onscrbutactivate(this,0,1);
				else this.design._onscrbutactivate(this,0,0);
			if(pos<w-havew) this.design._onscrbutactivate(this,1,1);
				else this.design._onscrbutactivate(this,1,0);
		}
	},
	_setscrolls: function() { //set scroll buttons status accroding to tab widths
		var w=0,havew=this.parts.listp.offsetWidth;
		if(this.parts.listp.clientWidth>0 && this.parts.listp.clientWidth<havew) havew=this.parts.listp.clientWidth;
		if(this.data.length>0) {
			var o=this.data[this.data.length-1];
			if(this.props.rtl || window._rtl) {
				var o2=this.data[0];
				w=o2.obj.offsetLeft+o2.obj.offsetWidth-o.obj.offsetLeft;
			} else w=o.obj.offsetLeft+o.obj.offsetWidth;
		}
		if(havew<w) { //enable scrolls
			this.parts.scrbut.style.display='block';
			havew-=this.parts.scrbut.offsetWidth;
		} else this.parts.scrbut.style.display='none';
			
		if(this.scrollpos.pos==null) {
			if((this.props.rtl || window._rtl) && this.data.length>0) this.scrollpos.pos=this.data[this.data.length-1].obj.offsetLeft+w-havew;
				else this.scrollpos.pos=0;
		} else if(this.scrollpos.havewidth!=havew) 
					if(this.props.rtl || window._rtl) this.scrollpos.pos+=this.scrollpos.havewidth-havew;

		this.scrollpos.havewidth=havew;
		this.scrollpos.tabswidth=w;
		this.scrollTabPane(0);
//		alert(w+','+havew);
	},
	show: function(rel) {
		if(!this.state.init) {pend_show=[rel];return;}
  		$(this.top).show();
	    this.state.visible=true;
//	    if(rel) load();
	},
	resizeTo: function(w,h) {
		this.width=w;
		this.height=h;
		var d=this.decor;
//		$(this.top).css({height:h+'px',width:w+'px'});
		$(this.top).width(w).height(h);
		$(this.parts.content).css({width:(w-d.cdw)+'px',height:(h-d.cdh)+'px'});
		$(this.parts.listp).css({width:(w-d.pdw)+'px'});
		if(this.props.onresize) this.props.onresize(w-d.cdw,h-d.cdh,this,this.name);
		this._setscrolls();
	},
	addTab: function(title,dat,topt,idx) {
		var i= idx!=undefined && idx>=0 && idx<this.data.length ? idx : this.data.length;
		var opt=topt || {};
		var id=opt.id || '';
		if(!id || id.length==0) id='_tc'+this.idx+'tb'+(maxid++);
		var data={
			id:id,
			title:title || '.',
			dat:dat || '',
			cont:null,
			markloadcont:null,
			obj:null,
			ishidden: opt.hidden,
			clbut:null,
			link:null,
			href:opt.href,
			target:opt.target,
			label:null,
			close:opt.close==undefined ? this.props.close : opt.close,
			icon:opt.icon,
			markload:opt.markload,
			firstload:0,
			onload:opt.onload==undefined ? this.props.onload: opt.onload,
			onshow:opt.onshow==undefined ? this.props.onshow : opt.onshow,
			onhide:opt.onhide==undefined ? this.props.onhide : opt.onhide,
			onbeforechange:opt.onbeforechange==undefined ? this.props.onbeforechange : opt.onbeforechange,
			onchange:opt.onchange==undefined ? this.props.onchange : opt.onchange,
			onbeforeclose:opt.onbeforeclose==undefined ? this.props.onbeforeclose : opt.onbeforeclose,
			onclose:opt.onclose==undefined ? this.props.onclose : opt.onclose
			};

		if(i<this.data.length) this.data.splice(i,0,data);
			else this.data[i]=data;
		this.design.insert_item(this,i);
		this._setscrolls();
		return i;
	},
	tabHidden: function(idx,ishidden) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		var a=this.data[idx];
		a.obj.style.display=ishidden ? 'none' : ''; 
		a.ishidden=!!ishidden;
		this._setscrolls();
	},
	activateTab: function(idx,first) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length || this.active_tab==idx) if(first && this.data.length>0) idx=0; else return;
		this.design._ontabactivate(this,idx);
		if(this.active_tab>=0 && this.active_tab<this.data.length) {
			if(typeof this.data[this.active_tab].onhide == 'function') this.data[this.active_tab].onhide.call(this.app,this,this.active_tab,this.data[this.active_tab].id);
			this.design._ontabdeactivate(this,this.active_tab);
		}
		this.active_tab=idx;
		this._setscrolls();
		if(typeof this.data[idx].onchange == 'function') if(!this.data[idx].onchange.call(this.app,this,idx,this.data[idx].id)) return;
		this.load(idx);
	},
	closeTab: function(idx) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		if(idx==this.active_tab && typeof this.data[idx].onhide == 'function') this.data[idx].onhide.call(this.app,this,idx,this.data[idx].id);

		this.design.remove_item(this,idx);
		var id=this.data[idx].id;
		var f=this.data[idx].onclose;
		this.data.splice(idx,1);
		if(idx==this.active_tab) {
			this.active_tab=-1;
			if(idx==this.data.length) 
				if(idx==0) this._assign_content(-1);
					else this.activateTab(idx-1);
				else this.activateTab(idx);
		} else if(idx<this.active_tab) this.active_tab--;
		this._setscrolls();
		if(f) f(this,idx,id);
	},
	setTitle: function(idx,title) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		this.data[idx].title=title;
		this.design.set_title(this,idx);
		this._setscrolls();
	},
	content: function(idx,c) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		if(!this.data[idx].cont) {
			this.data[idx].cont=document.createElement('DIV');
			$(this.data[idx].cont).addClass("u-tabc-content");
		}
		$(this.data[idx].cont).html(c);
		this.data[idx].firstload=1;
		if(idx==this.active_tab) this._assign_content(idx);
	},
	_assign_content: function(idx,altcont) {
		if(altcont) this.parts.content=altcont;
			else if(idx<0) this.parts.content=this.parts.emptycontent;
			else this.parts.content=this.data[idx].cont;
		$(this.parts.content).css({width:(this.width-this.decor.cdw)+'px',height:(this.height-this.decor.cdh)+'px'});
		this.parts.body.replaceChild(this.parts.content,this.parts.body.firstChild);
		if(!altcont && idx>=0 && typeof this.data[idx].onload == 'function' && this.data[idx].firstload) this.data[idx].onload.call(this.app,this,idx,this.data[idx].id);
		if(!altcont && idx>=0 && typeof this.data[idx].onshow == 'function') this.data[idx].onshow.call(this.app,this,idx,this.data[idx].id);
		this.data[idx].firstload=0;
	},
	markload: function(idx,txt) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		var c;
		if(this.data[idx].markload) { //this tab has its own markload page
			if(!this.data[idx].markloadcont) {
				this.data[idx].markloadcont=document.createElement('DIV');
				$(this.data[idx].markloadcont).addClass("u-tabc-content").html(this.data[idx].markload);
			}
			c=this.data[idx].markloadcont;
		} else {
			if(!this.parts.markloadcont) {
				this.parts.markloadcont=document.createElement('DIV');
				$(this.parts.markloadcont).addClass("u-tabc-content").html(this.props.markload);
			}
			c=this.parts.markloadcont;
		}
		this._assign_content(idx,c);
	},
	idxbyid: function(id) {
		if(typeof id=='string') {
			for(var i=0;i<this.data.length;i++) if(this.data[i].id==id) return i;
			return -1;
		} else return id;
	},
	load: function(idx,reload) {
		idx=this.idxbyid(idx);
		if(idx<0 || idx>=this.data.length) return;
		if(this.data[idx].cont!=null && !reload) { //content is already loaded
			this._assign_content(idx);			
			return;
		}
	    var c=this.data[idx].dat;
    	if(typeof (c) == 'string') this.content(idx,c);
    	else if(typeof c == 'function') this.content(idx,c());
    	else if(typeof c == 'object') {
			this.markload(idx);
			if(!c.success && c.xml===false) {c.dataType='text';c.success=new Function("data","st","var w=_uTabCtrl.all["+this.idx+"];if(w)w.content('"+this.data[idx].id+"',data);");}
	   			else if(!c.success && c.xml!==false) c.success=new Function("data","st","var w=_uTabCtrl.all["+this.idx+"];_uParseXML(data,w,'"+this.data[idx].id+"');");
			if(!c.error) c.error=new Function("xml","st","er","var w=_uTabCtrl.all["+this.idx+"];if(w)w._onerror('"+this.data[idx].id+"',xml,st,er);");
			try {
			if(c.form && (c.form.length>0 || c.form.nodeType)) //have form
	   			_uPostForm(c.form,c);
	   		else if(c.url) _uAjaxRequest(c.url,c);
			} catch(e) {this._onerror(this.data[idx].id,null,'',e);}
    	}
    	return true;
	},
	_onerror: function(id,xml,st,er) {
		var idx=this.idxbyid(id);
		if(idx<0 || idx>=this.data.length) return;
	    var o=this.props.onerror;
	    if(o && typeof(o)=='function') o.apply(this.app,arguments);
			else this.content(idx,'Error during load. Try to <a href="javascript://" onclick="var w=_uTabCtrl.all[\''+this.idx+'\'];if(w)w.load(\''+this.data[idx].id+'\',1);">reload</a>.');
	},
	destroy: function() {
		//remove items
		this.data.splice(0,this.data.length);
		this.parts=null;
		this.top.parentNode.removeChild(this.top);
		this.top=null;
		if(this.props.ondestroy) this.props.ondestroy(this,this.name);
	}
};

function _uWnd (name,title,width,height,opts,content,menuitems,app) {
    if(name && name.length>0) {
		var t=_uWnd.getbyname(name);
		if(t) {t.reload(content);return false;}
    }
    this.desktop=this.opts && this.opts.desktop || _uWnd.defdesktop;
//opts:
//	header - whether window has header
//	min - show minimize button
//	max - show maximize/restore button
//	close - show close button
//	hidden - whether initially hidden
//	modal - whether window is modal
//	alert - window has z-index above modal windows
//	popup - whether window is closed when clicked outside
//	nomove - window cannot be moved
//	resize - whether window can be resized
//  fixed - whether window is fixed to viewport
    this.props=$.extend({
	x: 'auto',
	y: 'auto',
	header: title ? 1 : 0,
	min: this.desktop ? 1 : 0,
	max: this.desktop ? 1 : 0,
	session: null,
	close: 1,
	center: 0, //center window even for desktop (not cascaded)
	customButtons: null, //{ 'name': [init_visible,actionfunc(wnd,'name'),thispar]... }  'xt-name' class, 'xt-name-over' will be used when mouseover
	hidden: 0,
	modal: 0, //system modal window if no parent window specified. just disables parent otherwise
	parent: null, //parent window, necessary for modal mode if window is not system modal
	nomove: 0,
	resize: 1,
	fixed: _uWnd.defdesktop || opts.desktop ? 0 : 1,
	autosize: 1,
	autosizewidth: 0,
	autosizeonimages: 0, //restart auto size on every image load if content has images
	hideonresize: 0, //make content invisible during autosize
	waitimages: 0, //if >0, then do not show content until all images are loaded (timeout is specified value), only during autosize
	markload: '<div align="left"><div class="myWinLoad"></div></div>', //default mark load text
	markdisablecont: '<div class="myWinLoad"></div>', //default content of disabling layer (grided mode)
	markdisableclass: 'myWinGrid', //default class for disabling layer

	popup: 0,
	alert: 0,
	align: 'center',
	shadow: 1,
	design: 'std',
	fadetype: 1, //0 - no fade, 1 - animate opacity, 2 - move down and opacity
	fadespeed: 800,
	fadeclosetype: 1, //0 - no fade, 1 - animate opacity, 2 - move down and opacity
	fadeclosespeed: 250,
	minh: 50,
	minw: 0,
	maxh: 0,
	maxw: 0,
	icon: '',
	havemenu: menuitems ? 1 : 0,
	menuopts: null, //object with menu options, will be passed to menu constructor
	desktop: null,
	onerror: null,
	onclose: null, //(wnd,wndidx) called after window is destroyed
	onbeforeclose: null, //(wnd) called after user 'close' event appears (button or taskbar). if true, then ignore close
	oninit: null, //called when window finished its initialization and content can be loaded, if returns false, no default content is assigned to window (can be used to assign already created tab control)
	oncontent: null, //(wnd,contElem) called after content is loaded into window and its object became accessible
	onmousemove: null, //(wnd,x,y,{ctrl:0,alt:0,shift:0,meta:0},event) send when mouse is moving over content area, x and y relative to content	
	onposchange: null, //(wnd) called when window position, size of min/max state is changed
	onactivate: null, //(wnd) called when window is activated (got focus)
	ondeactivate: null, //(wnd) called when window is deactivated (lost focus)
	notaskbar: 0,
	trayicon: null, //just string with icon image URL or object with all optional fields (image must be if window have no icon){title:title, img:image, param:param, thisobj:thisobj, ondown:handler,onclick:handler,onrdown:handler} if thisobj redefined, no standard handlers will be set. param is true for animated show/hide
	traymenu: null, //tray menu which will be set by standard onrdown handler (array with items)
	notabdestroy:0
    }, opts || {});
	if(this.props.modal) this.props.min=0;
	if(this.props.session) {
		this.props.x=this.props.session.x;
		this.props.y=this.props.session.y;
	}
//content is string, function returning string or object:
//  url - load window content (on show) by using request to this url, if xml=true, content should be set by _uWnd.content(name,content) or wnd.content(content), otherwise result assumed to be plain html
//  form - send request (for 'url' option) using data from this form ID. if no 'url', use 'action'
//  xml - whether result of remote request is raw html or parsed XML
//  type - 'get' or 'post' methods when 'form' is specified, otherwise use form's 'method' attribute
//  cache - whether to allow browser to cache result of remote request
//  async - whether to do async remote request
//  success - alternative function(data,status) to process successful request (default depends on 'xml')
//  error - handler of error requests. 
//  dataType - data type to return to 'success' function
    $.extend(this,
	{
	name: name,
	title: title ? title : '',
	letsize: 1, //average width of letters in title
	width: width && width>10 ? width : 300,
	height: height && height>10 ? height : 200,
	decor: {w:0, h:0, th:0}, //width of window decoration (it is added to content width to get window width)
	_content: content,
	state: {visible:false,minimized:false,maximized:false,loaded:false,init:false,disabled:false,grided:false,noshadow:false,resizing:false,destroyed:false},
	grid: null, //grid object for modal windows
	frame: null, //background iframe for IE
	sh: null,//array of shadow objects
	sh_sz: [4,2], //shadow outdent and indent in pixels
	xpos: 0,
	ypos: 0,
	zpos: this.props.modal || this.props.alert ? _uWnd.getModalTopZ() : _uWnd.getTopZ(),
	_drag: new _uDraggable(this,this._ondragmousemove,null,this.onstartdrag,this.onstopdrag),
	_resize: new _uDraggable(this,this._onrsmousemove,null,this.onstartrs,this.onstoprs),
	restRect: null,
//		rsBut: {},
	minheight: this.props.minh,
	minwidth: this.props.minw,
	maxheight: this.props.maxh,
	maxwidth: this.props.maxw,
	pend_show: null,
	autosz: {active:false},
	imgloader: {timer:null,active:false},
	menu: null,
	app: app || null, //parent application. if assigned then all event handlers and content function are called in context of app
	tabctrl: null
	});
    this.design=this.props.design && _uWnd.designs[this.props.design] || _uWnd.designs['std'];
    this.idx=_uWnd.nextidx++;
    _uWnd.all[this.idx]=this;
    if(!_uWnd.globalset) {
	_uWnd.globalset=true;
//		$(document).bind("click",_uMenu.allmenushide);
//	$(document).bind("mouseup",_uWnd._onmouseup);
	$(document).bind("mousedown",_uWnd.closepopup);
//	$(document).bind("mousemove",_uWnd._onmousemove);
//		if($.browser.msie)$(document).bind("mouseout",function(e) {if(!e.relatedTarget && !e.toElement)_uWnd._dragging=null});
	$(window).bind("scroll",_uWnd._onscroll);
	$(window).bind("resize",_uWnd._onresize);
    }
    this.init(menuitems);
}

_uWnd.all={};
_uWnd.nextidx=0;
_uWnd.zchilds=[];
_uWnd.lastz=0;
_uWnd.minz=10000;
_uWnd.maxz=20000;
_uWnd.lastmodalz=0;
_uWnd.minmodalz=21000;
_uWnd.maxmodalz=25000;
_uWnd.globalset=false;
_uWnd.defdesktop=null;
_uWnd.activewnd=null;
_uWnd.globalmousedown=function(){
	_uMENU.hideallmenus();
	_uSuggestList.hideall();
	_uComboBox.hideall();
	_uWnd.closepopup();
};
_uWnd.alerts=null;
_uWnd.alert=function(txt,title,opts) {
    opts=$.extend({w:150,h:100,tm:5000,close:1,align:'center',icon:'',name:''},opts || {});
    var d,x,y,by,p,maxy;
    if(!(d=_uWnd.defdesktop)) {
    	d=_uWnd.getdims();
    	x=d.clientW-opts.w-5;
    	by=d.clientH-opts.h-5;//bottom y
    	p=_uWnd.alerts;
    	maxy=0;
    	d=null;
    } else {
		x=d.width-d.calcexclude(1)-opts.w-5;
		by=d.height-d.calcexclude(3)-opts.h-5;
		p=d.alerts;
		maxy=d.calcexclude(2);
    }
   	y=by;
    if(p) {
		if(p.y-(opts.h+5)>=0) y=p.y-(opts.h+5);
		while(p) {if(p.y>maxy) maxy=p.y;p=p.prev;}
		if(maxy>0 && by-maxy>=opts.h+5)y=by;
    }
    var w=new _uWnd(opts.name,title,opts.w,opts.h,{close:opts.close,min:0,max:0,icon:opts.icon,align:opts.align,x:x,y:y,alert:1,autosize:0,fixed:1,shadow:0,resize:0,nomove:1,hidden:0,notaskbar:1,fadetype:2,fadespeed:500,fadeclosetype:2,fadeclosespeed:500,onclose:function(w,idx){_uWnd.rmalert(w,idx);}},txt);
    if(!d)_uWnd.alerts={prev:_uWnd.alerts,wnd:w,y:y};
    	else d.alerts={prev:d.alerts,wnd:w,y:y};
    if(opts.tm>0) setTimeout("var w=_uWnd.all["+w.idx+"];if(w)w.close();",opts.tm);
    return w;
};
_uWnd.rmalert=function(w,idx) {
    var a=w.desktop ? w.desktop.alerts : _uWnd.alerts,p=null;
    while(a && a.wnd!==w) {p=a;a=a.prev;}
    if(a && a.wnd===w) if(p) p.prev=a.prev; else {
    	if(w.desktop) w.desktop.alerts=a.prev; else _uWnd.alerts=a.prev;
    }
};
_uWnd._onscroll=function(e) {
    if(!$.browser.msie) return;
    var d=_uWnd.getdims(),a=_uWnd.all;
    for(var i in a) 
	if(a[i]) if(a[i].props.fixed || a[i].grid) a[i].moveTo(a[i].xpos,a[i].ypos);
};
_uWnd._onresize=function(e,dsk) { //if dsk then select by desktop, otherwize without desktop
    var d=_uWnd.getdims(),a=_uWnd.all;
    for(var i in a) if(a[i])  if((!dsk && !a[i].desktop) || a[i].desktop==dsk) a[i]._onresize(d);
};
_uWnd.closepopup=function() {
    var a=_uWnd.all;
    for(var i in a)	if(a[i] && a[i].props.popup) a[i].closeevent();
};
_uWnd.findparent=function(elem){ //find parent window for specified element
	var p=elem;
	while(p && p!=document.body) {
		if(p.id && p.id.indexOf && p.id.indexOf('_uwndTop')==0 && p._uwndobj) return p._uwndobj;
		p=p.parentNode;
	}
	return null;
};
_uWnd.getbyname=function(name) {
    var a=this.all;
    for(var i in a) if(a[i] && a[i].name==name) return a[i];
    return null;
};
_uWnd.getTopZ=function() {
  with(_uWnd) {
    var z=lastz;
    if(z<minz) z=minz; else z+=5;
    if(z+5>maxz) {
		var x=minz;
		var ar=[];
		for(var i in all) if(all[i]) ar[ar.length]=all[i];
		for(var i=0;i<zchilds.length;i++) if(zchilds[i]) ar[ar.length]=zchilds[i];
		ar.sort(function(a,b){return a.zpos-b.zpos});
		for(var i=0;i<ar.length;i++) {
		    ar[i].setZ(x);x+=5;
		}
		z=x;
    }
    lastz=z;
    return z;
  }
};
_uWnd.getModalTopZ=function() {
  with(_uWnd) {
    var z=lastmodalz;
    if(z<minmodalz) z=minmodalz; else z+=5;
    if(z+5>maxmodalz) {
		var x=minmodalz;
		var ar=[];
		for(var i in all) if(all[i] && all[i].props && (all[i].props.modal || all[i].props.alert)) ar[ar.length]=all[i];
		ar.sort(function(a,b){return a.zpos-b.zpos});
		for(var i=0;i<ar.length;i++) {
		    ar[i].setZ(x);x+=5;
		}
		z=x;
    }
    lastmodalz=z;
    return z;
  }
};
_uWnd.getdims=function() {
    var d=document;
    var s='';
    return {clientW: Math.min($.browser.opera && window.innerWidth || $(window).width(),$.browser.safari && d.body.clientWidth || $(window).width(),$(window).width()),
	    clientH: Math.min($.browser.opera && window.innerHeight || $(window).height(),$.browser.safari && d.body.clientHeight || $(window).height(),$(window).height()),
	    clientLeft: $(d).scrollLeft(),
	    clientTop: $(d).scrollTop(),
	    docW: $(d).width(),
	    docH: $(d).height()};
};
_uWnd.csize=function(elem,name) {
    if ( name != "width" && name != "height" ) return 0;
    var val, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
    val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
    var padding = 0, border = 0;
    jQuery.each( which, function() {
	padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
	border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
    });
    val -= Math.round(padding + border);
    return Math.max(0, val);
}
_uWnd.close=function(name) {
    var w=_uWnd.getbyname(name);
    if(w) w.close();
}
_uWnd.content=function(name,c) {
    var w=_uWnd.getbyname(name);
    if(w)w.content(c);
}
_uWnd.reload=function(name,c) {
    var w=_uWnd.getbyname(name);
    if(w)w.reload(c);
}
_uWnd.setTitle=function(name,t) {
    var w=_uWnd.getbyname(name);
    if(w)w.setTitle(t);
}
_uWnd.activatetopwnd=function(dsk) {
    var maxz=0,maxw=null,a=_uWnd.all;
    for(var i in a) {
		if(!a[i] || (dsk && a[i].desktop!=dsk) || !a[i].state.visible || a[i].state.minimized) continue;
		if(a[i].zpos>maxz){maxz=a[i].zpos;maxw=a[i];}
	}
	if(maxw)maxw.activate();
		else if(dsk)dsk.activewnd=null;else _uWnd.activewnd=null;
};
_uWnd.designs={
    std: {
	sh_sz: [4,2], //design specific shadow config
	altcloseclass: 'xt-close2',

	shadow_init: function(top) {
	    var sh=[];
	    for(var i=0;i<3;i++) {
			sh[i]=document.createElement("div");
			top.appendChild(sh[i]);
			$(sh[i]).attr("class","x-sh").css({position:"absolute",zIndex:1});
	    }
	    $(sh[0]).addClass("xsl").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px",top:"0px"}).html('<div class="xstl"><div class="xsml"></div></div>');
	    $(sh[1]).addClass("xsr").css({width:(this.sh_sz[0]+this.sh_sz[1])+"px",top:"0px"}).html('<div class="xstr"><div class="xsmr"></div></div>');
	    $(sh[2]).addClass("xsb").css({height:(this.sh_sz[0]+this.sh_sz[1])+"px",left:(-this.sh_sz[0])+"px"}).html('<div class="xsbl"><div class="xsbr"><div class="xsbc"></div></div></div>');
	    return sh;
	},
	shadow_resize: function(sh,w,h) {
	    $(sh[0]).css({height:(h-this.sh_sz[1])+"px"});
	    $(sh[1]).css({height:(h-this.sh_sz[1])+"px",left:(w-this.sh_sz[1])+"px"});
	    $(sh[2]).css({width:(w+this.sh_sz[0]*2)+"px",top:(h-this.sh_sz[1])+"px"});
	},
	shadow_hide: function(sh) {
	    $(sh[0]).add(sh[1]).add(sh[2]).hide();
	},
	shadow_show: function(sh) {
	    $(sh[0]).add(sh[1]).add(sh[2]).show();
	},
	custButMargin: 5,
	wnd_init: function(o,wnd,title,align,inith,head,icon,resize,menu) {
		$(wnd).addClass("xw-plain").addClass("x-unselectable");
	    if(resize) $(wnd).addClass("xw-resize");
		var custbuts='';
		if(o.props.customButtons) for(var i in o.props.customButtons) 
			custbuts+='<div class="xt xt-'+i+'"></div>';
	    $(wnd).html(
		(head ? '<div class="xw-tl"><div class="xw-tr"><div class="xw-tc">'
+ '<div class="xw-sps"></div><div class="xw-hdr">'
+ '<div class="xt xt-close"></div><div class="xt xt-maxi"></div><div class="xt xt-rest"></div><div class="xt xt-mini"></div>'
+ custbuts
+ (icon ? '<img unselectable="on" onmousedown="return false;" class="xw-icon x-unselectable" src="'+icon+'">' : '')
+ '<span class="xw-hdr-text">'+title+'</span></div></div></div></div>' :
		'<div class="xw-tl"><div class="xw-tr"><div class="xw-tc xw-tsps"></div></div></div>')
+ '<div class="xw-ml"><div class="xw-mr"><div class="xw-mc">'
+ (menu ? '<div class="u-wndmenufr"><div class="u-wndmenu" style="position:relative"></div></div>' : '' )
+ '<div class="xw-body">'
+ '<div style="overflow:scroll;height:'+inith+'px">'
+ '<div class="myWinCont" style="display:none;overflow:hidden"'+(align ? ' align="'+align+'"' : '')+'></div><div class="'+o.props.markdisableclass+'" style="display:none;overflow:hidden;position:absolute;z-index:30000"></div><div class="myWinCont" style="overflow:hidden"'+(align ? ' align="'+align+'"' : '')+'></div></div></div></div></div></div>'
+ '<div class="xw-bl"><div class="xw-br"><div class="xw-bc"></div></div></div>'
+ '<div class="xw-bl" style="display:none"><div class="xw-br"><div class="xw-bcm"></div></div></div>'
+ '<div class="xw-blank" style="display:none"></div>'
	    );
	    var p={};
	    p.upper=$(wnd).find(".xw-tl")[0];
	    p.center=$(wnd).find(".xw-ml")[0];
	    p.bottom=$(wnd).find(".xw-bl")[0];
	    p.bottomc=$(wnd).find(".xw-bc")[1];
	    $(wnd).find(".xw-mc").bind("mousedown",o,function(e){e.stopPropagation();e.data.activate(e);_uWnd.globalmousedown();});
	    p.markload=$(wnd).find(".myWinCont")[0];
	    $(p.markload).html(o.props.markload);
	    p.wndcont=$(wnd).find(".myWinCont")[1];
	    p.markdis=$(wnd).find("."+o.props.markdisableclass)[0];
	    $(p.markdis).html(o.props.markdisablecont);
	    p.hwndcont=p.wndcont.parentNode;
	    if(head) {
		p.hdr=$(wnd).find(".xw-hdr")[0];
		p.htitle=$(wnd).find(".xw-hdr-text")[0];
		var buts={cbut:"xt-close",mbut:"xt-mini",xbut:"xt-maxi",rbut:"xt-rest",icon:"xw-icon"};
		for(var i in buts) {
		    p[i]=$(p.hdr).find("."+buts[i])[0];
		}
		p.custom={};
		for(var i in o.props.customButtons) {
			p.custom[i]=$(p.hdr).find(".xt-"+i)[0];
		}
	    } else {
		p.hdr=p.htitle=p.cbut=p.mbut=p.xbut=p.rbut=p.icon=null;
	    }
	    if(menu) p.menu=$(wnd).find(".u-wndmenu")[0]; else p.menu=null;
	    $(wnd).find("div,span").andSelf().attr("unselectable","on");
	    return p;
	},
	onstartautosz: function(o) {
//		o.parts.hwndcont.style.overflow="hidden";
		o.parts.wndcont.style.overflow="hidden";
		o.parts.wndcont.style.height="auto";
	},
	onstopautosz: function(o,onlyscroll) { //onlyscroll true to request restoration if sctool behaivor only
//		o.parts.hwndcont.style.overflowY="auto";
		if(!onlyscroll) o.parts.hwndcont.style.visibility="visible";
		o.parts.wndcont.style.overflow="auto";
		o.parts.wndcont.style.height="100%";
	},
	get_szbuts: function(wnd) {
	    var rs={nw:"xw-tl",n:"xw-sps",ne:"xw-tr",w:"xw-ml",e:"xw-mr",sw:"xw-bl",s:"xw-bc",se:"xw-br"};
	    for(var i in rs) {
			rs[i]=$(wnd).find("."+rs[i])[0];
	    }
	    if(!rs.n) rs.n=$(wnd).find(".xw-tsps")[0];
	    return rs;
	},
	onbuttonover: function(e) {
		var cls=e.data.cls;
		if(e.data.state)
	    	$(this).addClass(cls+'-over');
	    else
	    	$(this).removeClass(cls+'-over');
	},
	onstartdrag: function(o) {
	    if($.browser.msie) o.parts.upper.style.filter="Alpha(Opacity='70')";
		else o.parts.upper.style.opacity=0.7;
	    if(!o.state.minimized) {
		o.hideSh();
		$(o.parts.center).add(o.parts.bottom).hide();
		$(o.wnd).find(".xw-blank").css('width',o.width+'px').css('height',(o.height-o.decor.th)+'px').show();
	    }
	},
	onstopdrag: function(o) {
	    if($.browser.msie) o.parts.upper.style.filter="Alpha(Opacity='100')";
		else o.parts.upper.style.opacity=1;
	    if(!o.state.minimized) {
		o.showSh();
		$(o.parts.center).add(o.parts.bottom).show();
		$(o.wnd).find(".xw-blank").hide();
	    }
	},
	onactivate: function(o) {
		$(o.wnd).addClass("xw-active");
	},
	ondeactivate: function(o) {
		$(o.wnd).removeClass("xw-active");
	},
	onstartresize: function(o) {
	},
	onstopresize: function(o) {
	},
	onminimize: function(o) {
	    $(o.parts.center).css("display","none");
	    $(o.parts.bottomc).addClass("xw-bcm");
	    o.hideSh();
	},
	onrestore: function(o) {
	    $(o.parts.bottomc).removeClass("xw-bcm");
	    $(o.parts.center).css("display","block");
	    o.showSh();
	}
    }	
};


_uWnd.prototype={
setZ:function(z) {
  with(this){
    zpos=z
    $(top).css("z-index",z);
    if(grid)$(grid).css("z-index",z-1);
  }
},
saveSession: function() { //return data sutable to restore window state
    var r;
    if(this.state.maximized || this.state.minimized) r=this.restRect;
        else r=[this.xpos,this.ypos,this.width,this.height];
    return {
                x:r[0],
                y:r[1],
                w:r[2]-this.decor.w,
                h:r[3]-this.decor.h,
                s:this.state.maximized ? 'max' : (this.state.minimized ? 'min' : '')
	};
},
moveTo:function(_x,_y,frominit) {
    var d=_uWnd.getdims();
  with(this) {
    if(_x=='auto' && _y=='auto' && desktop && !props.fixed && !props.autosize && !props.center) {
    	var p=desktop.getwndcoord(width,height);
    	_x=p.x;
    	_y=p.y;
    } else {
	    if(_x=='auto') {
			if(desktop && !props.fixed) _x=Math.floor((desktop.calcwidth()-width)/2);
				else _x=Math.floor((d.clientW-width)/2)+(props.fixed?0:d.clientLeft);
	    	if(_x<0) _x=0;
	    }
	    if(_y=='auto') {
			if(desktop && !props.fixed) _y=Math.floor((desktop.calcheight()-height)/2);
	    		else _y=Math.floor((d.clientH-height)/2)+(props.fixed?0:d.clientTop);
	    	if(_y<0) _y=0;
	    }
	}
    if(props.fixed && $.browser.msie) $(top).css("left",(d.clientLeft+_x)+'px').css("top",(d.clientTop+_y)+'px');
	else $(top).css("left",_x+'px').css("top",_y+'px');
    if(grid) 
	if($.browser.msie) $(grid).css("left",d.clientLeft+'px').css("top",d.clientTop+'px');
	    else $(grid).css("left",'0px').css("top",'0px');
    xpos=_x;
    ypos=_y;
    if(this.props.onposchange && !frominit) this.props.onposchange.apply(this.app,[this]);
  }
},
setTitle:function(t) {
    if(t!=null)this.title=t;
    if(!this.title)this.title='';
  with(this) {
    if(!props.header) return;
    var ts=width-decor.w,l;
    ts-=_countbuttonwidth();
    l=title.length;
    if(l*letsize>ts) l=Math.floor(ts/letsize)-2;
    if(l<title.length) 
	$(parts.htitle).attr("title",title).text(title.substr(0,l)+'...');
	else
	$(parts.htitle).attr("title",'').text(title);
  }
},
resizeTo:function(w,h,center,frominit) {
  with(this) {
    if(center) {
        var d=_uWnd.getdims();
		var _x=xpos,_y=ypos;
	    if(props.x=='auto') {
			if(desktop && !props.fixed) _x=Math.floor((desktop.calcwidth()-w)/2);
				else _x=Math.floor((d.clientW-w)/2)+(props.fixed?0:d.clientLeft);
	    	if(_x<0) _x=0;
	    }
	    if(props.y=='auto') {
			if(desktop && !props.fixed) _y=Math.floor((desktop.calcheight()-h)/2);
	    		else _y=Math.floor((d.clientH-h)/2)+(props.fixed?0:d.clientTop);
	    	if(_y<0) _y=0;
	    }
		if(_x!=xpos | _y!=ypos) moveTo(_x,_y,1);
    }
    $(wnd).css("width",w+'px');
    $(parts.wndcont).css("width",(w-decor.w)+'px');
    $(parts.hwndcont).css("height",(h-decor.h)+'px');
    if(parts.markdis) $(parts.markdis).css({height:(h-decor.h)+'px',width:(w-decor.w)+'px'});

    if(menu) $(parts.menu).css("width",(w-decor.w)+'px');

    if(tabctrl) tabctrl.resizeTo(w-decor.w,h-decor.h);
    if(frame) $(frame).css("width",w+'px').css("height",h+'px');
    width=w;
    height=h;
    if(this.props.onposchange && !frominit && !this.state.maximized && !this.state.minimized) this.props.onposchange.apply(this.app,[this]);
    _resizeSh();

    setTitle();
  }
},
_onresize:function(d) {
    if(this.state.maximized) 
		if(this.desktop && !this.props.fixed) {
		    this.moveTo(this.desktop.calcexclude(0),this.desktop.calcexclude(2),1);
	    	this.resizeTo(this.desktop.calcwidth(),this.desktop.calcheight(),0,1);
		} else this.resizeTo(d.clientW,d.clientH);
    if(this.grid) $(this.grid).css("width",d.clientW+'px').css("height",d.clientH+'px');
},
_resizeSh:function() {
    if(this.sh)this.design.shadow_resize(this.sh,this.width,this.height);
},
hideSh:function() {
    if(this.sh)this.design.shadow_hide(this.sh);
},
showSh:function() {
    if(this.sh && !this.state.noshadow)this.design.shadow_show(this.sh);
},
shadow_init:function() {
    this.sh=this.design.shadow_init(this.top);
},
showcustombutton: function(name,state) {
	if(!this.props.customButtons[name]) return;
	this.props.customButtons[name][0]=state;
	if(!this.parts.custom[name]) return; //window not initted yet
	if(!state) $(this.parts.custom[name]).css("display","none");
		else $(this.parts.custom[name]).css("display","block");
},
init: function(menuitems) {
    var p=this.props,t=document.createElement("div"),w;
//top parent for window and optional shadow
	t.id="_uwndTop"+this.idx;
	t._uwndobj=this;
    if(!this.desktop) $($("body")[0]).prepend(t);
    	else this.desktop.dsk.appendChild(t);
    this.top=t;
    if(!p.fixed || $.browser.msie)	$(t).css("position","absolute"); else $(t).css("position","fixed");
    $(t).css("visibility",'hidden').css("display",'block').css("z-index",this.zpos);
//grid for modal windows
    if (p.modal){
		var g=document.createElement("div"),d=_uWnd.getdims();
		$(g).addClass('myWinGrid').css("width",d.clientW+'px').css("height",d.clientH+'px').css("z-index",this.zpos-1).hide().bind('mousedown',function(e){e.stopPropagation();e.preventDefault();_uWnd.globalmousedown();});
		if($.browser.msie)	$(g).css("position","absolute"); else $(g).css("position","fixed");
	    if(!this.desktop) $($("body")[0]).prepend(g);
	    	else this.desktop.dsk.appendChild(g);
		this.grid=g;
    }
    if($.browser.msie && parseFloat($.browser.version)<7){
        this.frame=document.createElement("iframe");
        with(this.frame.style) {
            filter="Alpha(Opacity='0')";
            display="block";
            position="absolute";
//            zIndex=0;
            borderWidth=0;
            width=this.width+'px';
            height=this.height+'px';
        }
	t.appendChild(this.frame);
    }

    if(p.shadow && !($.browser.msie && parseFloat($.browser.version)<7)) {
		this.shadow_init();
		this._resizeSh();
    }
    this.moveTo(p.x,p.y,1);
//window
    w=document.createElement("div");
    w.id="_uwndWnd"+this.idx;
    t.appendChild(w);
    this.wnd=w;
    $(w).css({position: "absolute",width: this.width+'px',zIndex:2,left:0});

	if(!_uWnd._activateonmousedown) _uWnd._activateonmousedown=function(e){e.stopPropagation();e.data.activate(e);_uWnd.globalmousedown();};
	if(!_uWnd._activateonmousedownign) _uWnd._activateonmousedownign=function(e){e.data.activate(e);_uWnd.globalmousedown();};
    this.parts=this.design.wnd_init(this,w,this.title,p.align,60,p.header,p.icon,p.resize,p.havemenu);
    if(p.header) {
		var bb={cbut:"xt-close",mbut:"xt-mini",xbut:"xt-maxi",rbut:"xt-rest"};
		if(!_uWnd._retfalse) _uWnd._retfalse=function(e){return false;};
		if(!_uWnd._onclickcustom) _uWnd._onclickcustom=function(e){var d=e.data;d.wnd.activate(e);d.func.call(d.thispar,d.wnd,d.name);};
		if(!_uWnd._onbuttonclose) _uWnd._onbuttonclose=function(e){e.data.activate(e);e.data.closeevent();};
		if(!_uWnd._onbuttonmin) _uWnd._onbuttonmin=function(e){e.data.activate(e);e.data.minimize()};
		if(!_uWnd._onbuttonmax) _uWnd._onbuttonmax=function(e){e.data.activate(e);e.data.maximize()};
		if(!_uWnd._onbuttonrest) _uWnd._onbuttonrest=function(e){e.data.activate(e);e.data.restore()};

		for(var i in bb)
		    $(this.parts[i]).bind("dblclick",_uWnd._retfalse).bind("mouseover",{cls:bb[i],state:1},this.design.onbuttonover).bind("mouseout",{cls:bb[i],state:0},this.design.onbuttonover).bind("mousedown",this,_uWnd._activateonmousedown);

		for(var i in p.customButtons) {
		    $(this.parts.custom[i]).bind("dblclick",_uWnd._retfalse).bind("mouseover",{cls:'xt-'+i,state:1},this.design.onbuttonover).bind("mouseout",{cls:'xt-'+i,state:0},this.design.onbuttonover).bind("mousedown",this,_uWnd._activateonmousedown);
			if(!p.customButtons[i][0]) $(this.parts.custom[i]).css("display","none");
			if(p.customButtons[i][1]) $(this.parts.custom[i]).bind("click",{wnd:this,name:i,func:p.customButtons[i][1],thispar:p.customButtons[i][2]},_uWnd._onclickcustom); //e.stopPropagation
		}

		if(!p.close) $(this.parts.cbut).css("display","none");
		$(this.parts.cbut).bind("click",this,_uWnd._onbuttonclose); //e.stopPropagation
		if(!p.min) $(this.parts.mbut).css("display","none");
		$(this.parts.mbut).bind("click",this,_uWnd._onbuttonmin); //e.stopPropagation
		if(!p.max) $(this.parts.xbut).css("display","none");
		$(this.parts.xbut).bind("click",this,_uWnd._onbuttonmax); //e.stopPropagation
		$(this.parts.rbut).css("display","none").bind("click",this,_uWnd._onbuttonrest); //e.stopPropagation
		if(p.close && !p.min && !p.max && this.design.altcloseclass) {//use alternative class
			$(this.parts.cbut).addClass(this.design.altcloseclass);
		}

		if(!p.nomove) $(this.parts.hdr).addClass("xw-draggable");
		$(this.parts.hdr).add(this.parts.htitle).bind("mousedown",this,function(e) {e.stopPropagation();e.data.activate(e);_uWnd.globalmousedown();return e.data._ondragmousedown(e);});
		if(p.max || p.min) $(this.parts.hdr).bind("dblclick",this,function(e){var a=e.data;if(a.state.maximized || a.state.minimized)a.restore();else a.maximize();});
    }

    var rs=this.design.get_szbuts(w);
	if(!_uWnd._onresizebuttondown) _uWnd._onresizebuttondown=function(e){e.stopPropagation();e.data.w.activate(e);_uWnd.globalmousedown();return e.data.w._onrsmousedown(e,e.data.tp);};
    for(var i in rs) {
		$(rs[i]).bind("mousedown",{w:this,tp:i},_uWnd._onresizebuttondown);
    }
    $(this.parts.wndcont).bind("mousedown",this,_uWnd._activateonmousedown);
    $(w).bind("mousedown",this,_uWnd._activateonmousedownign);
	if(p.havemenu) {
		var mopts=$.extend({
				parentnode:this.parts.menu,
				wnd:this,
				noabs:1,
				horiz:1,
				statical:1,
				width:'auto'
			},p.menuopts || {});
		this.menu=new _uMENU('',{},mopts,menuitems,true);
	}
    if(typeof this._content == 'object' && this._content.constructor==_uTabCtrl) {
    	this.tabctrl=this._content;
    	this.tabctrl.props.parentnode=this.parts.wndcont;
    	this.tabctrl.wnd=this;
    	this.tabctrl.init(true); //tab must be created with noinit property
    } else this.tabctrl=null;
	
	if(p.trayicon && this.desktop) {
		var to={};
		if(p.trayicon.contructor==String) to.img=p.trayicon;
			else if(p.trayicon.contructor!=Object) if(p.icon)to.img=p.icon;
		if(to.img) {
			if(!p.trayicon.thisobj) { //set standard handlers
				to.thisobj=this;
				if(!p.trayicon.ondown) to.ondown=this.ontrayicondown;
				if(!p.trayicon.onrdown) to.onrdown=this.ontrayiconrdown;
				to.param=p.trayicon.param;
			} else $.extend(to,p.trayicon);
			if(!to.title) to.title=this.title || '';
			this.trayicon=this.desktop.addTrayIcon(to.img,to.title,to.thisobj,to.ondown,to.onclick,to.onrdown,to.param);
			if(p.traymenu) {
				this.traymenu=new _uMENU('',{align:'U'},{hidden:1},p.traymenu);
			}
		}
	}
    if(!p.hidden) this.show(false);
    if(this.desktop && !p.modal && !p.popup && !p.alert && p.header && !p.notaskbar) this.desktop._addwindow(this);
    if(!p.alert) this.activate();
    if(p.header || this.menu) setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w.init1();",10);
	else setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w.init2();",10);
},
init1: function() {
	if(this.props.header) {
  		if(!this.title) this.letsize=8;
    		else
  			with(this) {
    			if(title.length==0) letsize=8;
				else letsize=parts.htitle.offsetWidth/title.length;
    			parts.htitle.innerHTML='...';
  			}
  	}
	if(this.menu) this.menu.init1(true);
    setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w.init2();",10);
},
init2: function() {
  with(this) {
	decor.sbw=parts.hwndcont.offsetWidth-parts.hwndcont.clientWidth;
	decor.sbh=parts.hwndcont.offsetHeight-parts.hwndcont.clientHeight;
    decor.w=width-_uWnd.csize(parts.wndcont,"width")-decor.sbw;
    decor.h=wnd.offsetHeight-60;
    decor.th=parts.upper.offsetHeight;
	parts.hwndcont.style.overflow='hidden';
	if(tabctrl)tabctrl.init1(true);
	if(props.session)
	    resizeTo(props.session.w+decor.w,props.session.h+decor.h,0,1);
		else
    	resizeTo(width,height,0,1);
	if(menu)menu._setsize();

    state.init=true;
	var rel=pend_show ? pend_show[0] : false;
    if(props.oninit) if(!props.oninit.call(app,this,name)) rel=false;
    $(top).css("display",'none').css("visibility",'visible');
    var s=props.session;
    if(s && s.s=='min') minimize(1);
    	else if(s && s.s=='max') maximize(1);
    	else
    		if(pend_show) show(rel,pend_show[1],pend_show[2]);
  }
},
deactivate: function() {
    var o=this.desktop ? this.desktop : _uWnd;
	if(o.activewnd && o.activewnd==this) o.activewnd=null;
	this.design.ondeactivate(this);
	if(this.desktop)this.desktop._onwnddeactivate(this);
    if(this.props.ondeactivate) this.props.ondeactivate.apply(this.app,[this]);
},
activate: function(e) {
    if(this.state.disabled) return;
    var o=this.desktop ? this.desktop : _uWnd;
	if(o.activewnd && o.activewnd!=this) o.activewnd.deactivate();
	o.activewnd=this;
	this.design.onactivate(this);
	if(this.desktop)this.desktop._onwndactivate(this);
    if(this.props.onactivate) this.props.onactivate.apply(this.app,[this]);
	if(this.props.modal || this.props.alert) {
	    if(this.zpos==_uWnd.lastmodalz) return;
    	this.setZ(_uWnd.getModalTopZ());
	} else {
	    if(this.zpos==_uWnd.lastz) return;
    	this.setZ(_uWnd.getTopZ());
	}
},
ontrayicondown:function(anim,icon,e) {
	if(!this.state.visible && !this.state.minimized) if(anim) this.show(false); else this.show(false,0,0);
		else if(this.state.minimized) {
			if(this.state.beforemin=='max')this.maximize();
				else this.restore();
		} else if(this.props.min && !this.props.notaskbar) this.minimize();
			else if(anim) this.hide(); else this.hide(0,0);

},
ontrayiconrdown:function(pp,icon,e) {
	if(!this.traymenu) return;
	this.traymenu.show({pos:{x:e.pageX,y:e.pageY}});
	_uMENU.ignoreclick=this.traymenu;

},
show: function(rel,fadetp,fadesp) {
  if(arguments.length<2 || fadetp==undefined) fadetp=this.props.fadetype;
  if(arguments.length<3 || fadesp==undefined) fadesp=this.props.fadespeed;
  with(this) {
    if(!state.init) {pend_show=[rel,fadetp,fadesp];return;}
    if(grid) $(grid).show();
    if(fadetp==1) {
		state.disabled=true;
		if($.browser.safari) hideSh();
		if($.browser.msie) {
		    state.noshadow=true;
		    hideSh();
	    	$(wnd).hide();
	    	$(top).show();
	    	$(wnd).css("opacity","0").show().animate( {opacity: 1} , {duration:fadesp,complete:new Function("var w=_uWnd.all["+idx+"];if(w){w.state.noshadow=false;w.state.disabled=false;w.showSh();}")});
		} else $(top).fadeIn(fadesp,new Function("var w=_uWnd.all["+idx+"];if(w)w.state.disabled=false;if($.browser.safari)w.showSh();"));
    } else if(fadetp==2) {
		state.disabled=true;
		var endy=parseInt($(top).css("top"));
		$(top).css("top", (endy+(height>100 ? 100 : height))+'px');
		if($.browser.msie) {
		    state.noshadow=true;
		    hideSh();
		    $(wnd).hide();
		    $(top).show().animate( {top: endy+"px"} , {duration:fadesp,complete:new Function("var w=_uWnd.all["+idx+"];if(w){w.state.noshadow=false;w.state.disabled=false;w.showSh();}")});
		    $(wnd).css("opacity","0").show().animate( {opacity: 1} , fadesp);
		} else $(top).css("opacity","0").show().animate( {top: endy+"px", opacity: 1} , {duration:fadesp,complete:new Function("var w=_uWnd.all["+idx+"];if(w)w.state.disabled=false;")});
    } else {$(top).show();state.disabled=false;}
    state.visible=true;
    if(!state.loaded || rel) load();
  }
},
hide: function(fadetp,fadesp,doclose) {
    if(arguments.length<1 || fadetp==undefined) fadetp=this.props.fadeclosetype;
    if(arguments.length<2 || fadesp==undefined) fadesp=this.props.fadeclosespeed;
    this.state.disabled=true;
    if(fadetp==1)
		if($.browser.msie) {
		    this.state.noshadow=true;
		    this.hideSh();
		    $(this.wnd).animate( {opacity: 0} , {duration:fadesp,complete:doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null});
		} else $(this.top).fadeOut(fadesp, doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null);
    else if(fadetp==2) {
		var endy=parseInt($(this.top).css("top"))+(this.height>100 ? 100 : this.height);
		if($.browser.msie) {
		    this.state.noshadow=true;
		    this.hideSh();
		    $(this.top).animate( {top: endy+"px"} , {duration:fadesp,complete:doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null});
		    $(this.wnd).animate( {opacity: 0} , fadesp);
		} else $(this.top).animate( {top: endy+"px", opacity: 0} , {duration:fadesp,complete:doclose ? new Function("var w=_uWnd.all["+this.idx+"];if(w)w.close(true);") : null});
    } 
    else {$(this.top).hide();doclose=false;}
    if(this.grid) $(this.grid).hide();
    this.state.visible=false;
	_uWnd.activatetopwnd(this.desktop);
    if(doclose)return 1;
    return 0;
},
markload: function() {
    this.parts.wndcont.style.display='none';
    this.parts.markload.style.display='block';
},
showgrid: function() {
	if(this.parts.markdis) this.parts.markdis.style.display='block';
},
hidegrid: function() {
	if(this.parts.markdis) this.parts.markdis.style.display='none';
},
reload: function(c) {
    this._content=c;
    if(typeof c == 'object' && c.constructor==_uTabCtrl)
    	this.tabctrl=c;
    	else
    	this.tabctrl=null;
    this.state.loaded=false;
    this.state.disabled=false;
    this.load();
    if(!this.props.hidden && !this.state.visible) this.show(false);
},
load: function() {
	if(this.tabctrl) return;
    var c=this._content;
	if(typeof (c) == 'string') this.content(c);
    else if(typeof c == 'function') this.content(c.apply(this.app,[]));
    else if(typeof c == 'object') {
	this.markload();
	if(!c.success && c.xml===false) {c.dataType='text';c.success=new Function("data","st","var w=_uWnd.all["+this.idx+"];if(w)w.content(data);");}
	    else if(!c.success && c.xml!==false) c.success=new Function("data","st","var w=_uWnd.all["+this.idx+"];_uParseXML(data,w);");
	if(!c.error) c.error=new Function("xml","st","er","var w=_uWnd.all["+this.idx+"];if(w)w._onerror(xml,st,er);");
	try {
	if(c.form && c.form.length>0) //have form
	    _uPostForm(c.form,c);
	    else if(c.url) _uAjaxRequest(c.url,c);
	} catch(e) {this._onerror(null,'',e);}
    }
},
_onerror: function(xml,st,er) {
    var o=this.props.onerror;
    if(o && typeof(o)=='function') o.apply(this,arguments);
	else this.close();	
},
_checkimgload: function(load) {
	var im=this.imgloader;
	var i;
	if(!im.active) return;
	if(load) im.count++;
	if(im.images) for(i=0;i<im.images.length;i++)	if(!im.images[i].complete) break;
	if(i>=im.images.length){this._stopimgload(true);return;}

	if(im.count>=im.images.length) { //after some events complete was not updated
		if(im.timer) clearTimeout(im.timer);
    	im.timer=setTimeout("var w=_uWnd.all["+this.idx+"];if(w){w.imgloader.timer=null;w._checkimgload();}",100);
	}
	if($.browser.opera && im.images2) {
		for(i=0;i<im.images2.length;i++) if(!im.images2[i].complete) return;
		$(im.images2).unbind();
		im.images2=null;
		this.parts.hwndcont.style.visibility='hidden';
    	this.parts.markload.style.display='none';
    	$(this.parts.wndcont).css("display","block");
	}
},
_stopimgload: function(start) {
	var im=this.imgloader;
	if(im.active) {
		im.active=false;
		if(im.stoptimer) {clearTimeout(im.stoptimer);im.stoptimer=null;}
		if(im.timer) {clearTimeout(im.timer);im.timer=null;}
		if(im.images) {im.images.unbind();im.images=null;}
		if(im.images2) {$(im.images2).unbind();im.images2=null;}

		if(start) {
			if(this.props.hideonresize) this.parts.hwndcont.style.visibility='hidden';
    		this.parts.markload.style.display='none';
    		$(this.parts.wndcont).css("display","block");
	    	this.autosz.load=true;
	    	this.delaychecksize();
	    }
	}
},
content: function(c) {
	this._stopimgload();
	this.stopautosize();
    var a=this.autosz,w=this.parts.wndcont,p=this.props,im=this.imgloader;

    this.state.loaded=true;
	if(p.autosize && p.waitimages>0) { //hide content until all images are loaded
		this.markload();
    	$(w).html(c);
	    if(this.props.oncontent) this.props.oncontent.apply(this.app,[this,w]);

    	im.active=true;
		im.stoptimer=setTimeout("var w=_uWnd.all["+this.idx+"];if(w)w._stopimgload(true);",p.waitimages);
		if(!_uWnd.waitimagesfunc) _uWnd.waitimagesfunc=function(e) {
				var im=e.data.imgloader;
				if(im.timer) clearTimeout(im.timer);
		    	im.timer=setTimeout("var w=_uWnd.all["+e.data.idx+"];if(w){w.imgloader.timer=null;w._checkimgload(1);}",10);
		    	};
		im.count=0;
    	im.images=$(w).find("img").bind('error',this,_uWnd.waitimagesfunc).bind('load',this,_uWnd.waitimagesfunc);
		if($.browser.opera && im.images.length>0) { //opera does not preload hidden images
			im.images2=[];
			for(var i=0;i<im.images.length;i++) im.images2[i]=$("<img>").attr("src",im.images[i].src).bind('load',this,_uWnd.waitimagesfunc)[0];
		}
    	this._checkimgload();
	} else {
		if(p.autosize && p.hideonresize)this.parts.hwndcont.style.visibility='hidden';
    	this.parts.markload.style.display='none';
    	$(w).css("display","block").html(c);
	    if(this.props.oncontent) this.props.oncontent.apply(this.app,[this,w]);
	    a.load=true;
	    if(p.autosize)this.delaychecksize();
	    	else this.design.onstopautosz(this);
    }

},
onexternalload: function() {
	this._stopimgload();
	this.stopautosize();

    this.state.loaded=true;
    this.autosz.load=true;
    if(this.props.autosize)this.delaychecksize();

},
stopautosize: function() {
	var a=this.autosz;
	if(a.inittimer) {clearTimeout(a.inittimer);a.inittimer=null;}
	if(a.timer){clearTimeout(a.timer);a.timer=null;}
	if(a.images) {$(a.images).unbind();a.images=null;}
	if(a.active)this.design.onstopautosz(this);
	a.active=false;
},
delaychecksize: function(d) { //true if called due to autosizeonimages, delay
	d=d || 10;
	var a=this.autosz;
	if(a.inittimer) clearTimeout(a.inittimer);
    a.inittimer=setTimeout("var w=_uWnd.all["+this.idx+"];if(w);w.checksize();",d);
 
},
_countbuttonwidth: function() {
	var w=0;
	var buts={cbut:1,mbut:1,xbut:1,rbut:1,icon:1};
	for(var i in buts) if(this.parts[i])w+=this.parts[i].offsetWidth;
	for(var i in this.props.customButtons) w+=this.parts.custom[i].offsetWidth+this.design.custButMargin;
	return w;
},
checksize: function(autoload) { //true if called due to autosizeonimages
    var a=this.autosz,w=this.parts.wndcont;
	a.inittimer=null;
    if(this.state.maximized || this.state.minimized) return;
    this.stopdrag();
    this.stopresize();
    if(a.load) {
		a.load=false;
		if(a.images) {$(a.images).unbind();a.images=null;}
		if(this.props.autosizeonimages) {
			if(!_uWnd.autosizeonimagesfunc) _uWnd.autosizeonimagesfunc=function(e) {e.data.delaychecksize();};
			a.images=$(w).find("img").bind('load',this,_uWnd.autosizeonimagesfunc);
		}
    }
    a.active=true;
	this.design.onstartautosz(this);
	if(a.timer){clearTimeout(a.timer);a.timer=null;}

    var d=_uWnd.getdims(),minw=10,minh=10,maxw,maxh;
    if(this.props.header) {
		minw+=this._countbuttonwidth();
    }   
    minw=Math.max(minw,this.minwidth);
    minh=Math.max(minh,this.minheight); 
    maxw=this.maxwidth;
    if(maxw==0) maxw=d.clientW-this.decor.w;
    maxh=this.maxheight;
    if(maxh==0) maxh=d.clientH-this.decor.h;

    var contW,contH; //scrollwidth and height
	if(this.props.autosizewidth) {
		$(this.parts.wndcont).css("width",'10px');
		contW=w.scrollWidth;
		$(this.parts.wndcont).css({width:(this.width-this.decor.w)+'px'});
	} else contW=w.scrollWidth;
    contH=w.scrollHeight;
//    a.tw=Math.min(Math.max(w.scrollWidth+scrW,w.offsetWidth,minw),maxw);
//    a.th=Math.min(Math.max(w.scrollHeight+scrH,w.clientHeight ? w.clientHeight : w.offsetHeight,minh),maxh);
	a.tw=Math.max(contW,minw);
	a.th=Math.max(contH,minh);
	var havescroll=false;
	if(a.tw>maxw) {a.tw=maxw;a.th+=this.decor.sbh;havescroll=true;}
	if(a.th>maxh) {
		a.th=maxh;
		if(a.tw+this.decor.sbw<=maxw) {a.tw+=this.decor.sbw;havescroll=true;}
			else a.tw=maxw;
		}
	if(havescroll) this.design.onstopautosz(this,true); //to enable scrolls during resize

    a.timer=setTimeout("try{_uWnd.all["+this.idx+"]._checksize();}catch(e){}",10);
},
_checksize: function() {
    this.stopdrag();
    this.stopresize();
    var a=this.autosz, dw=a.tw-(this.width-this.decor.w), dh=a.th-(this.height-this.decor.h),ws=10,hs=10;
    if(dw!=0) {
		if(dw>0) ws=Math.min(ws,dw);
	    	else if(dw<0) ws=Math.max(-ws,dw);
		this.resizeTo(this.width+ws,this.height,true,1);
    } else if(dh!=0) {
		if(dh>0) hs=Math.min(hs,dh);
	    	else if(dh<0) hs=Math.max(-hs,dh);
		this.resizeTo(this.width,this.height+hs,true,1);
    } else {
    	a.timer=null;
    	a.active=false;
//		if(this.props.hideonresize)
		this.design.onstopautosz(this);
    	return;
    }
    a.timer=setTimeout("try{_uWnd.all["+this.idx+"]._checksize();}catch(e){}",10);
},
closeevent: function() { //close event from user. insertion point for overrides
	if(this.props.onbeforeclose) if(this.props.onbeforeclose.apply(this.app,[this])) return;
	this.close(); //default action
},
close: function(nohide) {
	if(this.state.destroyed) return;
	if(this.desktop) this.desktop._removewindow(this);
    if(!nohide && this.state.visible) {
    	var a=this.hide(this.props.fadeclosetype,this.props.fadeclosespeed,true);
    	if(a==1) return;
    }
    this.top.parentNode.removeChild(this.top);
    if(this.grid) this.grid.parentNode.removeChild(this.grid);
	if(this.tabctrl && !this.props.notabdestroy) this.tabctrl.destroy();
    _uWnd.all[this.idx]=null;
    this.state.destroyed=true;
    this.state.visible=false;
    if(this.props.onclose) this.props.onclose.apply(this.app,[this,this.idx]);
	if(this.app) this.app._ondestroywnd(this);
//	delete this;
},
minimize: function(frominit) {
  with(this) {
    if(autosz.active || !props.min || !props.header || props.modal || props.alert || props.popup) return;
    state.beforemin=state.maximized ? 'max' : '';
    stopdrag();
    stopresize();
    if(!state.maximized && !state.minimized) restRect=[xpos,ypos,width,height,props.fixed];
    if(props.onposchange && !state.minimized && !frominit) props.onposchange.apply(app,[this]);
    state.maximized=false;
    state.minimized=true;
	this.deactivate();
	if(!frominit) _uWnd.activatetopwnd(this.desktop);

    if(!desktop) {
	   	$(parts.mbut).css("display","none");
	   	if(props.max)$(parts.xbut).css("display","block");
	   	$(parts.rbut).css("display","block");
	   	$(wnd).removeClass("xw-resize");

    	if(!props.fixed && !$.browser.msie) $(top).css("position","fixed");
	    design.onminimize(this);
	    props.fixed=true;
	    moveTo(0,0,1);
	    resizeTo(200,30,0,1);
	} else {
		if(!frominit) {
			hide(0);
			desktop._onwndminimize(this,xpos,ypos,width,height);
		}
	}
  }
},
maximize: function(frominit) {
  with(this) {
    if(autosz.active || !props.max || !props.header) return;
    stopdrag();
    stopresize();
    if(!state.maximized && !state.minimized) restRect=[xpos,ypos,width,height,props.fixed];
    if(state.minimized) {this.design.onrestore(this);if(desktop)show(false,0);}
    if(props.onposchange && !state.maximized && !frominit) props.onposchange.apply(app,[this]);
    state.maximized=true;
    state.minimized=false;

    $(parts.hdr).removeClass("xw-draggable");
    $(wnd).removeClass("xw-resize");
    $(parts.xbut).css("display","none");
    if(props.min)$(parts.mbut).css("display","block");
    $(parts.rbut).css("display","block");
    if(!desktop && !props.fixed && !$.browser.msie) $(top).css("position","fixed");

    hideSh();
	if(desktop && !props.fixed) {
	    moveTo(desktop.calcexclude(0),desktop.calcexclude(2),1);
	    resizeTo(desktop.calcwidth(),desktop.calcheight(),0,1);
	} else  {
	    var d=_uWnd.getdims();
	    props.fixed=true;
	    moveTo(0,0,1);
	    resizeTo(d.clientW,d.clientH,0,1);
	}
	if(frominit) {show(false,0);}
  }
},
restore: function() {
  with(this) {
    if(!props.header) return;
    stopdrag();
    stopresize();
    if(this.props.onposchange && (state.minimized || state.maximized)) props.onposchange.apply(app,[this]);

    $(parts.rbut).css("display","none");
    if(state.maximized) $(parts.xbut).css("display","block");
    if(state.minimized) $(parts.mbut).css("display","block");
    if(!props.nomove)$(parts.hdr).addClass("xw-draggable");
    if(props.resize)$(wnd).addClass("xw-resize");

    if(!desktop) {
	    if(state.minimized) design.onrestore(this);
	} else {
		if(state.minimized) show(false,0);
//		desktop.onwndrestore(this);
	}
    showSh();
    state.maximized=state.minimized=false;
    var r=restRect;
    if(r) {
		props.fixed=r[4];
		if(!props.fixed && !$.browser.msie) $(top).css("position","absolute");
		moveTo(r[0],r[1],1);
		resizeTo(r[2],r[3],0,1);
    }
  }
},
_ondragmousemove: function(dx,dy,x,y) {
    var d=_uWnd.getdims();
	x+=dx;
	y+=dy;
    if(x+this.width<30) x=30-this.width;
    if(y<-5) y=-5;
	if(this.desktop && !this.props.fixed) {
	if(x>this.desktop.width-20) x=this.desktop.width-20;
	if(y>this.desktop.height-20) y=this.desktop.height-20;
	} else if(this.props.fixed) {
	if(x>d.clientW-20) x=d.clientW-20;
	if(y>d.clientH-20) y=d.clientH-20;
    } else {
	if(x>d.docW-20) x=d.docW-20;
	if(y>d.docH-20) y=d.docH-20;
    }
    this.moveTo(x,y);
},
onstartdrag: function() {
	this.design.onstartdrag(this);
},
onstopdrag: function() {
	this.design.onstopdrag(this);
},
_ondragmousedown: function(e) {
  with(this){
    if(props.nomove || state.resizing || state.maximized || state.disabled || e.which!=1) return;
	_drag.start(e,xpos,ypos);
    props.x=xpos;
    props.y=ypos;
  }
},
stopdrag: function() {
	this._drag.stop();
},
_onrsmousemove: function(dx,dy,tx,ty,tw,th,m) {
    var x,y,w,h,d=_uWnd.getdims(),minw=10,minh=10,maxw,maxh;
    x=tx;
    y=ty;
    w=tw;
    h=th;
    if(this.props.header) {
		minw+=this._countbuttonwidth();
    }
    minw=Math.max(minw,this.minwidth)+this.decor.w;
    minh=Math.max(minh,this.minheight)+this.decor.h;
    maxw=this.maxwidth;
    if(maxw==0) maxw=d.clientW; else maxw+=this.decor.w;
    maxh=this.maxheight;
    if(maxh==0) maxh=d.clientH; else maxh+=this.decor.h;
//	self.status=minw;
    if(m.indexOf('n')>=0){
	y=ty+dy;
	if(y<0) y=0;
	h=ty+th-y;
	if(h<minh) {h=minh;y=ty+th-h;}
	    else if(h>maxh) {h=maxh;y=ty+th-h;}
    }
    if(m.indexOf('s')>=0){
	h=th+dy;
	if(h<minh) h=minh;
	    else if(h>maxh) h=maxh;
    }
    if(m.indexOf('w')>=0){
	x=tx+dx;
	if(x<0) x=0;
	w=tx+tw-x;
	if(w<minw) {w=minw;x=tx+tw-w;}
	    else if(w>maxw) {w=maxw;x=tx+tw-w;}
    }
    if(m.indexOf('e')>=0){
	w=tw+dx;
	if(w<minw) w=minw;
	    else if(w>maxw) w=maxw;
    }
    this.moveTo(x,y);
    this.resizeTo(w,h);
},
_onrsmousedown: function(e,b) {
  with(this) {
    if(_drag.active || state.disabled || state.maximized || state.minimized || 
	autosz.active || !props.resize || e.which!=1) return;
    props.x=xpos;
    props.y=ypos;
	this.stopautosize();
	_resize.start(e,xpos,ypos,width,height,b);
  }
},
onstartrs: function() {
	this.design.onstartresize(this);
},
onstoprs: function() {
	this.design.onstopresize(this);
},
stopresize: function() {
	this._resize.stop();
}

};

function _txt(sign) { 
		var lng=window._uDeflang,a,p=arguments;
		if(!lng) a=sign;
			else {
				var db=window._uSigns;
				if(!db || !db[lng])a=sign;
					else {
						if(sign in db[lng]) a=db[lng][sign];
							else a=sign;
					}
			}
		function _txtproc(str,param) {
			return p[param];
		}

		if(p.length>1) {
			a=a.replace(/%([1-9])/g,_txtproc);
		}
		return a;
}

function _uColorBox(did,fid){
	var hex_Red=new Array("00","33","66","99","CC","FF");
	var hex_Green=new Array("00","33","66","99","CC","FF");
	var hex_Blue=new Array("00","33","66","99","CC","FF");
	var hex_Gray=new Array("909090","939393","969696","999999","9C9C9C","9F9F9F","C0C0C0","C3C3C3","C6C6C6","C9C9C9","CCCCCC","CFCFF","F0F0F0","F3F3F3","F6F6F6","F9F9F9","FCFCFC","FFFFFF");
	var hexred="00", hexgreen="00", hexblue="00", hexgray="00";
	var red=0, green=0, blue=0;
	var x=0, y=0, z=0;
	var xyz=0;
	var ctable='<table border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">';
	while (y<6){
		ctable+='<tr>';
		var x=0;
		var hexblue=hex_Blue[blue];
		while (x<6){
			var z=0;
			var hexgreen=hex_Green[green];
			while (z<6){
				var hexred=hex_Red[red];
				var hexadecimal=""+hexred+hexgreen+hexblue;
				ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="$(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hexadecimal+'\'" bgcolor="'+hexadecimal+'"></td>';
				z++;red++;
				if (red==6){red=0;}
			}
			x++;green++;
			if (green==6)green=0;
			xyz++;
			if (xyz==3){ctable+='</tr>'; xyz=0;}
		}
		y++; blue++
		if (blue==6)blue=0;
	}
	for (var i=0;i<hex_Gray.length;i++){
		ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="$(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hex_Gray[i]+'\'" bgcolor="'+hex_Gray[i]+'"></td>';
	}
	ctable+='</table>';
	$('#'+did).html(ctable);
}

//ucoz specific
//wnd can be _uWnd _uTabCtrl or _uApp
function _uParseXML(xml,wnd,tabid) {xml = xml.documentElement;
var tabctrl=null,app=null;

if(typeof wnd=='object' && wnd.constructor==_uTabCtrl) {tabctrl=wnd;wnd=null;}
	else if(typeof _uApp!='undefined' && typeof wnd=='object' && wnd.appname) {app=wnd;wnd=null;}

if (xml == null) { alert("Server connection Error. Sorry."); }
for (var i = 0; i < xml.childNodes.length; i++) {
if (xml.childNodes[i].nodeName == "cmd"){ var cmd=''; var target=''; var data;
for (var j=0; j<xml.childNodes[i].attributes.length; j++) {
if (xml.childNodes[i].attributes[j].name == "p")cmd = xml.childNodes[i].attributes[j].value;
if (xml.childNodes[i].attributes[j].name == "t")target = xml.childNodes[i].attributes[j].value;}
if (xml.childNodes[i].firstChild && xml.childNodes[i].firstChild.data ) data = xml.childNodes[i].firstChild.data; else data = '';
if (cmd=='innerHTML' && target.match(/^layerContent(.+)/)) _uWnd.content(RegExp.$1,data);
if (cmd=='innerHTML' && target.match(/^layerTitle(.+)/)) _uWnd.setTitle(RegExp.$1,data);
if (cmd=='innerHTML') $('#'+target).html(data);
else if (cmd=='+innerHTML') $('#'+target).prepend(data);
else if (cmd=='innerHTML+') $('#'+target).append(data);
else if (cmd=='innerHTMLspanAll') $("span."+target).html(data);
else if (cmd=='innerHTMLdivAll') $("div."+target).html(data);
else if (cmd=='value') $('#'+target).val(data);
else if (cmd=='jsa') includeJSfile(data,target);
else if (cmd=='js') eval(data);
else if (cmd=='content' && target.length>0) {
	var r=target.match(/^([^:]+):(.+)/);
	if(r) _uTabCtrl.content(r[1],r[2],data);
	else _uWnd.content(target,data);
}
else if (cmd=='title' && target.length>0) {
	var r=target.match(/^([^:]+):(.+)/);
	if(r) _uTabCtrl.setTitle(r[1],r[2],data);
	else _uWnd.setTitle(target,data);
}
else if (cmd=='close' && target.length>0) {
	var r=target.match(/^([^:]+):(.+)/);
	if(r) 
		if(!data || parseInt(data)==NaN)_uTabCtrl.closeTab(r[1],r[2]);else setTimeout("_uTabCtrl.closeTab('"+r[1]+"','"+r[2]+"');",parseInt(data));
	else
		if(!data || parseInt(data)==NaN)_uWnd.close(target);else setTimeout("_uWnd.close('"+target+"');",parseInt(data));
}
else if(wnd) {
    if(cmd=='content') wnd.content(data);
    else if(cmd=='title') wnd.setTitle(data);
    else if(cmd=='close') if(!data || parseInt(data)==NaN)wnd.close();else setTimeout("var w=_uWnd.all["+wnd.idx+"];if(w)w.close();",parseInt(data));
    }
else if(tabctrl && tabid) {
    if(cmd=='content') tabctrl.content(tabid,data);
    else if(cmd=='title') {tabctrl.setTitle(tabid,data);}
    else if(cmd=='close') if(!data || parseInt(data)==NaN)tabctrl.closeTab(tabid);else setTimeout("var w=_uTabCtrl.all["+tabctrl.idx+"];if(w)w.closeTab('"+tabid+"');",parseInt(data));
    }
}}
}

var _defAjaxError=function(xmlreq, status, err) {
//this - options for request
//typically only one of status or err (exception) will have info
	try {
		_show_log_form();return;
	} catch(e){}
	window.location.reload();
}
var _hookAjaxError=null; //function(xmlreq, status, err)
//this - options for request

function _uAjaxRequest(url,options) {
    if(!url) return null;
    var o = $.extend({
//noerrorhook:1   - can be used to prevent error hook from being used    	
		app: 0, //application PID
		async: 1,
		cache: true,
		dataType: 'xml',
		error: _defAjaxError,
	    type: 'GET',
		success: _defAjaxSuccess,
		timeout: 25000
// 		data: {f1: val1, f2: val2, f3: [val4,val5]}
    }, options || {});
    if(_hookAjaxError && !o.noerrorhook) {o.prev_error=o.error;o.error=_hookAjaxError;}
    o.url=url;
//    if(o.app>0 && !o.nosuccesshook) {o.prev_success=o.success;o.success=_hookAjaxSuccess;}
    return jQuery.ajax(o);
}
//by default use app in options
var _hookAjaxSuccess=function(data, status) {
	if(!this.prev_success) return;
	if(this.app>0 && typeof _uApp!='undefined' && _uApp.all[this.app] && !_uApp.all[this.app].exited && this.prev_success!=_defAjaxSuccess) this.prev_success.call(_uApp.all[this.app],data,status);
		else this.prev_success.call(this,data,status);
};

//by default call _uParseXML for xml reply
var _defAjaxSuccess=function(data, status) {
//this - options for request
	if(this.dataType=='xml') {
		if(this.app>0 && typeof _uApp!='undefined' && _uApp.all[this.app] && !_uApp.all[this.app].exited) 
			_uParseXML(data,_uApp.all[this.app]);
			else
			_uParseXML(data);
	}
}


//by default try to find onerror attribute and execute it
var _defAjaxFormError=function(xmlreq, status, err) {
//this - options for request
//typically only one of status or err (exception) will have info
	if(!this._formobj) return;
	var a=this._formobj.onerror || this._formobj.getAttribute('onerror');
	if(!a) return;
	if(typeof a == 'string') {
		try {a=new Function(a);} catch(e){return;}
	}
	if(typeof a == 'function' || typeof a=='object') {
		try {a.call(this._formobj,xmlreq, status, err);} catch(e){return;}
	}
}

function _uPostForm(formid,options) {
    if(!formid && options && options.url) { _uAjaxRequest(options.url,options);return;}
    var f;
    if(typeof(formid)!='object') f=$('#'+formid); else f=$(formid);
    if(!f.length) return;
    var o = $.extend({
//noerrorhook:1   - can be used to prevent error hook from being used    	
		app: 0, //pid of application
		url: f.attr('action') || window.location.toString(),
		type: f.attr('method') || 'GET',
		error: _defAjaxFormError,
		success: _defAjaxSuccess,
		dataType: 'xml',
		semantic: false //true if form contains type=image
    }, options || {});
    if(_hookAjaxError && !o.noerrorhook) {o.prev_error=o.error;o.error=_hookAjaxError;}
    o._formobj=f[0];
    if(o.app>0 && !o.nosuccesshook) {o.prev_success=o.success;o.success=_hookAjaxSuccess;}
    f.ajaxSubmit(o);
}


function includeJSfile(src,id){
if (id && document.getElementById(id)){return;}
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
if(id) js.setAttribute('id',id);
js.setAttribute('src',src);
document.getElementsByTagName('head').item(0).appendChild(js);
}


var _entrRm={};
function _entrRem(bID,u,imgurl,text){
    if (!text){text='Are you sure?';}
    if (!_entrRm[bID] && confirm(text)){_entrRm[bID]=1;
	document.getElementById(bID).src=imgurl+'/img/fr/EmnAjax.gif';
	_uPostForm('',{url:u});
    }	
}


function _coloredTDs(r,c){
    var cl='';
    if (typeof(r)!='object'){r=document.getElementById(r);}
    if (typeof(document.getElementsByTagName)!='undefined'){cl=r.getElementsByTagName('td');}
    else if (typeof(r.cells)!='undefined') {cl=r.cells;}
    else {return false;}
    for (var i=0;i<cl.length;i++) {
	cl[i].className=c;
    }
}

function openLayerB(n,f,url,t,w,h,resize,anyVar2,grid,multypart,align){
    new _uWnd(n,t,w,h,{autosize: resize ? 1 : 0,modal: grid ? 1 : 0,align:align ? align : 'center'},{url:url,form:f,cache:1});
}

function _showOnTop(n,f){
	var z=_uWnd.getTopZ();
        if (f){
                document.getElementById(n).style.zIndex=z+1;
        }
        else {
                document.getElementById('outLayer'+n).style.zIndex=z+1;
        }
}

function encodeHtmlVal(s) {
	return String(s).replace(/&/g,'&'+'amp;').replace(/'/g,'&'+'#39;').replace(/"/g,'&'+'quot;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;');
}

//recursively dump SIMPLE objects  (numbers, strings, bool, simple arrays, simple objects)
function dumpObject(o,depth,ex) {
	var tp=typeof o,s;
	if(arguments.length<2) depth=10;
	function hexencode(n,s) {
		var j,d=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'],v='';
		for(j=0;j<s;j++) {v=''+d[n%16]+v;n>>>=4;}
		return v;
	}
	if(tp=='object')
		if(!o) tp='null';
		else if (o.constructor==String) tp='string';
		else if (o.constructor==Number) tp='number';
		else if (o.constructor==Boolean) tp='boolean';
		else if (o.constructor==Array) tp='array';
	switch(tp) {
		case 'number': case 'boolean': case 'null': case 'undefined': return String(o);
		case 'string': 
			return '"'+o.replace(/([\\"])/g,"\\$1").
				replace(/\n/g,"\\n").
				replace(/([\x00-\x1f])/g,function(s,c){return '\\x'+hexencode(c.charCodeAt(0),2);}).
				replace(/([\u2028\u2029])/g,function(s,c){return '\\u'+hexencode(c.charCodeAt(0),4);})+'"';
		case 'array':
			if(depth<=0) return '[?]';
			s='';
			for(var i=0;i<o.length;i++) {
				if(i>0) s+=',';
				s+=dumpObject(o[i]);
			}
			return '['+s+']';
		case 'object':
			if(depth<=0) return '{?}';
			s='';
			for(var i in o) {
				if(ex && ex[i]) continue;
				if(s) s+=',';
				try {
				s+=dumpObject(i)+':'+dumpObject(o[i],depth-1);
				} catch(e) {s+=dumpObject(i)+':?';}
			}
			return '{'+s+'}';
	}
}

function _uHighlightA(parent,url,hlclass) {
	var ls=$(parent).find("a").get(),o=null,l=0;
	for(var j in ls) {
		if (ls[j].href && url.indexOf(ls[j].href)>=0) {
			if (!o || l<ls[j].href.length){
				o=ls[j]; 
				l=ls[j].href.length; 
			} 
		} 
	}
	if(o) $(o).addClass(hlclass);
}
function _uBuildMenu(id,ishoriz,hlurl,hlclass,alignclass,hidetm){
		var p,i,subs,m,al,t,it,f;
		p=$(id)[0];
		if(!p) return;
		hidetm=hidetm || 2000;
		f=function(e){_uMENU.hideallmenus();this.__umenu.show();};
		if($.browser.msie) p.style.zoom='1';
		subs=$(id + ">ul").children("li").children("ul");
		for(i=0;i<subs.length;i++) {
			m=_ubuild_submenus(subs[i]);
			al=it=subs[i].parentNode;
			if(!ishoriz && alignclass && (t=$(al).children("."+alignclass)[0]) )al=t;
			it.__umenu=new _uMENU('',{alignObj:al,align:ishoriz ? 'D' : (window._rtl ? 'L' : 'R')},{parentnode:p,hidetimer:hidetm},m);
			$(it).bind("mouseover",f);
			it.removeChild(subs[i]);
		}
		if(!hlurl || !hlclass) return;
		setTimeout("_uHighlightA($('"+id+"')[0],'"+hlurl+"','"+hlclass+"');",100);
	}

function _uReplaceMenu(id,ishoriz,hlurl,hlclass,removeclass){
		var p,m,mm;
		p=$(id)[0];
		if(!p) return;
		if($.browser.msie) p.style.zoom='1';
		mm=$(id).children("ul")[0];
		if(!mm) return;
		if(removeclass)$(mm).find("."+removeclass).remove();
		m=_ubuild_submenus(mm);
		mm.parentNode.__umenu=new _uMENU('',{},{width:'auto',horiz: ishoriz, statical:1,parentnode:p,noabs:1},m);
		mm.parentNode.removeChild(mm);
		if(!hlurl || !hlclass) return;
		setTimeout("_uHighlightA($('"+id+"')[0],'"+hlurl+"','"+hlclass+"');",100);
	}

		
function _ubuild_submenus(ul) {
		var ch=$(ul).children("li"),i,res=[],subul,m,ls;
		for(i=0;i<ch.length;i++) {
			subul=$(ch[i]).children("ul")[0];
			if(subul) {
				m=_ubuild_submenus(subul);
				subul.parentNode.removeChild(subul);
				ls=$(ch[i]).find("a").get();
				res[res.length]=[$(ch[i]).html(),m,ls.length>0 ? {action:'a'} : null];
			} else {
				ls=$(ch[i]).find("a").get();
				res[res.length]=[$(ch[i]).html(),ls.length>0 ? 'a' : ''];
			}
		}
		return res;
}

function _uColorBox(did,fid){
var hex_Red=new Array("00","33","66","99","CC","FF");
var hex_Green=new Array("00","33","66","99","CC","FF");
var hex_Blue=new Array("00","33","66","99","CC","FF");
var hex_Gray=new Array("909090","939393","969696","999999","9C9C9C","9F9F9F","C0C0C0","C3C3C3","C6C6C6","C9C9C9","CCCCCC","CFCFCF","F0F0F0","F3F3F3","F6F6F6","F9F9F9","FCFCFC","FFFFFF");
var hexred="00";var hexgreen="00";var hexblue="00";var hexgray="00";
var red=0;var green=0;var blue=0;
var x=0;var y=0;var z=0;
var xyz=0;
var ctable='<table border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">';
while (y<6){
ctable+='<tr>';
var x=0;
var hexblue=hex_Blue[blue];
while (x<6){
var z=0;
var hexgreen=hex_Green[green];
while (z<6){
var hexred=hex_Red[red];
var hexadecimal=""+hexred+hexgreen+hexblue;
ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="$(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hexadecimal+'\'" bgcolor="'+hexadecimal+'"></td>';
z++;red++;
if (red==6){red=0;}
}
x++;green++;
if (green==6){green=0;}
xyz++;
if (xyz==3){ctable+='</tr>'; xyz=0;}
}
y++; blue++
if (blue==6){blue=0;}
}
for (var i=0;i<hex_Gray.length;i++){
ctable+='<td style="width:8px;height:8px;cursor:pointer;" onclick="$(\'#'+did+'\').hide(); getElementById(\''+fid+'\').value=\''+hex_Gray[i]+'\'" bgcolor="'+hex_Gray[i]+'"></td>';
};
ctable+='</table>';
$('#'+did).html(ctable);
}

function _uButton(frm,type,opts){ // formID, type['s','b','r'], options
	var props = $.extend({
	text:'Ok',
	content:'',
	style:0		//0,1
	},opts || {});

	var tp = {
		's':'onclick="if (this.dis){return;} this.className=\'myBtnCont x-unselectable myBtnDis\'; this.dis=true; document.getElementById(\'subm'+frm+'\').click();"',
		'r':'onclick="document.getElementById(\''+frm+'\').reset();"'
	};
    var t = (tp[type]!='undefined') ? tp[type] : '';
	var s = (props.style==1) ? ['myBtnLeft','myBtnCenter','myBtnRight'] : ['myBtnLeftA','myBtnCenterA','myBtnRightA'];

	var hid = (type=='s') ? '<input type="image" src="/.s/img/1px.gif" style="width:1px;" name="subm'+frm+'" id="subm'+frm+'" />' : '';
	var dis = (props.style==2) ? 'myBtnCont x-unselectable myBtnDis' : 'myBtnCont x-unselectable';

	var bt = '<table border="0" cellpadding="0" cellspacing="0" onmousedown="this.className=\'downBtn\'" onmouseover="this.className=\'overBtn\'" onmouseout="this.className=\'outBtn\'">'
+'<tr><td class="'+s[0]+'"><img border="0" src="/.s/img/1px.gif"></td>'
+'<td class="'+s[1]+'"><div class="'+dis+'" unselectable="on" '+t+' '+props.content+'><a href="javascript://" onclick="return false;">'+props.text+'</a></div></td>'
+'<td class="'+s[2]+'"><img border="0" src="/.s/img/1px.gif"></td>'
+'<td style="visibility:hidden;">'+hid+'</td></tr></table>'
	return bt;	
}