/* Code is organized as follows:
 * 1) jQuery Code
 * 2) Thickbox Code
 * 3) Popup Code
 * 4) Cookie Code
 * 5) CheckEnterForSubmit() function
 */



/********************  jQuery Begin  ********************/

/* prevent execution of jQuery if included more than once */
if(typeof window.jQuery == "undefined") {
/*
 * jQuery 1.1.2 - New Wave Javascript
 *
 * Copyright (c) 2007 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2007-02-28 12:03:00 -0500 (Wed, 28 Feb 2007) $
 * $Rev: 1465 $
 */

// Global undefined variable
window.undefined = window.undefined;
var jQuery = function(a,c) {
	// If the context is global, return a new object
	if ( window == this )
		return new jQuery(a,c);

	// Make sure that a selection was provided
	a = a || document;
	
	// HANDLE: $(function)
	// Shortcut for document ready
	if ( jQuery.isFunction(a) )
		return new jQuery(document)[ jQuery.fn.ready ? "ready" : "load" ]( a );
	
	// Handle HTML strings
	if ( typeof a  == "string" ) {
		// HANDLE: $(html) -> $(array)
		var m = /^[^<]*(<(.|\s)+>)[^>]*$/.exec(a);
		if ( m )
			a = jQuery.clean( [ m[1] ] );
		
		// HANDLE: $(expr)
		else
			return new jQuery( c ).find( a );
	}
	
	return this.setArray(
		// HANDLE: $(array)
		a.constructor == Array && a ||

		// HANDLE: $(arraylike)
		// Watch for when an array-like object is passed as the selector
		(a.jquery || a.length && a != window && !a.nodeType && a[0] != undefined && a[0].nodeType) && jQuery.makeArray( a ) ||

		// HANDLE: $(*)
		[ a ] );
};

// Map over the $ in case of overwrite
if ( typeof $ != "undefined" )
	jQuery._$ = $;
	
// Map the jQuery namespace to the '$' one
var $ = jQuery;

jQuery.fn = jQuery.prototype = {
	jquery: "1.1.2",

	size: function() {
		return this.length;
	},
	
	length: 0,

	get: function( num ) {
		return num == undefined ?

			// Return a 'clean' array
			jQuery.makeArray( this ) :

			// Return just the object
			this[num];
	},
	pushStack: function( a ) {
		var ret = jQuery(a);
		ret.prevObject = this;
		return ret;
	},
	setArray: function( a ) {
		this.length = 0;
		[].push.apply( this, a );
		return this;
	},
	each: function( fn, args ) {
		return jQuery.each( this, fn, args );
	},
	index: function( obj ) {
		var pos = -1;
		this.each(function(i){
			if ( this == obj ) pos = i;
		});
		return pos;
	},

	attr: function( key, value, type ) {
		var obj = key;
		
		// Look for the case where we're accessing a style value
		if ( key.constructor == String )
			if ( value == undefined )
				return this.length && jQuery[ type || "attr" ]( this[0], key ) || undefined;
			else {
				obj = {};
				obj[ key ] = value;
			}
		
		// Check to see if we're setting style values
		return this.each(function(index){
			// Set all the styles
			for ( var prop in obj )
				jQuery.attr(
					type ? this.style : this,
					prop, jQuery.prop(this, obj[prop], type, index, prop)
				);
		});
	},

	css: function( key, value ) {
		return this.attr( key, value, "curCSS" );
	},

	text: function(e) {
		if ( typeof e == "string" )
			return this.empty().append( document.createTextNode( e ) );

		var t = "";
		jQuery.each( e || this, function(){
			jQuery.each( this.childNodes, function(){
				if ( this.nodeType != 8 )
					t += this.nodeType != 1 ?
						this.nodeValue : jQuery.fn.text([ this ]);
			});
		});
		return t;
	},

	wrap: function() {
		// The elements to wrap the target around
		var a = jQuery.clean(arguments);

		// Wrap each of the matched elements individually
		return this.each(function(){
			// Clone the structure that we're using to wrap
			var b = a[0].cloneNode(true);

			// Insert it before the element to be wrapped
			this.parentNode.insertBefore( b, this );

			// Find the deepest point in the wrap structure
			while ( b.firstChild )
				b = b.firstChild;

			// Move the matched element to within the wrap structure
			b.appendChild( this );
		});
	},
	append: function() {
		return this.domManip(arguments, true, 1, function(a){
			this.appendChild( a );
		});
	},
	prepend: function() {
		return this.domManip(arguments, true, -1, function(a){
			this.insertBefore( a, this.firstChild );
		});
	},
	before: function() {
		return this.domManip(arguments, false, 1, function(a){
			this.parentNode.insertBefore( a, this );
		});
	},
	after: function() {
		return this.domManip(arguments, false, -1, function(a){
			this.parentNode.insertBefore( a, this.nextSibling );
		});
	},
	end: function() {
		return this.prevObject || jQuery([]);
	},
	find: function(t) {
		return this.pushStack( jQuery.map( this, function(a){
			return jQuery.find(t,a);
		}), t );
	},
	clone: function(deep) {
		return this.pushStack( jQuery.map( this, function(a){
			var a = a.cloneNode( deep != undefined ? deep : true );
			a.$events = null; // drop $events expando to avoid firing incorrect events
			return a;
		}) );
	},

	filter: function(t) {
		return this.pushStack(
			jQuery.isFunction( t ) &&
			jQuery.grep(this, function(el, index){
				return t.apply(el, [index])
			}) ||

			jQuery.multiFilter(t,this) );
	},

	not: function(t) {
		return this.pushStack(
			t.constructor == String &&
			jQuery.multiFilter(t, this, true) ||

			jQuery.grep(this, function(a) {
				return ( t.constructor == Array || t.jquery )
					? jQuery.inArray( a, t ) < 0
					: a != t;
			})
		);
	},

	add: function(t) {
		return this.pushStack( jQuery.merge(
			this.get(),
			t.constructor == String ?
				jQuery(t).get() :
				t.length != undefined && (!t.nodeName || t.nodeName == "FORM") ?
					t : [t] )
		);
	},
	is: function(expr) {
		return expr ? jQuery.filter(expr,this).r.length > 0 : false;
	},

	val: function( val ) {
		return val == undefined ?
			( this.length ? this[0].value : null ) :
			this.attr( "value", val );
	},

	html: function( val ) {
		return val == undefined ?
			( this.length ? this[0].innerHTML : null ) :
			this.empty().append( val );
	},
	domManip: function(args, table, dir, fn){
		var clone = this.length > 1; 
		var a = jQuery.clean(args);
		if ( dir < 0 )
			a.reverse();

		return this.each(function(){
			var obj = this;

			if ( table && jQuery.nodeName(this, "table") && jQuery.nodeName(a[0], "tr") )
				obj = this.getElementsByTagName("tbody")[0] || this.appendChild(document.createElement("tbody"));

			jQuery.each( a, function(){
				fn.apply( obj, [ clone ? this.cloneNode(true) : this ] );
			});

		});
	}
};

jQuery.extend = jQuery.fn.extend = function() {
	// copy reference to target object
	var target = arguments[0],
		a = 1;

	// extend jQuery itself if only one argument is passed
	if ( arguments.length == 1 ) {
		target = this;
		a = 0;
	}
	var prop;
	while (prop = arguments[a++])
		// Extend the base object
		for ( var i in prop ) target[i] = prop[i];

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function() {
		if ( jQuery._$ )
			$ = jQuery._$;
		return jQuery;
	},

	// This may seem like some crazy code, but trust me when I say that this
	// is the only cross-browser way to do this. --John
	isFunction: function( fn ) {
		return !!fn && typeof fn != "string" && !fn.nodeName && 
			typeof fn[0] == "undefined" && /function/i.test( fn + "" );
	},
	
	// check if an element is in a XML document
	isXMLDoc: function(elem) {
		return elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
	},
	// args is for internal usage only
	each: function( obj, fn, args ) {
		if ( obj.length == undefined )
			for ( var i in obj )
				fn.apply( obj[i], args || [i, obj[i]] );
		else
			for ( var i = 0, ol = obj.length; i < ol; i++ )
				if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break;
		return obj;
	},
	
	prop: function(elem, value, type, index, prop){
			// Handle executable functions
			if ( jQuery.isFunction( value ) )
				value = value.call( elem, [index] );
				
			// exclude the following css properties to add px
			var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i;

			// Handle passing in a number to a CSS property
			return value && value.constructor == Number && type == "curCSS" && !exclude.test(prop) ?
				value + "px" :
				value;
	},

	className: {
		// internal only, use addClass("class")
		add: function( elem, c ){
			jQuery.each( c.split(/\s+/), function(i, cur){
				if ( !jQuery.className.has( elem.className, cur ) )
					elem.className += ( elem.className ? " " : "" ) + cur;
			});
		},

		// internal only, use removeClass("class")
		remove: function( elem, c ){
			elem.className = c ?
				jQuery.grep( elem.className.split(/\s+/), function(cur){
					return !jQuery.className.has( c, cur );	
				}).join(" ") : "";
		},

		// internal only, use is(".class")
		has: function( t, c ) {
			t = t.className || t;
			// escape regex characters
			c = c.replace(/([\.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
			return t && new RegExp("(^|\\s)" + c + "(\\s|$)").test( t );
		}
	},
	swap: function(e,o,f) {
		for ( var i in o ) {
			e.style["old"+i] = e.style[i];
			e.style[i] = o[i];
		}
		f.apply( e, [] );
		for ( var i in o )
			e.style[i] = e.style["old"+i];
	},

	css: function(e,p) {
		if ( p == "height" || p == "width" ) {
			var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"];

			jQuery.each( d, function(){
				old["padding" + this] = 0;
				old["border" + this + "Width"] = 0;
			});

			jQuery.swap( e, old, function() {
				if (jQuery.css(e,"display") != "none") {
					oHeight = e.offsetHeight;
					oWidth = e.offsetWidth;
				} else {
					e = jQuery(e.cloneNode(true))
						.find(":radio").removeAttr("checked").end()
						.css({
							visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0"
						}).appendTo(e.parentNode)[0];

					var parPos = jQuery.css(e.parentNode,"position");
					if ( parPos == "" || parPos == "static" )
						e.parentNode.style.position = "relative";

					oHeight = e.clientHeight;
					oWidth = e.clientWidth;

					if ( parPos == "" || parPos == "static" )
						e.parentNode.style.position = "static";

					e.parentNode.removeChild(e);
				}
			});

			return p == "height" ? oHeight : oWidth;
		}

		return jQuery.curCSS( e, p );
	},

	curCSS: function(elem, prop, force) {
		var ret;
		
		if (prop == "opacity" && jQuery.browser.msie)
			return jQuery.attr(elem.style, "opacity");
			
		if (prop == "float" || prop == "cssFloat")
		    prop = jQuery.browser.msie ? "styleFloat" : "cssFloat";

		if (!force && elem.style[prop])
			ret = elem.style[prop];

		else if (document.defaultView && document.defaultView.getComputedStyle) {

			if (prop == "cssFloat" || prop == "styleFloat")
				prop = "float";

			prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase();
			var cur = document.defaultView.getComputedStyle(elem, null);

			if ( cur )
				ret = cur.getPropertyValue(prop);
			else if ( prop == "display" )
				ret = "none";
			else
				jQuery.swap(elem, { display: "block" }, function() {
				    var c = document.defaultView.getComputedStyle(this, "");
				    ret = c && c.getPropertyValue(prop) || "";
				});

		} else if (elem.currentStyle) {

			var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});
			ret = elem.currentStyle[prop] || elem.currentStyle[newProp];
			
		}

		return ret;
	},
	
	clean: function(a) {
		var r = [];

		jQuery.each( a, function(i,arg){
			if ( !arg ) return;

			if ( arg.constructor == Number )
				arg = arg.toString();
			
			 // Convert html string into DOM nodes
			if ( typeof arg == "string" ) {
				// Trim whitespace, otherwise indexOf won't work as expected
				var s = jQuery.trim(arg), div = document.createElement("div"), tb = [];

				var wrap =
					 // option or optgroup
					!s.indexOf("<opt") &&
					[1, "<select>", "</select>"] ||
					
					(!s.indexOf("<thead") || !s.indexOf("<tbody") || !s.indexOf("<tfoot")) &&
					[1, "<table>", "</table>"] ||
					
					!s.indexOf("<tr") &&
					[2, "<table><tbody>", "</tbody></table>"] ||
					
				 	// <thead> matched above
					(!s.indexOf("<td") || !s.indexOf("<th")) &&
					[3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
					
					[0,"",""];

				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + s + wrap[2];
				
				// Move to the right depth
				while ( wrap[0]-- )
					div = div.firstChild;
				
				// Remove IE's autoinserted <tbody> from table fragments
				if ( jQuery.browser.msie ) {
					
					// String was a <table>, *may* have spurious <tbody>
					if ( !s.indexOf("<table") && s.indexOf("<tbody") < 0 ) 
						tb = div.firstChild && div.firstChild.childNodes;
						
					// String was a bare <thead> or <tfoot>
					else if ( wrap[1] == "<table>" && s.indexOf("<tbody") < 0 )
						tb = div.childNodes;

					for ( var n = tb.length-1; n >= 0 ; --n )
						if ( jQuery.nodeName(tb[n], "tbody") && !tb[n].childNodes.length )
							tb[n].parentNode.removeChild(tb[n]);
					
				}
				
				arg = [];
				for (var i=0, l=div.childNodes.length; i<l; i++)
					arg.push(div.childNodes[i]);
			}

			if ( arg.length === 0 && !jQuery.nodeName(arg, "form") )
				return;
			
			if ( arg[0] == undefined || jQuery.nodeName(arg, "form") )
				r.push( arg );
			else
				r = jQuery.merge( r, arg );

		});

		return r;
	},
	
	attr: function(elem, name, value){
		var fix = jQuery.isXMLDoc(elem) ? {} : {
			"for": "htmlFor",
			"class": "className",
			"float": jQuery.browser.msie ? "styleFloat" : "cssFloat",
			cssFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat",
			innerHTML: "innerHTML",
			className: "className",
			value: "value",
			disabled: "disabled",
			checked: "checked",
			readonly: "readOnly",
			selected: "selected"
		};
		
		// IE actually uses filters for opacity ... elem is actually elem.style
		if ( name == "opacity" && jQuery.browser.msie && value != undefined ) {
			// 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
			return elem.filter = elem.filter.replace(/alpha\([^\)]*\)/gi,"") +
				( value == 1 ? "" : "alpha(opacity=" + value * 100 + ")" );

		} else if ( name == "opacity" && jQuery.browser.msie )
			return elem.filter ? 
				parseFloat( elem.filter.match(/alpha\(opacity=(.*)\)/)[1] ) / 100 : 1;
		
		// Mozilla doesn't play well with opacity 1
		if ( name == "opacity" && jQuery.browser.mozilla && value == 1 )
			value = 0.9999;
			

		// Certain attributes only work when accessed via the old DOM 0 way
		if ( fix[name] ) {
			if ( value != undefined ) elem[fix[name]] = value;
			return elem[fix[name]];

		} else if ( value == undefined && jQuery.browser.msie && jQuery.nodeName(elem, "form") && (name == "action" || name == "method") )
			return elem.getAttributeNode(name).nodeValue;

		// IE elem.getAttribute passes even for style
		else if ( elem.tagName ) {
			if ( value != undefined ) elem.setAttribute( name, value );
			if ( jQuery.browser.msie && /href|src/.test(name) && !jQuery.isXMLDoc(elem) ) 
				return elem.getAttribute( name, 2 );
			return elem.getAttribute( name );

		// elem is actually elem.style ... set the style
		} else {
			name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});
			if ( value != undefined ) elem[name] = value;
			return elem[name];
		}
	},
	trim: function(t){
		return t.replace(/^\s+|\s+$/g, "");
	},

	makeArray: function( a ) {
		var r = [];

		if ( a.constructor != Array )
			for ( var i = 0, al = a.length; i < al; i++ )
				r.push( a[i] );
		else
			r = a.slice( 0 );

		return r;
	},

	inArray: function( b, a ) {
		for ( var i = 0, al = a.length; i < al; i++ )
			if ( a[i] == b )
				return i;
		return -1;
	},
	merge: function(first, second) {
		var r = [].slice.call( first, 0 );

		// Now check for duplicates between the two arrays
		// and only add the unique items
		for ( var i = 0, sl = second.length; i < sl; i++ )
			// Check for duplicates
			if ( jQuery.inArray( second[i], r ) == -1 )
				// The item is unique, add it
				first.push( second[i] );

		return first;
	},
	grep: function(elems, fn, inv) {
		// If a string is passed in for the function, make a function
		// for it (a handy shortcut)
		if ( typeof fn == "string" )
			fn = new Function("a","i","return " + fn);

		var result = [];

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, el = elems.length; i < el; i++ )
			if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
				result.push( elems[i] );

		return result;
	},
	map: function(elems, fn) {
		// If a string is passed in for the function, make a function
		// for it (a handy shortcut)
		if ( typeof fn == "string" )
			fn = new Function("a","return " + fn);

		var result = [], r = [];

		// Go through the array, translating each of the items to their
		// new value (or values).
		for ( var i = 0, el = elems.length; i < el; i++ ) {
			var val = fn(elems[i],i);

			if ( val !== null && val != undefined ) {
				if ( val.constructor != Array ) val = [val];
				result = result.concat( val );
			}
		}

		var r = result.length ? [ result[0] ] : [];

		check: for ( var i = 1, rl = result.length; i < rl; i++ ) {
			for ( var j = 0; j < i; j++ )
				if ( result[i] == r[j] )
					continue check;

			r.push( result[i] );
		}

		return r;
	}
});
 
/*
 * Whether the W3C compliant box model is being used.
 *
 * @property
 * @name $.boxModel
 * @type Boolean
 * @cat JavaScript
 */
new function() {
	var b = navigator.userAgent.toLowerCase();

	// Figure out what browser is being used
	jQuery.browser = {
		safari: /webkit/.test(b),
		opera: /opera/.test(b),
		msie: /msie/.test(b) && !/opera/.test(b),
		mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
	};

	// Check to see if the W3C box model is being used
	jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat";
};

jQuery.each({
	parent: "a.parentNode",
	parents: "jQuery.parents(a)",
	next: "jQuery.nth(a,2,'nextSibling')",
	prev: "jQuery.nth(a,2,'previousSibling')",
	siblings: "jQuery.sibling(a.parentNode.firstChild,a)",
	children: "jQuery.sibling(a.firstChild)"
}, function(i,n){
	jQuery.fn[ i ] = function(a) {
		var ret = jQuery.map(this,n);
		if ( a && typeof a == "string" )
			ret = jQuery.multiFilter(a,ret);
		return this.pushStack( ret );
	};
});

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after"
}, function(i,n){
	jQuery.fn[ i ] = function(){
		var a = arguments;
		return this.each(function(){
			for ( var j = 0, al = a.length; j < al; j++ )
				jQuery(a[j])[n]( this );
		});
	};
});

jQuery.each( {
	removeAttr: function( key ) {
		jQuery.attr( this, key, "" );
		this.removeAttribute( key );
	},
	addClass: function(c){
		jQuery.className.add(this,c);
	},
	removeClass: function(c){
		jQuery.className.remove(this,c);
	},
	toggleClass: function( c ){
		jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this, c);
	},
	remove: function(a){
		if ( !a || jQuery.filter( a, [this] ).r.length )
			this.parentNode.removeChild( this );
	},
	empty: function() {
		while ( this.firstChild )
			this.removeChild( this.firstChild );
	}
}, function(i,n){
	jQuery.fn[ i ] = function() {
		return this.each( n, arguments );
	};
});

jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){
	jQuery.fn[ n ] = function(num,fn) {
		return this.filter( ":" + n + "(" + num + ")", fn );
	};
});

jQuery.each( [ "height", "width" ], function(i,n){
	jQuery.fn[ n ] = function(h) {
		return h == undefined ?
			( this.length ? jQuery.css( this[0], n ) : null ) :
			this.css( n, h.constructor == String ? h : h + "px" );
	};
});
jQuery.extend({
	expr: {
		"": "m[2]=='*'||jQuery.nodeName(a,m[2])",
		"#": "a.getAttribute('id')==m[2]",
		":": {
			// Position Checks
			lt: "i<m[3]-0",
			gt: "i>m[3]-0",
			nth: "m[3]-0==i",
			eq: "m[3]-0==i",
			first: "i==0",
			last: "i==r.length-1",
			even: "i%2==0",
			odd: "i%2",

			// Child Checks
			"nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling',a)==a",
			"first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a",
			"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
			"only-child": "jQuery.sibling(a.parentNode.firstChild).length==1",

			// Parent Checks
			parent: "a.firstChild",
			empty: "!a.firstChild",

			// Text Check
			contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0",

			// Visibility
			visible: 'a.type!="hidden"&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
			hidden: 'a.type=="hidden"||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',

			// Form attributes
			enabled: "!a.disabled",
			disabled: "a.disabled",
			checked: "a.checked",
			selected: "a.selected||jQuery.attr(a,'selected')",

			// Form elements
			text: "a.type=='text'",
			radio: "a.type=='radio'",
			checkbox: "a.type=='checkbox'",
			file: "a.type=='file'",
			password: "a.type=='password'",
			submit: "a.type=='submit'",
			image: "a.type=='image'",
			reset: "a.type=='reset'",
			button: 'a.type=="button"||jQuery.nodeName(a,"button")',
			input: "/input|select|textarea|button/i.test(a.nodeName)"
		},
		".": "jQuery.className.has(a,m[2])",
		"@": {
			"=": "z==m[4]",
			"!=": "z!=m[4]",
			"^=": "z&&!z.indexOf(m[4])",
			"$=": "z&&z.substr(z.length - m[4].length,m[4].length)==m[4]",
			"*=": "z&&z.indexOf(m[4])>=0",
			"": "z",
			_resort: function(m){
				return ["", m[1], m[3], m[2], m[5]];
			},
			_prefix: "z=a[m[3]];if(!z||/href|src/.test(m[3]))z=jQuery.attr(a,m[3]);"
		},
		"[": "jQuery.find(m[2],a).length"
	},
	
	// The regular expressions that power the parsing engine
	parse: [
		// Match: [@value='test'], [@foo]
		/^\[ *(@)([a-z0-9_-]*) *([!*$^=]*) *('?"?)(.*?)\4 *\]/i,

		// Match: [div], [div p]
		/^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,

		// Match: :contains('foo')
		/^(:)([a-z0-9_-]*)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/i,

		// Match: :even, :last-chlid
		/^([:.#]*)([a-z0-9_*-]*)/i
	],

	token: [
		/^(\/?\.\.)/, "a.parentNode",
		/^(>|\/)/, "jQuery.sibling(a.firstChild)",
		/^(\+)/, "jQuery.nth(a,2,'nextSibling')",
		/^(~)/, function(a){
			var s = jQuery.sibling(a.parentNode.firstChild);
			return s.slice(jQuery.inArray(a,s) + 1);
		}
	],

	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 ];

		// Make sure that the context is a DOM Element
		if ( context && !context.nodeType )
			context = null;

		// Set the correct context (if none is provided)
		context = context || document;

		// Handle the common XPath // expression
		if ( !t.indexOf("//") ) {
			context = context.documentElement;
			t = t.substr(2,t.length);

		// And the / root expression
		} else if ( !t.indexOf("/") ) {
			context = context.documentElement;
			t = t.substr(1,t.length);
			if ( t.indexOf("/") >= 1 )
				t = t.substr(t.indexOf("/"),t.length);
		}

		// Initialize the search
		var ret = [context], done = [], last = null;

		// 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).replace( /^\/\//i, "" );

			var foundToken = false;

			// An attempt at speeding up child selectors that
			// point to a specific element tag
			var re = /^[\/>]\s*([a-z0-9*-]+)/i;
			var m = re.exec(t);

			if ( m ) {
				// Perform our own iteration and filter
				jQuery.each( ret, function(){
					for ( var c = this.firstChild; c; c = c.nextSibling )
						if ( c.nodeType == 1 && ( jQuery.nodeName(c, m[1]) || m[1] == "*" ) )
							r.push( c );
				});

				ret = r;
				t = t.replace( re, "" );
				if ( t.indexOf(" ") == 0 ) continue;
				foundToken = true;
			} else {
				// Look for pre-defined expression tokens
				for ( var i = 0; i < jQuery.token.length; i += 2 ) {
					// Attempt to match each, individual, token in
					// the specified order
					var re = jQuery.token[i];
					var m = re.exec(t);

					// If the token match was found
					if ( m ) {
						// Map it against the token's handler
						r = ret = jQuery.map( ret, jQuery.isFunction( jQuery.token[i+1] ) ?
							jQuery.token[i+1] :
							function(a){ return eval(jQuery.token[i+1]); });

						// And remove the token
						t = jQuery.trim( t.replace( re, "" ) );
						foundToken = true;
						break;
					}
				}
			}

			// 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 ( ret[0] == context ) ret.shift();

					// Merge the result sets
					jQuery.merge( done, ret );

					// Reset the context
					r = ret = [context];

					// Touch up the selector string
					t = " " + t.substr(1,t.length);

				} else {
					// Optomize for the case nodeName#idName
					var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i;
					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 = /^([#.]?)([a-z0-9\\*_-]*)/i;
						m = re2.exec(t);
					}

					// Try to do a global search by ID, where we can
					if ( m[1] == "#" && ret[ret.length-1].getElementById ) {
						// Optimization for HTML document case
						var oid = ret[ret.length-1].getElementById(m[2]);
						
						// Do a quick check for the existence of the actual ID attribute
						// to avoid selecting by the name attribute in IE
						if ( jQuery.browser.msie && oid && oid.id != m[2] )
							oid = jQuery('[@id="'+m[2]+'"]', ret[ret.length-1])[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 {
						// Pre-compile a regular expression to handle class searches
						if ( m[1] == "." )
							var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");

						// We need to find all descendant elements, it is more
						// efficient to use getAll() when we are already further down
						// the tree - we try to recognize that here
						jQuery.each( ret, function(){
							// Grab the tag name being searched for
							var tag = m[1] != "" || m[0] == "" ? "*" : m[2];

							// Handle IE7 being really dumb about <object>s
							if ( jQuery.nodeName(this, "object") && tag == "*" )
								tag = "param";

							jQuery.merge( r,
								m[1] != "" && ret.length != 1 ?
									jQuery.getAll( this, [], m[1], m[2], rec ) :
									this.getElementsByTagName( tag )
							);
						});

						// It's faster to filter by class and be done with it
						if ( m[1] == "." && ret.length == 1 )
							r = jQuery.grep( r, function(e) {
								return rec.test(e.className);
							});

						// Same with ID filtering
						if ( m[1] == "#" && ret.length == 1 ) {
							// Remember, then wipe out, the result set
							var tmp = r;
							r = [];

							// Then try to find the element with the ID
							jQuery.each( tmp, function(){
								if ( this.getAttribute("id") == m[2] ) {
									r = [ this ];
									return false;
								}
							});
						}

						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);
			}
		}

		// Remove the root context
		if ( ret && ret[0] == context ) ret.shift();

		// And combine the results
		jQuery.merge( done, ret );

		return done;
	},

	filter: function(t,r,not) {
		// Look for common filter expressions
		while ( t && /^[a-z[({<*:.#]/i.test(t) ) {

			var p = jQuery.parse, m;

			jQuery.each( p, function(i,re){
		
				// Look for, and replace, string-like sequences
				// and finally build a regexp out of it
				m = re.exec( t );

				if ( m ) {
					// Remove what we just matched
					t = t.substring( m[0].length );

					// Re-organize the first match
					if ( jQuery.expr[ m[1] ]._resort )
						m = jQuery.expr[ m[1] ]._resort( m );

					return false;
				}
			});

			// :not() is a special case that can be optimized by
			// keeping it out of the expression list
			if ( m[1] == ":" && m[2] == "not" )
				r = jQuery.filter(m[3], r, true).r;

			// Handle classes as a special case (this will help to
			// improve the speed, as the regexp will only be compiled once)
			else if ( m[1] == "." ) {

				var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
				r = jQuery.grep( r, function(e){
					return re.test(e.className || "");
				}, not);

			// Otherwise, find the expression to execute
			} else {
				var f = jQuery.expr[m[1]];
				if ( typeof f != "string" )
					f = jQuery.expr[m[1]][m[2]];

				// Build a custom macro to enclose it
				eval("f = function(a,i){" +
					( jQuery.expr[ m[1] ]._prefix || "" ) +
					"return " + f + "}");

				// Execute it against the current filter
				r = jQuery.grep( r, f, not );
			}
		}

		// Return an array of filtered elements (r)
		// and the modified expression string (t)
		return { r: r, t: t };
	},
	
	getAll: function( o, r, token, name, re ) {
		for ( var s = o.firstChild; s; s = s.nextSibling )
			if ( s.nodeType == 1 ) {
				var add = true;

				if ( token == "." )
					add = s.className && re.test(s.className);
				else if ( token == "#" )
					add = s.getAttribute("id") == name;
	
				if ( add )
					r.push( s );

				if ( token == "#" && r.length ) break;

				if ( s.firstChild )
					jQuery.getAll( s, r, token, name, re );
			}

		return r;
	},
	parents: function( elem ){
		var matched = [];
		var cur = elem.parentNode;
		while ( cur && cur != document ) {
			matched.push( cur );
			cur = cur.parentNode;
		}
		return matched;
	},
	nth: function(cur,result,dir,elem){
		result = result || 1;
		var num = 0;
		for ( ; cur; cur = cur[dir] ) {
			if ( cur.nodeType == 1 ) num++;
			if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem ||
				result == "odd" && num % 2 == 1 && cur == elem ) return cur;
		}
	},
	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType == 1 && (!elem || 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(element, type, handler, data) {
		// For whatever reason, IE has trouble passing the window object
		// around, causing it to be cloned in the process
		if ( jQuery.browser.msie && element.setInterval != undefined )
			element = window;

		// if data is passed, bind to handler
		if( data ) 
			handler.data = data;

		// Make sure that the function being executed has a unique ID
		if ( !handler.guid )
			handler.guid = this.guid++;

		// Init the element's event structure
		if (!element.$events)
			element.$events = {};

		// Get the current list of functions bound to this event
		var handlers = element.$events[type];

		// If it hasn't been initialized yet
		if (!handlers) {
			// Init the event handler queue
			handlers = element.$events[type] = {};

			// Remember an existing handler, if it's already there
			if (element["on" + type])
				handlers[0] = element["on" + type];
		}

		// Add the function to the element's handler list
		handlers[handler.guid] = handler;

		// And bind the global event handler to the element
		element["on" + type] = this.handle;

		// Remember the function in a global list (for triggering)
		if (!this.global[type])
			this.global[type] = [];
		this.global[type].push( element );
	},

	guid: 1,
	global: {},

	// Detach an event or set of events from an element
	remove: function(element, type, handler) {
		if (element.$events) {
			var i,j,k;
			if ( type && type.type ) { // type is actually an event object here
				handler = type.handler;
				type    = type.type;
			}
			
			if (type && element.$events[type])
				// remove the given handler for the given type
				if ( handler )
					delete element.$events[type][handler.guid];
					
				// remove all handlers for the given type
				else
					for ( i in element.$events[type] )
						delete element.$events[type][i];
						
			// remove all handlers		
			else
				for ( j in element.$events )
					this.remove( element, j );
			
			// remove event handler if no more handlers exist
			for ( k in element.$events[type] )
				if (k) {
					k = true;
					break;
				}
			if (!k) element["on" + type] = null;
		}
	},

	trigger: function(type, data, element) {
		// Clone the incoming data, if any
		data = jQuery.makeArray(data || []);

		// Handle a global trigger
		if ( !element )
			jQuery.each( this.global[type] || [], function(){
				jQuery.event.trigger( type, data, this );
			});

		// Handle triggering a single element
		else {
			var handler = element["on" + type ], val,
				fn = jQuery.isFunction( element[ type ] );

			if ( handler ) {
				// Pass along a fake event
				data.unshift( this.fix({ type: type, target: element }) );
	
				// Trigger the event
				if ( (val = handler.apply( element, data )) !== false )
					this.triggered = true;
			}

			if ( fn && val !== false )
				element[ type ]();

			this.triggered = false;
		}
	},

	handle: function(event) {
		// 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;

		// Empty object is for triggered events with no data
		event = jQuery.event.fix( event || window.event || {} ); 

		// returned undefined or false
		var returnValue;

		var c = this.$events[event.type];

		var args = [].slice.call( arguments, 1 );
		args.unshift( event );

		for ( var j in c ) {
			// Pass in a reference to the handler function itself
			// So that we can later remove it
			args[0].handler = c[j];
			args[0].data = c[j].data;

			if ( c[j].apply( this, args ) === false ) {
				event.preventDefault();
				event.stopPropagation();
				returnValue = false;
			}
		}

		// Clean up added properties in IE to prevent memory leak
		if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;

		return returnValue;
	},

	fix: function(event) {
		// Fix target property, if necessary
		if ( !event.target && event.srcElement )
			event.target = event.srcElement;

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == undefined && event.clientX != undefined ) {
			var e = document.documentElement, b = document.body;
			event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
			event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
		}
				
		// check if target is a textnode (safari)
		if (jQuery.browser.safari && event.target.nodeType == 3) {
			// store a copy of the original event object 
			// and clone because target is read only
			var originalEvent = event;
			event = jQuery.extend({}, originalEvent);
			
			// get parentnode from textnode
			event.target = originalEvent.target.parentNode;
			
			// add preventDefault and stopPropagation since 
			// they will not work on the clone
			event.preventDefault = function() {
				return originalEvent.preventDefault();
			};
			event.stopPropagation = function() {
				return originalEvent.stopPropagation();
			};
		}
		
		// fix preventDefault and stopPropagation
		if (!event.preventDefault)
			event.preventDefault = function() {
				this.returnValue = false;
			};
			
		if (!event.stopPropagation)
			event.stopPropagation = function() {
				this.cancelBubble = true;
			};
			
		return event;
	}
};

jQuery.fn.extend({
	bind: function( type, data, fn ) {
		return this.each(function(){
			jQuery.event.add( this, type, fn || data, data );
		});
	},
	one: function( type, data, fn ) {
		return this.each(function(){
			jQuery.event.add( this, type, function(event) {
				jQuery(this).unbind(event);
				return (fn || data).apply( this, arguments);
			}, data);
		});
	},
	unbind: function( type, fn ) {
		return this.each(function(){
			jQuery.event.remove( this, type, fn );
		});
	},
	trigger: function( type, data ) {
		return this.each(function(){
			jQuery.event.trigger( type, data, this );
		});
	},
	toggle: function() {
		// Save reference to arguments for access in closure
		var a = arguments;

		return this.click(function(e) {
			// Figure out which function to execute
			this.lastToggle = this.lastToggle == 0 ? 1 : 0;
			
			// Make sure that clicks stop
			e.preventDefault();
			
			// and execute the function
			return a[this.lastToggle].apply( this, [e] ) || false;
		});
	},
	hover: function(f,g) {
		
		// A private function for handling mouse 'hovering'
		function handleHover(e) {
			// Check if mouse(over|out) are still within the same parent element
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
	
			// Traverse up the tree
			while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
			
			// If we actually just moused on to a sub-element, ignore it
			if ( p == this ) return false;
			
			// Execute the right function
			return (e.type == "mouseover" ? f : g).apply(this, [e]);
		}
		
		// Bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	},
	ready: function(f) {
		// If the DOM is already ready
		if ( jQuery.isReady )
			// Execute the function immediately
			f.apply( document, [jQuery] );
			
		// Otherwise, remember the function for later
		else {
			// Add the function to the wait list
			jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
		}
	
		return this;
	}
});

jQuery.extend({
	/*
	 * All the code that makes DOM Ready work nicely.
	 */
	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.apply( document );
				});
				
				// Reset the list of functions
				jQuery.readyList = null;
			}
			// Remove event lisenter to avoid memory leak
			if ( jQuery.browser.mozilla || jQuery.browser.opera )
				document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
		}
	}
});

new function(){

	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,o){
		
		// Handle event binding
		jQuery.fn[o] = function(f){
			return f ? this.bind(o, f) : this.trigger(o);
		};
			
	});
	
	// If Mozilla is used
	if ( jQuery.browser.mozilla || jQuery.browser.opera )
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
	
	// If IE is used, use the excellent hack by Matthias Miller
	// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
	else if ( jQuery.browser.msie ) {
	
		// Only works if you document.write() it
		document.write("<scr" + "ipt id=__ie_init defer=true " + 
			"src=//:><\/script>");
	
		// Use the defer script hack
		var script = document.getElementById("__ie_init");
		
		// script does not exist if jQuery is loaded dynamically
		if ( script ) 
			script.onreadystatechange = function() {
				if ( this.readyState != "complete" ) return;
				this.parentNode.removeChild( this );
				jQuery.ready();
			};
	
		// Clear from memory
		script = null;
	
	// If Safari  is used
	} else if ( jQuery.browser.safari )
		// Continually check to see if the document.readyState is valid
		jQuery.safariTimer = setInterval(function(){
			// loaded and complete are both valid states
			if ( document.readyState == "loaded" || 
				document.readyState == "complete" ) {
	
				// If either one are found, remove the timer
				clearInterval( jQuery.safariTimer );
				jQuery.safariTimer = null;
	
				// and execute any waiting functions
				jQuery.ready();
			}
		}, 10); 

	// A fallback to window.onload, that will always work
	jQuery.event.add( window, "load", jQuery.ready );
	
};

// Clean up after IE to avoid memory leaks
if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.event.global;
		for ( var type in global ) {
			var els = global[type], i = els.length;
			if ( i && type != 'unload' )
				do
					jQuery.event.remove(els[i-1], type);
				while (--i);
		}
	});
jQuery.fn.extend({
	loadIfModified: function( url, params, callback ) {
		this.load( url, params, callback, 1 );
	},
	load: function( url, params, callback, ifModified ) {
		if ( jQuery.isFunction( url ) )
			return this.bind("load", url);

		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,
			data: params,
			ifModified: ifModified,
			complete: function(res, status){
				if ( status == "success" || !ifModified && status == "notmodified" )
					// Inject the HTML into all the matched elements
					self.attr("innerHTML", res.responseText)
					  // Execute all the scripts inside of the newly-injected HTML
					  .evalScripts()
					  // Execute callback
					  .each( callback, [res.responseText, status, res] );
				else
					callback.apply( self, [res.responseText, status, res] );
			}
		});
		return this;
	},
	serialize: function() {
		return jQuery.param( this );
	},
	evalScripts: function() {
		return this.find("script").each(function(){
			if ( this.src )
				jQuery.getScript( this.src );
			else
				jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
		}).end();
	}

});

// If IE is used, create a wrapper for the XMLHttpRequest object
if ( !window.XMLHttpRequest )
	XMLHttpRequest = function(){
		return new ActiveXObject("Microsoft.XMLHTTP");
	};

// Attach a bunch of functions for handling common AJAX events

jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
	jQuery.fn[o] = function(f){
		return this.bind(o, f);
	};
});

jQuery.extend({
	get: function( url, data, callback, type, ifModified ) {
		// shift arguments if data argument was ommited
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = null;
		}
		
		return jQuery.ajax({
			url: url,
			data: data,
			success: callback,
			dataType: type,
			ifModified: ifModified
		});
	},
	getIfModified: function( url, data, callback, type ) {
		return jQuery.get(url, data, callback, type, 1);
	},
	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
		});
	},

	// timeout (ms)
	//timeout: 0,
	ajaxTimeout: function( timeout ) {
		jQuery.ajaxSettings.timeout = timeout;
	},
	ajaxSetup: function( settings ) {
		jQuery.extend( jQuery.ajaxSettings, settings );
	},

	ajaxSettings: {
		global: true,
		type: "GET",
		timeout: 0,
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		data: null
	},
	
	// Last-Modified header cache for next request
	lastModified: {},
	ajax: function( s ) {
		// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
		s = jQuery.extend({}, jQuery.ajaxSettings, s);

		// if data available
		if ( s.data ) {
			// convert data if not already a string
			if (s.processData && typeof s.data != "string")
    			s.data = jQuery.param(s.data);
			// append data to url for get requests
			if( s.type.toLowerCase() == "get" ) {
				// "?" + data or "&" + data (in case there are already params)
				s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + 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" );

		var requestDone = false;

		// Create the request object
		var xml = new XMLHttpRequest();

		// Open the socket
		xml.open(s.type, s.url, s.async);

		// Set the correct header, if data is being sent
		if ( s.data )
			xml.setRequestHeader("Content-Type", s.contentType);

		// Set the If-Modified-Since header, if ifModified mode.
		if ( s.ifModified )
			xml.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
		xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");

		// Make sure the browser sends the right content length
		if ( xml.overrideMimeType )
			xml.setRequestHeader("Connection", "close");
			
		// Allow custom headers/mimetypes
		if( s.beforeSend )
			s.beforeSend(xml);
			
		if ( s.global )
		    jQuery.event.trigger("ajaxSend", [xml, 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 ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;
				
				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}
				
				var status;
				try {
					status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
						s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
					// Make sure that the request was successful or notmodified
					if ( status != "error" ) {
						// Cache Last-Modified header, if ifModified mode.
						var modRes;
						try {
							modRes = xml.getResponseHeader("Last-Modified");
						} catch(e) {} // swallow exception thrown by FF if header is not available
	
						if ( s.ifModified && modRes )
							jQuery.lastModified[s.url] = modRes;
	
						// process the data (runs the xml through httpData regardless of callback)
						var data = jQuery.httpData( xml, s.dataType );
	
						// 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", [xml, s] );
					} else
						jQuery.handleError(s, xml, status);
				} catch(e) {
					status = "error";
					jQuery.handleError(s, xml, status, e);
				}

				// The request was completed
				if( s.global )
					jQuery.event.trigger( "ajaxComplete", [xml, s] );

				// Handle the global AJAX counter
				if ( s.global && ! --jQuery.active )
					jQuery.event.trigger( "ajaxStop" );

				// Process result
				if ( s.complete )
					s.complete(xml, status);

				// Stop memory leaks
				if(s.async)
					xml = null;
			}
		};
		
		// 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 ( xml ) {
					// Cancel the request
					xml.abort();

					if( !requestDone )
						onreadystatechange( "timeout" );
				}
			}, s.timeout);
			
		// Send the data
		try {
			xml.send(s.data);
		} catch(e) {
			jQuery.handleError(s, xml, null, e);
		}
		
		// firefox 1.5 doesn't fire statechange for sync requests
		if ( !s.async )
			onreadystatechange();
		
		// return XMLHttpRequest to allow aborting the request etc.
		return xml;
	},

	handleError: function( s, xml, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error ) s.error( xml, status, e );

		// Fire the global callback
		if ( s.global )
			jQuery.event.trigger( "ajaxError", [xml, s, e] );
	},

	// Counter for holding the number of active queries
	active: 0,

	// Determines if an XMLHttpRequest was successful or not
	httpSuccess: function( r ) {
		try {
			return !r.status && location.protocol == "file:" ||
				( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
				jQuery.browser.safari && r.status == undefined;
		} catch(e){}
		return false;
	},

	// Determines if an XMLHttpRequest returns NotModified
	httpNotModified: function( xml, url ) {
		try {
			var xmlRes = xml.getResponseHeader("Last-Modified");

			// Firefox always returns 200. check Last-Modified date
			return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
				jQuery.browser.safari && xml.status == undefined;
		} catch(e){}
		return false;
	},

	/* Get the data out of an XMLHttpRequest.
	 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
	 * otherwise return plain text.
	 * (String) data - The type of data that you're expecting back,
	 * (e.g. "xml", "html", "script")
	 */
	httpData: function( r, type ) {
		var ct = r.getResponseHeader("content-type");
		var data = !type && ct && ct.indexOf("xml") >= 0;
		data = type == "xml" || data ? r.responseXML : r.responseText;

		// 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" )
			eval( "data = " + data );

		// evaluate scripts within html
		if ( type == "html" )
			jQuery("<div>").html(data).evalScripts();

		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( a[j] ) );

		// Return the resulting serialization
		return s.join("&");
	},
	
	// evalulates a script in global context
	// not reliable for safari
	globalEval: function( data ) {
		if ( window.execScript )
			window.execScript( data );
		else if ( jQuery.browser.safari )
			// safari doesn't provide a synchronous global eval
			window.setTimeout( data, 0 );
		else
			eval.call( window, data );
	}

});
jQuery.fn.extend({

	show: function(speed,callback){
		var hidden = this.filter(":hidden");
		speed ?
			hidden.animate({
				height: "show", width: "show", opacity: "show"
			}, speed, callback) :
			
			hidden.each(function(){
				this.style.display = this.oldblock ? this.oldblock : "";
				if ( jQuery.css(this,"display") == "none" )
					this.style.display = "block";
			});
		return this;
	},

	hide: function(speed,callback){
		var visible = this.filter(":visible");
		speed ?
			visible.animate({
				height: "hide", width: "hide", opacity: "hide"
			}, speed, callback) :
			
			visible.each(function(){
				this.oldblock = this.oldblock || jQuery.css(this,"display");
				if ( this.oldblock == "none" )
					this.oldblock = "block";
				this.style.display = "none";
			});
		return this;
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,
	toggle: function( fn, fn2 ){
		var args = arguments;
		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle( fn, fn2 ) :
			this.each(function(){
				jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]
					.apply( jQuery(this), args );
			});
	},
	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.each(function(){
			var state = jQuery(this).is(":hidden") ? "show" : "hide";
			jQuery(this).animate({height: state}, 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 ) {
		return this.queue(function(){
		
			this.curAnim = jQuery.extend({}, prop);
			var opt = jQuery.speed(speed, easing, callback);
			
			for ( var p in prop ) {
				var e = new jQuery.fx( this, opt, p );
				if ( prop[p].constructor == Number )
					e.custom( e.cur(), prop[p] );
				else
					e[ prop[p] ]( prop );
			}
			
		});
	},
	queue: function(type,fn){
		if ( !fn ) {
			fn = type;
			type = "fx";
		}
	
		return this.each(function(){
			if ( !this.queue )
				this.queue = {};
	
			if ( !this.queue[type] )
				this.queue[type] = [];
	
			this.queue[type].push( fn );
		
			if ( this.queue[type].length == 1 )
				fn.apply(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 : 
			{ slow: 600, fast: 200 }[opt.duration]) || 400;
	
		// Queueing
		opt.old = opt.complete;
		opt.complete = function(){
			jQuery.dequeue(this, "fx");
			if ( jQuery.isFunction( opt.old ) )
				opt.old.apply( this );
		};
	
		return opt;
	},
	
	easing: {},
	
	queue: {},
	
	dequeue: function(elem,type){
		type = type || "fx";
	
		if ( elem.queue && elem.queue[type] ) {
			// Remove self
			elem.queue[type].shift();
	
			// Get next function
			var f = elem.queue[type][0];
		
			if ( f ) f.apply( elem );
		}
	},

	/*
	 * I originally wrote fx() as a clone of moo.fx and in the process
	 * of making it small in size the code became illegible to sane
	 * people. You've been warned.
	 */
	
	fx: function( elem, options, prop ){

		var z = this;

		// The styles
		var y = elem.style;
		
		// Store display property
		var oldDisplay = jQuery.css(elem, "display");

		// Make sure that nothing sneaks out
		y.overflow = "hidden";

		// Simple function for setting a style value
		z.a = function(){
			if ( options.step )
				options.step.apply( elem, [ z.now ] );

			if ( prop == "opacity" )
				jQuery.attr(y, "opacity", z.now); // Let attr handle opacity
			else if ( parseInt(z.now) ) // My hate for IE will never die
				y[prop] = parseInt(z.now) + "px";
			
			y.display = "block"; // Set display property to block for animation
		};

		// Figure out the maximum number to run to
		z.max = function(){
			return parseFloat( jQuery.css(elem,prop) );
		};

		// Get the current size
		z.cur = function(){
			var r = parseFloat( jQuery.curCSS(elem, prop) );
			return r && r > -10000 ? r : z.max();
		};

		// Start an animation from one number to another
		z.custom = function(from,to){
			z.startTime = (new Date()).getTime();
			z.now = from;
			z.a();

			z.timer = setInterval(function(){
				z.step(from, to);
			}, 13);
		};

		// Simple 'show' function
		z.show = function(){
			if ( !elem.orig ) elem.orig = {};

			// Remember where we started, so that we can go back to it later
			elem.orig[prop] = this.cur();

			options.show = true;

			// Begin the animation
			z.custom(0, elem.orig[prop]);

			// Stupid IE, look what you made me do
			if ( prop != "opacity" )
				y[prop] = "1px";
		};

		// Simple 'hide' function
		z.hide = function(){
			if ( !elem.orig ) elem.orig = {};

			// Remember where we started, so that we can go back to it later
			elem.orig[prop] = this.cur();

			options.hide = true;

			// Begin the animation
			z.custom(elem.orig[prop], 0);
		};
		
		//Simple 'toggle' function
		z.toggle = function() {
			if ( !elem.orig ) elem.orig = {};

			// Remember where we started, so that we can go back to it later
			elem.orig[prop] = this.cur();

			if(oldDisplay == "none")  {
				options.show = true;
				
				// Stupid IE, look what you made me do
				if ( prop != "opacity" )
					y[prop] = "1px";

				// Begin the animation
				z.custom(0, elem.orig[prop]);	
			} else {
				options.hide = true;

				// Begin the animation
				z.custom(elem.orig[prop], 0);
			}		
		};

		// Each step of an animation
		z.step = function(firstNum, lastNum){
			var t = (new Date()).getTime();

			if (t > options.duration + z.startTime) {
				// Stop the timer
				clearInterval(z.timer);
				z.timer = null;

				z.now = lastNum;
				z.a();

				if (elem.curAnim) elem.curAnim[ prop ] = true;

				var done = true;
				for ( var i in elem.curAnim )
					if ( elem.curAnim[i] !== true )
						done = false;

				if ( done ) {
					// Reset the overflow
					y.overflow = "";
					
					// Reset the display
					y.display = oldDisplay;
					if (jQuery.css(elem, "display") == "none")
						y.display = "block";

					// Hide the element if the "hide" operation was done
					if ( options.hide ) 
						y.display = "none";

					// Reset the properties, if the item has been hidden or shown
					if ( options.hide || options.show )
						for ( var p in elem.curAnim )
							if (p == "opacity")
								jQuery.attr(y, p, elem.orig[p]);
							else
								y[p] = "";
				}

				// If a callback was provided, execute it
				if ( done && jQuery.isFunction( options.complete ) )
					// Execute the complete function
					options.complete.apply( elem );
			} else {
				var n = t - this.startTime;
				// Figure out where in the animation we are and set the number
				var p = n / options.duration;
				
				// If the easing function exists, then use it 
				z.now = options.easing && jQuery.easing[options.easing] ?
					jQuery.easing[options.easing](p, n,  firstNum, (lastNum-firstNum), options.duration) :
					// else use default linear easing
					((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;

				// Perform the next step of the animation
				z.a();
			}
		};
	
	}
});
}

/********************  jQuery End   ********************/
























































/********************  Thickbox Begin  ********************/
/*
 * Thickbox 2.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2006 cody lindley
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 * Thickbox is built on top of the very light weight jQuery library.
 */
var refreshParent = false;
var scrollMode = false;

//on page load call TB_init
$(document).ready(TB_init);
$(window).scroll(TB_changeScrollMode);

//add thickbox to href elements that have a class of .thickbox
function TB_init(){
    $("a.thickbox").unbind("click").click(function(){
	var t = this.title || this.name || null;
	var g = this.rel || false;
	TB_show(t,this.href,g);
	this.blur();
	return false;
	});
}

function TB_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
	    if (document.getElementById("TB_HideSelect") == null) {
	    $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
	    //$("#TB_overlay").click(TB_remove);
	    }
    	
	    if(caption==null){caption=""};
    	
    	
    	
	    //$("body").append("<div id='TB_load'><img src='img/loadingAnimation.gif' /></div>");
	    TB_load_position();
		
		
        if(url.indexOf("?")!==-1){ //If there is a query string involved
		    var baseURL = url.substr(0, url.indexOf("?"));
        }else{ 
   		    var baseURL = url;
        }
        var urlString = /\.jpg|\.jpeg|\.png|\.gif|\.bmp/g;
        var urlType = baseURL.toLowerCase().match(urlString);
		
		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = TB_parseQuery( queryString );
		
		var pageSize = TB_getPageSize();
		TB_WIDTH = (params['width']*1) + 30;
		if (pageSize[0] < TB_WIDTH)
		    TB_WIDTH = pageSize[0] - 20;
		ajaxContentW = TB_WIDTH - 30;
		
		if (params['height'] == "*")
	    {
	        TB_HEIGHT = pageSize[1] - 50;
	    }
	    else
	    {
		    TB_HEIGHT = (params['height']*1) + 40;
		    if (pageSize[1] < TB_HEIGHT)
		        TB_HEIGHT = pageSize[1] - 70;
		}
		ajaxContentH = TB_HEIGHT - 45;
		
		urlNoQuery = url.split('TB_');
	    var rand_no = Math.random();
        var frameURL = urlNoQuery[0] + "&d=" + rand_no;
		$("#TB_window").append("<div id=\"popupTitleBar\"><div id=\"popupTitle\">" + caption + "</div><div id=\"popupControls\"><a href='#' id='TB_closeWindowButton' title='Close'><img style=\"margin:0px; border-width:0px\" src=\"submodal/close_btn.gif\" alt=\"close\" border=\"0\" width=\"24\" height=\"24\" /></a></div></div><div  style=\"background: url( '/img/content_shadow.gif' ) 0px 0px repeat-x; width:100%\">&nbsp;</div><iframe frameborder='0' hspace='0' src='"+frameURL+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showIframe()'> </iframe>");
				
		$("#TB_closeWindowButton").click(TB_remove);
		
		$("#TB_ajaxContent").html($('#' + params['inlineId']).html());
		TB_position();
		$("#TB_load").remove();
		$("#TB_window").css({display:"block"}); 

        $(window).unbind("resize");
		$(window).resize(TB_position);
		$(window).resize(TB_overlaySize);
		
		$(window).unbind("scroll");
	    $(window).scroll(TB_position);
	    $(window).scroll(TB_overlaySize);
    	
	    if (scrollMode == false)
	        TB_overlaySizeFirstTime();
	    else
	        TB_overlaySize();
	        
		document.onkeyup = function(e){ 	
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			if(keycode == 27){ // close
				TB_remove();
			}	
		}
		
	} catch(e) {
		alert( e );
	}
}

//helper functions below

function TB_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function TB_remove() {
    $(window).unbind();
    if(refreshParent == true)
    { parent.location.href = parent.location.href; }
	$('#TB_window,#TB_overlay,#TB_HideSelect').remove();
	$("#TB_load").remove();
	TB_overlaySize();
	return false;
}

function TB_position() {
    var pagesize = TB_getPageSize();	
	var arrayPageScroll = TB_getPageScrollTop();	
	$("#TB_window").css({width:TB_WIDTH+"px",left: (arrayPageScroll[0] + (pagesize[0] - TB_WIDTH)/2)+"px", top: (arrayPageScroll[1] + (pagesize[1]-TB_HEIGHT)/2)+"px" });
}

function TB_changeScrollMode()
{
    scrollMode = true;
}

function TB_overlaySizeFirstTime()
{
    $("#TB_HideSelect").css({"height":"100%","width":"100%"});
	$("#TB_overlay").css({"height":"100%", "width":"100%"});
}
function TB_overlaySize(){
	if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX) {	
		yScroll = window.innerHeight + window.scrollMaxY;
		xScroll = window.innerWidth + window.scrollMaxX;
		var deff = document.documentElement;
		var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
		var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
		xScroll -= (window.innerWidth - wff);
		yScroll -= (window.innerHeight - hff);
	} else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
		xScroll = document.body.scrollWidth;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
		xScroll = document.body.offsetWidth;
  	}
  	$("#TB_overlay").css({"height":yScroll +"px", "width":xScroll +"px"});
	$("#TB_HideSelect").css({"height":yScroll +"px","width":xScroll +"px"});
	scrollMode = true;
	//alert("Scroll Time");
	
}

function TB_load_position() {
	var pagesize = TB_getPageSize();
	var arrayPageScroll = TB_getPageScrollTop();
	$("#TB_load")
	.css({left: (arrayPageScroll[0] + (pagesize[0] - 100)/2)+"px", top: (arrayPageScroll[1] + ((pagesize[1]-100)/2))+"px" })
	.css({display:"block"});
}

function TB_parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function TB_getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	}
	yScrolltop = yScrolltop - 15;
	arrayPageScroll = new Array(xScrollleft,yScrolltop) 
	return arrayPageScroll;
}

function TB_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}
/********************  Thickbox  End   ********************/

























































/********************  Popup Begin  ********************/
var win = null;
if(window.opener == null) window.name = "Main";

function kill()
{
	if(win) { win.close(); }
}

if(window.addEventListener)
{
	window.addEventListener("unload", kill, false);
}
else
{
	window.attachEvent("onunload", kill);
}

function EditPop(url, name, w, h)
{
	var left = (screen.width - w) / 2;
	var top = (screen.height - h) / 2;
	
	var features = "height=" + h + ",width=" + w + ",top=" + top + ",left=" + left;
	features += ",close=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes";
	
	if(win && !win.closed) win.close();
	win = window.open(url, name, features);
	
	if(parseInt(navigator.appVersion) >= 4)
	{
		win.window.focus();
		if(!win.opener) win.opener = self;
	}
}

function refreshParent_wLink(href) {
    window.opener.location.href = href;
    window.close();
}

function refreshParentWindow() {
window.opener.location.href = window.opener.location.href;
window.close();
}

function closePop() { 
window.close();
}

function hideMsg(){
document.getElementById("MsgZone").style.display="none";
}

function refreshModal_Parent() {
window.opener.location.href = window.opener.location.href;
}

function closeModal_Pop() {
window.opener.location.href = window.opener.location.href;
}

//function helpcenter(url)
//{
//	var width = 850;
//	var height = 700;
//	
//    var features = "width=" + width + ",height=" + height + ",resizable=1,status=1,";
//    features += "scrollbars=1,menubar=1";
//    
//    var hc_wnd = window.open(url, 'HelpCenter', features);
//    hc_wnd.focus();
//}

function helpcenter(element)
{
	var name = "HelpCenter";
	
	if(element)
	{
		element.target = name;
	}
	
	var width = 850;
	var height = 700;
	
    var features = "width=" + width + ",height=" + height + ",resizable=1,status=1,";
    features += "scrollbars=1,menubar=1";
    
    var hc_wnd = window.open('', 'HelpCenter', features);
    hc_wnd.focus();
}
/********************  Popup  End   ********************/


















/********************  Cookie Begin  ********************/
function createCookie(name, value, days)
{
	var expires = "";
	if(days)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 86400000)); // 86400000 = number of milliseconds in a day.
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	var c;
	for(var i = 0; i < ca.length; i++)
	{
		c = ca[i];
		while(c.charAt(0) == ' ')
		{
			c = c.substring(1, c.length);
		}
		
		if(c.indexOf(nameEQ) == 0)
		{
			return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name, "", -1);
}
/********************  Cookie  End   ********************/





















function findUser(encURL)
    {
        refreshParent_wLink('MySurvey_ResponsesDetail.aspx?' + encURL);
    }
    function checkEnter(e, btnName){
    if (btnName == null)
        btnName = "btnUpdate";
        
	var characterCode;
	if (e && e.which) {
		characterCode = e.which
		}
	else {
		e = event;
		characterCode = e.keyCode;
		}	 
	if (characterCode == 13) {
		WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btnName, "", true, "", "", false, true));
		return false;
		}
	return true;
}


function checkEnter(e, btnName){
    if (btnName == null)
        btnName = "btnUpdate";
        
	var characterCode;
	if (e && e.which) {
		characterCode = e.which
		}
	else {
		e = event;
		characterCode = e.keyCode;
		}	 
	if (characterCode == 13) {
		WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btnName, "", true, "", "", false, true));
		return false;
		}
	return true;
}



function CheckEnterForSubmit(e, buttonID)
{
	e = (e) ? e : window.event;

	var charcode = (e.which) ? e.which : e.keyCode;
	
	if(charcode == 13) // ENTER
	{
		var element = document.getElementById(buttonID);
		if(element)
		{
			var executeCode = "";
			switch(element.tagName.toUpperCase())
			{
				case "A":
					executeCode = element.href;
					break;
				case "INPUT":
				case "BUTTON":
					executeCode = element.onclick;
					break;
			}

			if(executeCode.indexOf("javascript:") != -1)
			{
				executeCode = executeCode.replace("javascript:", "");
			}
			
			eval(decodeURI(executeCode));
		}
	}
	
	return false;
}

























































function changeCollectorTitle(newTitle)
{
    document.getElementById("Wc_collector_bar_lblColTitle").innerHTML = newTitle;
}

function changeSurveyTitle(newTitle)
{
    document.getElementById("Wc_survey_bar_lblSurveyTitle").innerHTML = newTitle;
    
    //--used for collectorWizard screen
    if (document.getElementById("lblSurveyNameHeading"))
    {
        var _truncTitle = newTitle;
        if (_truncTitle.length > 40)
            _truncTitle = _truncTitle.substring(0, 40) + "...";
        document.getElementById("lblSurveyNameHeading").innerHTML = _truncTitle;
    }
 }
 
function printpage()
{
	window.print();
}

/*** EVENT HANDLERS ***/
function addListener(type, element, func)
{
	if(window.attachEvent)
	{
		element.attachEvent("on" + type, func);
	}
	else
	{
		element.addEventListener(type, func, false);
	}
}







//mkGUI begin
<!-- Hide the script from old browsers --
function mkLblOn(label)
{
label.style.textDecoration = 'underline';
label.style.backgroundColor = '#C3D2E8';
label.style.cursor = 'pointer';
}

function mkLblOff(label)
{
label.style.textDecoration = 'none';
label.style.backgroundColor = '';
label.style.cursor = '';
}

function mkChkToggle(_bChecked, _onDivID, _offDivID)
{
    if(_bChecked==true)
    {
        if (_offDivID != null)
            document.getElementById(_offDivID).style.display='none';
        if (_onDivID != null)
            document.getElementById(_onDivID).style.display='inline';
    }
    else
    {
        if (_onDivID != null)
            document.getElementById(_onDivID).style.display='none';
        if (_offDivID != null)
            document.getElementById(_offDivID).style.display='inline';
    }
}

function mkHovClick(_chkID, _onDivID, _offDivID)
{
var _chkObj = document.getElementById(_chkID);

if (_chkObj.checked)
_chkObj.checked = false;
else
_chkObj.checked = true;

mkChkToggle(_chkObj.checked, _onDivID, _offDivID);  
}



//--question builder functions---

	function radioToggle(_inputName, _selectedIndex, _toggleDivID)
	{
	   // alert(_dropdownObj.options[_dropdownObj.selectedIndex].value);
		   // alert(_selectedValue);
		   document.getElementById(_toggleDivID).style.display='none';
		   
		    var inputs = document.getElementsByTagName('input');
            if (inputs)
            {
                for (var i = 0; i < inputs.length; ++i) 
                {
                    //if (inputs[i].type == 'radio')
                    //    alert(inputs[i].name + ': ' + inputs[i].value);
                        
                    if (inputs[i].type == 'radio' && inputs[i].name == _inputName && inputs[i].value == _selectedIndex  && inputs[i].checked)
                    {
                        document.getElementById(_toggleDivID).style.display='inline';
                    }

                }
            }

		}
		
		function toggleCommentFormat(_dropdownObj)
	    {
	        if (_dropdownObj.options[_dropdownObj.selectedIndex].value == '0')
	        {
	            document.getElementById('Validate_Other').style.display='none';
	            document.getElementById('Validate_RequiredFormatText').style.display='none';
	        }
	        else
	        {
	            document.getElementById('Validate_RequiredFormatText').style.display='inline';
	            dropdownToggle(_dropdownObj,_dropdownObj.options[_dropdownObj.selectedIndex].value == '6','Validate_NoOther','Validate_Other',true,true,'OpenEndedValidationMinText','OpenEndedValidationMaxText');
	        }
	        
	    }
	    
	    function basicToggle(_toggleState, _toggleDivID, _toggleDivID2, _hide)
		{
			if(_toggleState == true)
			{
			    //alert(_toggleDivID + ": " + document.getElementById(_toggleDivID).style.display);
			    if (_hide == true)
			    {
				    document.getElementById(_toggleDivID).style.display='inline';
				    if (_toggleDivID2 != null)
				        document.getElementById(_toggleDivID2).style.display='none';
				}
				else
			    {
				    document.getElementById(_toggleDivID).style.visibility='visible';
				    if (_toggleDivID2 != null)
				        document.getElementById(_toggleDivID2).style.visibility='hidden';
				}
			}
			else
			{
				if (_hide == true)
				{
				    if (_toggleDivID2 != null)
				        document.getElementById(_toggleDivID2).style.display='inline';
				    document.getElementById(_toggleDivID).style.display='none';
				}
				else
			    {
			        if (_toggleDivID2 != null)
			            document.getElementById(_toggleDivID2).style.visibility='visible';
				    document.getElementById(_toggleDivID).style.visibility='hidden';
				}
			}
			
		}
		
		function dropdownToggle(_dropdownObj, _toggleState, _toggleDivID, _toggleDivID2, _hide, _changeFormatSpanText, minTextID, maxTextID)
		{
			basicToggle(_toggleState, _toggleDivID, _toggleDivID2, _hide);
			
			if (_changeFormatSpanText == true)
			{
			    var _minText = document.getElementById(minTextID);
			    var _maxText = document.getElementById(maxTextID);
			    var _date = new Date();
			    switch(_dropdownObj.options[_dropdownObj.selectedIndex].value)
			    {
			        case '0':
			            document.getElementById(_toggleDivID).style.display='none';
			            document.getElementById(_toggleDivID2).style.display='none';
			        case '6':
			            _minText.value = '0';
			            _maxText.value = '5000';
			            break;
			        case '1':
			            _minText.value = '0';
			            _maxText.value = '100';
			            break;
			        case '2':
			            _minText.value = '0.0';
			            _maxText.value = '100.0';
			            break;
			        case '3':
			            //alert(_date.getMonth());
			            //alert(_date.getDate());
			            //alert(_date.getYear());
			            _minText.value = _date.getMonth() + "/" + _date.getDate() + "/" + _date.getFullYear();
			            _maxText.value = '1/1/2010';
			            break;
			        case '4':
			            _minText.value = _date.getDate() + "/" + _date.getMonth() + "/" + _date.getFullYear();
			            _maxText.value = '1/1/2010';
			            break;
			        case '5':
			            _minText.value = '0.00';
			            _maxText.value = '1000.00';
			            break;
			    }
			}
		}
	    
		function widthToggle(_dropdownObj, percentSpan, fixedSpan)
		{
		    var _selectedIndex = _dropdownObj.selectedIndex;
		    if (_selectedIndex == 0)
			{
				document.getElementById(fixedSpan).style.display='none';
				document.getElementById(percentSpan).style.display='inline';
			}
			else if (_selectedIndex == 1)
			{
				document.getElementById(fixedSpan).style.display='inline';
				document.getElementById(percentSpan).style.display='none';
			}
		}
		
		function ratingMenuToggle(_dropdownObj)
		{
		    var _selectedIndex = _dropdownObj.selectedIndex;
		    for (i=0; i<=15; i++)
		    {
		        if (i <= (_selectedIndex+1))
			    {
				    document.getElementById('OuterRatingSpan_' + (i+1)).style.display='inline';
			    }
			    else
			    {
				    document.getElementById('OuterRatingSpan_' + (i+1)).style.display='none';
			    }
			}
		}
		function matrixMenuToggle(_dropdownObj)
		{
		    var _selectedIndex = _dropdownObj.selectedIndex;
		    for (i=0; i<=8; i++)
		    {
		        if (i <= (_selectedIndex))
			    {
				    document.getElementById('OuterSpan_' + (i+1)).style.display='inline';
			    }
			    else
			    {
				    document.getElementById('OuterSpan_' + (i+1)).style.display='none';
			    }
			}
		}
		
		function exampleHighlightOld(_topPos, _leftPos, _width, _height)
		{
			document.getElementById('highlight').style.backgroundPosition='-' + _leftPos + 'px ' + '-' + _topPos + 'px';
			document.getElementById('highlight').style.top=_topPos + 'px';
			document.getElementById('highlight').style.left=_leftPos + 'px';
			document.getElementById('highlight').style.width=_width + 'px';
			document.getElementById('highlight').style.height=_height + 'px';
		}
	
		function exampleHighlight(_topPos, _leftPos, _width, _height)
		{
			document.getElementById('highlight').style.top=_topPos + 'px';
			document.getElementById('highlight').style.left=_leftPos + 'px';
			document.getElementById('highlight').style.width=_width + 'px';
			document.getElementById('highlight').style.height=_height + 'px';
		}

function highlightRows()
{
    if (document.getElementById && document.createTextNode)
    {
        var tables=document.getElementsByTagName('TABLE');
        for (var i=0;i<tables.length;i++)
        {
            if (tables[i].className=='Grid' || tables[i].className=='GridAlt')
            {
                var trs=tables[i].getElementsByTagName('tr');
                for(var j=0;j<trs.length;j++)
                {
                    var rowNode = trs[j];
                    if (rowNode.className == 'hl')
                    {
                        rowNode.onmouseover=function(){this.style.backgroundColor='#ffffdc'; };
                        rowNode.onmouseout=function(){this.style.backgroundColor='#ffffff'; }; 
                    }
                }
            }
            
        }
    }
}	
// --End Hiding Here -->

//mkGUI end















//begin ami.js

/*
Last Modified: 05/02/07 19:38:56

AJS JavaScript library
    A very small library with a lot of functionality
AUTHOR
    4mir Salihefendic (http://amix.dk) - amix@amix.dk
LICENSE
    Copyright (c) 2006 Amir Salihefendic. All rights reserved.
    Copyright (c) 2005 Bob Ippolito. All rights reserved.
    http://www.opensource.org/licenses/mit-license.php
VERSION
    3.72
SITE
    http://orangoo.com/AmiNation/AJS
**/
if(!AJS) {
var AJS = {
    BASE_URL: "",

    drag_obj: null,
    drag_elm: null,
    _drop_zones: [],
    _drag_zones: [],
    _cur_pos: null,

    ajaxErrorHandler: null,

////
// General accessor functions
////
    getQueryArgument: function(var_name) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if (pair[0] == var_name) {
                return pair[1];
            }
        }
        return null;
    },

    isIe: function() {
        return (navigator.userAgent.toLowerCase().indexOf("msie") != -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1);
    },
    isNetscape7: function() {
        return (navigator.userAgent.toLowerCase().indexOf("netscape") != -1 && navigator.userAgent.toLowerCase().indexOf("7.") != -1);
    },
    isSafari: function() {
        return (navigator.userAgent.toLowerCase().indexOf("khtml") != -1);
    },
    isOpera: function() {
        return (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
    },
    isMozilla: function() {
        return (navigator.userAgent.toLowerCase().indexOf("gecko") != -1 && navigator.productSub >= 20030210);
    },


////
// Array functions
////
    //Shortcut: AJS.$A
    createArray: function(v) {
        if(AJS.isArray(v) && !AJS.isString(v))
            return v;
        else if(!v)
            return [];
        else
            return [v];
    },

    forceArray: function(args) {
        var r = [];
        AJS.map(args, function(elm) {
            r.push(elm);
        });
        return r;
    },

    join: function(delim, list) {
        try {
            return list.join(delim);
        }
        catch(e) {
            var r = list[0] || '';
            AJS.map(list, function(elm) {
                r += delim + elm;
            }, 1);
            return r + '';
        }
    },

    isIn: function(elm, list) {
        var i = AJS.getIndex(elm, list);
        if(i != -1)
            return true;
        else
            return false;
    },

    getIndex: function(elm, list/*optional*/, eval_fn) {
        for(var i=0; i < list.length; i++)
            if(eval_fn && eval_fn(list[i]) || elm == list[i])
                return i;
        return -1;
    },

    getFirst: function(list) {
        if(list.length > 0)
            return list[0];
        else
            return null;
    },

    getLast: function(list) {
        if(list.length > 0)
            return list[list.length-1];
        else
            return null;
    },

    update: function(l1, l2) {
        for(var i in l2)
            l1[i] = l2[i];
        return l1;
    },

    flattenList: function(list) {
        var r = [];
        var _flatten = function(r, l) {
            AJS.map(l, function(o) {
                if(o == null) {}
                else if (AJS.isArray(o))
                    _flatten(r, o);
                else
                    r.push(o);
            });
        }
        _flatten(r, list);
        return r;
    },


////
// Functional programming
////
    map: function(list, fn,/*optional*/ start_index, end_index) {
        var i = 0, l = list.length;
        if(start_index)
             i = start_index;
        if(end_index)
             l = end_index;
        for(i; i < l; i++)
            fn.apply(null, [list[i], i]);
    },

    rmap: function(list, fn) {
        var i = list.length-1, l = 0;
        for(i; i >= l; i--)
            fn.apply(null, [list[i], i]);
    },

    filter: function(list, fn, /*optional*/ start_index, end_index) {
        var r = [];
        AJS.map(list, function(elm) {
            if(fn(elm))
                r.push(elm);
        }, start_index, end_index);
        return r;
    },

    partial: function(fn) {
        var args = AJS.forceArray(arguments);
        return AJS.$b(fn, null, args.slice(1, args.length).reverse(), false, true);
    },


////
// DOM functions
////
    //Shortcut: AJS.$
    getElement: function(id) {
        if(AJS.isString(id) || AJS.isNumber(id))
            return document.getElementById(id);
        else
            return id;
    },

    //Shortcut: AJS.$$
    getElements: function(/*id1, id2, id3*/) {
        var args = AJS.forceArray(arguments);
        var elements = new Array();
            for (var i = 0; i < args.length; i++) {
                var element = AJS.getElement(args[i]);
                elements.push(element);
            }
            return elements;
    },

    //Shortcut: AJS.$bytc
    getElementsByTagAndClassName: function(tag_name, class_name, /*optional*/ parent) {
        var class_elements = [];
        if(!AJS.isDefined(parent))
            parent = document;
        if(!AJS.isDefined(tag_name))
            tag_name = '*';

        var els = parent.getElementsByTagName(tag_name);
        var els_len = els.length;
        var pattern = new RegExp("(^|\\s)" + class_name + "(\\s|$)");

        for (i = 0, j = 0; i < els_len; i++) {
            if ( pattern.test(els[i].className) || class_name == null ) {
                class_elements[j] = els[i];
                j++;
            }
        }
        return class_elements;
    },

    _nodeWalk: function(elm, tag_name, class_name, fn_next_elm) {
        var p = fn_next_elm(elm);

        var checkFn;
        if(tag_name && class_name) {
            checkFn = function(p) {
                return AJS.nodeName(p) == tag_name && AJS.hasClass(p, class_name);
            }
        }
        else if(tag_name) {
            checkFn = function(p) { return AJS.nodeName(p) == tag_name; }
        }
        else {
            checkFn = function(p) { return AJS.hasClass(p, class_name); }
        }

        while(p) {
            if(checkFn(p))
                return p;
            p = fn_next_elm(p);
        }
        return null;
    },

    getParentBytc: function(elm, tag_name, class_name) {
        return AJS._nodeWalk(elm, tag_name, class_name, function(m) { return m.parentNode; });
    },

    getPreviousSiblingBytc: function(elm, tag_name, class_name) {
        return AJS._nodeWalk(elm, tag_name, class_name, function(m) { return m.previousSibling; });
    },

    getNextSiblingBytc: function(elm, tag_name, class_name) {
        return AJS._nodeWalk(elm, tag_name, class_name, function(m) { return m.nextSibling; });
    },

    //Shortcut: AJS.$f
    getFormElement: function(form, name) {
        form = AJS.$(form);
        var r = null;
        AJS.map(form.elements, function(elm) {
            if(elm.name && elm.name == name)
                r = elm;
        });
        return r;
    },

    formContents: function(form) {
        var form = AJS.$(form);
        var r = {};
        var fn = function(elms) {
            AJS.map(elms, function(e) {
                if(e.name)
                    r[e.name] = e.value || '';
            });
        }
        fn(AJS.$bytc('input', null, form));
        fn(AJS.$bytc('textarea', null, form));
        return r;
    },

    getBody: function() {
        return AJS.$bytc('body')[0]
    },

    nodeName: function(elm) {
        return elm.nodeName.toLowerCase();
    },

    hasParent: function(elm, parent_to_consider, max_look_up) {
        if(elm == parent_to_consider)
            return true;
        if(max_look_up == 0)
            return false;
        return AJS.hasParent(elm.parentNode, parent_to_consider, max_look_up-1);
    },

    isElementHidden: function(elm) {
        return ((elm.style.display == "none") || (elm.style.visibility == "hidden"));
    },

    //Shortcut: AJS.DI
    documentInsert: function(elm) {
        if(typeof(elm) == 'string')
            elm = AJS.HTML2DOM(elm);
        document.write('<span id="dummy_holder"></span>');
        AJS.swapDOM(AJS.$('dummy_holder'), elm);
    },

    cloner: function(element) {
        return function() {
            return element.cloneNode(true);
        }
    },

    appendToTop: function(elm/*, elms...*/) {
        var args = AJS.forceArray(arguments).slice(1);
        if(args.length >= 1) {
            var first_child = elm.firstChild;
            if(first_child) {
                while(true) {
                    var t_elm = args.shift();
                    if(t_elm)
                        AJS.insertBefore(t_elm, first_child);
                    else
                        break;
                }
            }
            else {
                AJS.ACN.apply(null, arguments);
            }
        }
        return elm;
    },

    //Shortcut: AJS.ACN
    appendChildNodes: function(elm/*, elms...*/) {
        if(arguments.length >= 2) {
            AJS.map(arguments, function(n) {
                if(AJS.isString(n))
                    n = AJS.TN(n);
                if(AJS.isDefined(n))
                    elm.appendChild(n);
            }, 1);
        }
        return elm;
    },

    //Shortcut: AJS.RCN
    replaceChildNodes: function(elm/*, elms...*/) {
        var child;
        while ((child = elm.firstChild))
            elm.removeChild(child);
        if (arguments.length < 2)
            return elm;
        else
            return AJS.appendChildNodes.apply(null, arguments);
        return elm;
    },

    insertAfter: function(elm, reference_elm) {
        reference_elm.parentNode.insertBefore(elm, reference_elm.nextSibling);
        return elm;
    },

    insertBefore: function(elm, reference_elm) {
        reference_elm.parentNode.insertBefore(elm, reference_elm);
        return elm;
    },

    showElement: function(/*elms...*/) {
        var args = AJS.forceArray(arguments);
        AJS.map(args, function(elm) { elm.style.display = ''});
    },

    hideElement: function(elm) {
        var args = AJS.forceArray(arguments);
        AJS.map(args, function(elm) { elm.style.display = 'none'});
    },

    swapDOM: function(dest, src) {
        dest = AJS.getElement(dest);
        var parent = dest.parentNode;
        if (src) {
            src = AJS.getElement(src);
            parent.replaceChild(src, dest);
        } else {
            parent.removeChild(dest);
        }
        return src;
    },

    removeElement: function(/*elm1, elm2...*/) {
        var args = AJS.forceArray(arguments);
        AJS.map(args, function(elm) { AJS.swapDOM(elm, null); });
    },

    createDOM: function(name, attrs) {
        var i=0, attr;
        elm = document.createElement(name);

        if(AJS.isDict(attrs[i])) {
            for(k in attrs[0]) {
                attr = attrs[0][k];
                if(k == "style")
                    elm.style.cssText = attr;
                else if(k == "class" || k == 'className')
                    elm.className = attr;
                else {
                    elm.setAttribute(k, attr);
                }
            }
            i++;
        }

        if(attrs[0] == null)
            i = 1;

        AJS.map(attrs, function(n) {
            if(n) {
                if(AJS.isString(n) || AJS.isNumber(n))
                    n = AJS.TN(n);
                elm.appendChild(n);
            }
        }, i);
        return elm;
    },

    _createDomShortcuts: function() {
        var elms = [
                "ul", "li", "td", "tr", "th",
                "tbody", "table", "input", "span", "b",
                "a", "div", "img", "button", "h1",
                "h2", "h3", "br", "textarea", "form",
                "p", "select", "option", "iframe", "script",
                "center", "dl", "dt", "dd", "small",
                "pre"
        ];
        var extends_ajs = function(elm) {
            var c_dom = "return AJS.createDOM.apply(null, ['" + elm + "', arguments]);";
            var c_fun_dom = 'function() { ' + c_dom + '    }';
            eval("AJS." + elm.toUpperCase() + "=" + c_fun_dom);
        }
        AJS.map(elms, extends_ajs);
        AJS.TN = function(text) { return document.createTextNode(text) };
    },

    getCssDim: function(dim) {
        if(AJS.isString(dim))
            return dim;
        else
            return dim + "px";
    },
    getCssProperty: function(elm, prop) {
        elm = AJS.$(elm);
        var y;
        if(elm.currentStyle)
            y = elm.currentStyle[prop];
	else if (window.getComputedStyle)
            y = document.defaultView.getComputedStyle(elm,null).getPropertyValue(prop);
	return y;
    },

    setStyle: function(/*elm1, elm2..., property, new_value*/) {
        var args = AJS.forceArray(arguments);
        var new_val = args.pop();
        var property = args.pop();
        AJS.map(args, function(elm) { 
            elm.style[property] = AJS.getCssDim(new_val);
        });
    },

    setWidth: function(/*elm1, elm2..., width*/) {
        var args = AJS.forceArray(arguments);
        args.splice(args.length-1, 0, 'width');
        AJS.setStyle.apply(null, args);
    },
    setHeight: function(/*elm1, elm2..., height*/) {
        var args = AJS.forceArray(arguments);
        args.splice(args.length-1, 0, 'height');
        AJS.setStyle.apply(null, args);
    },
    setLeft: function(/*elm1, elm2..., left*/) {
        var args = AJS.forceArray(arguments);
        args.splice(args.length-1, 0, 'left');
        AJS.setStyle.apply(null, args);
    },
    setTop: function(/*elm1, elm2..., top*/) {
        var args = AJS.forceArray(arguments);
        args.splice(args.length-1, 0, 'top');
        AJS.setStyle.apply(null, args);
    },
    setClass: function(/*elm1, elm2..., className*/) {
        var args = AJS.forceArray(arguments);
        var c = args.pop();
        AJS.map(args, function(elm) { elm.className = c});
    },
    addClass: function(/*elm1, elm2..., className*/) {
        var args = AJS.forceArray(arguments);
        var cls = args.pop();
        var add_class = function(o) {
            if(!new RegExp("(^|\\s)" + cls + "(\\s|$)").test(o.className))
                o.className += (o.className ? " " : "") + cls;
        };
        AJS.map(args, function(elm) { add_class(elm); });
    },
    hasClass: function(elm, cls) {
        if(!elm.className)
            return false;
        return elm.className == cls || 
               elm.className.search(new RegExp(" " + cls)) != -1
    },
    removeClass: function(/*elm1, elm2..., className*/) {
        var args = AJS.forceArray(arguments);
        var cls = args.pop();
        var rm_class = function(o) {
            o.className = o.className.replace(new RegExp("\\s?" + cls, 'g'), "");
        };
        AJS.map(args, function(elm) { rm_class(elm); });
    },

    setHTML: function(elm, html) {
        elm.innerHTML = html;
        return elm;
    },

    RND: function(tmpl, ns, scope) {
        scope = scope || window;
        var fn = function(w, g) {
            g = g.split("|");
            var cnt = ns[g[0]];
            for(var i=1; i < g.length; i++)
                cnt = scope[g[i]](cnt);
            if(cnt == '')
                return '';
            if(cnt == 0 || cnt == -1)
                cnt += '';
            return cnt || w;
        };
        return tmpl.replace(/%\(([A-Za-z0-9_|.]*)\)/g, fn);
    },

    HTML2DOM: function(html,/*optional*/ first_child) {
        var d = AJS.DIV();
        d.innerHTML = html;
        if(first_child)
            return d.childNodes[0];
        else
            return d;
    },

    preloadImages: function(/*img_src1, ..., img_srcN*/) {
        AJS.AEV(window, 'load', AJS.$p(function(args) {
            AJS.map(args, function(src) {
                var pic = new Image();
                pic.src = src;
            });
        }, arguments));
    },


////
// Effects
////
    setOpacity: function(elm, p) {
        elm.style.opacity = p;
        elm.style.filter = "alpha(opacity="+ p*100 +")";
    },


////
// Ajax functions
////
    getXMLHttpRequest: function() {
        var try_these = [
            function () { return new XMLHttpRequest(); },
            function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
            function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
            function () { return new ActiveXObject('Msxml2.XMLHTTP.4.0'); },
            function () { throw "Browser does not support XMLHttpRequest"; }
        ];
        for (var i = 0; i < try_these.length; i++) {
            var func = try_these[i];
            try {
                return func();
            } catch (e) {
            }
        }
    },

    getRequest: function(url, data, type) {
        if(!type)
            type = "POST";
        var req = AJS.getXMLHttpRequest();

        if(url.indexOf("http://") == -1) {
            if(AJS.BASE_URL != '') {
                if(AJS.BASE_URL.lastIndexOf('/') != AJS.BASE_URL.length-1)
                    AJS.BASE_URL += '/';
                url = AJS.BASE_URL + url;
            }
        }

        req.open(type, url, true);
        if(type == "POST")
            req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        return AJS._sendXMLHttpRequest(req);
    },

    _sendXMLHttpRequest: function(req, data) {
        var d = new AJSDeferred(req);

        var onreadystatechange = function () {
            if (req.readyState == 4) {
                var status = '';
                try {
                    status = req.status;
                }
                catch(e) {};
                if(status == 200 || status == 304 || req.responseText == null) {
                    d.callback();
                }
                else {
                    if(AJS.ajaxErrorHandler)
                        AJS.ajaxErrorHandler(req.responseText, req);
                    else 
                        d.errback();
                }
            }
        }
        req.onreadystatechange = onreadystatechange;
        return d;
    },

    _reprString: function(o) {
        return ('"' + o.replace(/(["\\])/g, '\\$1') + '"'
        ).replace(/[\f]/g, "\\f"
        ).replace(/[\b]/g, "\\b"
        ).replace(/[\n]/g, "\\n"
        ).replace(/[\t]/g, "\\t"
        ).replace(/[\r]/g, "\\r");
    },

    serializeJSON: function(o) {
        var objtype = typeof(o);
        if (objtype == "undefined") {
            return "undefined";
        } else if (objtype == "number" || objtype == "boolean") {
            return o + "";
        } else if (o === null) {
            return "null";
        }
        if (objtype == "string") {
            return AJS._reprString(o);
        }
        var me = arguments.callee;
        if (objtype != "function" && typeof(o.length) == "number") {
            var res = [];
            for (var i = 0; i < o.length; i++) {
                var val = me(o[i]);
                if (typeof(val) != "string") {
                    val = "undefined";
                }
                res.push(val);
            }
            return "[" + res.join(",") + "]";
        }
        // it's a function with no adapter, bad
        if (objtype == "function")
            return null;
        res = [];
        for (var k in o) {
            var useKey;
            if (typeof(k) == "number") {
                useKey = '"' + k + '"';
            } else if (typeof(k) == "string") {
                useKey = AJS._reprString(k);
            } else {
                // skip non-string or number keys
                continue;
            }
            val = me(o[k]);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }
            res.push(useKey + ":" + val);
        }
        return "{" + res.join(",") + "}";
    },

    loadJSONDoc: function(url) {
        var d = AJS.getRequest(url);
        var eval_req = function(data, req) {
            var text = req.responseText;
            if(text == "Error")
                d.errback(req);
            else
                return AJS.evalTxt(text);
        };
        d.addCallback(eval_req);
        return d;
    },

    evalTxt: function(txt) {
        try {
            return eval('('+ txt + ')');
        }
        catch(e) {
            return eval(txt);
        }
    },

    evalScriptTags: function(html) {
        var script_data = html.match(/<script.*?>((\n|\r|.)*?)<\/script>/g);
        if(script_data != null) {
            for(var i=0; i < script_data.length; i++) {
                var script_only = script_data[i].replace(/<script.*?>/g, "");
                script_only = script_only.replace(/<\/script>/g, "");
                eval(script_only);
            }
        }
    },

    queryArguments: function(data) {
        var post_data = [];
        for(k in data)
            post_data.push(k + "=" + AJS.urlencode(data[k]));
        return post_data.join("&");
    },


////
// Position and size
////
    getMousePos: function(e) {
        var posx = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY)
        {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)
        {
            posx = e.clientX + document.body.scrollLeft;
            posy = e.clientY + document.body.scrollTop;
        }
        return {x: posx, y: posy};
    },

    getScrollTop: function() {
        //From: http://www.quirksmode.org/js/doctypes.html
        var t;
        if (document.documentElement && document.documentElement.scrollTop)
                t = document.documentElement.scrollTop;
        else if (document.body)
                t = document.body.scrollTop;
        return t;
    },

    absolutePosition: function(elm) {
        var posObj = {'x': elm.offsetLeft, 'y': elm.offsetTop};
        if(elm.offsetParent) {
            var temp_pos = AJS.absolutePosition(elm.offsetParent);
            posObj.x += temp_pos.x;
            posObj.y += temp_pos.y;
        }
        // safari bug
        if (AJS.isSafari() && elm.style.position == 'absolute' ) {
            posObj.x -= document.body.offsetLeft;
            posObj.y -= document.body.offsetTop;
        }
        return posObj;
    },

    getWindowSize: function(doc) {
        doc = doc || document;
        var win_w, win_h;
        if (self.innerHeight) {
            win_w = self.innerWidth;
            win_h = self.innerHeight;
        } else if (doc.documentElement && doc.documentElement.clientHeight) {
            win_w = doc.documentElement.clientWidth;
            win_h = doc.documentElement.clientHeight;
        } else if (doc.body) {
            win_w = doc.body.clientWidth;
            win_h = doc.body.clientHeight;
        }
        return {'w': win_w, 'h': win_h};
    },

    isOverlapping: function(elm1, elm2) {
        var pos_elm1 = AJS.absolutePosition(elm1);
        var pos_elm2 = AJS.absolutePosition(elm2);

        var top1 = pos_elm1.y;
        var left1 = pos_elm1.x;
        var right1 = left1 + elm1.offsetWidth;
        var bottom1 = top1 + elm1.offsetHeight;
        var top2 = pos_elm2.y;
        var left2 = pos_elm2.x;
        var right2 = left2 + elm2.offsetWidth;
        var bottom2 = top2 + elm2.offsetHeight;
        var getSign = function(v) {
            if(v > 0) return "+";
            else if(v < 0) return "-";
            else return 0;
        }

        if ((getSign(top1 - bottom2) != getSign(bottom1 - top2)) &&
                (getSign(left1 - right2) != getSign(right1 - left2)))
            return true;
        return false;
    },


////
// Events
////
    getEventElm: function(e) {
        if(e && !e.type && !e.keyCode)
            return e
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
        return targ;
    },

    _getRealScope: function(fn, /*optional*/ extra_args, dont_send_event, rev_extra_args) {
        var scope = window;
        extra_args = AJS.$A(extra_args);
        if(fn._cscope)
            scope = fn._cscope;

        return function() {
            //Append all the orginal arguments + extra_args
            var args = [];
            var i = 0;
            if(dont_send_event)
                i = 1;

            AJS.map(arguments, function(arg) { args.push(arg) }, i);
            args = args.concat(extra_args);
            if(rev_extra_args)
                args = args.reverse();
            return fn.apply(scope, args);
        };
    },

    _unloadListeners: function() {
        if(AJS.listeners)
            AJS.map(AJS.listeners, function(elm, type, fn) { AJS.REV(elm, type, fn) });
        AJS.listeners = [];
    },

    setEventKey: function(e) {
        e.key = e.keyCode ? e.keyCode : e.charCode;

        if(window.event) {
            e.ctrl = window.event.ctrlKey;
            e.shift = window.event.shiftKey;
        }
        else {
            e.ctrl = e.ctrlKey;
            e.shift = e.shiftKey;
        }
        switch(e.key) {
            case 63232:
                e.key = 38;
                break;
            case 63233:
                e.key = 40;
                break;
            case 63235:
                e.key = 39;
                break;
            case 63234:
                e.key = 37;
                break;
        }
    },

    //Shortcut: AJS.AEV
    addEventListener: function(elm, type, fn, /*optional*/listen_once, cancle_bubble) {
        if(!cancle_bubble)
            cancle_bubble = false;

        var elms = AJS.$A(elm);
        AJS.map(elms, function(elmz) {
            if(listen_once)
                fn = AJS._listenOnce(elmz, type, fn);
            
            //Hack since it does not work in all browsers
            if(AJS.isIn(type, ['submit', 'load', 'scroll', 'resize'])) {
                var old = elm['on' + type];
                elm['on' + type] = function() {
                    if(old) {
                        fn(arguments);
                        return old(arguments);
                    }
                    else
                        return fn(arguments);
                };
                return;
            }

            //Fix keyCode
            if(AJS.isIn(type, ['keypress', 'keydown', 'keyup', 'click'])) {
                var old_fn = fn;
                fn = function(e) {
                    AJS.setEventKey(e);
                    return old_fn.apply(null, arguments);
                }
            }

            if (elmz.attachEvent) {
                //FIXME: We ignore cancle_bubble for IE... could be a problem?
                elmz.attachEvent("on" + type, fn);
            }
            else if(elmz.addEventListener)
                elmz.addEventListener(type, fn, cancle_bubble);

            AJS.listeners = AJS.$A(AJS.listeners);
            AJS.listeners.push([elmz, type, fn]);
        });
    },

    //Shortcut: AJS.REV
    removeEventListener: function(elm, type, fn, /*optional*/cancle_bubble) {
        if(!cancle_bubble)
            cancle_bubble = false;
        if(elm.removeEventListener) {
            elm.removeEventListener(type, fn, cancle_bubble);
            if(AJS.isOpera())
                elm.removeEventListener(type, fn, !cancle_bubble);
        }
        else if(elm.detachEvent)
            elm.detachEvent("on" + type, fn);
    },

    //Shortcut: AJS.$b
    bind: function(fn, scope, /*optional*/ extra_args, dont_send_event, rev_extra_args) {
        fn._cscope = scope;
        return AJS._getRealScope(fn, extra_args, dont_send_event, rev_extra_args);
    },

    bindMethods: function(self) {
        for (var k in self) {
            var func = self[k];
            if (typeof(func) == 'function') {
                self[k] = AJS.$b(func, self);
            }
        }
    },

    _listenOnce: function(elm, type, fn) {
        var r_fn = function() {
            AJS.removeEventListener(elm, type, r_fn);
            fn(arguments);
        }
        return r_fn;
    },

    callLater: function(fn, interval) {
        var fn_no_send = function() {
            fn();
        };
        window.setTimeout(fn_no_send, interval);
    },

    preventDefault: function(e) {
        if(AJS.isIe()) 
            window.event.returnValue = false;
        else 
            e.preventDefault();
    },


////
// Drag and drop
////
    dragAble: function(elm, /*optional*/ handler, args) {
        if(!args)
            args = {};
        if(!AJS.isDefined(args['move_x']))
            args['move_x'] = true;
        if(!AJS.isDefined(args['move_y']))
            args['move_y'] = true;
        if(!AJS.isDefined(args['moveable']))
            args['moveable'] = false;
        if(!AJS.isDefined(args['hide_on_move']))
            args['hide_on_move'] = true;
        if(!AJS.isDefined(args['on_mouse_up']))
            args['on_mouse_up'] = null;
        if(!AJS.isDefined(args['cursor']))
            args['cursor'] = 'move';
        if(!AJS.isDefined(args['max_move']))
            args['max_move'] = {'top': null, 'left': null};

        elm = AJS.$(elm);

        if(!handler)
            handler = elm;

        handler = AJS.$(handler);
        var old_cursor = handler.style.cursor;
        handler.style.cursor = args['cursor'];
        elm.style.position = 'relative';

        AJS.addClass(handler, '_ajs_handler');
        handler._args = args;
        handler._elm = elm;
        AJS.AEV(handler, 'mousedown', AJS._dragStart);
    },

    _dragStart: function(e) {
        var handler = AJS.getEventElm(e);
        if(!AJS.hasClass(handler, '_ajs_handler')) {
            handler = AJS.getParentBytc(handler, null, '_ajs_handler');
        }
        if(handler)
            AJS._dragInit(e, handler._elm, handler._args);
    },

    dropZone: function(elm, args) {
        elm = AJS.$(elm);
        var item = {elm: elm};
        AJS.update(item, args);
        AJS._drop_zones.push(item);
    },

    removeDragAble: function(elm) {
        AJS.REV(elm, 'mousedown', AJS._dragStart);
        elm.style.cursor = '';
    },

    removeDropZone: function(elm) {
        var i = AJS.getIndex(elm, AJS._drop_zones, function(item) {
            if(item.elm == elm) return true;
        });
        if(i != -1) {
            AJS._drop_zones.splice(i, 1);
        }
    },

    _dragInit: function(e, click_elm, args) {
        AJS.drag_obj = new Object();
        AJS.drag_obj.args = args;

        AJS.drag_obj.click_elm = click_elm;
        AJS.drag_obj.mouse_pos = AJS.getMousePos(e);
        AJS.drag_obj.click_elm_pos = AJS.absolutePosition(click_elm);

        AJS.AEV(document, 'mousemove', AJS._dragMove, false, true);
        AJS.AEV(document, 'mouseup', AJS._dragStop, false, true);

        if (AJS.isIe())
            window.event.cancelBubble = true;
        AJS.preventDefault(e);
    },

    _initDragElm: function(elm) {
        if(AJS.drag_elm && AJS.drag_elm.style.display == 'none')
            AJS.removeElement(AJS.drag_elm);

        if(!AJS.drag_elm) {
            AJS.drag_elm = AJS.DIV();
            var d = AJS.drag_elm;
            AJS.insertBefore(d, AJS.getBody().firstChild);
            AJS.setHTML(d, elm.innerHTML);

            d.className = elm.className;
            d.style.cssText = elm.style.cssText;

            d.style.position = 'absolute';
            d.style.zIndex = 10000;

            var t = AJS.absolutePosition(elm);
            AJS.setTop(d, t.y);
            AJS.setLeft(d, t.x);

            if(AJS.drag_obj.args.on_init) {
                AJS.drag_obj.args.on_init(elm);
            }
        }
    },

    _dragMove: function(e) {
        var drag_obj = AJS.drag_obj;
        var click_elm = drag_obj.click_elm;

        AJS._initDragElm(click_elm);
        var drag_elm = AJS.drag_elm;

        if(drag_obj.args['hide_on_move'])
            click_elm.style.visibility = 'hidden';

        var cur_pos = AJS.getMousePos(e);

        var mouse_pos = drag_obj.mouse_pos;

        var click_elm_pos = drag_obj.click_elm_pos;

        AJS.map(AJS._drop_zones, function(d_z) {
            if(AJS.isOverlapping(d_z['elm'], drag_elm)) {
                if(d_z['elm'] != drag_elm) {
                    var on_hover = d_z['on_hover'];
                    if(on_hover)
                        on_hover(d_z['elm'], click_elm, drag_elm);
                }
            }
        });

        if(drag_obj.args['on_drag'])
            drag_obj.args['on_drag'](click_elm, e);

        var max_move_top = drag_obj.args['max_move']['top'];
        var max_move_left = drag_obj.args['max_move']['left'];
        var p;
        if(drag_obj.args['move_x']) {
            p = cur_pos.x - (mouse_pos.x - click_elm_pos.x);
            if(max_move_left == null || max_move_left <= p)
                AJS.setLeft(elm, p);
        }

        if(drag_obj.args['move_y']) {
            p = cur_pos.y - (mouse_pos.y - click_elm_pos.y);
            if(max_move_top == null || max_move_top <= p)
                AJS.setTop(elm, p);
        }
        if(AJS.isIe()) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        else
            e.preventDefault();
    },

    _dragStop: function(e) {
        var drag_obj = AJS.drag_obj;
        var drag_elm = AJS.drag_elm;
        var click_elm = drag_obj.click_elm;

        AJS.REV(document, "mousemove", AJS._dragMove, true);
        AJS.REV(document, "mouseup", AJS._dragStop, true);

        var dropped = false;
        AJS.map(AJS._drop_zones, function(d_z) {
            if(AJS.isOverlapping(d_z['elm'], click_elm)) {
                if(d_z['elm'] != click_elm) {
                    var on_drop = d_z['on_drop'];
                    if(on_drop) {
                        dropped = true;
                        on_drop(d_z['elm'], click_elm);
                    }
                }
            }
        });

        if(drag_obj.args['moveable']) {
            var t = parseInt(click_elm.style.top) || 0;
            var l = parseInt(click_elm.style.left) || 0;
            var drag_elm_xy = AJS.absolutePosition(drag_elm);
            var click_elm_xy = AJS.absolutePosition(click_elm);
            AJS.setTop(click_elm, t + drag_elm_xy.y - click_elm_xy.y);
            AJS.setLeft(click_elm, l + drag_elm_xy.x - click_elm_xy.x);
        }

        if(!dropped && drag_obj.args['on_mouse_up'])
            drag_obj.args['on_mouse_up'](click_elm, e);

        if(drag_obj.args['hide_on_move'])
            drag_obj.click_elm.style.visibility = 'visible';

        if(drag_obj.args.on_end) {
            drag_obj.args.on_end(click_elm);
        }

        AJS._dragObj = null;
        if(drag_elm)
            AJS.hideElement(drag_elm);
        AJS.drag_elm = null;
    },


////
// Misc.
////
    keys: function(obj) {
        var rval = [];
        for (var prop in obj) {
            rval.push(prop);
        }
        return rval;
    },

    values: function(obj) {
        var rval = [];
        for (var prop in obj) {
            rval.push(obj[prop]);
        }
        return rval;
    },

    urlencode: function(str) {
        return encodeURIComponent(str.toString());
    },

    isDefined: function(o) {
        return (o != "undefined" && o != null)
    },

    isArray: function(obj) {
        return obj instanceof Array;
    },

    isString: function(obj) {
        return (typeof obj == 'string');
    },

    isNumber: function(obj) {
        return (typeof obj == 'number');
    },

    isObject: function(obj) {
        return (typeof obj == 'object');
    },

    isFunction: function(obj) {
        return (typeof obj == 'function');
    },

    isDict: function(o) {
        var str_repr = String(o);
        return str_repr.indexOf(" Object") != -1;
    },

    exportToGlobalScope: function() {
        for(e in AJS)
            eval(e + " = AJS." + e);
    },

    log: function(o) {
        if(AJS.isMozilla())
            console.log(o);
        else {
            var div = AJS.DIV({'style': 'color: green'});
            AJS.ACN(AJS.getBody(), AJS.setHTML(div, ''+o));
        }
    }

}

AJS.Class = function(members) {
    var fn = function() {
        if(arguments[0] != 'no_init') {
            return this.init.apply(this, arguments);
        }
    }
    fn.prototype = members;
    AJS.update(fn, AJS.Class.prototype);
    return fn;
}
AJS.Class.prototype = {
    extend: function(members) {
        var parent = new this('no_init');
        for(k in members) {
            var prev = parent[k];
            var cur = members[k];
            if (prev && prev != cur && typeof cur == 'function') {
                cur = this._parentize(cur, prev);
            }
            parent[k] = cur;
        }
        return new AJS.Class(parent);
    },

    implement: function(members) {
        AJS.update(this.prototype, members);
    },

    _parentize: function(cur, prev) {
        return function(){
            this.parent = prev;
            return cur.apply(this, arguments);
        }
    }
};

//Shortcuts
AJS.$ = AJS.getElement;
AJS.$$ = AJS.getElements;
AJS.$f = AJS.getFormElement;
AJS.$b = AJS.bind;
AJS.$p = AJS.partial;
AJS.$FA = AJS.forceArray;
AJS.$A = AJS.createArray;
AJS.DI = AJS.documentInsert;
AJS.ACN = AJS.appendChildNodes;
AJS.RCN = AJS.replaceChildNodes;
AJS.AEV = AJS.addEventListener;
AJS.REV = AJS.removeEventListener;
AJS.$bytc = AJS.getElementsByTagAndClassName;

AJSDeferred = function(req) {
    this.callbacks = [];
    this.errbacks = [];
    this.req = req;
}
AJSDeferred.prototype = {
    excCallbackSeq: function(req, list) {
        var data = req.responseText;
        while (list.length > 0) {
            var fn = list.pop();
            var new_data = fn(data, req);
            if(new_data)
                data = new_data;
        }
    },

    callback: function () {
        this.excCallbackSeq(this.req, this.callbacks);
    },

    errback: function() {
        if(this.errbacks.length == 0)
            alert("Error encountered:\n" + this.req.responseText);

        this.excCallbackSeq(this.req, this.errbacks);
    },

    addErrback: function(fn) {
        this.errbacks.unshift(fn);
    },

    addCallback: function(fn) {
        this.callbacks.unshift(fn);
    },

    addCallbacks: function(fn1, fn2) {
        this.addCallback(fn1);
        this.addErrback(fn2);
    },

    sendReq: function(data) {
        if(AJS.isObject(data)) {
            this.req.send(AJS.queryArguments(data));
        }
        else if(AJS.isDefined(data))
            this.req.send(data);
        else {
            this.req.send("");
        }
    }
};

//Prevent memory-leaks
AJS.addEventListener(window, 'unload', AJS._unloadListeners);
AJS._createDomShortcuts()
}

script_loaded = true;

//end ami.js





//begin cookie support

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

//end cookie support






//begin googiespell.js

var GOOGIE_CUR_LANG = null;
var GOOGIE_DEFAULT_LANG = "en";

function GoogieSpell(img_dir, server_url) {
    var cookie_value;
    var lang;
    cookie_value = getCookie('language');

    if(cookie_value != null)
        GOOGIE_CUR_LANG = cookie_value;
    else
        GOOGIE_CUR_LANG = GOOGIE_DEFAULT_LANG;

    this.img_dir = img_dir;
    this.server_url = server_url;

    this.org_lang_to_word = {"da": "Dansk", "de": "Deutsch", "en": "English",
                                             "es": "Espa&#241;ol", "fr": "Fran&#231;ais", "it": "Italiano", 
                                             "nl": "Nederlands", "pl": "Polski", "pt": "Portugu&#234;s",
                                             "fi": "Suomi", "sv": "Svenska"};
    this.lang_to_word = this.org_lang_to_word;
    this.langlist_codes = AJS.keys(this.lang_to_word);

    this.show_change_lang_pic = true;
    this.change_lang_pic_placement = "left";

    this.report_state_change = true;

    this.ta_scroll_top = 0;
    this.el_scroll_top = 0;

    this.langTag = null;
    this.lang_chck_spell = "Check spelling";
    this.lang_revert = "Revert to";
    this.lang_close = "Close";
    this.lang_rsm_edt = "Resume editing";
    this.lang_no_error_found = "No spelling errors found";
    this.lang_no_suggestions = "No suggestions";
    this.spellAfter = true;
    
    this.show_spell_img = false;
    this.decoration = true;
    this.use_close_btn = false;
    this.edit_layer_dbl_click = true;
    this.report_ta_not_found = false;

    //Extensions
    this.custom_ajax_error = null;
    this.custom_no_spelling_error = null;
    this.custom_menu_builder = []; //Should take an eval function and a build menu function
    this.custom_item_evaulator = null; //Should take an eval function and a build menu function
    this.extra_menu_items = [];
    this.custom_spellcheck_starter = null;
    this.main_controller = true;

    //Observers
    this.lang_state_observer = null;
    this.spelling_state_observer = null;
    this.show_menu_observer = null;
    this.all_errors_fixed_observer = null;

    //Focus links - used to give the text box focus
    this.use_focus = false;
    this.focus_link_t = null;
    this.focus_link_b = null;

    //Counters
    this.cnt_errors = 0;
    this.cnt_errors_fixed = 0;

    //Set document on click to hide the language and error menu
    var fn = function(e) {
        var elm = AJS.getEventElm(e);
        if(elm.googie_action_btn != "1" && this.isLangWindowShown())
            this.hideLangWindow();
        if(elm.googie_action_btn != "1" && this.isErrorWindowShown())
            this.hideErrorWindow();
    };
    AJS.AEV(document, "click", AJS.$b(fn, this));
}

GoogieSpell.prototype.decorateTextarea = function(id) {
    if(typeof(id) == "string")
        this.text_area = AJS.$(id);
    else
        this.text_area = id;

    var r_width, r_height;

    if(this.text_area != null) {
        if(!AJS.isDefined(this.spell_container) && this.decoration) {
            var table = AJS.TABLE();
            var tbody = AJS.TBODY();
            var tr = AJS.TR();
            if(AJS.isDefined(this.force_width))
                r_width = this.force_width;
            else
                r_width = this.text_area.offsetWidth + "px";

            if(AJS.isDefined(this.force_height))
                r_height = this.force_height;
            else
                r_height = "";

            var spell_container = AJS.TD();
            this.spell_container = spell_container;

            tr.appendChild(spell_container);

            tbody.appendChild(tr);
            table.appendChild(tbody);

            if (this.spellAfter == true)
	        AJS.insertAfter(table, this.text_area);
	    else
        	AJS.insertBefore(table, this.text_area);

            //Set width
            AJS.setHeight(table, spell_container, r_height);
            AJS.setWidth(table, spell_container, r_width);

            spell_container.style.textAlign = "right";
            spell_container.style.whiteSpace = "nowrap";
        }

        this.checkSpellingState();
    }
    else 
        if(this.report_ta_not_found)
            alert("Text area not found");
}

//////
// API Functions (the ones that you can call)
/////
GoogieSpell.prototype.setSpellContainer = function(elm) {
    this.spell_container = AJS.$(elm);
}

GoogieSpell.prototype.setLanguages = function(lang_dict) {
    this.lang_to_word = lang_dict;
    this.langlist_codes = AJS.keys(lang_dict);
}

GoogieSpell.prototype.setForceWidthHeight = function(width, height) {
    /***
        Set to null if you want to use one of them
    ***/
    this.force_width = width;
    this.force_height = height;
}

GoogieSpell.prototype.setDecoration = function(bool) {
    this.decoration = bool;
}

GoogieSpell.prototype.dontUseCloseButtons = function() {
    this.use_close_btn = false;
}

GoogieSpell.prototype.appendNewMenuItem = function(name, call_back_fn, checker) {
    this.extra_menu_items.push([name, call_back_fn, checker]);
}

GoogieSpell.prototype.appendCustomMenuBuilder = function(eval, builder) {
    this.custom_menu_builder.push([eval, builder]);
}

GoogieSpell.prototype.setFocus = function() {
    try {
        this.focus_link_b.focus();
        this.focus_link_t.focus();
        return true;
    }
    catch(e) {
        return false;
    }
}


//////
// Set functions (internal)
/////
GoogieSpell.prototype.setStateChanged = function(current_state) {
    this.state = current_state;
    if(this.spelling_state_observer != null && this.report_state_change)
        this.spelling_state_observer(current_state, this);
}

GoogieSpell.prototype.setReportStateChange = function(bool) {
    this.report_state_change = bool;
}


//////
// Request functions
/////
GoogieSpell.prototype.getGoogleUrl = function() {
    return this.server_url + GOOGIE_CUR_LANG;
}

GoogieSpell.escapeSepcial = function(val) {
    return val.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

GoogieSpell.createXMLReq = function (text) {
    return '<?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1"><text>' + text + '</text></spellrequest>';
}

GoogieSpell.prototype.spellCheck = function(ignore) {
    var me = this;

    this.cnt_errors_fixed = 0;
    this.cnt_errors = 0;
    this.setStateChanged("checking_spell");

    if(this.main_controller)
        this.appendIndicator(this.spell_span);

    this.error_links = [];
    this.ta_scroll_top = this.text_area.scrollTop;

    try { this.hideLangWindow(); }
    catch(e) {}
    
    this.createEditLayer(this.text_area.offsetWidth, this.text_area.offsetHeight);

    this.createErrorWindow();
    AJS.getBody().appendChild(this.error_window);

    try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } 
    catch (e) { }

    if(this.main_controller)
        this.spell_span.onclick = null;

    this.orginal_text = this.text_area.value;

    if(this.text_area.value == '' || ignore) {
        if(!me.custom_no_spelling_error)
            me.flashNoSpellingErrorState();
        else
            me.custom_no_spelling_error(me);
        me.removeIndicator();
        return ;
    }

    //Create request
    var d = AJS.getRequest(this.getGoogleUrl());
    var reqdone = function(res_txt) {
        var r_text = res_txt;
        me.results = me.parseResult(r_text);

        if(r_text.match(/<c.*>/) != null) {
            //Before parsing be sure that errors were found
            me.showErrorsInIframe();
            me.resumeEditingState();
        }
        else {
            if(!me.custom_no_spelling_error)
                me.flashNoSpellingErrorState();
            else
                me.custom_no_spelling_error(me);
        }
        me.removeIndicator();
    };

    d.addCallback(reqdone);
    reqdone = null;

    var reqfailed = function(res_txt, req) {
        if(me.custom_ajax_error)
            me.custom_ajax_error(req);
        else
            alert("An error was encountered on the server. Please try again later.");

        if(me.main_controller) {
            AJS.removeElement(me.spell_span);
            me.removeIndicator();
        }
        me.checkSpellingState();
    };
    d.addErrback(reqfailed);
    reqfailed = null;

    var req_text = GoogieSpell.escapeSepcial(this.orginal_text);
    d.sendReq(GoogieSpell.createXMLReq(req_text));
}


//////
// Spell checking functions
/////
GoogieSpell.prototype.parseResult = function(r_text) {
    /***
     Retunrs an array
     result[item] -> ['attrs'], ['suggestions']
        ***/
    var re_split_attr_c = /\w+="(\d+|true)"/g;
    var re_split_text = /\t/g;

    var matched_c = r_text.match(/<c[^>]*>[^<]*<\/c>/g);
    var results = new Array();

    if(matched_c == null)
        return results;
    
    for(var i=0; i < matched_c.length; i++) {
        var item = new Array();
        this.errorFound();

        //Get attributes
        item['attrs'] = new Array();
        var split_c = matched_c[i].match(re_split_attr_c);
        for(var j=0; j < split_c.length; j++) {
            var c_attr = split_c[j].split(/=/);
            var val = c_attr[1].replace(/"/g, '');
            if(val != "true")
                item['attrs'][c_attr[0]] = parseInt(val);
            else {
                item['attrs'][c_attr[0]] = val;
            }
        }

        //Get suggestions
        item['suggestions'] = new Array();
        var only_text = matched_c[i].replace(/<[^>]*>/g, "");
        var split_t = only_text.split(re_split_text);
        for(var k=0; k < split_t.length; k++) {
        if(split_t[k] != "")
            item['suggestions'].push(split_t[k]);
        }
        results.push(item);
    }
    return results;
}

//////
// Counters
/////
GoogieSpell.prototype.errorFixed = function() { 
    this.cnt_errors_fixed++; 
    if(this.all_errors_fixed_observer)
        if(this.cnt_errors_fixed == this.cnt_errors) {
            this.hideErrorWindow();
            this.all_errors_fixed_observer();
        }
}
GoogieSpell.prototype.errorFound = function() { this.cnt_errors++; }

//////
// Error menu functions
/////
GoogieSpell.prototype.createErrorWindow = function() {
    this.error_window = AJS.DIV();
    this.error_window.className = "googie_window";
    this.error_window.googie_action_btn = "1";
}

GoogieSpell.prototype.isErrorWindowShown = function() {
    return this.error_window != null && this.error_window.style.visibility == "visible";
}

GoogieSpell.prototype.hideErrorWindow = function() {
    try {
        this.error_window.style.visibility = "hidden";
        if(this.error_window_iframe)
            this.error_window_iframe.style.visibility = "hidden";
    }
    catch(e) {}
}

GoogieSpell.prototype.updateOrginalText = function(offset, old_value, new_value, id) {
    var part_1 = this.orginal_text.substring(0, offset);
    var part_2 = this.orginal_text.substring(offset+old_value.length);
    this.orginal_text = part_1 + new_value + part_2;
    this.text_area.value = this.orginal_text;
    var add_2_offset = new_value.length - old_value.length;
    for(var j=0; j < this.results.length; j++) {
        //Don't edit the offset of the current item
        if(j != id && j > id){
            this.results[j]['attrs']['o'] += add_2_offset;
        }
    }
}

GoogieSpell.prototype.saveOldValue = function(elm, old_value) {
    elm.is_changed = true;
    elm.old_value = old_value;
}

GoogieSpell.prototype.createListSeparator = function() {
    var e_col = AJS.TD(" ");
    e_col.googie_action_btn = "1";
    e_col.style.cursor = "default";
    e_col.style.fontSize = "3px";
    e_col.style.borderTop = "1px solid #ccc";
    e_col.style.paddingTop = "3px";

    return AJS.TR(e_col);
}

GoogieSpell.prototype.correctError = function(id, elm, l_elm, /*optional*/ rm_pre_space) {
    var old_value = elm.innerHTML;
    var new_value = l_elm.innerHTML;
    var offset = this.results[id]['attrs']['o'];

    if(rm_pre_space) {
        var pre_length = elm.previousSibling.innerHTML;
        elm.previousSibling.innerHTML = pre_length.slice(0, pre_length.length-1);
        old_value = " " + old_value;
        offset--;
    }

    this.hideErrorWindow();

    this.updateOrginalText(offset, old_value, new_value, id);

    elm.innerHTML = new_value;
    
    elm.style.color = "green";
    elm.is_corrected = true;

    this.results[id]['attrs']['l'] = new_value.length;

    if(!AJS.isDefined(elm.old_value))
        this.saveOldValue(elm, old_value);
    
    this.errorFixed();
}

GoogieSpell.prototype.showErrorWindow = function(elm, id) {
    if(this.show_menu_observer)
        this.show_menu_observer(this);
    var me = this;

    var abs_pos = AJS.absolutePosition(elm);
    abs_pos.y -= this.edit_layer.scrollTop;
    this.error_window.style.visibility = "visible";

    AJS.setTop(this.error_window, (abs_pos.y+20));
    AJS.setLeft(this.error_window, (abs_pos.x));

    this.error_window.innerHTML = "";

    var table = AJS.TABLE({'class': 'googie_list'});
    table.googie_action_btn = "1";
    var list = AJS.TBODY();

    //Check if we should use custom menu builder, if not we use the default
    var changed = false;
    if(this.custom_menu_builder != []) {
        for(var k=0; k<this.custom_menu_builder.length; k++) {
            var eb = this.custom_menu_builder[k];
            if(eb[0]((this.results[id]))){
                changed = eb[1](this, list, elm);
                break;
            }
        }
    }
    if(!changed) {
        //Build up the result list
        var suggestions = this.results[id]['suggestions'];
        var offset = this.results[id]['attrs']['o'];
        var len = this.results[id]['attrs']['l'];

        if(suggestions.length == 0) {
            var row = AJS.TR();
            var item = AJS.TD({'style': 'cursor: default;'});
            var dummy = AJS.SPAN();
            dummy.innerHTML = this.lang_no_suggestions;
            AJS.ACN(item, AJS.TN(dummy.innerHTML));
            item.googie_action_btn = "1";
            row.appendChild(item);
            list.appendChild(row);
        }

        for(i=0; i < suggestions.length; i++) {
            var row = AJS.TR();
            var item = AJS.TD();
            var dummy = AJS.SPAN();
            dummy.innerHTML = suggestions[i];
            item.appendChild(AJS.TN(dummy.innerHTML));
            
            var fn = function(e) {
                var l_elm = AJS.getEventElm(e);
                this.correctError(id, elm, l_elm);
            };

            AJS.AEV(item, "click", AJS.$b(fn, this));

            item.onmouseover = GoogieSpell.item_onmouseover;
            item.onmouseout = GoogieSpell.item_onmouseout;
            row.appendChild(item);
            list.appendChild(row);
        }

        //The element is changed, append the revert
        if(elm.is_changed && elm.innerHTML != elm.old_value) {
            var old_value = elm.old_value;
            var revert_row = AJS.TR();
            var revert = AJS.TD();

            revert.onmouseover = GoogieSpell.item_onmouseover;
            revert.onmouseout = GoogieSpell.item_onmouseout;
            var rev_span = AJS.SPAN({'class': 'googie_list_revert'});
            rev_span.innerHTML = this.lang_revert + " " + old_value;
            revert.appendChild(rev_span);

            var fn = function(e) { 
                this.updateOrginalText(offset, elm.innerHTML, old_value, id);
                elm.is_corrected = true;
                elm.style.color = "#b91414";
                elm.innerHTML = old_value;
                this.hideErrorWindow();
            };
            AJS.AEV(revert, "click", AJS.$b(fn, this));

            revert_row.appendChild(revert);
            list.appendChild(revert_row);
        }
        
        //Append the edit box
        var edit_row = AJS.TR();
        var edit = AJS.TD({'style': 'cursor: default'});

        var edit_input = AJS.INPUT({'style': 'width: 120px; margin:0; padding:0', 'value': elm.innerHTML});
        edit_input.googie_action_btn = "1";

        var onsub = function () {
            if(edit_input.value != "") {
                if(!AJS.isDefined(elm.old_value))
                    this.saveOldValue(elm, elm.innerHTML);

                this.updateOrginalText(offset, elm.innerHTML, edit_input.value, id);
                elm.style.color = "green"
                elm.is_corrected = true;
                elm.innerHTML = edit_input.value;
                
                this.hideErrorWindow();
            }
            return false;
        };
        onsub = AJS.$b(onsub, this);
        
        var ok_pic = AJS.IMG({'src': this.img_dir + "ok.gif", 'style': 'width: 32px; height: 16px; margin-left: 2px; margin-right: 2px; cursor: pointer;'});
        var edit_form = AJS.FORM({'style': 'margin: 0; padding: 0; cursor: default;'}, edit_input, ok_pic);

        edit_form.googie_action_btn = "1";
        edit.googie_action_btn = "1";

        AJS.AEV(edit_form, "submit", onsub);
        AJS.AEV(ok_pic, "click", onsub);
        
        edit.appendChild(edit_form);
        edit_row.appendChild(edit);
        list.appendChild(edit_row);

        //Append extra menu items
        if(this.extra_menu_items.length > 0)
            AJS.ACN(list, this.createListSeparator());

        var loop = function(i) {
                if(i < me.extra_menu_items.length) {
                    var e_elm = me.extra_menu_items[i];

                    if(!e_elm[2] || e_elm[2](elm, me)) {
                        var e_row = AJS.TR();
                        var e_col = AJS.TD(e_elm[0]);

                        e_col.onmouseover = GoogieSpell.item_onmouseover;
                        e_col.onmouseout = GoogieSpell.item_onmouseout;

                        var fn = function() {
                            return e_elm[1](elm, me);
                        };
                        AJS.AEV(e_col, "click", fn);

                        AJS.ACN(e_row, e_col);
                        AJS.ACN(list, e_row);

                    }
                    loop(i+1);
                }
        }
        loop(0);
        loop = null;

        //Close button
        if(this.use_close_btn) {
            AJS.ACN(list, this.createCloseButton(this.hideErrorWindow));
        }
    }

    table.appendChild(list);
    this.error_window.appendChild(table);

    //Dummy for IE - dropdown bug fix
    if(AJS.isIe() && !this.error_window_iframe) {
        var iframe = AJS.IFRAME({'style': 'position: absolute; z-index: 0;'});
        AJS.ACN(AJS.getBody(), iframe);
        this.error_window_iframe = iframe;
    }
    if(AJS.isIe()) {
        var iframe = this.error_window_iframe;
        AJS.setTop(iframe, this.error_window.offsetTop);
        AJS.setLeft(iframe, this.error_window.offsetLeft);

        AJS.setWidth(iframe, this.error_window.offsetWidth);
        AJS.setHeight(iframe, this.error_window.offsetHeight);

        iframe.style.visibility = "visible";
    }

    //Set focus on the last element
    var link = this.createFocusLink('link');
    list.appendChild(AJS.TR(AJS.TD({'style': 'text-align: right; font-size: 1px; height: 1px; margin: 0; padding: 0;'}, link)));
    link.focus();
}


//////
// Edit layer (the layer where the suggestions are stored)
//////
GoogieSpell.prototype.createEditLayer = function(width, height) {
    this.edit_layer = AJS.DIV({'class': 'googie_edit_layer'});

    //Set the style so it looks like edit areas
    this.edit_layer.className = this.text_area.className;
    this.edit_layer.style.border = "1px solid #999";
    this.edit_layer.style.backgroundColor = "#f7f7f7";
    this.edit_layer.style.padding = "3px";
    this.edit_layer.style.margin = "0px";

    AJS.setWidth(this.edit_layer, (width-8));

    if(AJS.nodeName(this.text_area) != "input" || this.text_area.value == "") {
        this.edit_layer.style.overflow = "auto";
        AJS.setHeight(this.edit_layer, (height-6));
    }
    else {
        this.edit_layer.style.overflow = "hidden";
    }

    if(this.edit_layer_dbl_click) {
        var me = this;
        var fn = function(e) {
            if(AJS.getEventElm(e).className != "googie_link" && !me.isErrorWindowShown()) {
                me.resumeEditing();
                var fn1 = function() {
                    me.text_area.focus();
                    fn1 = null;
                };
                AJS.callLater(fn1, 10);
            }
            return false;
        };
        this.edit_layer.ondblclick = fn;
        fn = null;
    }
}

GoogieSpell.prototype.resumeEditing = function() {
    this.setStateChanged("spell_check");
    this.switch_lan_pic.style.display = "inline";

    this.el_scroll_top = this.edit_layer.scrollTop;

    this.hideErrorWindow();

    //Remove the EDIT_LAYER
    try {
        this.edit_layer.parentNode.removeChild(this.edit_layer);
        if(this.use_focus) {
            AJS.removeElement(this.focus_link_t);
            AJS.removeElement(this.focus_link_b);
        }
    }
    catch(e) {
    }

    AJS.showElement(this.text_area);

    if(this.main_controller)
        this.spell_span.className = "googie_no_style";

    this.text_area.scrollTop = this.el_scroll_top;

    elm.onmouseout = null;

    this.checkSpellingState(false);
}

GoogieSpell.prototype.createErrorLink = function(text, id) {
    var elm = AJS.SPAN({'class': 'googie_link'});
    var me = this;
    var d = function (e) {
        me.showErrorWindow(elm, id);
        d = null;
        return false;
    };
    AJS.AEV(elm, "click", d);

    elm.googie_action_btn = "1";
    elm.g_id = id;
    elm.is_corrected = false;
    elm.oncontextmenu = d;
    elm.innerHTML = text;
    return elm;
}

GoogieSpell.createPart = function(txt_part) {
    if(txt_part == " ")
        return AJS.TN(" ");
    var result = AJS.SPAN();

    var is_first = true;
    var is_safari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);

    var part = AJS.SPAN();
    txt_part = GoogieSpell.escapeSepcial(txt_part);
    txt_part = txt_part.replace(/\n/g, "<br>");
    txt_part = txt_part.replace(/    /g, " &nbsp;");
    txt_part = txt_part.replace(/^ /g, "&nbsp;");
    txt_part = txt_part.replace(/ $/g, "&nbsp;");
    
    part.innerHTML = txt_part;

    return part;
}

GoogieSpell.prototype.showErrorsInIframe = function() {
    var output = AJS.DIV();
    output.style.textAlign = "left";
    var pointer = 0;
    var results = this.results;

    if(results.length > 0) {
        for(var i=0; i < results.length; i++) {
            var offset = results[i]['attrs']['o'];
            var len = results[i]['attrs']['l'];
            
            var part_1_text = this.orginal_text.substring(pointer, offset);
            var part_1 = GoogieSpell.createPart(part_1_text);
            output.appendChild(part_1);
            pointer += offset - pointer;
            
            //If the last child was an error, then insert some space
            var err_link = this.createErrorLink(this.orginal_text.substr(offset, len), i);
            this.error_links.push(err_link);
            output.appendChild(err_link);
            pointer += len;
        }
        //Insert the rest of the orginal text
        var part_2_text = this.orginal_text.substr(pointer, this.orginal_text.length);

        var part_2 = GoogieSpell.createPart(part_2_text);
        output.appendChild(part_2);
    }
    else
        output.innerHTML = this.orginal_text;

    var me = this;
    if(this.custom_item_evaulator)
        AJS.map(this.error_links, function(elm){me.custom_item_evaulator(me, elm)});
    
    AJS.ACN(this.edit_layer, output);

    //Hide text area
    this.text_area_bottom = this.text_area.offsetTop + this.text_area.offsetHeight;

    AJS.hideElement(this.text_area);

    AJS.insertBefore(this.edit_layer, this.text_area);

    if(this.use_focus) {
        this.focus_link_t = this.createFocusLink('focus_t');
        this.focus_link_b = this.createFocusLink('focus_b');

        AJS.insertBefore(this.focus_link_t, this.edit_layer);
        AJS.insertAfter(this.focus_link_b, this.edit_layer);
    }

    this.edit_layer.scrollTop = this.ta_scroll_top;
}


//////
// Choose language menu
//////
GoogieSpell.prototype.createLangWindow = function() {
    this.language_window = AJS.DIV({'class': 'googie_window'});
    AJS.setWidth(this.language_window, 100);

    this.language_window.googie_action_btn = "1";

    //Build up the result list
    var table = AJS.TABLE({'class': 'googie_list'});
    AJS.setWidth(table, "100%");
    var list = AJS.TBODY();

    this.lang_elms = new Array();

    for(i=0; i < this.langlist_codes.length; i++) {
        var row = AJS.TR();
        var item = AJS.TD();
        item.googieId = this.langlist_codes[i];
        this.lang_elms.push(item);
        var lang_span = AJS.SPAN();
        lang_span.innerHTML = this.lang_to_word[this.langlist_codes[i]];
        item.appendChild(AJS.TN(lang_span.innerHTML));

        var fn = function(e) {
            var elm = AJS.getEventElm(e);
            this.deHighlightCurSel();

            this.setCurrentLanguage(elm.googieId);

            if(this.lang_state_observer != null) {
                this.lang_state_observer();
            }

            this.highlightCurSel();
            this.hideLangWindow();
            elm.className = "googie_lang_3d_on";
        };
        AJS.AEV(item, "click", AJS.$b(fn, this));

        item.onmouseover = function(e) { 
            var i_it = AJS.getEventElm(e);
            if(i_it.className != "googie_list_selected")
                i_it.className = "googie_list_onhover";
        };
        item.onmouseout = function(e) { 
            var i_it = AJS.getEventElm(e);
            if(i_it.className != "googie_list_selected")
                i_it.className = "googie_list_onout"; 
        };

        row.appendChild(item);
        list.appendChild(row);
    }

    //Close button
    if(this.use_close_btn) {
        list.appendChild(this.createCloseButton(this.hideLangWindow));
    }

    this.highlightCurSel();

    table.appendChild(list);
    this.language_window.appendChild(table);
}

GoogieSpell.prototype.setCurrentLanguage = function(lan_code) {
    GOOGIE_CUR_LANG = lan_code;

    //Set cookie
    var now = new Date();
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
    setCookie('language', lan_code, now);
    
    this.langTag.innerHTML = this.lang_to_word[GOOGIE_CUR_LANG];
   
    var allLinks = AJS.getElementsByTagAndClassName("span", "googie_check_spelling_link");
    var allLinks_len = allLinks.length;
    for (i = 0; i < allLinks_len; i++) {
    	if (allLinks[i].innerHTML != "Check spelling")
	    allLinks[i].innerHTML = this.lang_to_word[GOOGIE_CUR_LANG];
    }
}

GoogieSpell.prototype.isLangWindowShown = function() {
    return this.language_window != null && this.language_window.style.visibility == "visible";
}

GoogieSpell.prototype.hideLangWindow = function() {
    try {
        this.language_window.style.visibility = "hidden";
        this.switch_lan_pic.className = "googie_lang_3d_on";
    }
    catch(e) {}
}

GoogieSpell.prototype.deHighlightCurSel = function() {
    this.lang_cur_elm.className = "googie_list_onout";
}

GoogieSpell.prototype.highlightCurSel = function() {
    if(GOOGIE_CUR_LANG == null)
        GOOGIE_CUR_LANG = GOOGIE_DEFAULT_LANG;
    for(var i=0; i < this.lang_elms.length; i++) {
        if(this.lang_elms[i].googieId == GOOGIE_CUR_LANG) {
            this.lang_elms[i].className = "googie_list_selected";
            this.lang_cur_elm = this.lang_elms[i];
        }
        else {
            this.lang_elms[i].className = "googie_list_onout";
        }
    }
}

GoogieSpell.prototype.showLangWindow = function(elm, ofst_top, ofst_left) {
    if(this.show_menu_observer)
        this.show_menu_observer(this);
    if(!AJS.isDefined(ofst_top))
        ofst_top = 20;
    if(!AJS.isDefined(ofst_left))
        ofst_left = 100;

    this.createLangWindow();
    AJS.getBody().appendChild(this.language_window);

    var abs_pos = AJS.absolutePosition(elm);
    AJS.showElement(this.language_window);
    AJS.setTop(this.language_window, (abs_pos.y+ofst_top));
    AJS.setLeft(this.language_window, (abs_pos.x+ofst_left-this.language_window.offsetWidth));

    this.highlightCurSel();
    this.language_window.style.visibility = "visible";
}

GoogieSpell.prototype.createChangeLangPic = function() {
    this.langTag = AJS.SPAN({'class': 'googie_check_spelling_link'});
    
    
    
      this.langTag.innerHTML = this.lang_to_word[GOOGIE_CUR_LANG];;
      //var img = AJS.IMG({'src': this.img_dir + 'change_lang.gif', 'alt': "Change language"});
      this.langTag.googie_action_btn = "1";
      var switch_lan = AJS.SPAN({'style': 'font-size:11px; padding-left:5px'}, "(in", AJS.A({'class': 'googie_lang_3d_on', 'style': 'padding-left: 4px;'}, this.langTag), ")");
      //switch_lan.style = "font-size:11px;";
        //this.langTag = switch_lan);
        
      var fn = function(e) {
        var elm = AJS.getEventElm(e).parentNode;
        //alert(elm.className);
        
        if(elm.className == "googie_lang_3d_click") {
          elm.className = "googie_lang_3d_on";
          this.hideLangWindow();
          return false;
        }
        else {
            //alert("real show");
          //elm.className = "googie_lang_3d_click";
          this.showLangWindow(switch_lan);
          return false;
        }
      }
    
      //AJS.REV(switch_lan, "click", AJS.$b(fn, this));
      AJS.AEV(switch_lan, "click", AJS.$b(fn, this));
  return switch_lan;
}

GoogieSpell.prototype.createSpellDiv = function() {
    var chk_spell = AJS.SPAN({'class': 'googie_check_spelling_link'});

    chk_spell.innerHTML = this.lang_chck_spell;
    var spell_img = null;
    if(this.show_spell_img)
        spell_img = AJS.IMG({'src': this.img_dir + "spellc.gif"});
    return AJS.SPAN(spell_img, " ", chk_spell);
}


//////
// State functions
/////
GoogieSpell.prototype.flashNoSpellingErrorState = function(on_finish) {
    var no_spell_errors;

    if(on_finish) {
        var fn = function() {
            on_finish();
            this.checkSpellingState();
        };
        no_spell_errors = fn;
    }
    else
        no_spell_errors = this.checkSpellingState;

    this.setStateChanged("no_error_found");

    if(this.main_controller) {
        AJS.hideElement(this.switch_lan_pic);

        var dummy = AJS.IMG({'src': this.img_dir + "blank.gif", 'style': 'height: 10px; width: 1px;'});
        var rsm = AJS.SPAN();
        rsm.innerHTML = this.lang_no_error_found;

        AJS.RCN(this.spell_span, AJS.SPAN(dummy, rsm));

        this.spell_span.className = "googie_check_spelling_ok";
        this.spell_span.style.textDecoration = "none";
        this.spell_span.style.cursor = "default";

        AJS.callLater(AJS.$b(no_spell_errors, this), 1200, [false]);
    }
}

GoogieSpell.prototype.resumeEditingState = function() {
    this.setStateChanged("resume_editing");

    //Change link text to resume
    if(this.main_controller) {
        AJS.hideElement(this.switch_lan_pic);
        var dummy = AJS.IMG({'src': this.img_dir + "blank.gif", 'style': 'height: 10px; width: 1px;'});
        var rsm = AJS.SPAN();
        rsm.innerHTML = this.lang_rsm_edt;
        AJS.RCN(this.spell_span, AJS.SPAN(dummy, rsm));
    
        var fn = function(e) {
            this.resumeEditing();
        }
        this.spell_span.onclick = AJS.$b(fn, this);

        this.spell_span.className = "googie_resume_editing";
    }

    try { this.edit_layer.scrollTop = this.ta_scroll_top; }
    catch(e) { }
}

GoogieSpell.prototype.checkSpellingState = function(fire) {
    if(!AJS.isDefined(fire) || fire)
        this.setStateChanged("spell_check");

    if(this.show_change_lang_pic)
        this.switch_lan_pic = this.createChangeLangPic();
    else
        this.switch_lan_pic = AJS.SPAN();

    var span_chck = this.createSpellDiv();
    var fn = function() {
        this.spellCheck();
    };

    if(this.custom_spellcheck_starter)
        span_chck.onclick = this.custom_spellcheck_starter;
    else {
        span_chck.onclick = AJS.$b(fn, this);
    }

    this.spell_span = span_chck;
    if(this.main_controller) {
        if(this.change_lang_pic_placement == "left")
            AJS.RCN(this.spell_container, span_chck, " ", this.switch_lan_pic);
        else
            AJS.RCN(this.spell_container, this.switch_lan_pic, " ", span_chck);
    }
}


//////
// Misc. functions
/////
GoogieSpell.item_onmouseover = function(e) {
    var elm = AJS.getEventElm(e);
    if(elm.className != "googie_list_revert" && elm.className != "googie_list_close")
        elm.className = "googie_list_onhover";
    else
        elm.parentNode.className = "googie_list_onhover";
}
GoogieSpell.item_onmouseout = function(e) {
    var elm = AJS.getEventElm(e);
    if(elm.className != "googie_list_revert" && elm.className != "googie_list_close")
        elm.className = "googie_list_onout";
    else
        elm.parentNode.className = "googie_list_onout";
}

GoogieSpell.prototype.createCloseButton = function(c_fn) {
    return this.createButton(this.lang_close, 'googie_list_close', AJS.$b(c_fn, this));
}

GoogieSpell.prototype.createButton = function(name, css_class, c_fn) {
    var btn_row = AJS.TR();
    var btn = AJS.TD();

    btn.onmouseover = GoogieSpell.item_onmouseover;
    btn.onmouseout = GoogieSpell.item_onmouseout;

    var spn_btn;
    if(css_class != "") {
        spn_btn = AJS.SPAN({'class': css_class});
        spn_btn.innerHTML = name;
    }
    else {
        spn_btn = AJS.TN(name);
    }
    btn.appendChild(spn_btn);
    AJS.AEV(btn, "click", c_fn);
    btn_row.appendChild(btn);

    return btn_row;
}

GoogieSpell.prototype.removeIndicator = function(elm) {
    try { AJS.removeElement(this.indicator); }
    catch(e) {}
}

GoogieSpell.prototype.appendIndicator = function(elm) {
    var img = AJS.IMG({'src': this.img_dir + 'indicator.gif', 'style': 'margin-right: 5px;'});
    AJS.setWidth(img, 10);
    AJS.setHeight(img, 10);
    this.indicator = img;
    img.style.textDecoration = "none";
    try {
        AJS.insertBefore(img, elm);
    }
    catch(e) {}
}

GoogieSpell.prototype.createFocusLink = function(name) {
    return AJS.A({'href': 'javascript:;', name: name});
}


//end googiespell.js





//begin QuestionBuilder

var checks = new Array();
   
function setupCheckboxes()
{
	var inputs = document.getElementsByTagName("input");
	var icount = inputs.length;
	var i, check, ccount;
	
	for(i = 0; i < icount; i++)
	{
		if(inputs[i].type == "checkbox")
		{
			checks[checks.length] = inputs[i];
		}
	}
	
    ccount = checks.length;
	for(i = 0; i < ccount; i++)
	{
		check = checks[i];
		if(check.id.indexOf("Checkbox") > -1)
		{	// we only want to do this for checkboxes that
			// don't already have an onclick handler...
			if(!check.onclick)
			{
				check.onclick = ToggleCheckbox;
			}
		}
	}
}



        
function ToggleCheckbox(e)
{
	e = (e) ? e : window.event;

	var target = (e.target) ? e.target : e.srcElement;
	
	var newid = target.id.replace("Checkbox", "Required");
	var required = document.getElementById(newid);
	
	if(target.checked)
	{
		required.disabled = false;
	}
	else
	{
		required.checked = false;
		required.disabled = true;
	}
}

//end QuestionBuilder




//begin SurveyEditor

		function themeListChange(themeList, page)
        {
            var themeID = themeList.options[themeList.selectedIndex].value;
			//--look for the same theme and do change if different            
			if (document.getElementById("SurveyTheme").href.indexOf(themeID+".css") <= 0)
            {
                if (page == "Page")
                {
                MySurvey_EditorPage.themeList_changed(themeID, document.URL, themeListChange_callBack);  // asynchronous call
                }
                else if (page == "Full")
                {
                MySurvey_EditorFull.themeList_changed(themeID, document.URL, themeListChange_callBack);  // asynchronous call
                
                }
			}
        }


        function themeListChange_callBack(res)
        {
                
            //setActiveStyleSheet("SurveyTheme_" + res.value.ThemeID);
            var buttonColor = res.value.SurveyBackgroundColor;
            var buttonLabelColor = res.value.MatrixAltRowColor;
            

			//--assign link with new ThemeID for page display of new theme;
            document.getElementById("SurveyTheme").href = "_Themes/" + res.value.ThemeID+".css";
 
            
            buttonRowColor = res.value.SurveyBackgroundColor;
            buttonAltRowColor = res.value.MatrixAltRowColor;
			changeThemeButtons();

           var _questionHeaderSize = res.value.QuestionHeaderSize;
            var _requiredAsteriskSize = 0;
             switch (_questionHeaderSize)
            {
                case "xx-small":
                    _requiredAsteriskSize = 11;
                    break;
                case "x-small":
                case "small":
                    _requiredAsteriskSize = 12;
                    break;
                case "medium":
                case "large":
                    _requiredAsteriskSize = 15;
                    break;
            }
            eraseButtons(res.value.SurveyBackgroundColor, res.value.MatrixAltRowColor, _requiredAsteriskSize, res.value.RequiredAsteriskColor);  
        }
        
        function setActiveStyleSheet(title) {
          var i, a, main;
          for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
            if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
              a.disabled = true;
              if(a.getAttribute("title") == title) a.disabled = false;
            }
          }
        }
        
        function eraseButtons(newColor, newColorAlt, asteriskSize, asteriskColor)
        {

            var pageDiv = document.getElementById("PageContentDiv");
            var buttonItems = pageDiv.getElementsByTagName("IMG");
                     
            var buttonItemsLen = buttonItems.length;
            for (i=0; i<buttonItemsLen; i++)
            {
                var buttonItem = buttonItems[i];
                //alert(buttonItem.src);
                if (buttonItem.src.indexOf("Buttons/") > 0 && buttonItem.src.indexOf("Asterisk") <= 0)
                {
                    //alert("changed button");
                    buttonItem.src = "img/t.gif";
                }
                else if (buttonItem.src.indexOf("Asterisk") > 0)
                {
                    //alert("changed button");
                    buttonItem.src = "_ThemeBtn/Asterisk_" + asteriskSize + "_" + newColor + "_" + asteriskColor + ".gif";
                }
            }
            
            var inputItems = pageDiv.getElementsByTagName("INPUT");
                     
            var inputItemsLen = inputItems.length;
            for (i=0; i<inputItemsLen; i++)
            {
                var inputItem = inputItems[i];
                if (inputItem.id.indexOf("input_") >= 0)
                    inputItem.value = "";
            }
        }
        
        function changeThemeButtons()
        {
            var themeList = document.getElementById("ThemeList");
            if (themeList.options[themeList.selectedIndex].value < 100)
            {
                document.getElementById("ThemeEditButton").style.display = "none";
            }
            else
            {
                document.getElementById("ThemeEditButton").style.display = "inline";
            }
            
            
        }
    
    function initQuestionCopy(encSID, encQID)
    {
        if ($("a[@btnType=AddPageBtn]").attr("class").indexOf("TextBtnOrange") >= 0)
            cancelPageCopy(encSID);
            
        $("a[@btnType=AddQuestionBtn]").attr("class", "TextBtnOrange").html("&nbsp;Paste Question Here&nbsp;").unbind("click").click( function() { copyQuestion(this, this.href); return false; } );
        $("a[@btnType=CancelCopyBtn]").css("display", "inline").html("&nbsp;Cancel Copy&nbsp;");

        createCookie(encSID + "_CopyMode", encQID);
    }
    
    function initPageCopy(encSID, encSectionID)
    {
        //alert($("a[@btnType=AddQuestionBtn]").attr("class"))
        if ($("a[@btnType=AddQuestionBtn]").attr("class").indexOf("TextBtnOrange") >= 0)
            cancelQuestionCopy(encSID);
            
        $("a[@btnType=AddPageBtn]").attr("class", "TextBtnOrange").html("&nbsp;Paste Page Here&nbsp;").unbind("click").click( function() { copyPage(this, this.href); return false; } );
        $("a[@btnType=CancelCopyPageBtn]").css("display", "inline").html("&nbsp;Cancel Copy&nbsp;");

        createCookie(encSID + "_PageCopyMode", encSectionID);
    }
    
    function reInitQuestionCopy()
    {
        $("a[@btnType=AddQuestionBtn]").unbind("click").click( function() { copyQuestion(this, this.href); return false; } );
        
    }
    
    function reInitPageCopy()
    {
        $("a[@btnType=AddPageBtn]").unbind("click").click( function() { copyPage(this, this.href); return false; } );
        
    }
    
    function reInitQuestionMove()
    {
        $("a[@btnType=AddQuestionBtn]").unbind("click").click( function() { moveQuestion(this, this.href); return false; } );
        
    }
    
    function reInitPageMove()
    {
        $("a[@btnType=AddPageBtn]").unbind("click").click( function() { movePage(this, this.href); return false; } );
        
    }
    
    function reInitQuestionRestore(encSID, encQID)
    {
        $("a[@btnType=AddQuestionBtn]").unbind("click").click( function() { restoreQuestion(this, this.href); return false; } );
    }
    
    function initQuestionMove(encSID, encQID)
    {
        $("a[@btnType=AddQuestionBtn]").attr("class", "TextBtnOrange").html("&nbsp;Move Question Here&nbsp;").unbind("click").click( function() { moveQuestion(this, this.href); return false; } );
        $("a[@btnType=CancelCopyBtn]").css("display", "inline").html("&nbsp;Cancel Move&nbsp;");

        createCookie(encSID + "_MoveMode", encQID);
    }
    
    function initPageMove(encSID, encSectionID)
    {
        //alert($("a[@btnType=AddQuestionBtn]").attr("class"))
        if ($("a[@btnType=AddQuestionBtn]").attr("class").indexOf("TextBtnOrange") >= 0)
            cancelQuestionCopy(encSID);
            
        $("a[@btnType=AddPageBtn]").attr("class", "TextBtnOrange").html("&nbsp;Move Page Here&nbsp;").unbind("click").click( function() { movePage(this, this.href); return false; } );
        $("a[@btnType=CancelCopyPageBtn]").css("display", "inline").html("&nbsp;Cancel Move&nbsp;");

        createCookie(encSID + "_PageMoveMode", encSectionID);
    }
    
    function initQuestionRestore(encSID, encQID, redirectURL)
    {
        createCookie(encSID + "_RestoreMode", encQID);
        //alert("MySurvey_EditorPage.aspx?sm=" + redirectURL);
        window.location.href = "MySurvey_EditorPage.aspx?sm=" + redirectURL;
    }
    
    function cancelQuestionCopy(encSID)
    {
        $("a[@btnType=AddQuestionBtn]").unbind("click").attr("class", "TextBtn thickbox").html("&nbsp;Add Question Here&nbsp;");
        $("a[@btnType=CancelCopyBtn]").css("display", "none");
        
        eraseCookie(encSID + "_CopyMode");
        eraseCookie(encSID + "_MoveMode");
        eraseCookie(encSID + "_RestoreMode");
        TB_init(); 
        
    }
    
    function cancelPageCopy(encSID)
    {
        $("a[@btnType=AddPageBtn]").unbind("click").attr("class", "TextBtn thickbox").html("&nbsp;Add Page Here&nbsp;");
        $("a[@btnType=CancelCopyPageBtn]").css("display", "none");
        
        eraseCookie(encSID + "_PageCopyMode");
        eraseCookie(encSID + "_PageMoveMode");
        TB_init(); 
        
    }
    
// end SurveyEditor


// begin Survey.js

function getRuledClass(tdNode, isOn, isMatrix)
{
    var ruledClass = 'ruled';
    if (isMatrix){
		ruledClass += 'Matrix';}
    if (tdNode.getElementsByTagName('img')[0].className.indexOf('Alt') > 0){
        ruledClass += 'Alt';}
    return ruledClass;
}

function EraseForcedRanking(QID, OptionID, i) {
if (eval('fr_' + QID)[i] != null && eval('fr_' + QID)[i] != '')
		if (eval('fr_' + QID)[i].split('_')[1] == OptionID) eval('fr_' + QID)[i] = null;
}

function Ranking_unselectRow(qType, containerID, radioItems, selectedRow, selectedCol)
{
    var radioItemsLen = radioItems.length;
    for (i=0; i<radioItemsLen; i++)
    {
        var radioItem = radioItems[i];
		var ItemID =  radioItem.id;
        if ((ItemID.indexOf("R" + selectedRow + "_") > 0) && (ItemID.indexOf("C" + selectedCol + "_") < 0))
		{ 
		radioItem.className = RB_Style(radioItem.className, false);
		}
    }
}

function Ranking_unselectCol(qType, containerID, radioItems, selectedRow, selectedCol)
{
    var radioItemsLen = radioItems.length;
    for (i=0; i<radioItemsLen; i++)
    {
        var radioItem = radioItems[i];
		var ItemID =  radioItem.id;
		//if radioItem is on the same col, but not the same row, then unselect it.    
		if ((ItemID.indexOf("R" + selectedRow + "_") < 0) && (ItemID.indexOf("C" + selectedCol + "_") >= 0))
		{ 
            radioItem.className = RB_Style(radioItem.className, false); 
			var startIndex = ItemID.indexOf("R");
            var endIndex = ItemID.indexOf("_", startIndex);
            var newRow = ItemID.substr((startIndex + 1), (endIndex-startIndex-1));
            var newCheckedInput = document.getElementById("input_" + containerID + "_" + qType + "_" + newRow + "_0");
            //if the other row has the same column selected, then erase it.
			if (newCheckedInput.value == selectedCol)
			{ 
                newCheckedInput.value = "";
			}
        }
    }
}

function Ranking_click(groupID, qType, containerID, isNA)
{
    var radioDiv = document.getElementById("Radio_" + containerID);
    var radioItems = radioDiv.getElementsByTagName("IMG");
    var rowID = groupID.split('_')[0];
    var colID = groupID.split('_')[1];
    var selectedInputList = "";
    var clearedInputList = "";
    var checkedInput = document.getElementById("input_" + containerID + "_" + qType + "_" + rowID + "_0");
    
    var radioItemsLen = radioItems.length;
    for (i=0; i<radioItemsLen; i++)
    {
        var radioItem = radioItems[i];
        var ItemID =  radioItem.id;
        if (ItemID.indexOf("R" + rowID + "_") > 0 && ItemID.indexOf("C" + colID + "_") > 0)
        {
            if (radioItem.src.indexOf("RadioOff") >= 0 || (radioItem.src.indexOf("t.gif") >= 0 && radioItem.className.indexOf("RadioOff") >= 0))
            {
                checkedInput.value = colID;
				radioItem.className = RB_Style(radioItem.className, true);     
	            Ranking_unselectRow(qType, containerID, radioItems, rowID, colID);
	            if (isNA == false)
                    Ranking_unselectCol(qType, containerID, radioItems, rowID, colID);
            }
            else
            {
				checkedInput.value = "";
				radioItem.className = RB_Style(radioItem.className, false);    
			}
        }
    }
}

function RB_Style(rbClassName, isOn)
{
	var BtnClass='RadioOff';
	if(isOn){BtnClass='RadioOn';}
	if(rbClassName.indexOf('Alt') > 0){BtnClass+= "Alt";}   
	return BtnClass; 
}

function RB_click(groupID, selectedID, qType, QID, ignoreDoubleClick)
{
    var optionID = selectedID.split('_')[0];
    var radioDiv = document.getElementById("Radio_" + groupID);
    var radioItems = radioDiv.getElementsByTagName("IMG");
    var checkedInput = null;
    
	if (QID != null)
		//--Non matrix
        checkedInput = document.getElementById("input_" + QID + "_" + qType + "_" + groupID + "_0");
    else
        checkedInput = document.getElementById("input_" + groupID + "_" + qType + "_0_0");
                
	//--hard reset of input	 value
	checkedInput.value='';

	var radioItemsLen = radioItems.length;
	for (i=0; i<radioItemsLen; i++)
	{
		var radioItem = radioItems[i];
		var ItemID =  radioItem.id;
		var curOn =	 (radioItem.className.indexOf("On") > 0);
		if (curOn)
		{	//--deselect
		    if (ignoreDoubleClick != true || i+1 < radioItemsLen)
			    radioItem.className = RB_Style(radioItem.className, false);
			else
			    checkedInput.value = selectedID;
     
		}
		else if (ItemID.indexOf(optionID)>= 0)
		{
			//assign selected
			checkedInput.value = selectedID;
			radioItem.className = RB_Style(radioItem.className, true);     
		}
	}
}


function CB_Style(cbClassName, isOn)
{
	var BtnClass='CheckboxOff';	 
	if(isOn){BtnClass='CheckboxOn';}
	if(cbClassName.indexOf('Alt') > 0){BtnClass+= "Alt";} 
	return BtnClass; 
}

//--keepOn used for comment feild as checkbox item!!!!
function CB_click(groupID, selectedID, qType, QID, ForceChk, columnID)
{
    var optionID = selectedID.split('_')[0];
    var radioDiv = document.getElementById("Checkbox_" + groupID);
    var radioItems = radioDiv.getElementsByTagName("IMG");
    var checkedInput = null;
	
	if (columnID == null){columnID = 0}
    
	if (QID != null)
		//--Non matrix
        checkedInput = document.getElementById("input_" + QID + "_" + qType + "_" + groupID + "_" + columnID);
    else
        checkedInput = document.getElementById("input_" + groupID + "_" + qType + "_" + optionID + "_" + columnID);

    var radioItemsLen = radioItems.length;
    for (i=0; i<radioItemsLen; i++)
    {
        var radioItem = radioItems[i];
        if (radioItem.id.indexOf(optionID) > 0)
		{
			var curOn =	 (radioItem.className.indexOf("On") > 0);

			//--forcecheck (used on checkbox comment)
			if(ForceChk){
					if (checkedInput != null){checkedInput.value = selectedID;}         
					radioItem.className = CB_Style(radioItem.className, true);
					radioItem.buttonState = "On";
			}		
			else
			{
				if (curOn)
				{
				if (checkedInput != null){checkedInput.value = "";}
				radioItem.className = CB_Style(radioItem.className, false); 
				radioItem.buttonState = "Off";
				}
				else
				{	
					if (checkedInput != null){checkedInput.value = selectedID;}         
					radioItem.className = CB_Style(radioItem.className, true);
					radioItem.buttonState = "On";
				}
			}
		}
    }
}

function tableruler()
{
    if (document.getElementById && document.createTextNode)
    {
        var tables=document.getElementsByTagName('TABLE');
        for (var i=0;i<tables.length;i++)
        {
            if (tables[i].className.indexOf('rulermatrix') >= 0)
            {
                var tds=tables[i].getElementsByTagName('td');
                for(var j=0;j<tds.length;j++)
                {
                    var tdNode = tds[j];
                    if (tdNode.getElementsByTagName('img').length > 0)
                    {
                        tdNode.className = 'ruledcell';
                        //tdNode.onmouseover=function(){if (onButton==false) { this.className=getRuledClass(this, true, true); } return false}
                        //tdNode.onmouseout=function(){if (onButton==false) { this.className=getRuledClass(this, false, true); } return false} 
                        //tdNode.getElementsByTagName('img')[0].onmouseover=function(){onButton = true; alert(onButton); return false}
                        //tdNode.getElementsByTagName('img')[0].onmouseout=function(){onButton = false; alert(onButton); return false}
                    }
                }
            }
            else if (tables[i].className.indexOf('ruler') >= 0)
            {
                var trs=tables[i].getElementsByTagName('tr');
                for(var j=0;j<trs.length;j++)
                {
                    var rowNode = trs[j];
                    if (rowNode.getElementsByTagName('img').length > 0)
                    {
                        rowNode.onmouseover=function(){this.getElementsByTagName('td')[1].className='ruled'; return false};
                        rowNode.onmouseout=function(){this.getElementsByTagName('td')[1].className=''; return false};
                    }
                }
            }
        }
    }
}

// end Survey.js


//duplicate check

function onesubmit(element, delay)
{
	// This function takes an element (typically a submit button) and effectively
	// disables it immediately upon clicking so that duplicate submissions are not
	// sent to the server when users get a little click-happy.  The element is then
	// reset back to its original state after a delay of time (defaults to 1.5
	// seconds) so that users can use the buttons if they click Back in the browser.
	var tagname = element.tagName.toLowerCase();
	
	delay = (delay) ? delay : 1500;
	
	if(tagname == "a")
	{
		var href = element.href;
		var click = element.onclick;
		
		setTimeout(function() { element.href = "javascript:void(0);"; element.onclick = null; }, 0);
		setTimeout(function() { element.href = href; element.onclick = click; }, delay);
	}
	else if(tagname == "input")
	{
		var click = element.onclick;
		
		setTimeout(function() { element.disabled = true; element.onclick = null; }, 0);
		setTimeout(function() { element.disabled = false; element.onclick = click; }, delay);
	}
}
