(function(){
/*
 * jQuery 1.1.4 - 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-08-23 21:49:27 -0400 (Thu, 23 Aug 2007) $
 * $Rev: 2862 $
 */
// Map over jQuery in case of overwrite
if ( typeof jQuery != "undefined" )
	var _jQuery = jQuery;

var jQuery = window.jQuery = function(a,c) {
	// If the context is global, return a new object
	if ( window == this || !this.init )
		return new jQuery(a,c);
	
	return this.init(a,c);
};

// Map over the $ in case of overwrite
if ( typeof $ != "undefined" )
	var _$ = $;
	
// Map the jQuery namespace to the '$' one
window.$ = jQuery;

var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;

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

		// Handle HTML strings
		if ( typeof a  == "string" ) {
			var m = quickExpr.exec(a);
			if ( m && (m[1] || !c) ) {
				// HANDLE: jQuery(html) -> jQuery(array)
				if ( m[1] )
					a = jQuery.clean( [ m[1] ] );

				// HANDLE: jQuery("#id")
				else {
					var tmp = document.getElementById( m[3] );
					if ( tmp )
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( tmp.id != m[3] )
							return jQuery().find( a );
						else {
							this[0] = tmp;
							this.length = 1;
							return this;
						}
					else
						a = [];
				}

			// HANDLE: jQuery(expr)
			} else
				return new jQuery( c ).find( a );

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

		return this.setArray(
			// HANDLE: jQuery(array)
			a.constructor == Array && a ||

			// HANDLE: jQuery(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: jQuery(*)
			[ a ] );
	},
	jquery: "1.1.4",

	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;
		Array.prototype.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 != "object" && e != null )
			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, args = arguments;

		// Wrap each of the matched elements individually
		return this.each(function(){
			if ( !a )
				a = jQuery.clean(args, this.ownerDocument);

			// 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([]);
	},
	// IE6 throws an exception in combination with 'Slider' from the plugin 'Interface'
	/*find: function(t) {
		var data = jQuery.map(this, function(a){ return jQuery.find(t,a); });
		return this.pushStack( /[^+>] [^+>]/.test( t ) || t.indexOf("..") > -1 ?
			jQuery.unique( data ) : data );
	},*/
	find: function(t) {
		return this.pushStack( jQuery.map( this, function(a){
			return jQuery.find(t,a);
		}), t );
	},
	clone: function(deep) {
		deep = deep != undefined ? deep : true;
		var $this = this.add(this.find("*"));
		if (jQuery.browser.msie) {
			// Need to remove events on the element and its descendants
			$this.each(function() {
				this._$events = {};
				for (var type in this.$events)
					this._$events[type] = jQuery.extend({},this.$events[type]);
			}).unbind();
		}

		// Do the clone
		var r = this.pushStack( jQuery.map( this, function(a){
			return a.cloneNode( deep );
		}) );

		if (jQuery.browser.msie) {
			$this.each(function() {
				// Add the events back to the original and its descendants
				var events = this._$events;
				for (var type in events)
					for (var handler in events[type])
						jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
				this._$events = null;
			});
		}

		// copy form values over
		if (deep) {
			var inputs = r.add(r.find('*')).filter('select,input[@type=checkbox]');
			$this.filter('select,input[@type=checkbox]').each(function(i) {
				if (this.selectedIndex)
					inputs[i].selectedIndex = this.selectedIndex;
				if (this.checked)
					inputs[i].checked = true;
			});
		}

		// Return the cloned set
		return r;
	},

	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.multiFilter(expr,this).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 );
	},

	slice: function() {
		return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
	},
	domManip: function(args, table, dir, fn){
		var clone = this.length > 1, a; 

		return this.each(function(){
			if ( !a ) {
				a = jQuery.clean(args, this.ownerDocument);
				if ( dir < 0 )
					a.reverse();
			}

			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(){
				if ( jQuery.nodeName(this, "script") ) {
					if ( this.src )
						jQuery.ajax({ url: this.src, async: false, dataType: "script" });
					else
						jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
				} else
					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, al = arguments.length, deep = false;

	// Handle a deep copy situation
	if ( target.constructor == Boolean ) {
		deep = target;
		target = arguments[1] || {};
	}

	// extend jQuery itself if only one argument is passed
	if ( al == 1 ) {
		target = this;
		a = 0;
	}

	var prop;

	for ( ; a < al; a++ )
		// Only deal with non-null/undefined values
		if ( (prop = arguments[a]) != null )
			// Extend the base object
			for ( var i in prop ) {
				// Prevent never-ending loop
				if ( target == prop[i] )
					continue;

				// Recurse if we're merging object values
				if ( deep && typeof prop[i] == 'object' && target[i] )
					jQuery.extend( target[i], prop[i] );

				// Don't bring in undefined values
				else if ( prop[i] != undefined )
					target[i] = prop[i];
			}

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function(deep) {
		window.$ = _$;
		if ( deep )
			window.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 && 
			fn.constructor != Array && /function/i.test( fn + "" );
	},
	
	// check if an element is in a XML document
	isXMLDoc: function(elem) {
		return elem.documentElement && !elem.body ||
			elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
	},

	// Evalulates a script in a global context
	// Evaluates Async. in Safari 2 :-(
	globalEval: function( data ) {
		data = jQuery.trim( data );
		if ( 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 );
		}
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
	},
	// args is for internal usage only
	each: function( obj, fn, args ) {
		if ( args ) {
			if ( obj.length == undefined )
				for ( var i in obj )
					fn.apply( obj[i], args );
			else
				for ( var i = 0, ol = obj.length; i < ol; i++ )
					if ( fn.apply( obj[i], args ) === false ) break;

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

		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 != undefined ?
				jQuery.grep( elem.className.split(/\s+/), function(cur){
					return !jQuery.className.has( c, cur );	
				}).join(" ") : "";
		},

		// internal only, use is(".class")
		has: function( t, c ) {
			return jQuery.inArray( c, (t.className || t).toString().split(/\s+/) ) > -1;
		}
	},
	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(e).is(':visible') ) {
					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") || "static";
					if ( parPos == "static" )
						e.parentNode.style.position = "relative";

					oHeight = e.clientHeight;
					oWidth = e.clientWidth;

					if ( 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, stack = [], swap = [];

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

			var ret = document.defaultView.getComputedStyle(a,null);
			return !ret || ret.getPropertyValue("color") == "";
		}

		if (prop == "opacity" && jQuery.browser.msie) {
			ret = jQuery.attr(elem.style, "opacity");
			return ret == "" ? "1" : ret;
		}
		
		if (prop.match(/float/i))
			prop = styleFloat;

		if (!force && elem.style[prop])
			ret = elem.style[prop];

		else if (document.defaultView && document.defaultView.getComputedStyle) {

			if (prop.match(/float/i))
				prop = "float";

			prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase();
			var cur = document.defaultView.getComputedStyle(elem, null);

			if ( cur && !color(elem) )
				ret = cur.getPropertyValue(prop);

			// If the element isn't reporting its values properly in Safari
			// then some display: none elements are involved
			else {
				// Locate all of the parent display: none elements
				for ( var a = elem; a && color(a); a = a.parentNode )
					stack.unshift(a);

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

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

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

			if ( prop == "opacity" && ret == "" )
				ret = "1";

		} 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, doc) {
		var r = [];
		doc = doc || document;

		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).toLowerCase(), div = doc.createElement("div"), tb = [];

				var wrap =
					// option or optgroup
					!s.indexOf("<opt") &&
					[1, "<select>", "</select>"] ||
					
					!s.indexOf("<leg") &&
					[1, "<fieldset>", "</fieldset>"] ||
					
					s.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
					[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>"] ||
					
					!s.indexOf("<col") &&
					[2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"] ||

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

				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + arg + wrap[2];
				
				// Move to the right depth
				while ( wrap[0]-- )
					div = div.lastChild;
				
				// Remove IE's autoinserted <tbody> from table fragments
				if ( jQuery.browser.msie ) {
					
					// String was a <table>, *may* have spurious <tbody>
					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]);
	
					// IE completely kills leading whitespace when innerHTML is used	
					if ( /^\s/.test(arg) )	
						div.insertBefore( doc.createTextNode( arg.match(/^\s*/)[0] ), div.firstChild );

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

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

			if ( arg[0] == undefined || jQuery.nodeName(arg, "form") || arg.options )
				r.push( arg );
			else
				r = jQuery.merge( r, arg );

		});

		return r;
	},
	
	attr: function(elem, name, value){
		var fix = jQuery.isXMLDoc(elem) ? {} : jQuery.props;

		// Safari mis-reports the default selected property of a hidden option
		// Accessing the parent's selectedIndex property fixes it
		if ( name == "selected" && jQuery.browser.safari )
			elem.parentNode.selectedIndex;
		
		// 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 ( jQuery.browser.msie && name == "style" )
			return jQuery.attr( elem.style, "cssText", value );

		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 {
			// IE actually uses filters for opacity
			if ( name == "opacity" && jQuery.browser.msie ) {
				if ( 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
					elem.filter = (elem.filter || "").replace(/alpha\([^)]*\)/,"") +
						(parseFloat(value).toString() == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
				}
	
				return elem.filter ? 
					(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100).toString() : "";
			}
			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 = [];

		// Need to use typeof to fight Safari childNodes crashes
		if ( typeof a != "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) {
		// We have to loop this way because IE & Opera overwrite the length
		// expando of getElementsByTagName

		// Also, we need to make sure that the correct elements are being returned
		// (IE returns comment nodes in a '*' query)
		if ( jQuery.browser.msie ) {
			for ( var i = 0; second[i]; i++ )
				if ( second[i].nodeType != 8 )
					first.push(second[i]);
		} else
			for ( var i = 0; second[i]; i++ )
				first.push(second[i]);

		return first;
	},
	unique: function(first) {
		var r = [], num = jQuery.mergeNum++;

		try {
			for ( var i = 0, fl = first.length; i < fl; i++ )
				if ( num != first[i].mergeNum ) {
					first[i].mergeNum = num;
					r.push(first[i]);
				}
		} catch(e) {
			r = first;
		}

		return r;
	},

	mergeNum: 0,
	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 = eval("false||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 = eval("false||function(a){return " + fn + "}");

		var result = [];

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

		return result;
	}
});
 
/*
 * Whether the W3C compliant box model is being used.
 *
 * @property
 * @name $.boxModel
 * @type Boolean
 * @cat JavaScript
 */
var userAgent = navigator.userAgent.toLowerCase();

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

var styleFloat = jQuery.browser.msie ? "styleFloat" : "cssFloat";
	
jQuery.extend({
	// Check to see if the W3C box model is being used
	boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",
	
	styleFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat",
	
	props: {
		"for": "htmlFor",
		"class": "className",
		"float": styleFloat,
		cssFloat: styleFloat,
		styleFloat: styleFloat,
		innerHTML: "innerHTML",
		className: "className",
		value: "value",
		disabled: "disabled",
		checked: "checked",
		readonly: "readOnly",
		selected: "selected",
		maxlength: "maxLength"
	}
});

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( jQuery.unique(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 );
	};
});

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

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

jQuery.extend({
	expr: {
		"": "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
			"first-child": "a.parentNode.getElementsByTagName('*')[0]==a",
			"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
			"only-child": "!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",

			// Parent Checks
			parent: "a.firstChild",
			empty: "!a.firstChild",

			// Text Check
			contains: "(a.textContent||a.innerText||'').indexOf(m[3])>=0",

			// Visibility
			visible: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
			hidden: '"hidden"==a.type||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: "'text'==a.type",
			radio: "'radio'==a.type",
			checkbox: "'checkbox'==a.type",
			file: "'file'==a.type",
			password: "'password'==a.type",
			submit: "'submit'==a.type",
			image: "'image'==a.type",
			reset: "'reset'==a.type",
			button: '"button"==a.type||jQuery.nodeName(a,"button")',
			input: "/input|select|textarea|button/i.test(a.nodeName)",

			// :has()
			has: "jQuery.find(m[3],a).length"
		},
		// DEPRECATED
		"[": "jQuery.find(m[2],a).length"
	},
	
	// The regular expressions that power the parsing engine
	parse: [
		// Match: [@value='test'], [@foo]
		/^\[ *(@)([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,

		// DEPRECATED
		// Match: [div], [div p]
		/^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,

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

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

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

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

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

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

		// DEPRECATED
		// Handle the common XPath // expression
		if ( !t.indexOf("//") ) {
			//context = context.documentElement;
			t = t.substr(2,t.length);

		// DEPRECATED
		// And the / root expression
		} else if ( !t.indexOf("/") && !context.ownerDocument ) {
			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;

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

			// DEPRECATED
			t = jQuery.trim(t).replace( /^\/\//, "" );

			var foundToken = false;

			// An attempt at speeding up child selectors that
			// point to a specific element tag
			var re = quickChild;
			var m = re.exec(t);

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

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

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

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

					var nodeName = m[4], mergeNum = jQuery.mergeNum++;
					m = m[1];

					for ( var j = 0, rl = ret.length; j < rl; j++ )
						if ( m.indexOf("..") < 0 ) {
							var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
							for ( ; n; n = n.nextSibling )
								if ( n.nodeType == 1 ) {
									if ( m == "~" && n.mergeNum == mergeNum ) break;
									
									if (!nodeName || n.nodeName.toUpperCase() == nodeName.toUpperCase() ) {
										if ( m == "~" ) n.mergeNum = mergeNum;
										r.push( n );
									}
									
									if ( m == "+" ) break;
								}
						// DEPRECATED
						} else
							r.push( ret[j].parentNode );

					ret = r;

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

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

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

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

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

				} else {
					// Optimize for the case nodeName#idName
					var re2 = quickID;
					var m = re2.exec(t);
					
					// Re-organize the results, so that they're consistent
					if ( m ) {
					   m = [ 0, m[2], m[3], m[1] ];

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

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

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

					// Try to do a global search by ID, where we can
					if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
						// Optimization for HTML document case
						var oid = elem.getElementById(m[2]);
						
						// Do a quick check for the existence of the actual ID attribute
						// to avoid selecting by the name attribute in IE
						// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
						if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
							oid = jQuery('[@id="'+m[2]+'"]', elem)[0];

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

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

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

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

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

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

							r = tmp;
						}

						ret = r;
					}

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

			}

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

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

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

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

		return done;
	},

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

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

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

			var p = jQuery.parse, m;

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

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

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

			if ( !m )
				break;

			// :not() is a special case that can be optimized by
			// keeping it out of the expression list
			if ( m[1] == ":" && m[2] == "not" )
				r = jQuery.filter(m[3], r, true).r;

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

			else if ( m[1] == "@" ) {
				var tmp = [], type = m[3];
				
				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
					
					if ( z == null || /href|src|selected/.test(m[2]) )
						z = jQuery.attr(a,m[2]) || '';

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

			// We can get a speed boost by handling nth-child here
			} else if ( m[1] == ":" && m[2] == "nth-child" ) {
				var num = jQuery.mergeNum++, tmp = [],
					test = /(\d*)n\+?(\d*)/.exec(
						m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
						!/\D/.test(m[3]) && "n+" + m[3] || m[3]),
					first = (test[1] || 1) - 0, last = test[2] - 0;

				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var node = r[i], parentNode = node.parentNode;

					if ( num != parentNode.mergeNum ) {
						var c = 1;

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

						parentNode.mergeNum = num;
					}

					var add = false;

					if ( first == 1 ) {
						if ( last == 0 || node.nodeIndex == last )
							add = true;
					} else if ( (node.nodeIndex + last) % first == 0 )
						add = true;

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

				r = tmp;

			// 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
				f = eval("false||function(a,i){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 };
	},
	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 == result )
				break;

		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;
		
		// Make sure that the function being executed has a unique ID
		if ( !handler.guid )
			handler.guid = this.guid++;
			
		// if data is passed, bind to handler 
		if( data != undefined ) { 
        	// Create temporary function pointer to original handler 
			var fn = handler; 

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

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

			// Set the guid of unique handler to the same of original handler, so it can be removed 
			handler.guid = fn.guid;
		}

		// Init the element's event structure
		if (!element.$events)
			element.$events = {};
		
		if (!element.$handle)
			element.$handle = function() {
				// returned undefined or false
				var val;

				// 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 val;
				
				val = jQuery.event.handle.apply(element, arguments);
				
				return val;
			};

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

		// Init the event handler queue
		if (!handlers) {
			handlers = element.$events[type] = {};	
			
			// And bind the global event handler to the element
			if (element.addEventListener)
				element.addEventListener(type, element.$handle, false);
			else
				element.attachEvent("on" + type, element.$handle);
		}

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

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

	guid: 1,
	global: {},

	// Detach an event or set of events from an element
	remove: function(element, type, handler) {
		var events = element.$events, ret, index;

		if ( events ) {
			// type is actually an event object here
			if ( type && type.type ) {
				handler = type.handler;
				type = type.type;
			}
			
			if ( !type ) {
				for ( type in events )
					this.remove( element, type );

			} else if ( events[type] ) {
				// remove the given handler for the given type
				if ( handler )
					delete events[type][handler.guid];
				
				// remove all handlers for the given type
				else
					for ( handler in element.$events[type] )
						delete events[type][handler];

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

			// Remove the expando if it's no longer used
			for ( ret in events ) break;
			if ( !ret )
				element.$handle = element.$events = null;
		}
	},

	trigger: function(type, data, element) {
		// Clone the incoming data, if any
		data = jQuery.makeArray(data || []);

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

		// Handle triggering a single element
		} else {
			var val, ret, fn = jQuery.isFunction( element[ type ] || null );
			
			// Pass along a fake event
			data.unshift( this.fix({ type: type, target: element }) );

			// Trigger the event
			if ( jQuery.isFunction( element.$handle ) )
				val = element.$handle.apply( element, data );
			if ( !fn && element["on"+type] && element["on"+type].apply( element, data ) === false )
				val = false;

			if ( fn && val !== false && !(jQuery.nodeName(element, 'a') && type == "click") ) {
				this.triggered = true;
				element[ type ]();
			}

			this.triggered = false;
		}
	},

	handle: function(event) {
		// returned undefined or false
		var val;

		// Empty object is for triggered events with no data
		event = jQuery.event.fix( event || window.event || {} ); 

		var c = this.$events && this.$events[event.type], args = Array.prototype.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();
				val = 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 val;
	},

	fix: function(event) {
		// store a copy of the original event object 
		// and clone to set read-only properties
		var originalEvent = event;
		event = jQuery.extend({}, originalEvent);
		
		// add preventDefault and stopPropagation since 
		// they will not work on the clone
		event.preventDefault = function() {
			// if preventDefault exists run it on the original event
			if (originalEvent.preventDefault)
				originalEvent.preventDefault();
			// otherwise set the returnValue property of the original event to false (IE)
			originalEvent.returnValue = false;
		};
		event.stopPropagation = function() {
			// if stopPropagation exists run it on the original event
			if (originalEvent.stopPropagation)
				originalEvent.stopPropagation();
			// otherwise set the cancelBubble property of the original event to true (IE)
			originalEvent.cancelBubble = true;
		};
		
		// Fix target property, if necessary
		if ( !event.target && event.srcElement )
			event.target = event.srcElement;
				
		// check if target is a textnode (safari)
		if (jQuery.browser.safari && event.target.nodeType == 3)
			event.target = originalEvent.target.parentNode;

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

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var e = document.documentElement, b = document.body;
			event.pageX = event.clientX + (e && e.scrollLeft || b.scrollLeft || 0);
			event.pageY = event.clientY + (e && e.scrollTop || b.scrollTop || 0);
		}
			
		// Add which for key events
		if ( !event.which && (event.charCode || event.keyCode) )
			event.which = event.charCode || event.keyCode;
		
		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey )
			event.metaKey = event.ctrlKey;

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

jQuery.fn.extend({
	bind: function( type, data, fn ) {
		return type == "unload" ? this.one(type, data, fn) : this.each(function(){
			jQuery.event.add( this, type, fn || data, fn && data );
		});
	},
	one: function( type, data, fn ) {
		return this.each(function(){
			jQuery.event.add( this, type, function(event) {
				jQuery(this).unbind(event);
				return (fn || data).apply( this, arguments);
			}, fn && data);
		});
	},
	unbind: function( type, fn ) {
		return this.each(function(){
			jQuery.event.remove( this, type, fn );
		});
	},
	trigger: function( type, data ) {
		return this.each(function(){
			jQuery.event.trigger( type, data, this );
		});
	},
	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 = 0 == this.lastToggle ? 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.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) {
		// Attach the listeners
		bindReady();

		// 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 listener to avoid memory leak
			if ( jQuery.browser.mozilla || jQuery.browser.opera )
				document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
			
			// Remove script element used by IE hack
			if( !window.frames.length ) // don't remove if frames are present (#1187)
				jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
		}
	}
});

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

var readyBound = false;

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

	// 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 ( document.readyState != "complete" ) return;
				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 );
}
jQuery.fn.extend({
	// DEPRECATED
	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 successful, inject the HTML into all the matched elements
				if ( status == "success" || !ifModified && status == "notmodified" )
					self.html(res.responseText);

				// Add delay to account for Safari's delay in globalEval
				setTimeout(function(){
					self.each( callback, [res.responseText, status, res] );
				}, 13);
			}
		});
		return this;
	},
	serialize: function() {
		return jQuery.param( this );
	},

	// DEPRECATED
	// This method no longer does anything - all script evaluation is
	// taken care of within the HTML injection methods.
	evalScripts: function(){}

});

// 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({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type,
			ifModified: ifModified
		});
	},
	// DEPRECATED
	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
		});
	},
	// DEPRECATED
	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 ) {
		// Extend the settings, but re-extend 's' so that it can be
		// checked again later (in the test suite, specifically)
		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

		// 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; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
		var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : 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");

		// 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 ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;
				
				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}
				
				var status = isTimeout == "timeout" && "timeout" ||
					!jQuery.httpSuccess( xml ) && "error" ||
					s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
					"success";

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

				// Make sure that the request was successful or notmodified
				if ( status == "success" ) {
					// Cache Last-Modified header, if ifModified mode.
					var modRes;
					try {
						modRes = 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;
	
					// 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);

				// 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;
			}
		};
		
		if ( s.async ) {
			// don't attach the handler to the request, just poll it instead
			var ival = setInterval(onreadystatechange, 13); 

			// Timeout checker
			if ( s.timeout > 0 )
				setTimeout(function(){
					// Check to see if the request is still happening
					if ( 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 xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
		data = xml ? r.responseXML : r.responseText;

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";

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

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

		return data;
	},

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

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

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

		// Return the resulting serialization
		return s.join("&");
	}

});
jQuery.fn.extend({

	show: function(speed,callback){
		return speed ?
			this.animate({
				height: "show", width: "show", opacity: "show"
			}, speed, callback) :
			
			this.filter(":hidden").each(function(){
				this.style.display = this.oldblock ? this.oldblock : "";
				if ( jQuery.css(this,"display") == "none" )
					this.style.display = "block";
			}).end();
	},

	hide: function(speed,callback){
		return speed ?
			this.animate({
				height: "hide", width: "hide", opacity: "hide"
			}, speed, callback) :
			
			this.filter(":visible").each(function(){
				this.oldblock = this.oldblock || jQuery.css(this,"display");
				if ( this.oldblock == "none" )
					this.oldblock = "block";
				this.style.display = "none";
			}).end();
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,
	toggle: function( fn, fn2 ){
		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle( fn, fn2 ) :
			fn ?
				this.animate({
					height: "toggle", width: "toggle", opacity: "toggle"
				}, fn, fn2) :
				this.each(function(){
					jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
				});
	},
	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},
	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},
	slideToggle: function(speed, callback){
		return this.animate({height: "toggle"}, speed, callback);
	},
	fadeIn: function(speed, callback){
		return this.animate({opacity: "show"}, speed, callback);
	},
	fadeOut: function(speed, callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},
	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},
	animate: function( prop, speed, easing, callback ) {
		return this.queue(function(){
			var hidden = jQuery(this).is(":hidden"),
				opt = jQuery.speed(speed, easing, callback),
				self = this;
			
			for ( var p in prop ) {
				if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
					return jQuery.isFunction(opt.complete) && opt.complete.apply(this);

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

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

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

			this.curAnim = jQuery.extend({}, prop);
			
			jQuery.each( prop, function(name, val){
				var e = new jQuery.fx( self, opt, name );
				if ( val.constructor == Number )
					e.custom( e.cur() || 0, val );
				else
					e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
			});

			// For JS strict compliance
			return true;
		});
	},
	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: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
		}
	},
	
	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 );
		}
	},

	timers: [],

	/*
	 * 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;
		
		// 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 {
				y[prop] = parseInt(z.now) + "px";

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

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

			jQuery.timers.push(function(){
				return z.step(from, to);
			});

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

					if ( !timers.length )
						clearInterval( timer );
				}, 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] = jQuery.attr( elem.style, prop );

			options.show = true;

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

			// Make sure that we start at a small width/height to avoid any
			// flash of content
			if ( prop != "opacity" )
				y[prop] = "1px";
			
			// Start by showing the element
			jQuery(elem).show();
		};

		// 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] = jQuery.attr( elem.style, prop );

			options.hide = true;

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

		// Each step of an animation
		z.step = function(firstNum, lastNum){
			var t = (new Date()).getTime();

			if (t > options.duration + z.startTime) {
				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 ) {
					if ( options.display != null ) {
						// Reset the overflow
						y.overflow = options.overflow;
					
						// Reset the display
						y.display = options.display;
						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 )
							jQuery.attr(y, p, elem.orig[p]);
				}

				// If a callback was provided, execute it
				if ( done && jQuery.isFunction( options.complete ) )
					// Execute the complete function
					options.complete.apply( elem );

				return false;
			} else {
				var n = t - this.startTime;
				// Figure out where in the animation we are and set the number
				var p = n / options.duration;
				
				// Perform the easing function, defaults to swing
				z.now = jQuery.easing[options.easing || (jQuery.easing.swing ? "swing" : "linear")](p, n, firstNum, (lastNum-firstNum), options.duration);

				// Perform the next step of the animation
				z.a();
			}

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

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

/**
 * Get the value of a cookie with the given name.
 *
 * @example jQuery.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name jQuery.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = jQuery.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-03-27 16:29:43 -0500 (Tue, 27 Mar 2007) $
 * $Rev: 1601 $
 */

jQuery.fn._height = jQuery.fn.height;
jQuery.fn._width  = jQuery.fn.width;

/**
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 * See core docs on height() to see what happens when used on an element.
 *
 * @example jQuery("#testdiv").height()
 * @result 200
 *
 * @example jQuery(document).height()
 * @result 800
 *
 * @example jQuery(window).height()
 * @result 400
 *
 * @name height
 * @type Object
 * @cat Plugins/Dimensions
 */
jQuery.fn.height = function() {
	if ( this[0] == window )
		return self.innerHeight ||
			jQuery.boxModel && document.documentElement.clientHeight ||
			document.body.clientHeight;

	if ( this[0] == document )
		return Math.max( document.body.scrollHeight, document.body.offsetHeight );

	return this._height(arguments[0]);
};

/**
 * If used on document, returns the document's width (innerWidth)
 * If used on window, returns the viewport's (window) width
 * See core docs on height() to see what happens when used on an element.
 *
 * @example jQuery("#testdiv").width()
 * @result 200
 *
 * @example jQuery(document).width()
 * @result 800
 *
 * @example jQuery(window).width()
 * @result 400
 *
 * @name width
 * @type Object
 * @cat Plugins/Dimensions
 */
jQuery.fn.width = function() {
	if ( this[0] == window )
		return self.innerWidth ||
			jQuery.boxModel && document.documentElement.clientWidth ||
			document.body.clientWidth;

	if ( this[0] == document )
		return Math.max( document.body.scrollWidth, document.body.offsetWidth );

	return this._width(arguments[0]);
};

/**
 * Returns the inner height value (without border) for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example jQuery("#testdiv").innerHeight()
 * @result 800
 *
 * @name innerHeight
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.innerHeight = function() {
	return this[0] == window || this[0] == document ?
		this.height() :
		this.css('display') != 'none' ?
		 	this[0].offsetHeight - (parseInt(this.css("borderTopWidth")) || 0) - (parseInt(this.css("borderBottomWidth")) || 0) :
			this.height() + (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0);
};

/**
 * Returns the inner width value (without border) for the first matched element.
 * If used on document, returns the document's Width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example jQuery("#testdiv").innerWidth()
 * @result 1000
 *
 * @name innerWidth
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.innerWidth = function() {
	return this[0] == window || this[0] == document ?
		this.width() :
		this.css('display') != 'none' ?
			this[0].offsetWidth - (parseInt(this.css("borderLeftWidth")) || 0) - (parseInt(this.css("borderRightWidth")) || 0) :
			this.height() + (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0);
};

/**
 * Returns the outer height value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example jQuery("#testdiv").outerHeight()
 * @result 1000
 *
 * @name outerHeight
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.outerHeight = function() {
	return this[0] == window || this[0] == document ?
		this.height() :
		this.css('display') != 'none' ?
			this[0].offsetHeight :
			this.height() + (parseInt(this.css("borderTopWidth")) || 0) + (parseInt(this.css("borderBottomWidth")) || 0)
				+ (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0);
};

/**
 * Returns the outer width value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example jQuery("#testdiv").outerWidth()
 * @result 1000
 *
 * @name outerWidth
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.outerWidth = function() {
	return this[0] == window || this[0] == document ?
		this.width() :
		this.css('display') != 'none' ?
			this[0].offsetWidth :
			this.height() + (parseInt(this.css("borderLeftWidth")) || 0) + (parseInt(this.css("borderRightWidth")) || 0)
				+ (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0);
};

/**
 * Returns how many pixels the user has scrolled to the right (scrollLeft).
 * Works on containers with overflow: auto and window/document.
 *
 * @example jQuery("#testdiv").scrollLeft()
 * @result 100
 *
 * @name scrollLeft
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.scrollLeft = function() {
	if ( this[0] == window || this[0] == document )
		return self.pageXOffset ||
			jQuery.boxModel && document.documentElement.scrollLeft ||
			document.body.scrollLeft;

	return this[0].scrollLeft;
};

/**
 * Returns how many pixels the user has scrolled to the bottom (scrollTop).
 * Works on containers with overflow: auto and window/document.
 *
 * @example jQuery("#testdiv").scrollTop()
 * @result 100
 *
 * @name scrollTop
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.scrollTop = function() {
	if ( this[0] == window || this[0] == document )
		return self.pageYOffset ||
			jQuery.boxModel && document.documentElement.scrollTop ||
			document.body.scrollTop;

	return this[0].scrollTop;
};

/**
 * Returns the location of the element in pixels from the top left corner of the viewport.
 *
 * For accurate readings make sure to use pixel values for margins, borders and padding.
 *
 * @example jQuery("#testdiv").offset()
 * @result { top: 100, left: 100, scrollTop: 10, scrollLeft: 10 }
 *
 * @example jQuery("#testdiv").offset({ scroll: false })
 * @result { top: 90, left: 90 }
 *
 * @example var offset = {}
 * jQuery("#testdiv").offset({ scroll: false }, offset)
 * @result offset = { top: 90, left: 90 }
 *
 * @name offset
 * @param Object options A hash of options describing what should be included in the final calculations of the offset.
 *                       The options include:
 *                           margin: Should the margin of the element be included in the calculations? True by default.
 *                                   If set to false the margin of the element is subtracted from the total offset.
 *                           border: Should the border of the element be included in the calculations? True by default.
 *                                   If set to false the border of the element is subtracted from the total offset.
 *                           padding: Should the padding of the element be included in the calculations? False by default.
 *                                    If set to true the padding of the element is added to the total offset.
 *                           scroll: Should the scroll offsets of the parent elements be included in the calculations?
 *                                   True by default. When true, it adds the total scroll offsets of all parents to the
 *                                   total offset and also adds two properties to the returned object, scrollTop and
 *                                   scrollLeft. If set to false the scroll offsets of parent elements are ignored.
 *                                   If scroll offsets are not needed, set to false to get a performance boost.
 * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the
 *                            chain will not be broken and the result will be assigned to this object.
 * @type Object
 * @cat Plugins/Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(options, returnObject) {
	var x = 0, y = 0, elem = this[0], parent = this[0], absparent=false, relparent=false, op, sl = 0, st = 0, options = jQuery.extend({ margin: true, border: true, padding: false, scroll: true }, options || {});
	do {
		x += parent.offsetLeft || 0;
		y += parent.offsetTop  || 0;

		// Mozilla and IE do not add the border
		if (jQuery.browser.mozilla || jQuery.browser.msie) {
			// get borders
			var bt = parseInt(jQuery.css(parent, 'borderTopWidth')) || 0;
			var bl = parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;

			// add borders to offset
			x += bl;
			y += bt;

			// Mozilla removes the border if the parent has overflow property other than visible
			if (jQuery.browser.mozilla && parent != elem && jQuery.css(parent, 'overflow') != 'visible') {
				x += bl;
				y += bt;
			}
			
			// Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent
			if (jQuery.css(parent, 'position') == 'absolute') absparent = true;
			// IE does not include the border on the body if an element is position static and without an absolute or relative parent
			if (jQuery.css(parent, 'position') == 'relative') relparent = true;
		}

		if (options.scroll) {
			// Need to get scroll offsets in-between offsetParents
			op = parent.offsetParent;
			do {
				sl += parent.scrollLeft || 0;
				st += parent.scrollTop  || 0;

				parent = parent.parentNode;

				// Mozilla removes the border if the parent has overflow property other than visible
				if (jQuery.browser.mozilla && parent != elem && parent != op && jQuery.css(parent, 'overflow') != 'visible') {
					x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
					y += parseInt(jQuery.css(parent, 'borderTopWidth')) || 0;
				}
			} while (op && parent != op);
		} else
			parent = parent.offsetParent;

		if (parent && (parent.tagName.toLowerCase() == 'body' || parent.tagName.toLowerCase() == 'html')) {
			// Safari and IE Standards Mode doesn't add the body margin for elments positioned with static or relative
			if ((jQuery.browser.safari || (jQuery.browser.msie && jQuery.boxModel)) && jQuery.css(elem, 'position') != 'absolute') {
				x += parseInt(jQuery.css(parent, 'marginLeft')) || 0;
				y += parseInt(jQuery.css(parent, 'marginTop'))  || 0;
			}
			// Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent
			// IE does not include the border on the body if an element is positioned static and without an absolute or relative parent
			if ( (jQuery.browser.mozilla && !absparent) || 
			     (jQuery.browser.msie && jQuery.css(elem, 'position') == 'static' && (!relparent || !absparent)) ) {
				x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
				y += parseInt(jQuery.css(parent, 'borderTopWidth'))  || 0;
			}
			break; // Exit the loop
		}
	} while (parent);

	if ( !options.margin) {
		x -= parseInt(jQuery.css(elem, 'marginLeft')) || 0;
		y -= parseInt(jQuery.css(elem, 'marginTop'))  || 0;
	}

	// Safari and Opera do not add the border for the element
	if ( options.border && (jQuery.browser.safari || jQuery.browser.opera) ) {
		x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y += parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
	} else if ( !options.border && !(jQuery.browser.safari || jQuery.browser.opera) ) {
		x -= parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y -= parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
	}

	if ( options.padding ) {
		x += parseInt(jQuery.css(elem, 'paddingLeft')) || 0;
		y += parseInt(jQuery.css(elem, 'paddingTop'))  || 0;
	}

	// Opera thinks offset is scroll offset for display: inline elements
	if (options.scroll && jQuery.browser.opera && jQuery.css(elem, 'display') == 'inline') {
		sl -= elem.scrollLeft || 0;
		st -= elem.scrollTop  || 0;
	}

	var returnValue = options.scroll ? { top: y - st, left: x - sl, scrollTop:  st, scrollLeft: sl }
	                                 : { top: y, left: x };

	if (returnObject) { jQuery.extend(returnObject, returnValue); return this; }
	else              { return returnValue; }
};
/**
 * Interface Elements for jQuery
 * FX - drop
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

/**
 * Applies a dropping effect to element
 */
jQuery.fn.extend(
	{
		/**
		 * @name DropOutDown
		 * @description drops the element out down
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropOutDown : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this, speed, callback, 'down', 'out', easing);
			});
		},

		/**
		 * @name DropInDown
		 * @description drops the element in down
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropInDown : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'down', 'in', easing);
			});
		},

		/**
		 * @name DropToggleDown
		 * @description drops the element in/out down
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropToggleDown : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'down', 'toggle', easing);
			});
		},

		/**
		 * @name DropOutUp
		 * @description drops the element out up
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropOutUp : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this, speed, callback, 'up', 'out', easing);
			});
		},

		/**
		 * @name DropInUp
		 * @description drops the element in up
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropInUp : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'up', 'in', easing);
			});
		},

		/**
		 * @name DropToggleUp
		 * @description drops the element in/out up
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropToggleUp : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'up', 'toggle', easing);
			});
		},

		/**
		 * @name DropOutLeft
		 * @description drops the element out left
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropOutLeft : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this, speed, callback, 'left', 'out', easing);
			});
		},

		/**
		 * @name DropInLeft
		 * @description drops the element in left
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropInLeft : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'left', 'in', easing);
			});
		},

		/**
		 * @name DropToggleLeft
		 * @description drops the element in/out left
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropToggleLeft : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'left', 'toggle', easing);
			});
		},

		/**
		 * @name DropOutRight
		 * @description drops the element out right
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropOutRight : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this, speed, callback, 'right', 'out', easing);
			});
		},

		/**
		 * @name DropInRight
		 * @description drops the element in right
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropInRight : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'right', 'in', easing);
			});
		},

		/**
		 * @name DropToggleRight
		 * @description drops the element in/out right
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		DropToggleRight : function (speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.DropOutDirectiont(this,  speed, callback, 'right', 'toggle', easing);
			});
		}
	}
);

jQuery.fx.DropOutDirectiont = function (e, speed, callback, direction, type, easing)
{
	if (!jQuery.fxCheckTag(e)) {
		jQuery.dequeue(e, 'interfaceFX');
		return false;
	}
	var z = this;
	z.el = jQuery(e);
	z.easing = typeof callback == 'string' ? callback : easing||null;
	z.oldStyle = {};
	z.oldStyle.position = z.el.css('position');
	z.oldStyle.top = z.el.css('top');
	z.oldStyle.left = z.el.css('left');
	if (!e.ifxFirstDisplay)
		e.ifxFirstDisplay = z.el.css('display');
	if ( type == 'toggle') {
		type = z.el.css('display') == 'none' ? 'in' : 'out';
	}
	z.el.show();

	if (z.oldStyle.position != 'relative' && z.oldStyle.position != 'absolute') {
		z.el.css('position', 'relative');
	}
	z.type = type;
	callback = typeof callback == 'function' ? callback : null;
	/*sizes = ['em','px','pt','%'];
	for(i in sizes) {
		if (z.oldStyle.top.indexOf(sizes[i])>0) {
			z.topUnit = sizes[1];
			z.topSize = parseFloat(z.oldStyle.top)||0;
		}
		if (z.oldStyle.left.indexOf(sizes[i])>0) {
			z.leftUnit = sizes[1];
			z.leftSize = parseFloat(z.oldStyle.left)||0;
		}
	}*/

	directionIncrement = 1;
	switch (direction){
		case 'up':
			z.e = new jQuery.fx(z.el.get(0), jQuery.speed(speed - 15, z.easing,callback), 'top');
			z.point = parseFloat(z.oldStyle.top)||0;
			z.unit = z.topUnit;
			directionIncrement = -1;
		break;
		case 'down':
			z.e = new jQuery.fx(z.el.get(0), jQuery.speed(speed - 15, z.easing,callback), 'top');
			z.point = parseFloat(z.oldStyle.top)||0;
			z.unit = z.topUnit;
		break;
		case 'right':
			z.e = new jQuery.fx(z.el.get(0), jQuery.speed(speed - 15, z.easing,callback), 'left');
			z.point = parseFloat(z.oldStyle.left)||0;
			z.unit = z.leftUnit;
		break;
		case 'left':
			z.e = new jQuery.fx(z.el.get(0), jQuery.speed(speed - 15, z.easing,callback), 'left');
			z.point = parseFloat(z.oldStyle.left)||0;
			z.unit = z.leftUnit;
			directionIncrement = -1;
		break;
	}
	z.e2 = new jQuery.fx(
		z.el.get(0),
		jQuery.speed
		(
		 	speed, z.easing,
			function()
			{
				z.el.css(z.oldStyle);
				if (z.type == 'out') {
					z.el.css('display', 'none');
				} else
					z.el.css('display', z.el.get(0).ifxFirstDisplay == 'none' ? 'block' : z.el.get(0).ifxFirstDisplay);

				jQuery.dequeue(z.el.get(0), 'interfaceFX');
			}
		 ),
		'opacity'
	);
	if (type == 'in') {
		z.e.custom(z.point+ 100*directionIncrement, z.point);
		z.e2.custom(0,1);
	} else {
		z.e.custom(z.point, z.point + 100*directionIncrement);
		z.e2.custom(1,0);
	}
};


/**
 * Interface Elements for jQuery
 * Resizable
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

jQuery.iResize = {
	resizeElement: null,
	resizeDirection: null,
	dragged: null,
	pointer: null,
	sizes: null,
	position: null,
	/**
	 * internal: Start function
	 */
	startDrag: function(e) {
		jQuery.iResize.dragged = (this.dragEl) ? this.dragEl: this;
		jQuery.iResize.pointer = jQuery.iUtil.getPointer(e);

		// Save original size
		jQuery.iResize.sizes = {
			width: parseInt(jQuery(jQuery.iResize.dragged).css('width')) || 0,
			height: parseInt(jQuery(jQuery.iResize.dragged).css('height')) || 0
		};

		// Save original position
		jQuery.iResize.position = {
			top: parseInt(jQuery(jQuery.iResize.dragged).css('top')) || 0,
			left: parseInt(jQuery(jQuery.iResize.dragged).css('left')) || 0
		};

		// Assign event handlers
		jQuery(document)
			.bind('mousemove', jQuery.iResize.moveDrag)
			.bind('mouseup', jQuery.iResize.stopDrag);

		// Callback?
		if (typeof jQuery.iResize.dragged.resizeOptions.onDragStart === 'function') {
			jQuery.iResize.dragged.resizeOptions.onDragStart.apply(jQuery.iResize.dragged);
		}
		return false;
	},
	/**
	 * internal: Stop function
	 */
	stopDrag: function(e) {
		// Unbind event handlers
		jQuery(document)
			.unbind('mousemove', jQuery.iResize.moveDrag)
			.unbind('mouseup', jQuery.iResize.stopDrag);

		// Callback?
		if (typeof jQuery.iResize.dragged.resizeOptions.onDragStop === 'function') {
			jQuery.iResize.dragged.resizeOptions.onDragStop.apply(jQuery.iResize.dragged);
		}

		// Remove dragged element
		jQuery.iResize.dragged = null;
	},
	/**
	 * internal: Move function
	 */
	moveDrag: function(e) {
		if (!jQuery.iResize.dragged) {
			return;
		}

		pointer = jQuery.iUtil.getPointer(e);

		// Calculate new positions
		newTop = jQuery.iResize.position.top - jQuery.iResize.pointer.y + pointer.y;
		newLeft = jQuery.iResize.position.left - jQuery.iResize.pointer.x + pointer.x;
		newTop = Math.max(
						Math.min(newTop, jQuery.iResize.dragged.resizeOptions.maxBottom - jQuery.iResize.sizes.height),
						jQuery.iResize.dragged.resizeOptions.minTop
					);
		newLeft = Math.max(
						Math.min(newLeft, jQuery.iResize.dragged.resizeOptions.maxRight- jQuery.iResize.sizes.width),
						jQuery.iResize.dragged.resizeOptions.minLeft
					);

		// Callback
		if (typeof jQuery.iResize.dragged.resizeOptions.onDrag === 'function') {
			var newPos = jQuery.iResize.dragged.resizeOptions.onDrag.apply(jQuery.iResize.dragged, [newLeft, newTop]);
			if (typeof newPos == 'array' && newPos.length == 2) {
				newLeft = newPos[0];
				newTop = newPos[1];
			}
		}

		// Update the element
		jQuery.iResize.dragged.style.top = newTop + 'px';
		jQuery.iResize.dragged.style.left = newLeft + 'px';

		return false;
	},
	start: function(e) {
		// Bind event handlers
		jQuery(document)
			.bind('mousemove', jQuery.iResize.move)
			.bind('mouseup', jQuery.iResize.stop);

		// Initialize resizable
		jQuery.iResize.resizeElement = this.resizeElement;
		jQuery.iResize.resizeDirection = this.resizeDirection;
		jQuery.iResize.pointer = jQuery.iUtil.getPointer(e);
		jQuery.iResize.sizes = {
				width: parseInt(jQuery(this.resizeElement).css('width'))||0,
				height: parseInt(jQuery(this.resizeElement).css('height'))||0
			};
		jQuery.iResize.position = {
				top: parseInt(jQuery(this.resizeElement).css('top'))||0,
				left: parseInt(jQuery(this.resizeElement).css('left'))||0
			};

		// Callback function
		if (jQuery.iResize.resizeElement.resizeOptions.onStart) {
			jQuery.iResize.resizeElement.resizeOptions.onStart.apply(jQuery.iResize.resizeElement, [this]);
		}

		return false;
	},
	stop: function() {
		// Unbind event handlers
		jQuery(document)
			.unbind('mousemove', jQuery.iResize.move)
			.unbind('mouseup', jQuery.iResize.stop);

		// Callback function
		if (jQuery.iResize.resizeElement.resizeOptions.onStop) {
			jQuery.iResize.resizeElement.resizeOptions.onStop.apply(jQuery.iResize.resizeElement, [jQuery.iResize.resizeDirection]);
		}

		// Unbind
		jQuery.iResize.resizeElement = null;
		jQuery.iResize.resizeDirection = null;
	},
	getWidth: function(dx, side) {
		return Math.min(
						Math.max(jQuery.iResize.sizes.width + dx * side, jQuery.iResize.resizeElement.resizeOptions.minWidth),
						jQuery.iResize.resizeElement.resizeOptions.maxWidth
					);
	},
	getHeight: function(dy, side) {
		return Math.min(
						Math.max(jQuery.iResize.sizes.height + dy * side, jQuery.iResize.resizeElement.resizeOptions.minHeight),
						jQuery.iResize.resizeElement.resizeOptions.maxHeight
					);
	},
	getHeightMinMax: function(height) {
		return Math.min(
						Math.max(height, jQuery.iResize.resizeElement.resizeOptions.minHeight),
						jQuery.iResize.resizeElement.resizeOptions.maxHeight
					);
	},
	move: function(e) {
		if (jQuery.iResize.resizeElement == null) {
			return;
		}

		pointer = jQuery.iUtil.getPointer(e);
		dx = pointer.x - jQuery.iResize.pointer.x;
		dy = pointer.y - jQuery.iResize.pointer.y;

		newSizes = {
				width: jQuery.iResize.sizes.width,
				height: jQuery.iResize.sizes.height
			};
		newPosition = {
				top: jQuery.iResize.position.top,
				left: jQuery.iResize.position.left
			};

		switch (jQuery.iResize.resizeDirection){
			case 'e':
				newSizes.width = jQuery.iResize.getWidth(dx,1);
				break;
			case 'se':
				newSizes.width = jQuery.iResize.getWidth(dx,1);
				newSizes.height = jQuery.iResize.getHeight(dy,1);
				break;
			case 'w':
				newSizes.width = jQuery.iResize.getWidth(dx,-1);
				newPosition.left = jQuery.iResize.position.left - newSizes.width + jQuery.iResize.sizes.width;
				break;
			case 'sw':
				newSizes.width = jQuery.iResize.getWidth(dx,-1);
				newPosition.left = jQuery.iResize.position.left - newSizes.width + jQuery.iResize.sizes.width;
				newSizes.height = jQuery.iResize.getHeight(dy,1);
				break;
			case 'nw':
				newSizes.height = jQuery.iResize.getHeight(dy,-1);
				newPosition.top = jQuery.iResize.position.top - newSizes.height + jQuery.iResize.sizes.height;
				newSizes.width = jQuery.iResize.getWidth(dx,-1);
				newPosition.left = jQuery.iResize.position.left - newSizes.width + jQuery.iResize.sizes.width;
				break;
			case 'n':
				newSizes.height = jQuery.iResize.getHeight(dy,-1);
				newPosition.top = jQuery.iResize.position.top - newSizes.height + jQuery.iResize.sizes.height;
				break;
			case 'ne':
				newSizes.height = jQuery.iResize.getHeight(dy,-1);
				newPosition.top = jQuery.iResize.position.top - newSizes.height + jQuery.iResize.sizes.height;
				newSizes.width = jQuery.iResize.getWidth(dx,1);
				break;
			case 's':
				newSizes.height = jQuery.iResize.getHeight(dy,1);
				break;
		}

		if (jQuery.iResize.resizeElement.resizeOptions.ratio) {
			if (jQuery.iResize.resizeDirection == 'n' || jQuery.iResize.resizeDirection == 's')
				nWidth = newSizes.height * jQuery.iResize.resizeElement.resizeOptions.ratio;
			else
				nWidth = newSizes.width;
			nHeight = jQuery.iResize.getHeightMinMax(nWidth * jQuery.iResize.resizeElement.resizeOptions.ratio);
			nWidth = nHeight / jQuery.iResize.resizeElement.resizeOptions.ratio;

			switch (jQuery.iResize.resizeDirection){
				case 'n':
				case 'nw':
				case 'ne':
					newPosition.top += newSizes.height - nHeight;
				break;
			}

			switch (jQuery.iResize.resizeDirection){
				case 'nw':
				case 'w':
				case 'sw':
					newPosition.left += newSizes.width - nWidth;
				break;
			}

			newSizes.height = nHeight;
			newSizes.width = nWidth;
		}

		if (newPosition.top < jQuery.iResize.resizeElement.resizeOptions.minTop) {
			nHeight = newSizes.height + newPosition.top - jQuery.iResize.resizeElement.resizeOptions.minTop;
			newPosition.top = jQuery.iResize.resizeElement.resizeOptions.minTop;

			if (jQuery.iResize.resizeElement.resizeOptions.ratio) {
				nWidth = nHeight / jQuery.iResize.resizeElement.resizeOptions.ratio;
				switch (jQuery.iResize.resizeDirection){
					case 'nw':
					case 'w':
					case 'sw':
						newPosition.left += newSizes.width - nWidth;
					break;
				}
				newSizes.width = nWidth;
			}
			newSizes.height = nHeight;
		}

		if (newPosition.left < jQuery.iResize.resizeElement.resizeOptions.minLeft ) {
			nWidth = newSizes.width + newPosition.left - jQuery.iResize.resizeElement.resizeOptions.minLeft;
			newPosition.left = jQuery.iResize.resizeElement.resizeOptions.minLeft;

			if (jQuery.iResize.resizeElement.resizeOptions.ratio) {
				nHeight = nWidth * jQuery.iResize.resizeElement.resizeOptions.ratio;
				switch (jQuery.iResize.resizeDirection){
					case 'n':
					case 'nw':
					case 'ne':
						newPosition.top += newSizes.height - nHeight;
					break;
				}
				newSizes.height = nHeight;
			}
			newSizes.width = nWidth;
		}

		if (newPosition.top + newSizes.height > jQuery.iResize.resizeElement.resizeOptions.maxBottom) {
			newSizes.height = jQuery.iResize.resizeElement.resizeOptions.maxBottom - newPosition.top;
			if (jQuery.iResize.resizeElement.resizeOptions.ratio) {
				newSizes.width = newSizes.height / jQuery.iResize.resizeElement.resizeOptions.ratio;
			}

		}

		if (newPosition.left + newSizes.width > jQuery.iResize.resizeElement.resizeOptions.maxRight) {
			newSizes.width = jQuery.iResize.resizeElement.resizeOptions.maxRight - newPosition.left;
			if (jQuery.iResize.resizeElement.resizeOptions.ratio) {
				newSizes.height = newSizes.width * jQuery.iResize.resizeElement.resizeOptions.ratio;
			}

		}

		var newDimensions = false;
		if (jQuery.iResize.resizeElement.resizeOptions.onResize) {
			newDimensions = jQuery.iResize.resizeElement.resizeOptions.onResize.apply( jQuery.iResize.resizeElement, [ newSizes, newPosition ] );
			if (newDimensions) {
				if (newDimensions.sizes) {
					jQuery.extend(newSizes, newDimensions.sizes);
				}

				if (newDimensions.position) {
					jQuery.extend(newPosition, newDimensions.position);
				}
			}
		}
			elS = jQuery.iResize.resizeElement.style;
			elS.left = newPosition.left + 'px';
			elS.top = newPosition.top + 'px';
			elS.width = newSizes.width + 'px';
			elS.height = newSizes.height + 'px';

		return false;
	},
	/**
	 * Builds the resizable
	 */
	build: function(options) {
		if (!options || !options.handlers || options.handlers.constructor != Object) {
			return;
		}

		return this.each(
			function() {
				var el = this;
				el.resizeOptions = options;
				el.resizeOptions.minWidth = options.minWidth || 10;
				el.resizeOptions.minHeight = options.minHeight || 10;
				el.resizeOptions.maxWidth = options.maxWidth || 3000;
				el.resizeOptions.maxHeight = options.maxHeight || 3000;
				el.resizeOptions.minTop = options.minTop || -1000;
				el.resizeOptions.minLeft = options.minLeft || -1000;
				el.resizeOptions.maxRight = options.maxRight || 3000;
				el.resizeOptions.maxBottom = options.maxBottom || 3000;
				elPosition = jQuery(el).css('position');
				if (!(elPosition == 'relative' || elPosition == 'absolute')) {
					el.style.position = 'relative';
				}

				directions = /n|ne|e|se|s|sw|w|nw/g;
				for (i in el.resizeOptions.handlers) {
					if (i.toLowerCase().match(directions) != null) {
						if (el.resizeOptions.handlers[i].constructor == String) {
							handle = jQuery(el.resizeOptions.handlers[i]);
							if (handle.size() > 0) {
								el.resizeOptions.handlers[i] = handle.get(0);
							}
						}

						if (el.resizeOptions.handlers[i].tagName) {
							el.resizeOptions.handlers[i].resizeElement = el;
							el.resizeOptions.handlers[i].resizeDirection = i;
							jQuery(el.resizeOptions.handlers[i]).bind('mousedown', jQuery.iResize.start);
						}
					}
				}

				if (el.resizeOptions.dragHandle) {
					if (typeof el.resizeOptions.dragHandle === 'string') {
						handleEl = jQuery(el.resizeOptions.dragHandle);
						if (handleEl.size() > 0) {
							handleEl.each(function() {
									this.dragEl = el;
								});
							handleEl.bind('mousedown', jQuery.iResize.startDrag);
						}
					} else if (el.resizeOptions.dragHandle == true) {
						jQuery(this).bind('mousedown', jQuery.iResize.startDrag);
					}
				}
			}
		);
	},
	/**
	 * Destroys the resizable
	 */
	destroy: function() {
		return this.each(
			function() {
				var el = this;

				// Unbind the handlers
				for (i in el.resizeOptions.handlers) {
					el.resizeOptions.handlers[i].resizeElement = null;
					el.resizeOptions.handlers[i].resizeDirection = null;
					jQuery(el.resizeOptions.handlers[i]).unbind('mousedown', jQuery.iResize.start);
				}

				// Remove the draghandle
				if (el.resizeOptions.dragHandle) {
					if (typeof el.resizeOptions.dragHandle === 'string') {
						handle = jQuery(el.resizeOptions.dragHandle);
						if (handle.size() > 0) {
							handle.unbind('mousedown', jQuery.iResize.startDrag);
						}
					} else if (el.resizeOptions.dragHandle == true) {
						jQuery(this).unbind('mousedown', jQuery.iResize.startDrag);
					}
				}

				// Reset the options
				el.resizeOptions = null;
			}
		);
	}
};


jQuery.fn.extend ({
		/**
		 * Create a resizable element with a number of advanced options including callback, dragging
		 *
		 * @name Resizable
		 * @description Create a resizable element with a number of advanced options including callback, dragging
		 * @param Hash hash A hash of parameters. All parameters are optional.
		 * @option Hash handlers hash with keys for each resize direction (e, es, s, sw, w, nw, n) and value string selection
		 * @option Integer minWidth (optional) the minimum width that element can be resized to
		 * @option Integer maxWidth (optional) the maximum width that element can be resized to
		 * @option Integer minHeight (optional) the minimum height that element can be resized to
		 * @option Integer maxHeight (optional) the maximum height that element can be resized to
		 * @option Integer minTop (optional) the minmum top position to wich element can be moved to
		 * @option Integer minLeft (optional) the minmum left position to wich element can be moved to
		 * @option Integer maxRight (optional) the maximum right position to wich element can be moved to
		 * @option Integer maxBottom (optional) the maximum bottom position to wich element can be moved to
		 * @option Float ratio (optional) the ratio between width and height to constrain elements sizes to that ratio
		 * @option Mixed dragHandle (optional) true to make the element draggable, string selection for drag handle
		 * @option Function onDragStart (optional) A function to be executed whenever the dragging starts
		 * @option Function onDragStop (optional) A function to be executed whenever the dragging stops
		 * @option Function onDrag (optional) A function to be executed whenever the element is dragged
		 * @option Function onStart (optional) A function to be executed whenever the element starts to be resized
		 * @option Function onStop (optional) A function to be executed whenever the element stops to be resized
		 * @option Function onResize (optional) A function to be executed whenever the element is resized
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		Resizable: jQuery.iResize.build,
		/**
		 * Destroy a resizable
		 *
		 * @name ResizableDestroy
		 * @description Destroy a resizable
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		ResizableDestroy: jQuery.iResize.destroy
	});

	/**
 * Interface Elements for jQuery
 * Selectables
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

jQuery.selectHelper = null;
jQuery.selectKeyHelper = false;
jQuery.selectdrug = null;
jQuery.selectCurrent = [];	// For current selection
jQuery.selectKeyDown = function(e) {
	var pressedKey = e.charCode || e.keyCode || -1;
	if (pressedKey == 17 || pressedKey == 16) {
		jQuery.selectKeyHelper = true;
	}
};
jQuery.selectKeyUp = function(e) {
	jQuery.selectKeyHelper = false;
};
jQuery.selectstart = function(e) {
	this.f.pointer = jQuery.iUtil.getPointer(e);
	this.f.pos = jQuery.extend(
		jQuery.iUtil.getPosition(this),
		jQuery.iUtil.getSize(this)
	);

	this.f.scr = jQuery.iUtil.getScroll(this);
	this.f.pointer.x -= this.f.pos.x;
	this.f.pointer.y -= this.f.pos.y;
	jQuery(this).append(jQuery.selectHelper.get(0));
	if (this.f.hc)
		jQuery.selectHelper.addClass(this.f.hc).css('display','block');
	jQuery.selectHelper.css(
		{
			display: 'block',
			width: '0px',
			height: '0px'
		}
	);
	if (this.f.o) {
		jQuery.selectHelper.css('opacity', this.f.o);
	}

	jQuery.selectdrug = this;
	jQuery.selectedone = false;
	jQuery.selectCurrent = [];	// For current selection state
	this.f.el.each(
		function ()
		{
			this.pos = {
				x: this.offsetLeft + (this.currentStyle && !jQuery.browser.opera ?parseInt(this.currentStyle.borderLeftWidth)||0:0) + (jQuery.selectdrug.scrollLeft||0),
				y: this.offsetTop + (this.currentStyle && !jQuery.browser.opera ?parseInt(this.currentStyle.borderTopWidth)||0:0) + (jQuery.selectdrug.scrollTop||0),
				wb: this.offsetWidth,
				hb: this.offsetHeight
			};
			if (this.s == true) {
				if (jQuery.selectKeyHelper == false) {
					this.s = false;
					jQuery(this).removeClass(jQuery.selectdrug.f.sc);
				} else {
					jQuery.selectedone = true;

					// Save current state
					jQuery.selectCurrent[jQuery.selectCurrent.length] = jQuery.attr(this,'id');
				}
			}
		}
	);
	jQuery.selectcheck.apply(this, [e]);
	jQuery(document)
		.bind('mousemove', jQuery.selectcheck)
		.bind('mouseup', jQuery.selectstop);
	return false;
};
jQuery.selectcheck = function(e)
{
	if(!jQuery.selectdrug)
		return;
	jQuery.selectcheckApply.apply(jQuery.selectdrug, [e]);
};
jQuery.selectcheckApply = function(e)
{
	if(!jQuery.selectdrug)
		return;
	var pointer = jQuery.iUtil.getPointer(e);

	var scr = jQuery.iUtil.getScroll(jQuery.selectdrug);
	pointer.x += scr.l - this.f.scr.l - this.f.pos.x;
	pointer.y += scr.t - this.f.scr.t - this.f.pos.y;

	var sx = Math.min(pointer.x, this.f.pointer.x);
	var sw = Math.min(Math.abs(pointer.x - this.f.pointer.x), Math.abs(this.f.scr.w - sx));
	var sy = Math.min(pointer.y, this.f.pointer.y);
	var sh = Math.min(Math.abs(pointer.y - this.f.pointer.y), Math.abs(this.f.scr.h - sy));
	if (this.scrollTop > 0 && pointer.y - 20 < this.scrollTop) {
		var diff = Math.min(scr.t, 10);
		sy -= diff;
		sh += diff;
		this.scrollTop -= diff;
	} else if (this.scrollTop+ this.f.pos.h < this.f.scr.h && pointer.y + 20 > this.scrollTop + this.f.pos.h) {
		var diff = Math.min(this.f.scr.h - this.scrollTop, 10);
		this.scrollTop += diff;
		if (this.scrollTop != scr.t)
			sh += diff;
	}
	if (this.scrollLeft > 0 && pointer.x - 20 < this.scrollLeft) {
		var diff = Math.min(scr.l, 10);
		sx -= diff;
		sw += diff;
		this.scrollLeft -= diff;
	} else if (this.scrollLeft+ this.f.pos.w < this.f.scr.w && pointer.x + 20 > this.scrollLeft + this.f.pos.w) {
		var diff = Math.min(this.f.scr.w - this.scrollLeft, 10);
		this.scrollLeft += diff;
		if (this.scrollLeft != scr.l)
			sw += diff;
	}
	jQuery.selectHelper.css(
		{
			left:	sx + 'px',
			top:	sy + 'px',
			width:	sw + 'px',
			height:	sh + 'px'
		}
	);
	jQuery.selectHelper.l = sx + this.f.scr.l;
	jQuery.selectHelper.t = sy + this.f.scr.t;
	jQuery.selectHelper.r = jQuery.selectHelper.l + sw;
	jQuery.selectHelper.b = jQuery.selectHelper.t + sh;
	jQuery.selectedone = false;
	this.f.el.each(
		function () {
			// Locate the current element in the current selection
			iIndex = jQuery.selectCurrent.indexOf(jQuery.attr(this, 'id'));
			// In case we are currently OVER an item
			if (
				! ( this.pos.x > jQuery.selectHelper.r
				|| (this.pos.x + this.pos.wb) < jQuery.selectHelper.l
				|| this.pos.y > jQuery.selectHelper.b
				|| (this.pos.y + this.pos.hb) < jQuery.selectHelper.t
				)
			)
			{
				jQuery.selectedone = true;
				if (this.s != true) {
					this.s = true;
					jQuery(this).addClass(jQuery.selectdrug.f.sc);
				}

				// Check to see if this item was previously selected, if so, unselect it
				if (iIndex != -1) {
					this.s = false;
					jQuery(this).removeClass(jQuery.selectdrug.f.sc);
				}
			} else if (
						(this.s == true) &&
						(iIndex == -1)
					) {
				// If the item was marked as selected, but it was not selected when you started dragging unselect it.
				this.s = false;
				jQuery(this).removeClass(jQuery.selectdrug.f.sc);
			} else if (
						(!this.s) &&
						(jQuery.selectKeyHelper == true) &&
						(iIndex != -1)
					) {
				// Reselect the item if:
				// - we ARE multiselecting,
				// - dragged over an allready selected object (so it got unselected)
				// - But then dragged the selection out of it again.
				this.s = true;
				jQuery(this).addClass(jQuery.selectdrug.f.sc);
			}
		}
	);
	return false;
};
jQuery.selectstop = function(e)
{
	if(!jQuery.selectdrug)
		return;
	jQuery.selectstopApply.apply(jQuery.selectdrug, [e]);
};
jQuery.selectstopApply = function(e)
{
	jQuery(document)
		.unbind('mousemove', jQuery.selectcheck)
		.unbind('mouseup', jQuery.selectstop);
	if(!jQuery.selectdrug)
		return;
	jQuery.selectHelper.css('display','none');
	if (this.f.hc)
		jQuery.selectHelper.removeClass(this.f.hc);
	jQuery.selectdrug = false;
	jQuery('body').append(jQuery.selectHelper.get(0));
	//
	// In case we have selected some new items..
	if (jQuery.selectedone == true) {
		if (this.f.onselect)
			this.f.onselect(jQuery.Selectserialize(jQuery.attr(this,'id')));
	} else {
		if (this.f.onselectstop)
			this.f.onselectstop(jQuery.Selectserialize(jQuery.attr(this,'id')));
	}
	// Reset current selection
	jQuery.selectCurrent = [];
};

jQuery.Selectserialize = function(s)
{
	var h = '';
	var o = [];
	if (a = jQuery('#' + s)) {
		a.get(0).f.el.each(
			function ()
			{
				if (this.s == true) {
					if (h.length > 0) {
						h += '&';
					}
					h += s + '[]=' + jQuery.attr(this,'id');
					o[o.length] = jQuery.attr(this,'id');
				}
			}
		);
	}
	return {hash:h, o:o};
};
jQuery.fn.Selectable = function(o)
{
	if (!jQuery.selectHelper) {
		jQuery('body',document).append('<div id="selectHelper"></div>').bind('keydown', jQuery.selectKeyDown).bind('keyup', jQuery.selectKeyUp);
		jQuery.selectHelper = jQuery('#selectHelper');
		jQuery.selectHelper.css(
			{
				position:	'absolute',
				display:	'none'
			}
		);

		if (window.event) {
			jQuery('body',document).bind('keydown', jQuery.selectKeyDown).bind('keyup', jQuery.selectKeyUp);
		} else {
			jQuery(document).bind('keydown', jQuery.selectKeyDown).bind('keyup', jQuery.selectKeyUp);
		}
	}

    if (!o) {
		o = {};
	}
    return this.each(
		function()
		{
			if (this.isSelectable)
				return;
			this.isSelectable = true;
			this.f = {
				a : o.accept,
				o : o.opacity ? parseFloat(o.opacity) : false,
				sc : o.selectedclass ? o.selectedclass : false,
				hc : o.helperclass ? o.helperclass : false,
				onselect : o.onselect ? o.onselect : false,
				onselectstop : o.onselectstop ? o.onselectstop : false
			};
			this.f.el = jQuery('.' + o.accept);
			jQuery(this).bind('mousedown', jQuery.selectstart).css('position', 'relative');
		}
	);
};


/**
 * Interface Elements for jQuery
 * Slider
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

jQuery.iSlider = {
	tabindex : 1,
	set : function (values)
	{
		var values = values;
		return this.each(
			function()
			{
				this.slideCfg.sliders.each(
					function (key)
					{
						jQuery.iSlider.dragmoveBy(this,values[key]);
					}
				);
			}
		);
	},

	get : function()
	{
		var values = [];
		this.each(
			function(slider)
			{
				if (this.isSlider) {
					values[slider] = [];
					var elm = this;
					var sizes = jQuery.iUtil.getSize(this);
					this.slideCfg.sliders.each(
						function (key)
						{
							var x = this.offsetLeft;
							var y = this.offsetTop;
							xproc = parseInt(x * 100 / (sizes.w - this.offsetWidth));
							yproc = parseInt(y * 100 / (sizes.h - this.offsetHeight));
							values[slider][key] = [xproc||0, yproc||0, x||0, y||0];
						}
					);
				}
			}
		);
		return values;
	},

	modifyContainer : function (elm)
	{
		elm.dragCfg.containerMaxx = elm.dragCfg.cont.w - elm.dragCfg.oC.wb;
		elm.dragCfg.containerMaxy = elm.dragCfg.cont.h - elm.dragCfg.oC.hb;
		if (elm.SliderContainer.slideCfg.restricted ) {
			next = elm.SliderContainer.slideCfg.sliders.get(elm.SliderIteration+1);
			if (next) {
				elm.dragCfg.cont.w = (parseInt(jQuery(next).css('left'))||0) + elm.dragCfg.oC.wb;
				elm.dragCfg.cont.h = (parseInt(jQuery(next).css('top'))||0) + elm.dragCfg.oC.hb;
			}
			prev = elm.SliderContainer.slideCfg.sliders.get(elm.SliderIteration-1);
			if (prev) {
				var prevLeft = parseInt(jQuery(prev).css('left'))||0;
				var prevTop = parseInt(jQuery(prev).css('left'))||0;
				elm.dragCfg.cont.x += prevLeft;
				elm.dragCfg.cont.y += prevTop;
				elm.dragCfg.cont.w -= prevLeft;
				elm.dragCfg.cont.h -= prevTop;
			}
		}
		elm.dragCfg.maxx = elm.dragCfg.cont.w - elm.dragCfg.oC.wb;
		elm.dragCfg.maxy = elm.dragCfg.cont.h - elm.dragCfg.oC.hb;
		if(elm.dragCfg.fractions) {
			elm.dragCfg.gx = ((elm.dragCfg.cont.w - elm.dragCfg.oC.wb)/elm.dragCfg.fractions) || 1;
			elm.dragCfg.gy = ((elm.dragCfg.cont.h - elm.dragCfg.oC.hb)/elm.dragCfg.fractions) || 1;
			elm.dragCfg.fracW = elm.dragCfg.maxx / elm.dragCfg.fractions;
			elm.dragCfg.fracH = elm.dragCfg.maxy / elm.dragCfg.fractions;
		}

		elm.dragCfg.cont.dx = elm.dragCfg.cont.x - elm.dragCfg.oR.x;
		elm.dragCfg.cont.dy = elm.dragCfg.cont.y - elm.dragCfg.oR.y;

		jQuery.iDrag.helper.css('cursor', 'default');
	},

	onSlide : function(elm, x, y)
	{
		if (elm.dragCfg.fractions) {
				xfrac = parseInt(x/elm.dragCfg.fracW);
				xproc = xfrac * 100 / elm.dragCfg.fractions;
				yfrac = parseInt(y/elm.dragCfg.fracH);
				yproc = yfrac * 100 / elm.dragCfg.fractions;
		} else {
			xproc = parseInt(x * 100 / elm.dragCfg.containerMaxx);
			yproc = parseInt(y * 100 / elm.dragCfg.containerMaxy);
		}
		elm.dragCfg.lastSi = [xproc||0, yproc||0, x||0, y||0];
		if (elm.dragCfg.onSlide)
			elm.dragCfg.onSlide.apply(elm, elm.dragCfg.lastSi);
	},

	dragmoveByKey : function (event)
	{
		pressedKey = event.charCode || event.keyCode || -1;

		switch (pressedKey)
		{
			//end
			case 35:
				jQuery.iSlider.dragmoveBy(this.dragElem, [2000, 2000] );
			break;
			//home
			case 36:
				jQuery.iSlider.dragmoveBy(this.dragElem, [-2000, -2000] );
			break;
			//left
			case 37:
				jQuery.iSlider.dragmoveBy(this.dragElem, [-this.dragElem.dragCfg.gx||-1, 0] );
			break;
			//up
			case 38:
				jQuery.iSlider.dragmoveBy(this.dragElem, [0, -this.dragElem.dragCfg.gy||-1] );
			break;
			//right
			case 39:
				jQuery.iSlider.dragmoveBy(this.dragElem, [this.dragElem.dragCfg.gx||1, 0] );
			break;
			//down;
			case 40:
				jQuery.iDrag.dragmoveBy(this.dragElem, [0, this.dragElem.dragCfg.gy||1] );
			break;
		}
	},

	dragmoveBy : function (elm, position)
	{
		if (!elm.dragCfg) {
			return;
		}

		elm.dragCfg.oC = jQuery.extend(
			jQuery.iUtil.getPosition(elm),
			jQuery.iUtil.getSize(elm)
		);

		elm.dragCfg.oR = {
			x : parseInt(jQuery.css(elm, 'left'))||0,
			y : parseInt(jQuery.css(elm, 'top'))||0
		};

		elm.dragCfg.oP = jQuery.css(elm, 'position');
		if (elm.dragCfg.oP != 'relative' && elm.dragCfg.oP != 'absolute') {
			elm.style.position = 'relative';
		}

		jQuery.iDrag.getContainment(elm);
		jQuery.iSlider.modifyContainer(elm);

		dx = parseInt(position[0]) || 0;
		dy = parseInt(position[1]) || 0;

		nx = elm.dragCfg.oR.x + dx;
		ny = elm.dragCfg.oR.y + dy;
		if(elm.dragCfg.fractions) {
			newCoords = jQuery.iDrag.snapToGrid.apply(elm, [nx, ny, dx, dy]);
			if (newCoords.constructor == Object) {
				dx = newCoords.dx;
				dy = newCoords.dy;
			}
			nx = elm.dragCfg.oR.x + dx;
			ny = elm.dragCfg.oR.y + dy;
		}

		newCoords = jQuery.iDrag.fitToContainer.apply(elm, [nx, ny, dx, dy]);
		if (newCoords && newCoords.constructor == Object) {
			dx = newCoords.dx;
			dy = newCoords.dy;
		}

		nx = elm.dragCfg.oR.x + dx;
		ny = elm.dragCfg.oR.y + dy;

		if (elm.dragCfg.si && (elm.dragCfg.onSlide || elm.dragCfg.onChange)) {
			jQuery.iSlider.onSlide(elm, nx, ny);
		}
		nx = !elm.dragCfg.axis || elm.dragCfg.axis == 'horizontally' ? nx : elm.dragCfg.oR.x||0;
		ny = !elm.dragCfg.axis || elm.dragCfg.axis == 'vertically' ? ny : elm.dragCfg.oR.y||0;
		elm.style.left = nx + 'px';
		elm.style.top = ny + 'px';
	},

	build : function(o) {
		return this.each(
			function()
			{
				if (this.isSlider == true || !o.accept || !jQuery.iUtil || !jQuery.iDrag || !jQuery.iDrop){
					return;
				}
				toDrag = jQuery(o.accept, this);
				if (toDrag.size() == 0) {
					return;
				}
				var params = {
					containment: 'parent',
					si : true,
					onSlide : o.onSlide && o.onSlide.constructor == Function ? o.onSlide : null,
					onChange : o.onChange && o.onChange.constructor == Function ? o.onChange : null,
					handle: this,
					opacity: o.opacity||false
				};
				if (o.fractions && parseInt(o.fractions)) {
					params.fractions = parseInt(o.fractions)||1;
					params.fractions = params.fractions > 0 ? params.fractions : 1;
				}
				if (toDrag.size() == 1)
					toDrag.Draggable(params);
				else {
					jQuery(toDrag.get(0)).Draggable(params);
					params.handle = null;
					toDrag.Draggable(params);
				}
				toDrag.keydown(jQuery.iSlider.dragmoveByKey);
				toDrag.attr('tabindex',jQuery.iSlider.tabindex++);

				this.isSlider = true;
				this.slideCfg = {};
				this.slideCfg.onslide = params.onslide;
				this.slideCfg.fractions = params.fractions;
				this.slideCfg.sliders = toDrag;
				this.slideCfg.restricted = o.restricted ? true : false;
				sliderEl = this;
				sliderEl.slideCfg.sliders.each(
					function(nr)
					{
						this.SliderIteration = nr;
						this.SliderContainer = sliderEl;
					}
				);
				if (o.values && o.values.constructor == Array) {
					for (i = o.values.length -1; i>=0;i--) {
						if (o.values[i].constructor == Array && o.values[i].length == 2) {
							el = this.slideCfg.sliders.get(i);
							if (el.tagName) {
								jQuery.iSlider.dragmoveBy(el, o.values[i]);
							}
						}
					}
				}
			}
		);
	}
};
jQuery.fn.extend(
	{
		/**
		 * Create a slider width options
		 *
		 * @name Slider
		 * @description Create a slider width options
		 * @param Hash hash A hash of parameters. All parameters are optional.
		 * @option Mixed accepts string to select slider indicators or DOMElement slider indicator
		 * @option Integer factions (optional) number of sgments to divide and snap slider
		 * @option Function onSlide (optional) A function to be executed whenever slider indicator it is moved
		 * @option Function onChanged (optional) A function to be executed whenever slider indicator was moved
		 * @option Array values (optional) Initial values for slider indicators
		 * @option Boolean restricted (optional) if true the slider indicator can not be moved beyond adjacent indicators
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		Slider : jQuery.iSlider.build,
		/**
		 * Set value/position for slider indicators
		 *
		 * @name SliderSetValues
		 * @description Set value/position for slider indicators
		 * @param Array values array width values for each indicator
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		SliderSetValues : jQuery.iSlider.set,
		/**
		 * Get value/position for slider indicators
		 *
		 * @name SliderSetValues
		 * @description Get value/position for slider indicators
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		SliderGetValues : jQuery.iSlider.get
	}
);


/**
 * Interface Elements for jQuery
 * Sortables
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

/**
 * Allows you to resort elements within a container by dragging and dropping. Requires
 * the Draggables and Droppables plugins. The container and each item inside the container
 * must have an ID. Sortables are especially useful for lists.
 *
 * @see Plugins/Interface/Draggable
 * @see Plugins/Interface/Droppable
 * @author Stefan Petre
 * @name Sortable
 * @cat Plugins/Interface
 * @param Hash options        A hash of options
 * @option String accept      The class name for items inside the container (mandatory)
 * @option String activeclass The class for the container when one of its items has started to move
 * @option String hoverclass  The class for the container when an acceptable item is inside it
 * @option String helperclass The helper is used to point to the place where the item will be
 *                            moved. This is the class for the helper.
 * @option Float opacity      Opacity (between 0 and 1) of the item while being dragged
 * @option Boolean ghosting   When true, the sortable is ghosted when dragged
 * @option String tolerance   Either 'pointer', 'intersect', or 'fit'. See Droppable for more details
 * @option Boolean fit        When true, sortable must be inside the container in order to drop
 * @option Integer fx         Duration for the effect applied to the sortable
 * @option Function onchange  Callback that gets called when the sortable list changed. It takes
 *                            an array of serialized elements
 * @option Boolean floats     True if the sorted elements are floated
 * @option String containment Use 'parent' to constrain the drag to the container
 * @option String axis        Use 'horizontally' or 'vertically' to constrain dragging to an axis
 * @option String handle      The jQuery selector that indicates the draggable handle
 * @option DOMElement handle  The node that indicates the draggable handle
 * @option Function onHover   Callback that is called when an acceptable item is dragged over the
 *                            container. Gets the hovering DOMElement as a parameter
 * @option Function onOut     Callback that is called when an acceptable item leaves the container.
 *                            Gets the leaving DOMElement as a parameter
 * @option Object cursorAt    The mouse cursor will be moved to the offset on the dragged item
 *                            indicated by the object, which takes "top", "bottom", "left", and
 *                            "right" keys
 * @option Function onStart   Callback function triggered when the dragging starts
 * @option Function onStop    Callback function triggered when the dragging stops
 * @example                   jQuery('ul').Sortable(
 *                            	{
 *                            		accept : 'sortableitem',
 *                            		activeclass : 'sortableactive',
 *                             		hoverclass : 'sortablehover',
 *                             		helperclass : 'sorthelper',
 *                             		opacity: 	0.5,
 *                             		fit :	false
 *                             	}
 *                             )
 */

jQuery.iSort = {
	changed : [],
	collected : {},
	helper : false,
	inFrontOf: null,

	start : function ()
	{
		if (jQuery.iDrag.dragged == null) {
			return;
		}
		var shs, margins,c, cs;

		jQuery.iSort.helper.get(0).className = jQuery.iDrag.dragged.dragCfg.hpc;
		shs = jQuery.iSort.helper.get(0).style;
		shs.display = 'block';
		jQuery.iSort.helper.oC = jQuery.extend(
			jQuery.iUtil.getPosition(jQuery.iSort.helper.get(0)),
			jQuery.iUtil.getSize(jQuery.iSort.helper.get(0))
		);

		shs.width = jQuery.iDrag.dragged.dragCfg.oC.wb + 'px';
		shs.height = jQuery.iDrag.dragged.dragCfg.oC.hb + 'px';
		//shs.cssFloat = jQuery.iDrag.dragged.dragCfg.oF;
		margins = jQuery.iUtil.getMargins(jQuery.iDrag.dragged);
		shs.marginTop = margins.t;
		shs.marginRight = margins.r;
		shs.marginBottom = margins.b;
		shs.marginLeft = margins.l;
		if (jQuery.iDrag.dragged.dragCfg.ghosting == true) {
			c = jQuery.iDrag.dragged.cloneNode(true);
			cs = c.style;
			cs.marginTop = '0px';
			cs.marginRight = '0px';
			cs.marginBottom = '0px';
			cs.marginLeft = '0px';
			cs.display = 'block';
			jQuery.iSort.helper.empty().append(c);
		}
		jQuery(jQuery.iDrag.dragged).after(jQuery.iSort.helper.get(0));
		jQuery.iDrag.dragged.style.display = 'none';
	},

	check : function (e)
	{
		if (!e.dragCfg.so && jQuery.iDrop.overzone.sortable) {
			if (e.dragCfg.onStop)
				e.dragCfg.onStop.apply(dragged);
			jQuery(e).css('position', e.dragCfg.initialPosition || e.dragCfg.oP);
			jQuery(e).DraggableDestroy();
			jQuery(jQuery.iDrop.overzone).SortableAddItem(e);
		}
		jQuery.iSort.helper.removeClass(e.dragCfg.hpc).html('&nbsp;');
		jQuery.iSort.inFrontOf = null;
		var shs = jQuery.iSort.helper.get(0).style;
		shs.display = 'none';
		jQuery.iSort.helper.after(e);
		if (e.dragCfg.fx > 0) {
			jQuery(e).fadeIn(e.dragCfg.fx);
		}
		jQuery('body').append(jQuery.iSort.helper.get(0));
		var ts = [];
		var fnc = false;
		for(var i=0; i<jQuery.iSort.changed.length; i++){
			var iEL = jQuery.iDrop.zones[jQuery.iSort.changed[i]].get(0);
			var id = jQuery.attr(iEL, 'id');
			var ser = jQuery.iSort.serialize(id);
			if (iEL.dropCfg.os != ser.hash) {
				iEL.dropCfg.os = ser.hash;
				if (fnc == false && iEL.dropCfg.onChange) {
					fnc = iEL.dropCfg.onChange;
				}
				ser.id = id;
				ts[ts.length] = ser;
			}
		}
		jQuery.iSort.changed = [];
		if (fnc != false && ts.length > 0) {
			fnc(ts);
		}
	},

	checkhover : function(e,o)
	{
		if (!jQuery.iDrag.dragged)
			return;
		var cur = false;
		var i = 0;
		if ( e.dropCfg.el.size() > 0) {
			for (i = e.dropCfg.el.size(); i >0; i--) {
				if (e.dropCfg.el.get(i-1) != jQuery.iDrag.dragged) {
					if (!e.sortCfg.floats) {
						if (
						(e.dropCfg.el.get(i-1).pos.y + e.dropCfg.el.get(i-1).pos.hb/2) > jQuery.iDrag.dragged.dragCfg.ny
						) {
							cur = e.dropCfg.el.get(i-1);
						} else {
							break;
						}
					} else {
						if (
						(e.dropCfg.el.get(i-1).pos.x + e.dropCfg.el.get(i-1).pos.wb/2) > jQuery.iDrag.dragged.dragCfg.nx &&
						(e.dropCfg.el.get(i-1).pos.y + e.dropCfg.el.get(i-1).pos.hb/2) > jQuery.iDrag.dragged.dragCfg.ny
						) {
							cur = e.dropCfg.el.get(i-1);
						}
					}
				}
			}
		}
		//helpos = jQuery.iUtil.getPos(jQuery.iSort.helper.get(0));
		if (cur && jQuery.iSort.inFrontOf != cur) {
			jQuery.iSort.inFrontOf = cur;
			jQuery(cur).before(jQuery.iSort.helper.get(0));
		} else if(!cur && (jQuery.iSort.inFrontOf != null || jQuery.iSort.helper.get(0).parentNode != e) ) {
			jQuery.iSort.inFrontOf = null;
			jQuery(e).append(jQuery.iSort.helper.get(0));
		}
		jQuery.iSort.helper.get(0).style.display = 'block';
	},

	measure : function (e)
	{
		if (jQuery.iDrag.dragged == null) {
			return;
		}
		e.dropCfg.el.each (
			function ()
			{
				this.pos = jQuery.extend(
					jQuery.iUtil.getSizeLite(this),
					jQuery.iUtil.getPositionLite(this)
				);
			}
		);
	},

	serialize : function(s)
	{
		var i;
		var h = '';
		var o = {};
		if (s) {
			if (jQuery.iSort.collected[s] ) {
				o[s] = [];
				jQuery('#' + s + ' .' + jQuery.iSort.collected[s]).each(
					function ()
					{
						if (h.length > 0) {
							h += '&';
						}
						h += s + '[]=' + jQuery.attr(this,'id');
						o[s][o[s].length] = jQuery.attr(this,'id');
					}
				);
			} else {
				for ( a in s) {
					if (jQuery.iSort.collected[s[a]] ) {
						o[s[a]] = [];
						jQuery('#' + s[a] + ' .' + jQuery.iSort.collected[s[a]]).each(
							function ()
							{
								if (h.length > 0) {
									h += '&';
								}
								h += s[a] + '[]=' + jQuery.attr(this,'id');
								o[s[a]][o[s[a]].length] = jQuery.attr(this,'id');
							}
						);
					}
				}
			}
		} else {
			for ( i in jQuery.iSort.collected){
				o[i] = [];
				jQuery('#' + i + ' .' + jQuery.iSort.collected[i]).each(
					function ()
					{
						if (h.length > 0) {
							h += '&';
						}
						h += i + '[]=' + jQuery.attr(this,'id');
						o[i][o[i].length] = jQuery.attr(this,'id');
					}
				);
			}
		}
		return {hash:h, o:o};
	},

	addItem : function (e)
	{
		if ( !e.childNodes ) {
			return;
		}
		return this.each(
			function ()
			{
				if(!this.sortCfg || !jQuery(e).is('.' +  this.sortCfg.accept))
					jQuery(e).addClass(this.sortCfg.accept);
				jQuery(e).Draggable(this.sortCfg.dragCfg);
			}
		);
	},

	destroy: function()
	{
		return this.each(
			function()
			{
				jQuery('.' + this.sortCfg.accept).DraggableDestroy();
				jQuery(this).DroppableDestroy();
				this.sortCfg = null;
				this.isSortable = null;
			}
		);
	},

	build : function (o)
	{
		if (o.accept && jQuery.iUtil && jQuery.iDrag && jQuery.iDrop) {
			if (!jQuery.iSort.helper) {
				jQuery('body',document).append('<div id="sortHelper">&nbsp;</div>');
				jQuery.iSort.helper = jQuery('#sortHelper');
				jQuery.iSort.helper.get(0).style.display = 'none';
			}
			this.Droppable(
				{
					accept :  o.accept,
					activeclass : o.activeclass ? o.activeclass : false,
					hoverclass : o.hoverclass ? o.hoverclass : false,
					helperclass : o.helperclass ? o.helperclass : false,
					/*onDrop: function (drag, fx)
							{
								jQuery.iSort.helper.after(drag);
								if (fx > 0) {
									jQuery(drag).fadeIn(fx);
								}
							},*/
					onHover: o.onHover||o.onhover,
					onOut: o.onOut||o.onout,
					sortable : true,
					onChange : 	o.onChange||o.onchange,
					fx : o.fx ? o.fx : false,
					ghosting : o.ghosting ? true : false,
					tolerance: o.tolerance ? o.tolerance : 'intersect'
				}
			);

			return this.each(
				function()
				{
					var dragCfg = {
						revert : o.revert? true : false,
						zindex : 3000,
						opacity : o.opacity ? parseFloat(o.opacity) : false,
						hpc : o.helperclass ? o.helperclass : false,
						fx : o.fx ? o.fx : false,
						so : true,
						ghosting : o.ghosting ? true : false,
						handle: o.handle ? o.handle : null,
						containment: o.containment ? o.containment : null,
						onStart : o.onStart && o.onStart.constructor == Function ? o.onStart : false,
						onDrag : o.onDrag && o.onDrag.constructor == Function ? o.onDrag : false,
						onStop : o.onStop && o.onStop.constructor == Function ? o.onStop : false,
						axis : /vertically|horizontally/.test(o.axis) ? o.axis : false,
						snapDistance : o.snapDistance ? parseInt(o.snapDistance)||0 : false,
						cursorAt: o.cursorAt ? o.cursorAt : false
					};
					jQuery('.' + o.accept, this).Draggable(dragCfg);
					this.isSortable = true;
					this.sortCfg = {
						accept :  o.accept,
						revert : o.revert? true : false,
						zindex : 3000,
						opacity : o.opacity ? parseFloat(o.opacity) : false,
						hpc : o.helperclass ? o.helperclass : false,
						fx : o.fx ? o.fx : false,
						so : true,
						ghosting : o.ghosting ? true : false,
						handle: o.handle ? o.handle : null,
						containment: o.containment ? o.containment : null,
						floats: o.floats ? true : false,
						dragCfg : dragCfg
					}
				}
			);
		}
	}
};

jQuery.fn.extend(
	{
		Sortable : jQuery.iSort.build,
		/**
		 * A new item can be added to a sortable by adding it to the DOM and then adding it via
		 * SortableAddItem.
		 *
		 * @name SortableAddItem
		 * @param DOMElement elem A DOM Element to add to the sortable list
		 * @example jQuery('#sortable1').append('<li id="newitem">new item</li>')
		 *                         .SortableAddItem(jQuery("#new_item")[0])
		 * @type jQuery
		 * @cat Plugins/Interface
		 */
		SortableAddItem : jQuery.iSort.addItem,
		/**
		 * Destroy a sortable
		 *
		 * @name SortableDestroy
		 * @example jQuery('#sortable1').SortableDestroy();
		 * @type jQuery
		 * @cat Plugins/Interface
		 */
		SortableDestroy: jQuery.iSort.destroy
	}
);

/**
 * This function returns the hash and an object (can be used as arguments for $.post) for every
 * sortable in the page or specific sortables. The hash is based on the 'id' attributes of
 * container and items.
 *
 * @params String sortable The id of the sortable to serialize
 * @name $.SortSerialize
 * @type String
 * @cat Plugins/Interface
 */

jQuery.SortSerialize = jQuery.iSort.serialize;

/**
 * Interface Elements for jQuery
 * utility function
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

jQuery.iUtil = {
	getPosition : function(e)
	{
		var x = 0;
		var y = 0;
		var es = e.style;
		var restoreStyles = false;
		if (jQuery(e).css('display') == 'none') {
			var oldVisibility = es.visibility;
			var oldPosition = es.position;
			restoreStyles = true;
			es.visibility = 'hidden';
			es.display = 'block';
			es.position = 'absolute';
		}
		var el = e;
		while (el){
			x += el.offsetLeft + (el.currentStyle && !jQuery.browser.opera ?parseInt(el.currentStyle.borderLeftWidth)||0:0);
			y += el.offsetTop + (el.currentStyle && !jQuery.browser.opera ?parseInt(el.currentStyle.borderTopWidth)||0:0);
			el = el.offsetParent;
		}
		el = e;
		while (el && el.tagName  && el.tagName.toLowerCase() != 'body')
		{
			x -= el.scrollLeft||0;
			y -= el.scrollTop||0;
			el = el.parentNode;
		}
		if (restoreStyles == true) {
			es.display = 'none';
			es.position = oldPosition;
			es.visibility = oldVisibility;
		}
		return {x:x, y:y};
	},
	getPositionLite : function(el)
	{
		var x = 0, y = 0;
		while(el) {
			x += el.offsetLeft || 0;
			y += el.offsetTop || 0;
			el = el.offsetParent;
		}
		return {x:x, y:y};
	},
	getSize : function(e)
	{
		var w = jQuery.css(e,'width');
		var h = jQuery.css(e,'height');
		var wb = 0;
		var hb = 0;
		var es = e.style;
		if (jQuery(e).css('display') != 'none') {
			wb = e.offsetWidth;
			hb = e.offsetHeight;
		} else {
			var oldVisibility = es.visibility;
			var oldPosition = es.position;
			es.visibility = 'hidden';
			es.display = 'block';
			es.position = 'absolute';
			wb = e.offsetWidth;
			hb = e.offsetHeight;
			es.display = 'none';
			es.position = oldPosition;
			es.visibility = oldVisibility;
		}
		return {w:w, h:h, wb:wb, hb:hb};
	},
	getSizeLite : function(el)
	{
		return {
			wb:el.offsetWidth||0,
			hb:el.offsetHeight||0
		};
	},
	getClient : function(e)
	{
		var h, w, de;
		if (e) {
			w = e.clientWidth;
			h = e.clientHeight;
		} else {
			de = document.documentElement;
			w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
			h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		}
		return {w:w,h:h};
	},
	getScroll : function (e)
	{
		var t=0, l=0, w=0, h=0, iw=0, ih=0;
		if (e && e.nodeName.toLowerCase() != 'body') {
			t = e.scrollTop;
			l = e.scrollLeft;
			w = e.scrollWidth;
			h = e.scrollHeight;
			iw = 0;
			ih = 0;
		} else  {
			if (document.documentElement) {
				t = document.documentElement.scrollTop;
				l = document.documentElement.scrollLeft;
				w = document.documentElement.scrollWidth;
				h = document.documentElement.scrollHeight;
			} else if (document.body) {
				t = document.body.scrollTop;
				l = document.body.scrollLeft;
				w = document.body.scrollWidth;
				h = document.body.scrollHeight;
			}
			iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
			ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
		}
		return { t: t, l: l, w: w, h: h, iw: iw, ih: ih };
	},
	getMargins : function(e, toInteger)
	{
		var el = jQuery(e);
		var t = el.css('marginTop') || '';
		var r = el.css('marginRight') || '';
		var b = el.css('marginBottom') || '';
		var l = el.css('marginLeft') || '';
		if (toInteger)
			return {
				t: parseInt(t)||0,
				r: parseInt(r)||0,
				b: parseInt(b)||0,
				l: parseInt(l)
			};
		else
			return {t: t, r: r,	b: b, l: l};
	},
	getPadding : function(e, toInteger)
	{
		var el = jQuery(e);
		var t = el.css('paddingTop') || '';
		var r = el.css('paddingRight') || '';
		var b = el.css('paddingBottom') || '';
		var l = el.css('paddingLeft') || '';
		if (toInteger)
			return {
				t: parseInt(t)||0,
				r: parseInt(r)||0,
				b: parseInt(b)||0,
				l: parseInt(l)
			};
		else
			return {t: t, r: r,	b: b, l: l};
	},
	getBorder : function(e, toInteger)
	{
		var el = jQuery(e);
		var t = el.css('borderTopWidth') || '';
		var r = el.css('borderRightWidth') || '';
		var b = el.css('borderBottomWidth') || '';
		var l = el.css('borderLeftWidth') || '';
		if (toInteger)
			return {
				t: parseInt(t)||0,
				r: parseInt(r)||0,
				b: parseInt(b)||0,
				l: parseInt(l)||0
			};
		else
			return {t: t, r: r,	b: b, l: l};
	},
	getPointer : function(event)
	{
		var x = event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)) || 0;
		var y = event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop)) || 0;
		return {x:x, y:y};
	},
	traverseDOM : function(nodeEl, func)
	{
		func(nodeEl);
		nodeEl = nodeEl.firstChild;
		while(nodeEl){
			jQuery.iUtil.traverseDOM(nodeEl, func);
			nodeEl = nodeEl.nextSibling;
		}
	},
	purgeEvents : function(nodeEl)
	{
		jQuery.iUtil.traverseDOM(
			nodeEl,
			function(el)
			{
				for(var attr in el){
					if(typeof el[attr] === 'function') {
						el[attr] = null;
					}
				}
			}
		);
	},
	centerEl : function(el, axis)
	{
		var clientScroll = jQuery.iUtil.getScroll();
		var windowSize = jQuery.iUtil.getSize(el);
		if (!axis || axis == 'vertically')
			jQuery(el).css(
				{
					top: clientScroll.t + ((Math.max(clientScroll.h,clientScroll.ih) - clientScroll.t - windowSize.hb)/2) + 'px'
				}
			);
		if (!axis || axis == 'horizontally')
			jQuery(el).css(
				{
					left:	clientScroll.l + ((Math.max(clientScroll.w,clientScroll.iw) - clientScroll.l - windowSize.wb)/2) + 'px'
				}
			);
	},
	fixPNG : function (el, emptyGIF) {
		var images = jQuery('img[@src*="png"]', el||document), png;
		images.each( function() {
			png = this.src;
			this.src = emptyGIF;
			this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + png + "')";
		});
	}
};

// Helper function to support older browsers!
[].indexOf || (Array.prototype.indexOf = function(v, n){
	n = (n == null) ? 0 : n;
	var m = this.length;
	for (var i=n; i<m; i++)
		if (this[i] == v)
			return i;
	return -1;
});


/**
 * Interface Elements for jQuery
 * Easing formulas
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */

/**
 * Starting with jQuery 1.1  the fx function accepts easing formulas that can be used with .animation() and most of FX plugins from Interface. The object can be extended to accept new easing formulas
 */

 jQuery.extend({
	/**
	 *
	 * @param Integer p period step in animation
	 * @param Integer n current time
	 * @param Mixed firstNum begin value
	 * @param Mixed delta change in
	 * @param Integer duration duration
	 */
	easing :  {
		linear: function(p, n, firstNum, delta, duration) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * delta + firstNum;
		},

		easein: function(p, n, firstNum, delta, duration) {
			return delta*(n/=duration)*n*n + firstNum;
		},

		easeout: function(p, n, firstNum, delta, duration) {
			return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum;
		},

		easeboth: function(p, n, firstNum, delta, duration) {
			if ((n/=duration/2) < 1)
				return delta/2*n*n*n*n + firstNum;
				return -delta/2 * ((n-=2)*n*n*n - 2) + firstNum;
		},

		bounceout: function(p, n, firstNum, delta, duration) {
			if ((n/=duration) < (1/2.75)) {
				return delta*(7.5625*n*n) + firstNum;
			} else if (n < (2/2.75)) {
				return delta*(7.5625*(n-=(1.5/2.75))*n + .75) + firstNum;
			} else if (n < (2.5/2.75)) {
				return delta*(7.5625*(n-=(2.25/2.75))*n + .9375) + firstNum;
			} else {
				return delta*(7.5625*(n-=(2.625/2.75))*n + .984375) + firstNum;
			}
		},

		bouncein: function(p, n, firstNum, delta, duration) {
			if (jQuery.easing.bounceout)
				return delta - jQuery.easing.bounceout (p, duration - n, 0, delta, duration) + firstNum;
			return firstNum + delta;
		},

		bounceboth: function(p, n, firstNum, delta, duration) {
			if (jQuery.easing.bouncein && jQuery.easing.bounceout)
				if (n < duration/2)
					return jQuery.easing.bouncein(p, n*2, 0, delta, duration) * .5 + firstNum;
				return jQuery.easing.bounceout(p, n*2-duration, 0, delta, duration) * .5 + delta*.5 + firstNum;
			return firstNum + delta;
		},

		elasticin: function(p, n, firstNum, delta, duration) {
			var a, s;
   			if (n == 0)
   				return firstNum;
   			if ((n/=duration)==1)
   				return firstNum+delta;
   			a = delta * 0.3;
   			p=duration*.3;
			if (a < Math.abs(delta)) {
				a=delta;
				s=p/4;
			} else {
				s = p/(2*Math.PI) * Math.asin (delta/a);
			}
			return -(a*Math.pow(2,10*(n-=1)) * Math.sin( (n*duration-s)*(2*Math.PI)/p )) + firstNum;
		},

		elasticout:function(p, n, firstNum, delta, duration) {
			var a, s;
			if (n==0)
				return firstNum;
			if ((n/=duration/2)==2)
				return firstNum + delta;
   			a = delta * 0.3;
   			p=duration*.3;
			if (a < Math.abs(delta)){
				a = delta;
				s=p/4;
			} else {
				s = p/(2*Math.PI) * Math.asin (delta/a);
			}
			return a*Math.pow(2,-10*n) * Math.sin( (n*duration-s)*(2*Math.PI)/p ) + delta + firstNum;
		},

		elasticboth: function(p, n, firstNum, delta, duration) {
			var a, s;
			if (n==0)
				return firstNum;
			if ((n/=duration/2)==2)
				return firstNum + delta;
   			a = delta * 0.3;
   			p=duration*.3;
			if (a < Math.abs(delta)){
				a = delta;
				s=p/4;
			} else {
				s = p/(2*Math.PI) * Math.asin (delta/a);
			}
			if (n < 1) {
				return -.5*(a*Math.pow(2,10*(n-=1)) * Math.sin( (n*duration-s)*(2*Math.PI)/p )) + firstNum;
			}
			return a*Math.pow(2,-10*(n-=1)) * Math.sin( (n*duration-s)*(2*Math.PI)/p )*.5 + delta + firstNum;
		}
	}
});


/**
 * Interface Elements for jQuery
 * Draggable
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */

/**
 * Create a draggable element with a number of advanced options including callback, Google Maps type draggables,
 * reversion, ghosting, and grid dragging.
 *
 * @name Draggable
 * @descr Creates draggable elements that can be moved across the page.
 * @param Hash hash A hash of parameters. All parameters are optional.
 * @option String handle (optional) The jQuery selector matching the handle that starts the draggable
 * @option DOMElement handle (optional) The DOM Element of the handle that starts the draggable
 * @option Boolean revert (optional) When true, on stop-drag the element returns to initial position
 * @option Boolean ghosting (optional) When true, a copy of the element is moved
 * @option Integer zIndex (optional) zIndex depth for the element while it is being dragged
 * @option Float opacity (optional) A number between 0 and 1 that indicates the opacity of the element while being dragged
 * @option Integer grid (optional) (optional) A number of pixels indicating the grid that the element should snap to
 * @option Array grid (optional) A number of x-pixels and y-pixels indicating the grid that the element should snap to
 * @option Integer fx (optional) Duration for the effect (like ghosting or revert) applied to the draggable
 * @option String containment (optional) Define the zone where the draggable can be moved. 'parent' moves it inside parent
 *                           element, while 'document' prevents it from leaving the document and forcing additional
 *                           scrolling
 * @option Array containment An 4-element array (left, top, width, height) indicating the containment of the element
 * @option String axis (optional) Set an axis: vertical (with 'vertically') or horizontal (with 'horizontally')
 * @option Function onStart (optional) Callback function triggered when the dragging starts
 * @option Function onStop (optional) Callback function triggered when the dragging stops
 * @option Function onChange (optional) Callback function triggered when the dragging stop *and* the element was moved at least
 *                          one pixel
 * @option Function onDrag (optional) Callback function triggered while the element is dragged. Receives two parameters: x and y
 *                        coordinates. You can return an object with new coordinates {x: x, y: y} so this way you can
 *                        interact with the dragging process (for instance, build your containment)
 * @option Boolean insideParent Forces the element to remain inside its parent when being dragged (like Google Maps)
 * @option Integer snapDistance (optional) The element is not moved unless it is dragged more than snapDistance. You can prevent
 *                             accidental dragging and keep regular clicking enabled (for links or form elements,
 *                             for instance)
 * @option Object cursorAt (optional) The dragged element is moved to the cursor position with the offset specified. Accepts value
 *                        for top, left, right and bottom offset. Basically, this forces the cursor to a particular
 *                        position during the entire drag operation.
 * @option Boolean autoSize (optional) When true, the drag helper is resized to its content, instead of the dragged element's sizes
 * @option String frameClass (optional) When is set the cloned element is hidden so only a frame is dragged
 * @type jQuery
 * @cat Plugins/Interface
 * @author Stefan Petre
 */

jQuery.iDrag =	{
	helper : null,
	dragged: null,
	destroy : function()
	{
		return this.each(
			function ()
			{
				if (this.isDraggable) {
					this.dragCfg.dhe.unbind('mousedown', jQuery.iDrag.draginit);
					this.dragCfg = null;
					this.isDraggable = false;
					if(jQuery.browser.msie) {
						this.unselectable = "off";
					} else {
						this.style.MozUserSelect = '';
						this.style.KhtmlUserSelect = '';
						this.style.userSelect = '';
					}
				}
			}
		);
	},
	draginit : function (e)
	{
		if (jQuery.iDrag.dragged != null) {
			jQuery.iDrag.dragstop(e);
			return false;
		}
		var elm = this.dragElem;
		jQuery(document)
			.bind('mousemove', jQuery.iDrag.dragmove)
			.bind('mouseup', jQuery.iDrag.dragstop);
		elm.dragCfg.pointer = jQuery.iUtil.getPointer(e);
		elm.dragCfg.currentPointer = elm.dragCfg.pointer;
		elm.dragCfg.init = false;
		elm.dragCfg.fromHandler = this != this.dragElem;
		jQuery.iDrag.dragged = elm;
		if (elm.dragCfg.si && this != this.dragElem) {
				parentPos = jQuery.iUtil.getPosition(elm.parentNode);
				sliderSize = jQuery.iUtil.getSize(elm);
				sliderPos = {
					x : parseInt(jQuery.css(elm,'left')) || 0,
					y : parseInt(jQuery.css(elm,'top')) || 0
				};
				dx = elm.dragCfg.currentPointer.x - parentPos.x - sliderSize.wb/2 - sliderPos.x;
				dy = elm.dragCfg.currentPointer.y - parentPos.y - sliderSize.hb/2 - sliderPos.y;
				jQuery.iSlider.dragmoveBy(elm, [dx, dy]);
		}
		return jQuery.selectKeyHelper||false;
	},

	dragstart : function(e)
	{
		var elm = jQuery.iDrag.dragged;
		elm.dragCfg.init = true;

		var dEs = elm.style;

		elm.dragCfg.oD = jQuery.css(elm,'display');
		elm.dragCfg.oP = jQuery.css(elm,'position');
		if (!elm.dragCfg.initialPosition)
			elm.dragCfg.initialPosition = elm.dragCfg.oP;

		elm.dragCfg.oR = {
			x : parseInt(jQuery.css(elm,'left')) || 0,
			y : parseInt(jQuery.css(elm,'top')) || 0
		};
		elm.dragCfg.diffX = 0;
		elm.dragCfg.diffY = 0;
		if (jQuery.browser.msie) {
			var oldBorder = jQuery.iUtil.getBorder(elm, true);
			elm.dragCfg.diffX = oldBorder.l||0;
			elm.dragCfg.diffY = oldBorder.t||0;
		}

		elm.dragCfg.oC = jQuery.extend(
			jQuery.iUtil.getPosition(elm),
			jQuery.iUtil.getSize(elm)
		);
		if (elm.dragCfg.oP != 'relative' && elm.dragCfg.oP != 'absolute') {
			dEs.position = 'relative';
		}

		jQuery.iDrag.helper.empty();
		var clonedEl = elm.cloneNode(true);

		jQuery(clonedEl).css(
			{
				display:	'block',
				left:		'0px',
				top: 		'0px'
			}
		);
		clonedEl.style.marginTop = '0';
		clonedEl.style.marginRight = '0';
		clonedEl.style.marginBottom = '0';
		clonedEl.style.marginLeft = '0';
		jQuery.iDrag.helper.append(clonedEl);

		var dhs = jQuery.iDrag.helper.get(0).style;

		if (elm.dragCfg.autoSize) {
			dhs.width = 'auto';
			dhs.height = 'auto';
		} else {
			dhs.height = elm.dragCfg.oC.hb + 'px';
			dhs.width = elm.dragCfg.oC.wb + 'px';
		}

		dhs.display = 'block';
		dhs.marginTop = '0px';
		dhs.marginRight = '0px';
		dhs.marginBottom = '0px';
		dhs.marginLeft = '0px';

		//remeasure the clone to check if the size was changed by user's functions
		jQuery.extend(
			elm.dragCfg.oC,
			jQuery.iUtil.getSize(clonedEl)
		);

		if (elm.dragCfg.cursorAt) {
			if (elm.dragCfg.cursorAt.left) {
				elm.dragCfg.oR.x += elm.dragCfg.pointer.x - elm.dragCfg.oC.x - elm.dragCfg.cursorAt.left;
				elm.dragCfg.oC.x = elm.dragCfg.pointer.x - elm.dragCfg.cursorAt.left;
			}
			if (elm.dragCfg.cursorAt.top) {
				elm.dragCfg.oR.y += elm.dragCfg.pointer.y - elm.dragCfg.oC.y - elm.dragCfg.cursorAt.top;
				elm.dragCfg.oC.y = elm.dragCfg.pointer.y - elm.dragCfg.cursorAt.top;
			}
			if (elm.dragCfg.cursorAt.right) {
				elm.dragCfg.oR.x += elm.dragCfg.pointer.x - elm.dragCfg.oC.x -elm.dragCfg.oC.hb + elm.dragCfg.cursorAt.right;
				elm.dragCfg.oC.x = elm.dragCfg.pointer.x - elm.dragCfg.oC.wb + elm.dragCfg.cursorAt.right;
			}
			if (elm.dragCfg.cursorAt.bottom) {
				elm.dragCfg.oR.y += elm.dragCfg.pointer.y - elm.dragCfg.oC.y - elm.dragCfg.oC.hb + elm.dragCfg.cursorAt.bottom;
				elm.dragCfg.oC.y = elm.dragCfg.pointer.y - elm.dragCfg.oC.hb + elm.dragCfg.cursorAt.bottom;
			}
		}
		elm.dragCfg.nx = elm.dragCfg.oR.x;
		elm.dragCfg.ny = elm.dragCfg.oR.y;

		if (elm.dragCfg.insideParent || elm.dragCfg.containment == 'parent') {
			parentBorders = jQuery.iUtil.getBorder(elm.parentNode, true);
			elm.dragCfg.oC.x = elm.offsetLeft + (jQuery.browser.msie ? 0 : jQuery.browser.opera ? -parentBorders.l : parentBorders.l);
			elm.dragCfg.oC.y = elm.offsetTop + (jQuery.browser.msie ? 0 : jQuery.browser.opera ? -parentBorders.t : parentBorders.t);
			jQuery(elm.parentNode).append(jQuery.iDrag.helper.get(0));
		}
		if (elm.dragCfg.containment) {
			jQuery.iDrag.getContainment(elm);
			elm.dragCfg.onDragModifier.containment = jQuery.iDrag.fitToContainer;
		}

		if (elm.dragCfg.si) {
			jQuery.iSlider.modifyContainer(elm);
		}

		dhs.left = elm.dragCfg.oC.x - elm.dragCfg.diffX + 'px';
		dhs.top = elm.dragCfg.oC.y - elm.dragCfg.diffY + 'px';
		//resize the helper to fit the clone
		dhs.width = elm.dragCfg.oC.wb + 'px';
		dhs.height = elm.dragCfg.oC.hb + 'px';

		jQuery.iDrag.dragged.dragCfg.prot = false;

		if (elm.dragCfg.gx) {
			elm.dragCfg.onDragModifier.grid = jQuery.iDrag.snapToGrid;
		}
		if (elm.dragCfg.zIndex != false) {
			jQuery.iDrag.helper.css('zIndex', elm.dragCfg.zIndex);
		}
		if (elm.dragCfg.opacity) {
			jQuery.iDrag.helper.css('opacity', elm.dragCfg.opacity);
			if (window.ActiveXObject) {
				jQuery.iDrag.helper.css('filter', 'alpha(opacity=' + elm.dragCfg.opacity * 100 + ')');
			}
		}

		if(elm.dragCfg.frameClass) {
			jQuery.iDrag.helper.addClass(elm.dragCfg.frameClass);
			jQuery.iDrag.helper.get(0).firstChild.style.display = 'none';
		}
		if (elm.dragCfg.onStart)
			elm.dragCfg.onStart.apply(elm, [clonedEl, elm.dragCfg.oR.x, elm.dragCfg.oR.y]);
		if (jQuery.iDrop && jQuery.iDrop.count > 0 ){
			jQuery.iDrop.highlight(elm);
		}
		if (elm.dragCfg.ghosting == false) {
			dEs.display = 'none';
		}
		return false;
	},

	getContainment : function(elm)
	{
		if (elm.dragCfg.containment.constructor == String) {
			if (elm.dragCfg.containment == 'parent') {
				elm.dragCfg.cont = jQuery.extend(
					{x:0,y:0},
					jQuery.iUtil.getSize(elm.parentNode)
				);
				var contBorders = jQuery.iUtil.getBorder(elm.parentNode, true);
				elm.dragCfg.cont.w = elm.dragCfg.cont.wb - contBorders.l - contBorders.r;
				elm.dragCfg.cont.h = elm.dragCfg.cont.hb - contBorders.t - contBorders.b;
			} else if (elm.dragCfg.containment == 'document') {
				var clnt = jQuery.iUtil.getClient();
				elm.dragCfg.cont = {
					x : 0,
					y : 0,
					w : clnt.w,
					h : clnt.h
				};
			}
		} else if (elm.dragCfg.containment.constructor == Array) {
			elm.dragCfg.cont = {
				x : parseInt(elm.dragCfg.containment[0])||0,
				y : parseInt(elm.dragCfg.containment[1])||0,
				w : parseInt(elm.dragCfg.containment[2])||0,
				h : parseInt(elm.dragCfg.containment[3])||0
			};
		}
		elm.dragCfg.cont.dx = elm.dragCfg.cont.x - elm.dragCfg.oC.x;
		elm.dragCfg.cont.dy = elm.dragCfg.cont.y - elm.dragCfg.oC.y;
	},

	hidehelper : function(dragged)
	{
		if (dragged.dragCfg.insideParent || dragged.dragCfg.containment == 'parent') {
			jQuery('body', document).append(jQuery.iDrag.helper.get(0));
		}
		jQuery.iDrag.helper.empty().hide().css('opacity', 1);
		if (window.ActiveXObject) {
			jQuery.iDrag.helper.css('filter', 'alpha(opacity=100)');
		}
	},

	dragstop : function(e)
	{

		jQuery(document)
			.unbind('mousemove', jQuery.iDrag.dragmove)
			.unbind('mouseup', jQuery.iDrag.dragstop);

		if (jQuery.iDrag.dragged == null) {
			return;
		}
		var dragged = jQuery.iDrag.dragged;

		jQuery.iDrag.dragged = null;

		if (dragged.dragCfg.init == false) {
			return false;
		}
		if (dragged.dragCfg.so == true) {
			jQuery(dragged).css('position', dragged.dragCfg.oP);
		}
		var dEs = dragged.style;

		if (dragged.si) {
			jQuery.iDrag.helper.css('cursor', 'move');
		}
		if(dragged.dragCfg.frameClass) {
			jQuery.iDrag.helper.removeClass(dragged.dragCfg.frameClass);
		}

		if (dragged.dragCfg.revert == false) {
			if (dragged.dragCfg.fx > 0) {
				if (!dragged.dragCfg.axis || dragged.dragCfg.axis == 'horizontally') {
					var x = new jQuery.fx(dragged,{duration:dragged.dragCfg.fx}, 'left');
					x.custom(dragged.dragCfg.oR.x,dragged.dragCfg.nRx);
				}
				if (!dragged.dragCfg.axis || dragged.dragCfg.axis == 'vertically') {
					var y = new jQuery.fx(dragged,{duration:dragged.dragCfg.fx}, 'top');
					y.custom(dragged.dragCfg.oR.y,dragged.dragCfg.nRy);
				}
			} else {
				if (!dragged.dragCfg.axis || dragged.dragCfg.axis == 'horizontally')
					dragged.style.left = dragged.dragCfg.nRx + 'px';
				if (!dragged.dragCfg.axis || dragged.dragCfg.axis == 'vertically')
					dragged.style.top = dragged.dragCfg.nRy + 'px';
			}
			jQuery.iDrag.hidehelper(dragged);
			if (dragged.dragCfg.ghosting == false) {
				jQuery(dragged).css('display', dragged.dragCfg.oD);
			}
		} else if (dragged.dragCfg.fx > 0) {
			dragged.dragCfg.prot = true;
			var dh = false;
			if(jQuery.iDrop && jQuery.iSort && dragged.dragCfg.so) {
				dh = jQuery.iUtil.getPosition(jQuery.iSort.helper.get(0));
			}
			jQuery.iDrag.helper.animate(
				{
					left : dh ? dh.x : dragged.dragCfg.oC.x,
					top : dh ? dh.y : dragged.dragCfg.oC.y
				},
				dragged.dragCfg.fx,
				function()
				{
					dragged.dragCfg.prot = false;
					if (dragged.dragCfg.ghosting == false) {
						dragged.style.display = dragged.dragCfg.oD;
					}
					jQuery.iDrag.hidehelper(dragged);
				}
			);
		} else {
			jQuery.iDrag.hidehelper(dragged);
			if (dragged.dragCfg.ghosting == false) {
				jQuery(dragged).css('display', dragged.dragCfg.oD);
			}
		}

		if (jQuery.iDrop && jQuery.iDrop.count > 0 ){
			jQuery.iDrop.checkdrop(dragged);
		}
		if (jQuery.iSort && dragged.dragCfg.so) {
			jQuery.iSort.check(dragged);
		}
		if (dragged.dragCfg.onChange && (dragged.dragCfg.nRx != dragged.dragCfg.oR.x || dragged.dragCfg.nRy != dragged.dragCfg.oR.y)){
			dragged.dragCfg.onChange.apply(dragged, dragged.dragCfg.lastSi||[0,0,dragged.dragCfg.nRx,dragged.dragCfg.nRy]);
		}
		if (dragged.dragCfg.onStop)
			dragged.dragCfg.onStop.apply(dragged);
		return false;
	},

	snapToGrid : function(x, y, dx, dy)
	{
		if (dx != 0)
			dx = parseInt((dx + (this.dragCfg.gx * dx/Math.abs(dx))/2)/this.dragCfg.gx) * this.dragCfg.gx;
		if (dy != 0)
			dy = parseInt((dy + (this.dragCfg.gy * dy/Math.abs(dy))/2)/this.dragCfg.gy) * this.dragCfg.gy;
		return {
			dx : dx,
			dy : dy,
			x: 0,
			y: 0
		};
	},

	fitToContainer : function(x, y, dx, dy)
	{
		dx = Math.min(
				Math.max(dx,this.dragCfg.cont.dx),
				this.dragCfg.cont.w + this.dragCfg.cont.dx - this.dragCfg.oC.wb
			);
		dy = Math.min(
				Math.max(dy,this.dragCfg.cont.dy),
				this.dragCfg.cont.h + this.dragCfg.cont.dy - this.dragCfg.oC.hb
			);

		return {
			dx : dx,
			dy : dy,
			x: 0,
			y: 0
		}
	},

	dragmove : function(e)
	{
		if (jQuery.iDrag.dragged == null || jQuery.iDrag.dragged.dragCfg.prot == true) {
			return;
		}

		var dragged = jQuery.iDrag.dragged;

		dragged.dragCfg.currentPointer = jQuery.iUtil.getPointer(e);
		if (dragged.dragCfg.init == false) {
			distance = Math.sqrt(Math.pow(dragged.dragCfg.pointer.x - dragged.dragCfg.currentPointer.x, 2) + Math.pow(dragged.dragCfg.pointer.y - dragged.dragCfg.currentPointer.y, 2));
			if (distance < dragged.dragCfg.snapDistance){
				return;
			} else {
				jQuery.iDrag.dragstart(e);
			}
		}

		var dx = dragged.dragCfg.currentPointer.x - dragged.dragCfg.pointer.x;
		var dy = dragged.dragCfg.currentPointer.y - dragged.dragCfg.pointer.y;

		for (var i in dragged.dragCfg.onDragModifier) {
			var newCoords = dragged.dragCfg.onDragModifier[i].apply(dragged, [dragged.dragCfg.oR.x + dx, dragged.dragCfg.oR.y + dy, dx, dy]);
			if (newCoords && newCoords.constructor == Object) {
				dx = i != 'user' ? newCoords.dx : (newCoords.x - dragged.dragCfg.oR.x);
				dy = i != 'user' ? newCoords.dy : (newCoords.y - dragged.dragCfg.oR.y);
			}
		}

		dragged.dragCfg.nx = dragged.dragCfg.oC.x + dx - dragged.dragCfg.diffX;
		dragged.dragCfg.ny = dragged.dragCfg.oC.y + dy - dragged.dragCfg.diffY;

		if (dragged.dragCfg.si && (dragged.dragCfg.onSlide || dragged.dragCfg.onChange)) {
			jQuery.iSlider.onSlide(dragged, dragged.dragCfg.nx, dragged.dragCfg.ny);
		}

		if(dragged.dragCfg.onDrag)
			dragged.dragCfg.onDrag.apply(dragged, [dragged.dragCfg.oR.x + dx, dragged.dragCfg.oR.y + dy]);

		if (!dragged.dragCfg.axis || dragged.dragCfg.axis == 'horizontally') {
			dragged.dragCfg.nRx = dragged.dragCfg.oR.x + dx;
			jQuery.iDrag.helper.get(0).style.left = dragged.dragCfg.nx + 'px';
		}
		if (!dragged.dragCfg.axis || dragged.dragCfg.axis == 'vertically') {
			dragged.dragCfg.nRy = dragged.dragCfg.oR.y + dy;
			jQuery.iDrag.helper.get(0).style.top = dragged.dragCfg.ny + 'px';
		}

		if (jQuery.iDrop && jQuery.iDrop.count > 0 ){
			jQuery.iDrop.checkhover(dragged);
		}
		return false;
	},

	build : function(o)
	{
		if (!jQuery.iDrag.helper) {
			jQuery('body',document).append('<div id="dragHelper"></div>');
			jQuery.iDrag.helper = jQuery('#dragHelper');
			var el = jQuery.iDrag.helper.get(0);
			var els = el.style;
			els.position = 'absolute';
			els.display = 'none';
			els.cursor = 'move';
			els.listStyle = 'none';
			els.overflow = 'hidden';
			if (window.ActiveXObject) {
				el.unselectable = "on";
			} else {
				els.mozUserSelect = 'none';
				els.userSelect = 'none';
				els.KhtmlUserSelect = 'none';
			}
		}
		if (!o) {
			o = {};
		}
		return this.each(
			function()
			{
				if (this.isDraggable || !jQuery.iUtil)
					return;
				if (window.ActiveXObject) {
					this.onselectstart = function(){return false;};
					this.ondragstart = function(){return false;};
				}
				var el = this;
				var dhe = o.handle ? jQuery(this).find(o.handle) : jQuery(this);
				if(jQuery.browser.msie) {
					dhe.each(
						function()
						{
							this.unselectable = "on";
						}
					);
				} else {
					dhe.css('-moz-user-select', 'none');
					dhe.css('user-select', 'none');
					dhe.css('-khtml-user-select', 'none');
				}
				this.dragCfg = {
					dhe: dhe,
					revert : o.revert ? true : false,
					ghosting : o.ghosting ? true : false,
					so : o.so ? o.so : false,
					si : o.si ? o.si : false,
					insideParent : o.insideParent ? o.insideParent : false,
					zIndex : o.zIndex ? parseInt(o.zIndex)||0 : false,
					opacity : o.opacity ? parseFloat(o.opacity) : false,
					fx : parseInt(o.fx)||null,
					hpc : o.hpc ? o.hpc : false,
					onDragModifier : {},
					pointer : {},
					onStart : o.onStart && o.onStart.constructor == Function ? o.onStart : false,
					onStop : o.onStop && o.onStop.constructor == Function ? o.onStop : false,
					onChange : o.onChange && o.onChange.constructor == Function ? o.onChange : false,
					axis : /vertically|horizontally/.test(o.axis) ? o.axis : false,
					snapDistance : o.snapDistance ? parseInt(o.snapDistance)||0 : 0,
					cursorAt: o.cursorAt ? o.cursorAt : false,
					autoSize : o.autoSize ? true : false,
					frameClass : o.frameClass || false

				};
				if (o.onDragModifier && o.onDragModifier.constructor == Function)
					this.dragCfg.onDragModifier.user = o.onDragModifier;
				if (o.onDrag && o.onDrag.constructor == Function)
					this.dragCfg.onDrag = o.onDrag;
				if (o.containment && ((o.containment.constructor == String && (o.containment == 'parent' || o.containment == 'document')) || (o.containment.constructor == Array && o.containment.length == 4) )) {
					this.dragCfg.containment = o.containment;
				}
				if(o.fractions) {
					this.dragCfg.fractions = o.fractions;
				}
				if(o.grid){
					if(typeof o.grid == 'number'){
						this.dragCfg.gx = parseInt(o.grid)||1;
						this.dragCfg.gy = parseInt(o.grid)||1;
					} else if (o.grid.length == 2) {
						this.dragCfg.gx = parseInt(o.grid[0])||1;
						this.dragCfg.gy = parseInt(o.grid[1])||1;
					}
				}
				if (o.onSlide && o.onSlide.constructor == Function) {
					this.dragCfg.onSlide = o.onSlide;
				}

				this.isDraggable = true;
				dhe.each(
					function(){
						this.dragElem = el;
					}
				);
				dhe.bind('mousedown', jQuery.iDrag.draginit);
			}
		)
	}
};

/**
 * Destroy an existing draggable on a collection of elements
 *
 * @name DraggableDestroy
 * @descr Destroy a draggable
 * @type jQuery
 * @cat Plugins/Interface
 * @example jQuery('#drag2').DraggableDestroy();
 */

jQuery.fn.extend(
	{
		DraggableDestroy : jQuery.iDrag.destroy,
		Draggable : jQuery.iDrag.build
	}
);


/**
 * Interface Elements for jQuery
 * Droppables
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

/**
 * With the Draggables plugin, Droppable allows you to create drop zones for draggable elements.
 *
 * @name Droppable
 * @cat Plugins/Interface
 * @param Hash options A hash of options
 * @option String accept The class name for draggables to get accepted by the droppable (mandatory)
 * @option String activeclass When an acceptable draggable is moved, the droppable gets this class
 * @option String hoverclass When an acceptable draggable is inside the droppable, the droppable gets
 *                           this class
 * @option String tolerance  Choose from 'pointer', 'intersect', or 'fit'. The pointer options means
 *                           that the pointer must be inside the droppable in order for the draggable
 *                           to be dropped. The intersect option means that the draggable must intersect
 *                           the droppable. The fit option means that the entire draggable must be
 *                           inside the droppable.
 * @option Function onDrop   When an acceptable draggable is dropped on a droppable, this callback is
 *                           called. It passes the draggable DOMElement as a parameter.
 * @option Function onHover  When an acceptable draggable is hovered over a droppable, this callback
 *                           is called. It passes the draggable DOMElement as a parameter.
 * @option Function onOut    When an acceptable draggable leaves a droppable, this callback is called.
 *                           It passes the draggable DOMElement as a parameter.
 * @example                  jQuery('#dropzone1').Droppable(
 *                             {
 *                               accept : 'dropaccept',
 *                               activeclass: 'dropzoneactive',
 *                               hoverclass:	'dropzonehover',
 *                               ondrop:	function (drag) {
 *                                              alert(this); //the droppable
 *                                              alert(drag); //the draggable
 *                                        },
 *                               fit: true
 *                             }
 *                           )
 */

jQuery.iDrop = {
	fit : function (zonex, zoney, zonew, zoneh)
	{
		return 	zonex <= jQuery.iDrag.dragged.dragCfg.nx &&
				(zonex + zonew) >= (jQuery.iDrag.dragged.dragCfg.nx + jQuery.iDrag.dragged.dragCfg.oC.w) &&
				zoney <= jQuery.iDrag.dragged.dragCfg.ny &&
				(zoney + zoneh) >= (jQuery.iDrag.dragged.dragCfg.ny + jQuery.iDrag.dragged.dragCfg.oC.h) ? true :false;
	},
	intersect : function (zonex, zoney, zonew, zoneh)
	{
		return 	! ( zonex > (jQuery.iDrag.dragged.dragCfg.nx + jQuery.iDrag.dragged.dragCfg.oC.w)
				|| (zonex + zonew) < jQuery.iDrag.dragged.dragCfg.nx
				|| zoney > (jQuery.iDrag.dragged.dragCfg.ny + jQuery.iDrag.dragged.dragCfg.oC.h)
				|| (zoney + zoneh) < jQuery.iDrag.dragged.dragCfg.ny
				) ? true :false;
	},
	pointer : function (zonex, zoney, zonew, zoneh)
	{
		return	zonex < jQuery.iDrag.dragged.dragCfg.currentPointer.x
				&& (zonex + zonew) > jQuery.iDrag.dragged.dragCfg.currentPointer.x
				&& zoney < jQuery.iDrag.dragged.dragCfg.currentPointer.y
				&& (zoney + zoneh) > jQuery.iDrag.dragged.dragCfg.currentPointer.y
				? true :false;
	},
	overzone : false,
	highlighted : {},
	count : 0,
	zones : {},

	highlight : function (elm)
	{
		if (jQuery.iDrag.dragged == null) {
			return;
		}
		var i;
		jQuery.iDrop.highlighted = {};
		var oneIsSortable = false;
		for (i in jQuery.iDrop.zones) {
			if (jQuery.iDrop.zones[i] != null) {
				var iEL = jQuery.iDrop.zones[i].get(0);
				if (jQuery(jQuery.iDrag.dragged).is('.' + iEL.dropCfg.a)) {
					if (iEL.dropCfg.m == false) {
						iEL.dropCfg.p = jQuery.extend(
							jQuery.iUtil.getPositionLite(iEL),
							jQuery.iUtil.getSizeLite(iEL)
						);//jQuery.iUtil.getPos(iEL);
						iEL.dropCfg.m = true;
					}
					if (iEL.dropCfg.ac) {
						jQuery.iDrop.zones[i].addClass(iEL.dropCfg.ac);
					}
					jQuery.iDrop.highlighted[i] = jQuery.iDrop.zones[i];
					//if (jQuery.iSort && jQuery.iDrag.dragged.dragCfg.so) {
					if (jQuery.iSort && iEL.dropCfg.s && jQuery.iDrag.dragged.dragCfg.so) {
						iEL.dropCfg.el = jQuery('.' + iEL.dropCfg.a, iEL);
						elm.style.display = 'none';
						jQuery.iSort.measure(iEL);
						iEL.dropCfg.os = jQuery.iSort.serialize(jQuery.attr(iEL, 'id')).hash;
						elm.style.display = elm.dragCfg.oD;
						oneIsSortable = true;
					}
					if (iEL.dropCfg.onActivate) {
						iEL.dropCfg.onActivate.apply(jQuery.iDrop.zones[i].get(0), [jQuery.iDrag.dragged]);
					}
				}
			}
		}
		//if (jQuery.iSort && jQuery.iDrag.dragged.dragCfg.so) {
		if (oneIsSortable) {
			jQuery.iSort.start();
		}
	},
	/**
	 * remeasure the droppable
	 *
	 * useful when the positions/dimensions for droppables
	 * are changed while dragging a element
	 *
	 * this works for sortables too but with a greate processor
	 * penality because remeasures each sort items too
	 */
	remeasure : function()
	{
		jQuery.iDrop.highlighted = {};
		for (i in jQuery.iDrop.zones) {
			if (jQuery.iDrop.zones[i] != null) {
				var iEL = jQuery.iDrop.zones[i].get(0);
				if (jQuery(jQuery.iDrag.dragged).is('.' + iEL.dropCfg.a)) {
					iEL.dropCfg.p = jQuery.extend(
						jQuery.iUtil.getPositionLite(iEL),
						jQuery.iUtil.getSizeLite(iEL)
					);
					if (iEL.dropCfg.ac) {
						jQuery.iDrop.zones[i].addClass(iEL.dropCfg.ac);
					}
					jQuery.iDrop.highlighted[i] = jQuery.iDrop.zones[i];

					if (jQuery.iSort && iEL.dropCfg.s && jQuery.iDrag.dragged.dragCfg.so) {
						iEL.dropCfg.el = jQuery('.' + iEL.dropCfg.a, iEL);
						elm.style.display = 'none';
						jQuery.iSort.measure(iEL);
						elm.style.display = elm.dragCfg.oD;
					}
				}
			}
		}
	},

	checkhover : function (e)
	{
		if (jQuery.iDrag.dragged == null) {
			return;
		}
		jQuery.iDrop.overzone = false;
		var i;
		var applyOnHover = false;
		var hlt = 0;
		for (i in jQuery.iDrop.highlighted)
		{
			var iEL = jQuery.iDrop.highlighted[i].get(0);
			if (
					jQuery.iDrop.overzone == false
					 &&
					jQuery.iDrop[iEL.dropCfg.t](
					 	iEL.dropCfg.p.x,
						iEL.dropCfg.p.y,
						iEL.dropCfg.p.wb,
						iEL.dropCfg.p.hb
					)

			) {
				if (iEL.dropCfg.hc && iEL.dropCfg.h == false) {
					jQuery.iDrop.highlighted[i].addClass(iEL.dropCfg.hc);
				}
				//chec if onHover function has to be called
				if (iEL.dropCfg.h == false &&iEL.dropCfg.onHover) {
					applyOnHover = true;
				}
				iEL.dropCfg.h = true;
				jQuery.iDrop.overzone = iEL;
				//if(jQuery.iSort && jQuery.iDrag.dragged.dragCfg.so) {
				if(jQuery.iSort && iEL.dropCfg.s && jQuery.iDrag.dragged.dragCfg.so) {
					jQuery.iSort.helper.get(0).className = iEL.dropCfg.shc;
					jQuery.iSort.checkhover(iEL);
				}
				hlt ++;
			} else if(iEL.dropCfg.h == true) {
				//onOut function
				if (iEL.dropCfg.onOut) {
					iEL.dropCfg.onOut.apply(iEL, [e, jQuery.iDrag.helper.get(0).firstChild, iEL.dropCfg.fx]);
				}
				if (iEL.dropCfg.hc) {
					jQuery.iDrop.highlighted[i].removeClass(iEL.dropCfg.hc);
				}
				iEL.dropCfg.h = false;
			}
		}
		if (jQuery.iSort && !jQuery.iDrop.overzone && jQuery.iDrag.dragged.so) {
			jQuery.iSort.helper.get(0).style.display = 'none';
			//jQuery('body').append(jQuery.iSort.helper.get(0));
		}
		//call onhover
		if(applyOnHover) {
			jQuery.iDrop.overzone.dropCfg.onHover.apply(jQuery.iDrop.overzone, [e, jQuery.iDrag.helper.get(0).firstChild]);
		}
	},
	checkdrop : function (e)
	{
		var i;
		for (i in jQuery.iDrop.highlighted) {
			var iEL = jQuery.iDrop.highlighted[i].get(0);
			if (iEL.dropCfg.ac) {
				jQuery.iDrop.highlighted[i].removeClass(iEL.dropCfg.ac);
			}
			if (iEL.dropCfg.hc) {
				jQuery.iDrop.highlighted[i].removeClass(iEL.dropCfg.hc);
			}
			if(iEL.dropCfg.s) {
				jQuery.iSort.changed[jQuery.iSort.changed.length] = i;
			}
			if (iEL.dropCfg.onDrop && iEL.dropCfg.h == true) {
				iEL.dropCfg.h = false;
				iEL.dropCfg.onDrop.apply(iEL, [e, iEL.dropCfg.fx]);
			}
			iEL.dropCfg.m = false;
			iEL.dropCfg.h  = false;
		}
		jQuery.iDrop.highlighted = {};
	},
	destroy : function()
	{
		return this.each(
			function()
			{
				if (this.isDroppable) {
					if (this.dropCfg.s) {
						id = jQuery.attr(this,'id');
						jQuery.iSort.collected[id] = null;
						jQuery('.' + this.dropCfg.a, this).DraggableDestroy();
					}
					jQuery.iDrop.zones['d' + this.idsa] = null;
					this.isDroppable = false;
					this.f = null;
				}
			}
		);
	},
	build : function (o)
	{
		return this.each(
			function()
			{
				if (this.isDroppable == true || !o.accept || !jQuery.iUtil || !jQuery.iDrag){
					return;
				}
				this.dropCfg = {
					a : o.accept,
					ac: o.activeclass||false,
					hc:	o.hoverclass||false,
					shc: o.helperclass||false,
					onDrop:	o.ondrop||o.onDrop||false,
					onHover: o.onHover||o.onhover||false,
					onOut: o.onOut||o.onout||false,
					onActivate: o.onActivate||false,
					t: o.tolerance && ( o.tolerance == 'fit' || o.tolerance == 'intersect') ? o.tolerance : 'pointer',
					fx: o.fx ? o.fx : false,
					m: false,
					h: false
				};
				if (o.sortable == true && jQuery.iSort) {
					id = jQuery.attr(this,'id');
					jQuery.iSort.collected[id] = this.dropCfg.a;
					this.dropCfg.s = true;
					if(o.onChange) {
						this.dropCfg.onChange = o.onChange;
						this.dropCfg.os = jQuery.iSort.serialize(id).hash;
					}
				}
				this.isDroppable = true;
				this.idsa = parseInt(Math.random() * 10000);
				jQuery.iDrop.zones['d' + this.idsa] = jQuery(this);
				jQuery.iDrop.count ++;
			}
		);
	}
};

/**
 * Destroy an existing droppable on a collection of elements
 *
 * @name DroppableDestroy
 * @descr Destroy a droppable
 * @type jQuery
 * @cat Plugins/Interface
 * @example jQuery('#drag2').DroppableDestroy();
 */

jQuery.fn.extend(
	{
		DroppableDestroy : jQuery.iDrop.destroy,
		Droppable : jQuery.iDrop.build
	}
);


/**
 * Recalculate all Droppables
 *
 * @name $.recallDroppables
 * @type jQuery
 * @cat Plugins/Interface
 * @example $.recallDroppable();
 */

jQuery.recallDroppables = jQuery.iDrop.remeasure;


/**
 * Interface Elements for jQuery
 * FX
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

/**
 * Validates elements that can be animated
 */
jQuery.fxCheckTag = function(e)
{
	if (/^tr$|^td$|^tbody$|^caption$|^thead$|^tfoot$|^col$|^colgroup$|^th$|^body$|^header$|^script$|^frame$|^frameset$|^option$|^optgroup$|^meta$/i.test(e.nodeName) )
		return false;
	else
		return true;
};

/**
 * Destroy the wrapper used for some animations
 */
jQuery.fx.destroyWrapper = function(e, old)
{
	var c = e.firstChild;
	var cs = c.style;
	cs.position = old.position;
	cs.marginTop = old.margins.t;
	cs.marginLeft = old.margins.l;
	cs.marginBottom = old.margins.b;
	cs.marginRight = old.margins.r;
	cs.top = old.top + 'px';
	cs.left = old.left + 'px';
	e.parentNode.insertBefore(c, e);
	e.parentNode.removeChild(e);
};

/**
 * Builds a wrapper used for some animations
 */
jQuery.fx.buildWrapper = function(e)
{
	if (!jQuery.fxCheckTag(e))
		return false;
	var t = jQuery(e);
	var es = e.style;
	var restoreStyle = false;

	if (t.css('display') == 'none') {
		oldVisibility = t.css('visibility');
		t.css('visibility', 'hidden').show();
		restoreStyle = true;
	}
	var oldStyle = {};
	oldStyle.position = t.css('position');
	oldStyle.sizes = jQuery.iUtil.getSize(e);
	oldStyle.margins = jQuery.iUtil.getMargins(e);

	var oldFloat = e.currentStyle ? e.currentStyle.styleFloat : t.css('float');
	oldStyle.top = parseInt(t.css('top'))||0;
	oldStyle.left = parseInt(t.css('left'))||0;
	var wid = 'w_' + parseInt(Math.random() * 10000);
	var wr = document.createElement(/^img$|^br$|^input$|^hr$|^select$|^textarea$|^object$|^iframe$|^button$|^form$|^table$|^ul$|^dl$|^ol$/i.test(e.nodeName) ? 'div' : e.nodeName);
	jQuery.attr(wr,'id', wid);
	var wrapEl = jQuery(wr).addClass('fxWrapper');
	var wrs = wr.style;
	var top = 0;
	var left = 0;
	if (oldStyle.position == 'relative' || oldStyle.position == 'absolute'){
		top = oldStyle.top;
		left = oldStyle.left;
	}

	wrs.top = top + 'px';
	wrs.left = left + 'px';
	wrs.position = oldStyle.position != 'relative' && oldStyle.position != 'absolute' ? 'relative' : oldStyle.position;
	wrs.height = oldStyle.sizes.hb + 'px';
	wrs.width = oldStyle.sizes.wb + 'px';
	wrs.marginTop = oldStyle.margins.t;
	wrs.marginRight = oldStyle.margins.r;
	wrs.marginBottom = oldStyle.margins.b;
	wrs.marginLeft = oldStyle.margins.l;
	wrs.overflow = 'hidden';
	if (jQuery.browser.msie) {
		wrs.styleFloat = oldFloat;
	} else {
		wrs.cssFloat = oldFloat;
	}
	if (jQuery.browser == "msie") {
		es.filter = "alpha(opacity=" + 0.999*100 + ")";
	}
	es.opacity = 0.999;
	//t.wrap(wr);
	e.parentNode.insertBefore(wr, e);
	wr.appendChild(e);
	es.marginTop = '0px';
	es.marginRight = '0px';
	es.marginBottom = '0px';
	es.marginLeft = '0px';
	es.position = 'absolute';
	es.listStyle = 'none';
	es.top = '0px';
	es.left = '0px';
	if (restoreStyle) {
		t.hide();
		es.visibility = oldVisibility;
	}
	return {oldStyle:oldStyle, wrapper:jQuery(wr)};
};

/**
 * named colors
 */
jQuery.fx.namedColors = {
	aqua:[0,255,255],
	azure:[240,255,255],
	beige:[245,245,220],
	black:[0,0,0],
	blue:[0,0,255],
	brown:[165,42,42],
	cyan:[0,255,255],
	darkblue:[0,0,139],
	darkcyan:[0,139,139],
	darkgrey:[169,169,169],
	darkgreen:[0,100,0],
	darkkhaki:[189,183,107],
	darkmagenta:[139,0,139],
	darkolivegreen:[85,107,47],
	darkorange:[255,140,0],
	darkorchid:[153,50,204],
	darkred:[139,0,0],
	darksalmon:[233,150,122],
	darkviolet:[148,0,211],
	fuchsia:[255,0,255],
	gold:[255,215,0],
	green:[0,128,0],
	indigo:[75,0,130],
	khaki:[240,230,140],
	lightblue:[173,216,230],
	lightcyan:[224,255,255],
	lightgreen:[144,238,144],
	lightgrey:[211,211,211],
	lightpink:[255,182,193],
	lightyellow:[255,255,224],
	lime:[0,255,0],
	magenta:[255,0,255],
	maroon:[128,0,0],
	navy:[0,0,128],
	olive:[128,128,0],
	orange:[255,165,0],
	pink:[255,192,203],
	purple:[128,0,128],
	red:[255,0,0],
	silver:[192,192,192],
	white:[255,255,255],
	yellow:[255,255,0]
};

/**
 * parses a color to an object for reg, green and blue
 */
jQuery.fx.parseColor = function(color, notColor)
{
	if (jQuery.fx.namedColors[color])
		return {
			r: jQuery.fx.namedColors[color][0],
			g: jQuery.fx.namedColors[color][1],
			b: jQuery.fx.namedColors[color][2]
		};
	else if (result = /^rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)$/.exec(color))
		return {
			r: parseInt(result[1]),
			g: parseInt(result[2]),
			b: parseInt(result[3])
		};
	else if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)$/.exec(color))
		return {
			r: parseFloat(result[1])*2.55,
			g: parseFloat(result[2])*2.55,
			b: parseFloat(result[3])*2.55
		};
	else if (result = /^#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])$/.exec(color))
		return {
			r: parseInt("0x"+ result[1] + result[1]),
			g: parseInt("0x" + result[2] + result[2]),
			b: parseInt("0x" + result[3] + result[3])
		};
	else if (result = /^#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})$/.exec(color))
		return {
			r: parseInt("0x" + result[1]),
			g: parseInt("0x" + result[2]),
			b: parseInt("0x" + result[3])
		};
	else
		return notColor == true ? false : {r: 255, g: 255, b: 255};
};
/**
 * CSS rules that can be animated
 */
jQuery.fx.cssProps = {
	borderBottomWidth:1,
	borderLeftWidth:1,
	borderRightWidth:1,
	borderTopWidth:1,
	bottom:1,
	fontSize:1,
	height:1,
	left:1,
	letterSpacing:1,
	lineHeight:1,
	marginBottom:1,
	marginLeft:1,
	marginRight:1,
	marginTop:1,
	maxHeight:1,
	maxWidth:1,
	minHeight:1,
	minWidth:1,
	opacity:1,
	outlineOffset:1,
	outlineWidth:1,
	paddingBottom:1,
	paddingLeft:1,
	paddingRight:1,
	paddingTop:1,
	right:1,
	textIndent:1,
	top:1,
    width:1,
	zIndex:1
};
/**
 * CSS color rules that can be animated
 */
jQuery.fx.colorCssProps = {
	backgroundColor:1,
	borderBottomColor:1,
	borderLeftColor:1,
	borderRightColor:1,
	borderTopColor:1,
	color:1,
	outlineColor:1
};

jQuery.fx.cssSides = ['Top', 'Right', 'Bottom', 'Left'];
jQuery.fx.cssSidesEnd = {
	'borderWidth': ['border', 'Width'],
	'borderColor': ['border', 'Color'],
	'margin': ['margin', ''],
	'padding': ['padding', '']
};

/**
 * Overwrite animation to use new FX function
 */
jQuery.fn.extend({

	animate: function( prop, speed, easing, callback ) {
		return this.queue(function(){
			var opt = jQuery.speed(speed, easing, callback);
			var e = new jQuery.fxe( this, opt, prop );

		});
	},
	pause: function(speed, callback) {
		return this.queue(function(){
			var opt = jQuery.speed(speed, callback);
			var e = new jQuery.pause( this, opt );
		});
	},
	stop : function(step) {
		return this.each(function(){
			if (this.animationHandler)
				jQuery.stopAnim(this, step);

		});
	},
	stopAll : function(step) {
		return this.each(function(){
			if (this.animationHandler)
				jQuery.stopAnim(this, step);
			if ( this.queue && this.queue['fx'] )
				this.queue.fx = [];
		});
	}
});
/**
 * Improved FXC function that aniamtes collection of properties per timer. Accepts inline styles and class names to animate
 */
jQuery.extend({
	pause: function(elem, options)
	{
		var z = this, values;
		z.step = function()
		{
			if ( jQuery.isFunction( options.complete ) )
				options.complete.apply( elem );
		};
		z.timer=setInterval(function(){z.step();},options.duration);
		elem.animationHandler = z;
	},
	easing :  {
		linear: function(p, n, firstNum, delta, duration) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * delta + firstNum;
		}
	},
	fxe: function( elem, options, prop ){
		var z = this, values;

		// The styles
		var y = elem.style;
		var oldOverflow = jQuery.css(elem, "overflow");
		var oldDisplay= jQuery.css(elem, "display");
		var props = {};
		z.startTime = (new Date()).getTime();
		options.easing = options.easing && jQuery.easing[options.easing] ? options.easing : 'linear';

		z.getValues = function(tp, vp)
		{
			if (jQuery.fx.cssProps[tp]) {
				if (vp == 'show' || vp == 'hide' || vp == 'toggle') {
					if ( !elem.orig ) elem.orig = {};
					var r = parseFloat( jQuery.curCSS(elem, tp) );
					elem.orig[tp] = r && r > -10000 ? r : (parseFloat( jQuery.css(elem,tp) )||0);
					vp = vp == 'toggle' ? ( oldDisplay == 'none' ? 'show' : 'hide') : vp;
					options[vp] = true;
					props[tp] = vp == 'show' ? [0, elem.orig[tp]] : [elem.orig[tp], 0];
					if (tp != 'opacity')
						y[tp] = props[tp][0] + (tp != 'zIndex' && tp != 'fontWeight' ? 'px':'');
					else
						jQuery.attr(y, "opacity", props[tp][0]);
				} else {
					props[tp] = [parseFloat( jQuery.curCSS(elem, tp) ), parseFloat(vp)||0];
				}
			} else if (jQuery.fx.colorCssProps[tp])
				props[tp] = [jQuery.fx.parseColor(jQuery.curCSS(elem, tp)), jQuery.fx.parseColor(vp)];
			else if(/^margin$|padding$|border$|borderColor$|borderWidth$/i.test(tp)) {
				var m = vp.replace(/\s+/g, ' ').replace(/rgb\s*\(\s*/g,'rgb(').replace(/\s*,\s*/g,',').replace(/\s*\)/g,')').match(/([^\s]+)/g);
				switch(tp){
					case 'margin':
					case 'padding':
					case 'borderWidth':
					case 'borderColor':
						m[3] = m[3]||m[1]||m[0];
						m[2] = m[2]||m[0];
						m[1] = m[1]||m[0];
						for(var i = 0; i < jQuery.fx.cssSides.length; i++) {
							var nmp = jQuery.fx.cssSidesEnd[tp][0] + jQuery.fx.cssSides[i] + jQuery.fx.cssSidesEnd[tp][1];
							props[nmp] = tp == 'borderColor' ?
								[jQuery.fx.parseColor(jQuery.curCSS(elem, nmp)), jQuery.fx.parseColor(m[i])]
								: [parseFloat( jQuery.curCSS(elem, nmp) ), parseFloat(m[i])];
						}
						break;
					case 'border':
						for(var i = 0; i< m.length; i++) {
							var floatVal = parseFloat(m[i]);
							var sideEnd = !isNaN(floatVal) ? 'Width' : (!/transparent|none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset/i.test(m[i]) ? 'Color' : false);
							if (sideEnd) {
								for(var j = 0; j < jQuery.fx.cssSides.length; j++) {
									nmp = 'border' + jQuery.fx.cssSides[j] + sideEnd;
									props[nmp] = sideEnd == 'Color' ?
								[jQuery.fx.parseColor(jQuery.curCSS(elem, nmp)), jQuery.fx.parseColor(m[i])]
								: [parseFloat( jQuery.curCSS(elem, nmp) ), floatVal];
								}
							} else {
								y['borderStyle'] = m[i];
							}
						}
						break;
				}
			} else {
				y[tp] = vp;
			}
			return false;
		};

		for(p in prop) {
			if (p == 'style') {
				var newStyles = jQuery.parseStyle(prop[p]);
				for (np in newStyles) {
					this.getValues(np, newStyles[np]);
				}
			} else if (p == 'className') {
				if (document.styleSheets)
					for (var i=0; i<document.styleSheets.length; i++){
						var cssRules = document.styleSheets[i].cssRules||document.styleSheets[i].rules||null;
						if (cssRules) {
							for (var j=0; j<cssRules.length; j++) {
								if(cssRules[j].selectorText == '.' + prop[p]) {
									var rule = new RegExp('\.' + prop[p] + ' {');
									var styles = cssRules[j].style.cssText;
									var newStyles = jQuery.parseStyle(styles.replace(rule, '').replace(/}/g, ''));
									for (np in newStyles) {
										this.getValues(np, newStyles[np]);
									}
								}
							}
						}
					}
			} else {
				this.getValues(p, prop[p]);
			}
		}
		y.display = oldDisplay == 'none' ? 'block' : oldDisplay;
		y.overflow = 'hidden';

		/*if (options.show)
			y.display = "";*/

		z.step = function(){
			var t = (new Date()).getTime();
			if (t > options.duration + z.startTime) {
				clearInterval(z.timer);
				z.timer = null;
				for (p in props) {
					if ( p == "opacity" )
						jQuery.attr(y, "opacity", props[p][1]);
					else if (typeof props[p][1] == 'object')
						y[p] = 'rgb(' + props[p][1].r +',' + props[p][1].g +',' + props[p][1].b +')';
					else
						y[p] = props[p][1] + (p != 'zIndex' && p != 'fontWeight' ? 'px':'');
				}
				if ( options.hide || options.show )
					for ( var p in elem.orig )
						if (p == "opacity")
							jQuery.attr(y, p, elem.orig[p]);
						else
							y[p] = "";
				y.display = options.hide ? 'none' : (oldDisplay !='none' ? oldDisplay : 'block');
				y.overflow = oldOverflow;
				elem.animationHandler = null;
				if ( jQuery.isFunction( options.complete ) )
					options.complete.apply( elem );
			} else {
				var n = t - this.startTime;
				var pr = n / options.duration;
				for (p in props) {
					if (typeof props[p][1] == 'object') {
						y[p] = 'rgb('
						+ parseInt(jQuery.easing[options.easing](pr, n,  props[p][0].r, (props[p][1].r-props[p][0].r), options.duration))
						+ ','
						+ parseInt(jQuery.easing[options.easing](pr, n,  props[p][0].g, (props[p][1].g-props[p][0].g), options.duration))
						+ ','
						+ parseInt(jQuery.easing[options.easing](pr, n,  props[p][0].b, (props[p][1].b-props[p][0].b), options.duration))
						+')';
					} else {
						var pValue = jQuery.easing[options.easing](pr, n,  props[p][0], (props[p][1]-props[p][0]), options.duration);
						if ( p == "opacity" )
							jQuery.attr(y, "opacity", pValue);
						else
							y[p] = pValue + (p != 'zIndex' && p != 'fontWeight' ? 'px':'');
					}
				}

			}
		};
	z.timer=setInterval(function(){z.step();},13);
	elem.animationHandler = z;
	},
	stopAnim: function(elem, step)
	{
		if (step)
			elem.animationHandler.startTime -= 100000000;
		else {
			window.clearInterval(elem.animationHandler.timer);
			elem.animationHandler = null;
			jQuery.dequeue(elem, "fx");
		}
	}
}
);

jQuery.parseStyle = function(styles) {
	var newStyles = {};
	if (typeof styles == 'string') {
		styles = styles.toLowerCase().split(';');
		for(var i=0; i< styles.length; i++){
			rule = styles[i].split(':');
			if (rule.length == 2) {
				newStyles[jQuery.trim(rule[0].replace(/\-(\w)/g,function(m,c){return c.toUpperCase();}))] = jQuery.trim(rule[1]);
			}
		}
	}
	return newStyles;
};


/**
 * Interface Elements for jQuery
 * FX - blind
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */

/**
 * Applies a blinding animation to element
 */
jQuery.fn.extend(
	{
		/**
		 * @name BlindUp
		 * @description blinds the element up
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		BlindUp : function (speed, callback, easing)
		{
			return this.queue('interfaceFX',function(){
				new jQuery.fx.BlindDirection(this, speed, callback, 'up', easing);
			});
		},

		/**
		 * @name BlindDown
		 * @description blinds the element down
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		BlindDown : function (speed, callback, easing)
		{
			return this.queue('interfaceFX',function(){
				new jQuery.fx.BlindDirection(this, speed, callback, 'down', easing);
			});
		},

		/**
		 * @name BlindToggleVertically
		 * @description blinds the element up or down
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		BlindToggleVertically : function (speed, callback, easing)
		{
			return this.queue('interfaceFX',function(){
				new jQuery.fx.BlindDirection(this, speed, callback, 'togglever', easing);
			});
		},

		/**
		 * @name BlindLeft
		 * @description blinds the element left
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		BlindLeft : function (speed, callback, easing)
		{
			return this.queue('interfaceFX',function(){
				new jQuery.fx.BlindDirection(this, speed, callback, 'left', easing);
			});
		},

		/**
		 * @name BlindRight
		 * @description blinds the element right
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		BlindRight : function (speed, callback, easing)
		{
			return this.queue('interfaceFX',function(){
				new jQuery.fx.BlindDirection(this, speed, callback, 'right', easing);
			});
		},

		/**
		 * @name BlindToggleHorizontally
		 * @description blinds the element left and right
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		BlindToggleHorizontally : function (speed, callback, easing)
		{
			return this.queue('interfaceFX',function(){
				new jQuery.fx.BlindDirection(this, speed, callback, 'togglehor', easing);
			});
		}
	}
);

jQuery.fx.BlindDirection = function (e, speed, callback, direction, easing)
{
	if (!jQuery.fxCheckTag(e)) {
		jQuery.dequeue(e, 'interfaceFX');
		return false;
	}
	var z = this;
	z.el = jQuery(e);
	z.size = jQuery.iUtil.getSize(e);
	z.easing = typeof callback == 'string' ? callback : easing||null;
	if (!e.ifxFirstDisplay)
		e.ifxFirstDisplay = z.el.css('display');
	if ( direction == 'togglever') {
		direction = z.el.css('display') == 'none' ? 'down' : 'up';
	} else if (direction == 'togglehor') {
		direction = z.el.css('display') == 'none' ? 'right' : 'left';
	}
	z.el.show();
	z.speed = speed;
	z.callback = typeof callback == 'function' ? callback : null;
	z.fx = jQuery.fx.buildWrapper(e);
	z.direction = direction;
	z.complete = function()
	{
		if (z.callback && z.callback.constructor == Function) {
			z.callback.apply(z.el.get(0));
		}
		if(z.direction == 'down' || z.direction == 'right'){
			z.el.css('display', z.el.get(0).ifxFirstDisplay == 'none' ? 'block' : z.el.get(0).ifxFirstDisplay);
		} else {
			z.el.hide();
		}
		jQuery.fx.destroyWrapper(z.fx.wrapper.get(0), z.fx.oldStyle);
		jQuery.dequeue(z.el.get(0), 'interfaceFX');
	};
	switch (z.direction) {
		case 'up':
			fxh = new jQuery.fx(
				z.fx.wrapper.get(0),
				jQuery.speed(
					z.speed,
					z.easing,
					z.complete
				),
				'height'
			);
			fxh.custom(z.fx.oldStyle.sizes.hb, 0);
		break;
		case 'down':
			z.fx.wrapper.css('height', '1px');
			z.el.show();
			fxh = new jQuery.fx(
				z.fx.wrapper.get(0),
				jQuery.speed(
					z.speed,
					z.easing,
					z.complete
				),
				'height'
			);
			fxh.custom(0, z.fx.oldStyle.sizes.hb);
		break;
		case 'left':
			fxh = new jQuery.fx(
				z.fx.wrapper.get(0),
				jQuery.speed(
					z.speed,
					z.easing,
					z.complete
				),
				'width'
			);
			fxh.custom(z.fx.oldStyle.sizes.wb, 0);
		break;
		case 'right':
			z.fx.wrapper.css('width', '1px');
			z.el.show();
			fxh = new jQuery.fx(
				z.fx.wrapper.get(0),
				jQuery.speed(
					z.speed,
					z.easing,
					z.complete
				),
				'width'
			);
			fxh.custom(0, z.fx.oldStyle.sizes.wb);
		break;
	}
};

/**
 * Interface Elements for jQuery
 * FX - scale/grow/shrink/puff
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */
/**
 * Applies a scallign animation to element
 */
jQuery.fn.extend(
	{
		/**
		 * @name Grow
		 * @description scales the element from 0 to intitial size
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		Grow : function(speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.Scale(this, speed, 1, 100, true, callback, 'grow', easing);
			});
		},

		/**
		 * @name Shrink
		 * @description scales the element from intitial size to 0
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		Shrink : function(speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.Scale(this, speed, 100, 1, true, callback, 'shrink', easing);
			});
		},

		/**
		 * @name Puff
		 * @description makes element to dispear by scalling to 150% and fading it out
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		Puff : function(speed, callback, easing) {
			return this.queue('interfaceFX',function(){
				var easing = easing || 'easeout';
				new jQuery.fx.Scale(this, speed, 100, 150, true, callback, 'puff', easing);
			});
		},

		/**
		 * @name Scale
		 * @description scales the element
		 * @param Mixed speed animation speed, integer for miliseconds, string ['slow' | 'normal' | 'fast']
		 * @param Integer from initial scalling procentage
		 * @param Integer to final scalling procentage
		 * @param Boolean reastore whatever to restore the initital scalling procentage when animation ends
		 * @param Function callback (optional) A function to be executed whenever the animation completes.
		 * @param String easing (optional) The name of the easing effect that you want to use.
		 * @type jQuery
		 * @cat Plugins/Interface
		 * @author Stefan Petre
		 */
		Scale : function(speed, from, to, restore, callback, easing) {
			return this.queue('interfaceFX',function(){
				new jQuery.fx.Scale(this, speed, from, to, restore, callback, 'Scale', easing);
			});
		}
	}
);

jQuery.fx.Scale = function (e, speed, from, to, restore, callback, type, easing)
{
	if (!jQuery.fxCheckTag(e)) {
		jQuery.dequeue(e, 'interfaceFX');
		return false;
	}
	var z = this;
	z.el = jQuery(e);
	z.from = parseInt(from) || 100;
	z.to = parseInt(to) || 100;
	z.easing = typeof callback == 'string' ? callback : easing||null;
	z.callback = typeof callback == 'function' ? callback : null;
	z.duration = jQuery.speed(speed).duration;
	z.restore = restore|| null;
	z.oldP = jQuery.iUtil.getSize(e);
	z.oldStyle = {
		width: z.el.css('width'),
		height: z.el.css('height'),
		fontSize: z.el.css('fontSize')||'100%',
		position : z.el.css('position'),
		display : z.el.css('display'),
		top : z.el.css('top'),
		left : z.el.css('left'),
		overflow : z.el.css('overflow'),
		borderTopWidth : z.el.css('borderTopWidth'),
		borderRightWidth : z.el.css('borderRightWidth'),
		borderBottomWidth : z.el.css('borderBottomWidth'),
		borderLeftWidth : z.el.css('borderLeftWidth'),
		paddingTop : z.el.css('paddingTop'),
		paddingRight : z.el.css('paddingRight'),
		paddingBottom : z.el.css('paddingBottom'),
		paddingLeft : z.el.css('paddingLeft')
	};
	z.width = parseInt(z.oldStyle.width)||e.offsetWidth||0;
	z.height = parseInt(z.oldStyle.height)||e.offsetHeight||0;
	z.top = parseInt(z.oldStyle.top)||0;
	z.left = parseInt(z.oldStyle.left)||0;
	sizes = ['em','px','pt','%'];
	for(i in sizes) {
		if (z.oldStyle.fontSize.indexOf(sizes[i])>0) {
			z.fontUnit = sizes[i];
			z.fontSize = parseFloat(z.oldStyle.fontSize);
		}
		if (z.oldStyle.borderTopWidth.indexOf(sizes[i])>0) {
			z.borderTopUnit = sizes[i];
			z.borderTopSize = parseFloat(z.oldStyle.borderTopWidth)||0;
		}
		if (z.oldStyle.borderRightWidth.indexOf(sizes[i])>0) {
			z.borderRightUnit = sizes[i];
			z.borderRightSize = parseFloat(z.oldStyle.borderRightWidth)||0;
		}
		if (z.oldStyle.borderBottomWidth.indexOf(sizes[i])>0) {
			z.borderBottomUnit = sizes[i];
			z.borderBottomSize = parseFloat(z.oldStyle.borderBottomWidth)||0;
		}
		if (z.oldStyle.borderLeftWidth.indexOf(sizes[i])>0) {
			z.borderLeftUnit = sizes[i];
			z.borderLeftSize = parseFloat(z.oldStyle.borderLeftWidth)||0;
		}
		if (z.oldStyle.paddingTop.indexOf(sizes[i])>0) {
			z.paddingTopUnit = sizes[i];
			z.paddingTopSize = parseFloat(z.oldStyle.paddingTop)||0;
		}
		if (z.oldStyle.paddingRight.indexOf(sizes[i])>0) {
			z.paddingRightUnit = sizes[i];
			z.paddingRightSize = parseFloat(z.oldStyle.paddingRight)||0;
		}
		if (z.oldStyle.paddingBottom.indexOf(sizes[i])>0) {
			z.paddingBottomUnit = sizes[i];
			z.paddingBottomSize = parseFloat(z.oldStyle.paddingBottom)||0;
		}
		if (z.oldStyle.paddingLeft.indexOf(sizes[i])>0) {
			z.paddingLeftUnit = sizes[i];
			z.paddingLeftSize = parseFloat(z.oldStyle.paddingLeft)||0;
		}
	}


	if (z.oldStyle.position != 'relative' && z.oldStyle.position != 'absolute') {
		z.el.css('position', 'relative');
	}
	z.el.css('overflow', 'hidden');
	z.type = type;
	switch(z.type)
	{
		case 'grow':
			z.startTop = z.top + z.oldP.h/2;
			z.endTop = z.top;
			z.startLeft = z.left + z.oldP.w/2;
			z.endLeft = z.left;
			break;
		case 'shrink':
			z.endTop = z.top + z.oldP.h/2;
			z.startTop = z.top;
			z.endLeft = z.left + z.oldP.w/2;
			z.startLeft = z.left;
			break;
		case 'puff':
			z.endTop = z.top - z.oldP.h/4;
			z.startTop = z.top;
			z.endLeft = z.left - z.oldP.w/4;
			z.startLeft = z.left;
			break;
	}
	z.firstStep = false;
	z.t=(new Date).getTime();
	z.clear = function(){clearInterval(z.timer);z.timer=null;};
	z.step = function(){
		if (z.firstStep == false) {
			z.el.show();
			z.firstStep = true;
		}
		var t = (new Date).getTime();
		var n = t - z.t;
		var p = n / z.duration;
		if (t >= z.duration+z.t) {
			setTimeout(
				function(){
						o = 1;
					if (z.type) {
						t = z.endTop;
						l = z.endLeft;
						if (z.type == 'puff')
							o = 0;
					}
					z.zoom(z.to, l, t, true, o);
				},
				13
			);
			z.clear();
		} else {
			var s;
			o = 1;
			if (!jQuery.easing || !jQuery.easing[z.easing]) {
				s = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.to-z.from) + z.from;
			} else {
				s = jQuery.easing[z.easing](p, n, z.from, (z.to-z.from), z.duration);
			}
			if (z.type) {
				if (!jQuery.easing || !jQuery.easing[z.easing]) {
					t = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.endTop-z.startTop) + z.startTop;
					l = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.endLeft-z.startLeft) + z.startLeft;
					if (z.type == 'puff')
						o = ((-Math.cos(p*Math.PI)/2) + 0.5) * (-0.9999) + 0.9999;
				} else {
					t = jQuery.easing[z.easing](p, n, z.startTop, (z.endTop-z.startTop), z.duration);
					l = jQuery.easing[z.easing](p, n, z.startLeft, (z.endLeft-z.startLeft), z.duration);
					if (z.type == 'puff')
						o = jQuery.easing[z.easing](p, n, 0.9999, -0.9999, z.duration);
				}
			}
			z.zoom(s, l, t, false, o);
		}
	};
	z.timer=setInterval(function(){z.step();},13);
	z.zoom = function(percent, left, top, finish, opacity)
	{
		z.el
			.css('height', z.height * percent/100 + 'px')
			.css('width', z.width * percent/100 + 'px')
			.css('left', left + 'px')
			.css('top', top + 'px')
			.css('fontSize', z.fontSize * percent /100 + z.fontUnit);
		if (z.borderTopSize)
			z.el.css('borderTopWidth', z.borderTopSize * percent /100 + z.borderTopUnit);
		if (z.borderRightSize)
			z.el.css('borderRightWidth', z.borderRightSize * percent /100 + z.borderRightUnit);
		if (z.borderBottomSize)
			z.el.css('borderBottomWidth', z.borderBottomSize * percent /100 + z.borderBottomUnit);
		if (z.borderLeftSize)
			z.el.css('borderLeftWidth', z.borderLeftSize * percent /100 + z.borderLeftUnit);
		if (z.paddingTopSize)
			z.el.css('paddingTop', z.paddingTopSize * percent /100 + z.paddingTopUnit);
		if (z.paddingRightSize)
			z.el.css('paddingRight', z.paddingRightSize * percent /100 + z.paddingRightUnit);
		if (z.paddingBottomSize)
			z.el.css('paddingBottom', z.paddingBottomSize * percent /100 + z.paddingBottomUnit);
		if (z.paddingLeftSize)
			z.el.css('paddingLeft', z.paddingLeftSize * percent /100 + z.paddingLeftUnit);
		if (z.type == 'puff') {
			if (window.ActiveXObject)
				z.el.get(0).style.filter = "alpha(opacity=" + opacity*100 + ")";
			z.el.get(0).style.opacity = opacity;
		}
		if (finish){
			if (z.restore){
				z.el.css(z.oldStyle);
			}
			if (z.type == 'shrink' || z.type == 'puff'){
				z.el.css('display', 'none');
				if (z.type == 'puff') {
					if (window.ActiveXObject)
						z.el.get(0).style.filter = "alpha(opacity=" + 100 + ")";
					z.el.get(0).style.opacity = 1;
				}
			}else
				z.el.css('display', 'block');
			if (z.callback)
				z.callback.apply(z.el.get(0));

			jQuery.dequeue(z.el.get(0), 'interfaceFX');
		}
	};
};
//tableHover
/*
 * jQuery tableHover plugin
 * Version: 0.1.1
 *
 * Copyright (c) 2007 Roman Weich
 * http://p.sohei.org
 *
 * Dual licensed under the MIT and GPL licenses 
 * (This means that you can choose the license that best suits your project, and use it accordingly):
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Changelog: 
 * v 0.1.1 - 2007-06-05
 *	- fix: errors when using the plugin on a table not having a theader or tfoot
 * v 0.1.0 - 2007-05-31
 */

(function($)
{
	/**
	 * Calculates the actual cellIndex value of all cells in the table and stores it in the realCell property of each cell.
	 * Thats done because the cellIndex value isn't correct when colspans or rowspans are used.
	 * Originally created by Matt Kruse for his table library - Big Thanks! (see http://www.javascripttoolbox.com/)
	 * @param {element} table	The table element.
	 */
	var fixCellIndexes = function(table) 
	{
		var rows = table.rows;
		var len = rows.length;
		var matrix = [];
		for ( var i = 0; i < len; i++ )
		{
			var cells = rows[i].cells;
			var clen = cells.length;
			for ( var j = 0; j < clen; j++ )
			{
				var c = cells[j];
				var rowSpan = c.rowSpan || 1;
				var colSpan = c.colSpan || 1;
				var firstAvailCol = -1;
				if ( !matrix[i] )
				{ 
					matrix[i] = []; 
				}
				var m = matrix[i];
				// Find first available column in the first row
				while ( m[++firstAvailCol] ) {}
				c.realIndex = firstAvailCol;
				for ( var k = i; k < i + rowSpan; k++ )
				{
					if ( !matrix[k] )
					{ 
						matrix[k] = []; 
					}
					var matrixrow = matrix[k];
					for ( var l = firstAvailCol; l < firstAvailCol + colSpan; l++ )
					{
						matrixrow[l] = 1;
					}
				}
			}
		}
	};

	/**
	 * Sets the rowIndex of each row in the table. 
	 * Opera seems to get that wrong using document order instead of logical order on the tfoot-tbody part.
	 * @param {element} table	The table element.
	 */
	var fixRowIndexes = function(tbl) 
	{
		var v = 0, i, k, r = ( tbl.tHead ) ? tbl.tHead.rows : 0;
		if ( r )
		{
			for ( i = 0; i < r.length; i++ )
			{
				r[i].realRIndex = v++;
			}
		}
		for ( k = 0; k < tbl.tBodies.length; k++ )
		{
			r = tbl.tBodies[k].rows;
			if ( r )
			{
				for ( i = 0; i < r.length; i++ )
				{
					r[i].realRIndex = v++;
				}
			}
		}
		r = ( tbl.tFoot ) ? tbl.tFoot.rows : 0;
		if ( r )
		{
			for ( i = 0; i < r.length; i++ )
			{
				r[i].realRIndex = v++;
			}
		}
	};

	/**
	 * Highlights table rows and/or columns on mouse over.
	 * Fixes the highlight of the currently highlighted rows/columns on click.
	 * Works on tables with rowspans and colspans.
	 *
	 * @param {map} options			An object for optional settings (options described below).
	 *
	 * @option {boolean} allowHead		Allow highlighting when hovering over the table header.
	 *							Default value: true
	 * @option {boolean} allowBody		Allow highlighting when hovering over the table body.
	 *							Default value: true
	 * @option {boolean} allowFoot		Allow highlighting when hovering over the table footer.
	 *							Default value: true
	 *
	 * @option {boolean} headRows		If true the rows in the table header will be highlighted when hovering over them.
	 *							Default value: false
	 * @option {boolean} bodyRows		If true the rows in the table body will be highlighted when hovering over them.
	 *							Default value: true
	 * @option {boolean} footRows		If true the rows in the table footer will be highlighted when hovering over them.
	 *							Default value: false
	 * @option {boolean} spanRows		When hovering over a cell spanning over more than one row, highlight all spanned rows.
	 *							Default value: true
	 *
	 * @option {boolean} headCols		If true the cells in the table header (matching the currently hovered column) will be highlighted.
	 *							Default value: false
	 * @option {boolean} bodyCols		If true the cells in the table body (matching the currently hovered column) will be highlighted.
	 *							Default value: true
	 * @option {boolean} footCols		If true the cells in the table footer (matching the currently hovered column) will be highlighted.
	 *							Default value: false
	 * @option {boolean} spanCols		When hovering over a cell spanning over more than one column, highlight all spanned columns.
	 *							Default value: true
	 *
	 * @option {boolean} headCells		Set a special highlight class to the cell the mouse pointer is currently pointing at (inside the table header only).
	 *							Default value: false
	 * @option {boolean} bodyCells		Set a special highlight class to the cell the mouse pointer is currently pointing at (inside the table body only).
	 *							Default value: true
	 * @option {boolean} footCells		Set a special highlight class to the cell the mouse pointer is currently pointing at (inside the table footer only).
	 *							Default value: false
	 *
	 * @option {string} rowClass			The css class set to the currently highlighted row.
	 *							Default value: 'hover'
	 * @option {string} colClass			The css class set to the currently highlighted column.
	 *							Default value: '' (empty string)
	 * @option {string} cellClass			The css class set to the currently highlighted cell.
	 *							Default value: '' (empty string)
	 * @option {string} clickClass		The css class set to the currently highlighted row and column on mouse click.
	 *							Default value: '' (empty string)
	 *
	 * @example jQuery('#table').tableHover({});
	 * @desc Add simple row highlighting to #table with default settings.
	 *
	 * @example jQuery('#table').tableHover({rowClass: "someclass", colClass: "someotherclass"});
	 * @desc Add row and columnhighlighting to #table and set the specified css classes to the highlighted cells.
	 *
	 * @example jQuery('#table').tableHover({clickClass: "someclickclass"});
	 * @desc Add simple row highlighting to #table and set the specified css class on the cells when clicked.
	 *
	 * @example jQuery('#table').tableHover({allowBody: false, allowFoot: false, allowHead: true, colClass: "someclass"});
	 * @desc Add column highlighting on #table only highlighting the cells when hovering over the table header.
	 *
	 * @example jQuery('#table').tableHover({bodyCols: false, footCols: false, headCols: true, colClass: "someclass"});
	 * @desc Add column highlighting on #table only for the cells in the header.
	 *
	 * @type jQuery
	 *
	 * @name tableHover
	 * @cat Plugins/tableHover
	 * @author Roman Weich (http://p.sohei.org)
	 */
	$.fn.tableHover = function(options)
	{
		var settings = $.extend({
				allowHead : true,
				allowBody : true,
				allowFoot : true,

				headRows : false,
				bodyRows : true,
				footRows : false,
				spanRows : true,

				headCols : false,
				bodyCols : true,
				footCols : false,
				spanCols : true,

				headCells : false,
				bodyCells : true,
				footCells : false,
				//css classes,,
				rowClass : 'hover',
				colClass : '',
				cellClass : '',
				clickClass : ''
			}, options);

		return this.each(function() 
        {
			var colIndex = [], rowIndex = [], tbl = this, r, rCnt = 0, lastClick = [-1, -1];

			if ( !tbl.tBodies || !tbl.tBodies.length )
			{
				return;
			}

			/**
			 * Adds all rows and each of their cells to the row and column indexes.
			 * @param {array} rows		An array of table row elements to add.
			 * @param {string} nodeName	Defines whether the rows are in the header, body or footer of the table.
			 */
			var addToIndex = function(rows, nodeName)
			{
				var c, row, rowI, cI, rI, s;
				//loop through the rows
				for ( rowI = 0; rowI < rows.length; rowI++, rCnt++ )
				{
					row = rows[rowI];
					//each cell
					for ( cI = 0; cI < row.cells.length; cI++ )
					{
						c = row.cells[cI];
						//add to rowindex
						if ( (nodeName == 'TBODY' && settings.bodyRows) 
							|| (nodeName == 'TFOOT' && settings.footRows) 
							|| (nodeName == 'THEAD' && settings.headRows) )
						{
							s = c.rowSpan;
							while ( --s >= 0 )
							{
								rowIndex[rCnt + s].push(c);
							}
						}
						//add do colindex
						if ( (nodeName == 'TBODY' && settings.bodyCols)
								|| (nodeName == 'THEAD' && settings.headCols) 
								|| (nodeName == 'TFOOT' && settings.footCols) )
						{
							s = c.colSpan;
							while ( --s >= 0 )
							{
								rI = c.realIndex + s;
								if ( !colIndex[rI] )
								{
									colIndex[rI] = [];
								}
								colIndex[rI].push(c);
							}
						}
						//add hover event?
						if ( (nodeName == 'TBODY' && settings.allowBody) 
								|| (nodeName == 'THEAD' && settings.allowHead) 
								|| (nodeName == 'TFOOT' && settings.allowFoot) )
						{
							jQuery(c).bind('mouseover', over).bind('mouseout', out).click(click);
						}
					}
				}
			};

			/**
			 * Mouseover event handling. Set the highlight to the rows/cells.
			 */
			var over = function()
			{
				highlight(this, true);
			};

			/**
			 * Mouseout event handling. Remove the highlight from the rows/cells.
			 */
			var out = function()
			{
				highlight(this, false);
			};
			
			/**
			 * Mousedown event handling. Sets or removes the clickClass css style to the currently highlighted rows/cells.
			 */
			var click = function()
			{
				if ( settings.clickClass != '' )
				{
					var x = this.realIndex;
					var y = this.parentNode.realRIndex;
					//unclick
					jQuery('td.' + settings.clickClass + ', th.' + settings.clickClass, tbl).removeClass(settings.clickClass);
					if ( x != lastClick[0] || y != lastClick[1] )
					{
						//click..
						var s = '';
						if ( settings.rowClass != '' )
						{
							s += ',.' + settings.rowClass;
						}
						if ( settings.colClass != '' )
						{
							s += ',.' + settings.colClass;
						}
						if ( settings.cellClass != '' )
						{
							s += ',.' + settings.cellClass;
						}
						if ( s != '' )
						{
							jQuery('td, th', tbl).filter(s.substring(1)).addClass(settings.clickClass);
						}
						lastClick = [x, y];
					}
					else
					{
						lastClick = [-1, -1];
					}
				}
			};
			
			/**
			 * Adds or removes the highlight to/from the columns and rows.
			 * @param {element} cell	The cell with the mouseover/mouseout event.
			 * @param {boolean} on		Defines whether the style will be set or removed.
			 */
			var highlight = function(cell, on)
			{
				if ( on ) //create dummy funcs - dont want to test for on==true all the time
				{
					$.fn.tableHoverHover = $.fn.addClass;
				}
				else
				{
					$.fn.tableHoverHover = $.fn.removeClass;
				}
				//highlight columns
				var h = colIndex[cell.realIndex] || [], rH = [], i = 0, rI, nn;
				if ( settings.colClass != '' )
				{
					while ( settings.spanCols && ++i < cell.colSpan && colIndex[cell.realIndex + i] )
					{
						h = h.concat(colIndex[cell.realIndex + i]);
					}
					jQuery(h).tableHoverHover(settings.colClass);
				}
				//highlight rows
				if ( settings.rowClass != '' )
				{
					rI = cell.parentNode.realRIndex;
					if ( rowIndex[rI] )
					{
						rH = rH.concat(rowIndex[rI]);
					}
					i = 0;
					while ( settings.spanRows && ++i < cell.rowSpan )
					{
						if ( rowIndex[rI + i] )
						{
							rH = rH.concat(rowIndex[rI + i]);
						}
					}
					jQuery(rH).tableHoverHover(settings.rowClass);
				}
				//highlight cell
				if ( settings.cellClass != '' )
				{
					nn = cell.parentNode.parentNode.nodeName.toUpperCase();
					if ( (nn == 'TBODY' && settings.bodyCells)
							|| (nn == 'THEAD' && settings.headCells)
							|| (nn == 'TFOOT' && settings.footCells) )
					{
						jQuery(cell).tableHoverHover(settings.cellClass);
					}
				}
			};

			fixCellIndexes(tbl);
			fixRowIndexes(tbl);

			//init rowIndex
			for ( r = 0; r < tbl.rows.length; r++ )
			{
				rowIndex[r] = [];
			}
			//add header cells to index
			if ( tbl.tHead )
			{
				addToIndex(tbl.tHead.rows, 'THEAD');
			}
			//create index - loop through the bodies
			for ( r = 0; r < tbl.tBodies.length; r++ )
			{
				addToIndex(tbl.tBodies[r].rows, 'TBODY');
			}
			//add footer cells to index
			if ( tbl.tFoot )
			{
				addToIndex(tbl.tFoot.rows, 'TFOOT');
			}
		});
	};
})(jQuery); 
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-06-19 20:23:36 -0500 (Tue, 19 Jun 2007) $
 * $Rev: 2110 $
 *
 * Version 2.1
 */

(function($){

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

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

})(jQuery);
// Password strength meter
// This jQuery plugin is written by firas kassem [2007.04.05]
// Firas Kassem  phiras.wordpress.com || phiras at gmail {dot} com
// for more information : http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/
var toshortPass = '0px';
var shortPass = '34px';
var badPass = '66px';
var goodPass = '98px';
var strongPass = '130px';
var perfektPass = '166px';


function passwordStrength(password,username)
{
    score = 0 

    //password = 0
    if (password.length < 1 ) { return toshortPass }
    
    //password < 4
    if (password.length < 4 ) { return shortPass }
	
    //password == username
	if (password.toLowerCase()==username.toLowerCase()) return badPass
    
    //password length
    score += password.length * 4

    score += ( checkRepetition(1,password).length - password.length ) * 1
    score += ( checkRepetition(2,password).length - password.length ) * 1
    score += ( checkRepetition(3,password).length - password.length ) * 1
    score += ( checkRepetition(4,password).length - password.length ) * 1

    //password has 3 numbers
    if (password.match(/(.*[0-9].*[0-9].*[0-9])/))  score += 5 
    
    //password has 2 sybols
    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5 
    
    //password has Upper and Lower chars
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 10 
    
    //password has number and chars
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 15 
    //
    //password has number and symbol
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 10 
    
    //password has char and symbol
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 15 
    
    //password is just a nubers or chars
    if (password.match(/^\w+$/) || password.match(/^\d+$/) )  score -= 10 
    
    //verifing 0 < score < 100
    if ( score < 0 )  score = 0 
    if ( score > 100 )  score = 100 
    
    if (score < 40 )  return badPass 
    if (score < 60 )  return goodPass
	if (score < 80 )  return strongPass
    return perfektPass
}


// checkRepetition(1,'aaaaaaabcbc')   = 'abcbc'
// checkRepetition(2,'aaaaaaabcbc')   = 'aabc'
// checkRepetition(2,'aaaaaaabcdbcd') = 'aabcd'

function checkRepetition(pLen,str) {
    res = ""
    for ( i=0; i<str.length ; i++ ) {
        repeated=true
        for (j=0;j < pLen && (j+i+pLen) < str.length;j++)
            repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen))
        if (j<pLen) repeated=false
        if (repeated) {
            i+=pLen-1
            repeated=false
        }
        else {
            res+=str.charAt(i)
        }
    }
    return res
}

/**
 * The XMLHTTP object can be used as follows:
 *  
 *  XMLHTTP.request("GET", "/bla", function(r) {console.info("fertig");console.dir(r);});
 * 
 * (You can use the exact example in firebug to see the properties of the
 *	returned object)
 */
var XMLHTTP = new function() {
    var XML_SELF = this;
    // millisekunden, nach dem ein Request timeouten soll.
    var REQ_TIMEOUT = 65000;
    // Konstruktor auf XMLHttpRequest speichern, um Umdefinitionen zu begegnen
    var XHRConstructor = window.ActiveXObject ? ActiveXObject : XMLHttpRequest;
    var XHRArg = null;
    if (window.ActiveXObject) {
        try {
            // MSIE 6.x
            XHRArg = "Msxml2.XMLHTTP";
            // moeglicherweise exception ausloesen, dann falsche Version
            new XHRConstructor(XHRArg);
        } catch(e) {
            try {
                // MSIE 5.x
                XHRArg = "Microsoft.XMLHTTP";
                new XHRConstructor(XHRArg);
            } catch(e) {
                throw "no Support for XMLHttpRequest";
            }
        }
    } else if (window.XMLHttpRequest) {
        // Safari, KHTML, Mozilla, Opera
        try {
            new XHRConstructor();
        } catch(e) {
            throw "no Support for XMLHttpRequest";
        }
    }
    // create the request
    function create() {
        return new XHRConstructor(XHRArg);
    }
    // opens a request
    function send(r, method, url, reqCb, body, sync) {
        var async = (sync === true) ? false : true;
        if (r !== null) {
            r.open(method, url, async);
        	r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            if (body !== undefined) {
                if (typeof body === 'string') {
                    r.setRequestHeader("Content-length", body.length);
                    r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                } else {
                    throw "Senden eines Nicht-Strings als Body nicht moeglich: " + body;
                }
            }
            if (async) {
                r.onreadystatechange = reqCb;
            }
            r.send(body);
        } else {
            throw "Senden ohne Request nicht moeglich: " + r;
        }
    }
    function request(method, url, reqCb, body, sync, asXML) {
        var r = create();
        // Mindestens der Firefox setzt bei chunked-messages
        // den MimeType nicht korrekt... deshalb setzen wir
        // den hier hart.
        if (asXML === true && Obj.isFunction(r.overrideMimeType)) {
            r.overrideMimeType("text/xml");
        }
        if (sync === true) {
            send(r, method, url, null, body, true);
            // pruefen ob der request erfolgreich war und callback benachrichtigen.
            var s = r.status;
            // IE-Hack: Wenn der Server den Content bei längeren
            // Antworten aufsplittet, wird der MimeType nicht mehr 
            // korrekt gesetzt, und req.responseXML enthält nicht
            // das von uns erwartete XML-Dokument. Dies kann man
            // sich dann jedoch selber erzeugen:
            if (asXML === true && Browser.isIE) {
                r.responseXML.loadXML(r.responseText);
            }
            reqCb(r);
        } else {
            var answered = false;
            send(r, method, url, function() {
                // warten bis der request komplett durch ist.
                if ( !r || !r.readyState || r.readyState !== 4) {
                    return;
                }
                // pruefen ob der request erfolgreich war.
                var s = r.status; 
                if (!s) {
                    return;
                }
                answered = true;
                // IE-Hack: Wenn der Server den Content bei längeren
                // Antworten aufsplittet, wird der MimeType nicht mehr 
                // korrekt gesetzt, und req.responseXML enthält nicht
                // das von uns erwartete XML-Dokument. Dies kann man
                // sich dann jedoch selber erzeugen:
                if (asXML === true && Browser.isIE) {
                    r.responseXML.loadXML(r.responseText);
                }
                /* gesendete Daten an die Komponenten verteilen.
                 */
                 reqCb(r);
            }, body);
            window.setTimeout(function() {
                    if (!answered) {
                        reqCb({status:"timeout"});
                    }
                }, REQ_TIMEOUT);
        }
    }
    // öffentliche Methoden, die die interne Implementierung aufrufen.
    this.request = function(method, url, reqCb, body) {
        request(method, url, reqCb, body, false, false);
    };
    this.requestSync = function(method, url, reqCb, body) {
        request(method, url, reqCb, body, true, false);
    };
    this.requestXml = function(method, url, reqCb, body) {
        request(method, url, reqCb, body, false, true);
    };
    this.requestXmlSync = function(method, url, reqCb, body) {
        request(method, url, reqCb, body, true, true);
    };
    // auf einfachem Wege eine Instanz erzeugen
    this.create = create;
    /**
     * sicheres JSON-Parsing
     */ 
    this.parseJSON = function(jsonString) {
        try {
            /* Konqueror macht hier bei zu komplexem JSON ne Rekursion bis zum Stack Overflow.
            * Wir testen also hier auf den Konqueror und führen den Test für ihn erstmal nicht
            * aus.
            */ 
            if (/Konqueror|Safari|KHTML/.test(navigator.userAgent) || /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(jsonString)) {
                return eval('(' + jsonString + ')');
            } else {
                throw new SyntaxError("Invalid JSON");
            }
        } catch (e) {
            throw new SyntaxError("parseJSON");
        }
    }
    
    /**
     * A Problem with the function above is that no newlines may
     * be included in JSON-Variable texts. This function allows
     * this, but it is not entirely safe.
     */
    this.parseJSONUnsafe = function(jsonString) {
		return eval('(' + jsonString + ')');
    }
};
var catIsOut = true; // zeigt an, ob der Kategorie Filter ausgefahren ist.
var colorIsOut = true; // zeigt an, ob der Kategorie Filter ausgefahren ist.
var priceIsOut = true; // zeigt an, ob der Kategorie Filter ausgefahren ist.
var catsSelected =0; // wieviele Kategorien wurden ausgewhlt
var catsSelectedOffset =0;
var colorsSelected = 0; // wieviele Farben wurden ausgewhlt
var pricesSelected = 0; // wieviele Preise wurden ausgewhlt

var facetMore = "Filter &ouml;ffnen" ; // Label fr Runterklapppfeil
var facetLess = "Filter schliessen" ; // Label fr Runterklapppfeil



jQuery(document).ready(function() {
	if (ge('category_changer'))
	    filterInit();	
});


function filterInit(){
    categoryInit();
}

function categoryInit(){
	if (!ge('category_changer')) {
		// If there is no category change on
		// the page, leave this function.
		return;
	}

    var cat  = ge('category_changer');
    var aAs  = cat.getElementsByTagName("a");

    for(var i =0;i<aAs.length;i++){
        jQuery(aAs[i]).click(function(){change_category(this);return false;});
    }
}

function otherColorInitState(){
    ge('color_header').title=colorMore;
    colorIsOut = false;
    ge("triangle_color").alt = colorMore;
    ge("triangle_color").title =colorMore;
    ge("color_header").title = colorMore;
    ge("triangle_color").src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_down.gif";

    var color1  = ge('color_picker_d_1');
    var aImgs  = color1.getElementsByTagName("button");
    for(var i =0;i<aImgs.length;i++){
        aImgs[i].style.display = "none";;
    }
}

function priceInit(){}
function categoryReset(){
    var cat  = ge('category_changer');
    var aAs  = cat.getElementsByTagName("a");
    catsSelected = 0;
    for(var i =0;i<aAs.length;i++){
        aAs[i].firstChild.src = STATIC_CONTENT_PREFIX + "img/8x8_checkbox_off.gif";
        aAs[i].style.color = "#666";
        aAs[i].style.fontWeight = "normal";
    }
    ge('more_options').style.display = "none";
    optionsOut=false;
    ge('category_changer').style.height="auto";
    sortCategory("out");
}

function colorReset(){
    var color1  = ge('color_picker_d_1');
    var aLis  = color1.getElementsByTagName("li");
    colorsSelected = 0;
    for(var i =0;i<aLis.length;i++){
       aLis[i].style.display = "block";
       aLis[i].firstChild.src = STATIC_CONTENT_PREFIX + "img/16x16_color_field_off.gif"
    }

    var color2  = ge('color_picker_d_2');
    var aLis  = color2.getElementsByTagName("a");
    colorsSelected = 0;
    for(var i =0;i<aLis.length;i++){
       aLis[i].parentNode.style.display = "block";
       aLis[i].firstChild.src = STATIC_CONTENT_PREFIX + "img/8x8_checkbox_off.gif"
       aLis[i].style.color = "#666";
       aLis[i].style.fontWeight = "normal";
    }
    colorIsOut=false;
    toggleColor();
    change_tab_filter(1, 'color_picker');
}

// wird durch resetPriceRange in RangeFacet.html ersetzt
/*function priceReset(){
    ge('price_result').style.display = "none";
    ge('handle_max').style.left = "134px";
    shopping_slider(0,270);
    make_drag();
    change_tab_filter(1, 'price_changer');
}*/

function change_category (element){
    /*
     * ndert das Checkbox-Img bei der Kategorie-Auswahl

     */


	 var last = element.firstChild.src.lastIndexOf('/');
	 var part = element.firstChild.src.substring(last);

    if (part == "/8x8_checkbox_off.gif"){
        catsSelected++;
        element.firstChild.src = STATIC_CONTENT_PREFIX + "img/8x8_checkbox_on.gif";
        element.style.color = "#313131";
        element.style.fontWeight = "bold";
    }
    else{
        catsSelected--;
        element.firstChild.src = STATIC_CONTENT_PREFIX + "img/8x8_checkbox_off.gif";
        element.style.color = "#666";
        element.style.fontWeight = "normal";

        if(ge('triangle_cat').src.indexOf("_down.gif")!=-1){
            ge('category_changer').style.height = "315px";
            sortCategory("out");
        }
    }

}

/*
    ndert das Farbfeld-Img bei der Farb-Auswahl

*/
function change_color_scheme (element){
    if(element.src.indexOf("color_field_off.gif")!=-1){
        element.src = STATIC_CONTENT_PREFIX + "img/16x16_color_field_on.gif";
        colorsSelected++;
    }
    else{
        element.src = STATIC_CONTENT_PREFIX + "img/16x16_color_field_off.gif"
        colorsSelected--;
    }
}

function submitCats(){
    var getString ="?mode=rnd_rem&";

    var cat  = ge('category_changer');
    var aAs  = cat.getElementsByTagName("a");

    for(var i =0;i<aAs.length;i++){
        if(aAs[i].firstChild.src.indexOf("_on") != -1){
            getString+=aAs[i].id+"=1&";
            if(aAs[i].id.indexOf("ext_")!=-1 && getString.indexOf("optionsOut")==-1){
                getString+="optionsOut=true&";
            }
        }
    }
    window.location.href='index.php'+getString+'catsSelected='+catsSelected;
}

function submitColors(){window.location.href='index.php?mode=rnd_rem2';}
function submitColorsDummy(){window.location.href='index.php?color2=1';}
function submitPrices(){window.location.href='index.php?minprice=284&maxprice=519';}
function submitPricesDummy(){window.location.href='index.php?price2=1';}

function categoryTimeOut(dir){
    if(catIsOut){
        if(dir=="in")sortCategory('in');
    else sortCategory('out');
        //toggleCategory();
        catIsOut=false;
    }
}

function colorTimeOut(){
   if(colorIsOut){
    toggleColor();
    colorIsOut = false;
   }
}

function priceTimeOut(){
   if(priceIsOut){

    togglePrice();
    priceIsOut = false;
   }
}

/**
 * @ var cat auf category_changer
 * @ var dir in: zuklappen, out: aufklappen
 */
function sortCategory(dir){
    var cat             = ge('category_changer');
    var aImages         = cat.getElementsByTagName("img");
    var aAs             = cat.getElementsByTagName("a");
    var triangle_cat    = ge("triangle_cat"); // das Dreieck, das den Klappstatus anzeigt
    for(var i =0;i<aImages.length;i++){
        if(aImages[i].src.indexOf("checkbox_off.gif") != -1){
            if(dir=="in"){
                aAs[i].style.display = "none";
            }
            else if(dir=="out"){
                aAs[i].style.display = "block";
            }
        }
    }
    if(dir=="in"){
        triangle_cat.src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_down.gif";
        ge("triangle_cat").alt = facetMore;
        ge("triangle_cat").title = facetMore;
        ge("category_header").title = facetMore;
        ge('category_control').style.display = "none";
    }
    else{
        triangle_cat.src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_up.gif";  
        ge("triangle_cat").alt = facetLess;
        ge("triangle_cat").title =facetLess;
        ge("category_header").title = facetLess;
        ge('category_control').style.display = "block";
    }
}

function toggleCategory(){
    if(catIsOut){
        catIsOut = false;
        if(catsSelected>=catsSelectedOffset){
            sortCategory('in');
        }
        else{
            ge("triangle_cat").src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_down.gif";
            ge("triangle_cat").alt = facetMore;
            ge("triangle_cat").title = facetMore;
            ge("category_header").title = facetMore;
            ge('categoryToFold').style.display = "none";
            ge('category_control').style.display = "none";
        }
        if(optionsOut){
            //ge('more_options').style.display ="none";
            sortCategory('in');
            ge('category_changer').style.height = "auto";
            ge('more_options').style.height ="auto";
         }
    }
    else{
        if(catsSelected>=catsSelectedOffset){
            sortCategory('out');
        }
        ge('categoryToFold').style.display = "block";
        if(optionsOut){
            ge('category_changer').style.height="315px";
            //ge('more_options').style.display ="block";
            sortCategory('out');
            ge('more_options').style.height ="auto";
        }
        catIsOut = true;
        ge("triangle_cat").src = STATIC_CONTENT_PREFIX+ "img/15x15_triangle_up.gif";
        ge("triangle_cat").alt = facetLess;
        ge("triangle_cat").title = facetLess;
        ge("category_header").title = facetLess;
        ge('category_control').style.display = "block";
    }
}

function toggleColor(){
    if(colorIsOut){
        colorIsOut = false;
       //ge('colorToFold').style.display ="none";
        ge('color_picker').style.display = "none";
        ge("triangle_color").src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_down.gif";
        ge("triangle_color").alt = facetMore;
        ge("triangle_color").title = facetMore;
        ge("color_header").title = facetMore;
        var color1  = ge('color_picker_d_1');
        var aLis  = color1.getElementsByTagName("li");
        for(var i =0;i<aLis.length;i++){
            if(aLis[i].firstChild.className!="clearall"){
                if(aLis[i].firstChild.src.indexOf("off")!=-1)
                    aLis[i].style.display = "none";
                 else
                    aLis[i].style.display = "block";
            }
        }
        var color1  = ge('color_picker_d_1');
        var aImgs  = color1.getElementsByTagName("button");
        for(var i =0;i<aImgs.length;i++){
            aImgs[i].style.display = "none";
        }

        var color2  = ge('color_picker_d_2');
        var aLis  = color2.getElementsByTagName("a");
        for(var i =0;i<aLis.length;i++){
            if(aLis[i].firstChild.src.indexOf("off")!=-1)
                aLis[i].parentNode.style.display = "none";
             else
                aLis[i].parentNode.style.display = "block";
        }
        var color2  = ge('color_picker_d_2');
        var aImgs  = color2.getElementsByTagName("button");
        for(var i =0;i<aImgs.length;i++){
            aImgs[i].style.display = "none";
        }
    }
    else{
        colorIsOut = true;
        //ge('colorToFold').style.display="block";
        ge('color_picker').style.display = "block";
        ge("triangle_color").src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_up.gif";
        ge("triangle_color").alt = facetLess;
        ge("triangle_color").title = facetLess;
        ge("color_header").title = facetLess;

        var color1  = ge('color_picker_d_1');
        var aLis  = color1.getElementsByTagName("li");
        for(var i =0;i<aLis.length;i++){
            aLis[i].style.display = "block";
        }
        var color1  = ge('color_picker_d_1');
        var aImgs  = color1.getElementsByTagName("button");
        for(var i =0;i<aImgs.length;i++){
            aImgs[i].style.display = "block";
        }

        var color2  = ge('color_picker_d_2');
        var aLis  = color2.getElementsByTagName("a");
        for(var i =0;i<aLis.length;i++){
                aLis[i].parentNode.style.display = "block";
        }
        var color2  = ge('color_picker_d_2');
        var aImgs  = color2.getElementsByTagName("button");
        for(var i =0;i<aImgs.length;i++){
            aImgs[i].style.display = "block";
        }
    }
}

function togglePrice(){
    if(priceIsOut){
        priceIsOut = false;
        ge('priceToFold').style.display ="none";
        ge("triangle_price").src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_down.gif";
        ge("triangle_price").alt = facetMore;
        ge("triangle_price").title = facetMore;
        ge("price_header").title = facetMore;

    }
    else{
        priceIsOut = true;
        ge('priceToFold').style.display ="block";
        //ge('price_result').style.display ="none";
        ge("triangle_price").src = STATIC_CONTENT_PREFIX + "img/15x15_triangle_up.gif";
        ge("triangle_price").alt = facetLess;
        ge("triangle_price").title = facetLess;
        ge("price_header").title = facetLess;
    }
}

function toggleFacet( facetToFold ){
	if(ge('categoryToFold_' + facetToFold).style.display)  {
		if(ge('categoryToFold_' + facetToFold).style.display == "block"){
	        ge('categoryToFold_' + facetToFold).style.display ="none";
	        ge("triangle_" + facetToFold).src = STATIC_CONTENT_PREFIX + "img/close.gif";
	        persistFacetFowlding ( "true", facetToFold );
	        ge("triangle_" + facetToFold).alt = facetMore;
	        ge("triangle_" + facetToFold).title = facetMore;
	        ge("triangle_" + facetToFold).title = facetMore;
	    }
	    else if(ge('categoryToFold_' + facetToFold).style.display == "none") {
	        ge('categoryToFold_' + facetToFold).style.display ="block";
	        ge("triangle_" + facetToFold).src = STATIC_CONTENT_PREFIX + "img/open.gif";
	        persistFacetFowlding ( "false", facetToFold );
   	        ge("triangle_" + facetToFold).alt = facetLess;
	        ge("triangle_" + facetToFold).title = facetLess;
	        ge("triangle_" + facetToFold).title = facetLess;
	    }
	}
	else {
		ge('categoryToFold_' + facetToFold).style.display ="none";
	    ge("triangle_" + facetToFold).src = STATIC_CONTENT_PREFIX + "img/close.gif";
	    persistFacetFowlding ( "true", facetToFold );
       	ge("triangle_" + facetToFold).alt = facetMore;
        ge("triangle_" + facetToFold).title = facetMore;
        ge("triangle_" + facetToFold).title = facetMore;
	}
}

function persistFacetFowlding (closed, facetName) {
	
	var body = "closed=" + closed
		+ "&facetName=" + facetName;
	
	XMLHTTP.request(
		"POST",
		SHOP_BASEURL + "search.multiSelectFacet.facetTemplate.updateFowlding",
		function (r) { },
		body);
}

function moreOrLessOptions(){
    if(optionsOut){
        jQuery('#more_options').CloseVertically(300);
        optionsOut = false;
        jQuery('#category_search_form').CloseVertically(300);
        ge('more_categories').innerHTML = "weitere Optionen";
        ge('more_categories_prefix').innerHTML = "+ ";
        ge('category_changer').style.height = "auto";
        ge('more_categories').style.marginTop = "6px";
        ge('more_categories_prefix').style.marginTop = "6px";
        categoryTimeOut("out");
		ge('category_control').style.marginTop ="0px"; /* Neu vom koenig*/
    }
    else if(!optionsOut){
        jQuery('#more_options').OpenVertically(300);
        optionsOut = true;
        ge('category_search_field').value="Suchen";
        jQuery('#category_search_for').OpenVertically(300);
        ge('more_categories').innerHTML = "weniger Optionen";
        ge('more_categories_prefix').innerHTML = "- ";
        ge('more_categories').style.marginTop = "6px";
        ge('more_categories_prefix').style.marginTop = "6px";
        ge('category_changer').style.height = "315px";
		ge('category_control').style.marginTop ="10px"; /* Neu vom koenig*/
    }
}

function cat_search(val){
       var newVal       = document.createElement("strong");
       newVal.setAttribute("style","font-size:11px;");
       var newValText   = document.createTextNode(val);
       newVal.appendChild(newValText);
       var i =1;
       for(i;i<5;i++){
        var tempChild = newVal.cloneNode(true);
        ge('cat_link_'+i).insertBefore(tempChild,ge('cat_link_'+i).lastChild);
       }
}

function change_filterBG_on(element){
    element.style.backgroundColor ='rgb(256, 256, 256)';
}

function change_filterBG_off (element){
    element.style.backgroundColor='transparent';
}
var max_products_in_Tool = 2; /* Maximale Anzahl der zeigbaren Produkte im Tool, bedingt duch die Höhe des Tools */
//var tool_height =150; // Höhe der Tool-Bar, die an diverse Funktionen übergeben werden muss

var lastSelectedList;
var newListWasCanceled = false;
var formSubmitWasCanceled = false;
var maxListNameLength = 0;

jQuery(document).ready(function() {
	make_drag();
	lastSelectedList = getProductListSelection();
	initToolsHeight();
	hideHowTo();
    adjustDisplayedListItems();
});


/*
Produkte auf Tool ziehen
*/
function make_drag (searchString) {
    if ( searchString == null ) {
        searchString = '.products';
    }

    jQuery(searchString).Draggable(
		{
			revert: 	true,
			fx: 		0,
			opacity: 	0.4,
			zIndex: 	1000,
			onStart:   	function() {
									hideHowTo('drag');
									hide_quickview();
									jQuery('#tool_container_fixed').height( jQuery('body').height() );
									jQuery('#notice_container_fixed').height( jQuery('body').height() );
									IS_OVERVIEW = false;
									jQuery(".prod_img").css("border", "1px solid #CCC"
									);
									jQuery("a.prod_desc_link").css("text-decoration", "none");

			},
			onDrag:		function() {IS_OVERVIEW = false;jQuery(".prod_img").css("border", "1px solid #CCC");
									jQuery("a.prod_desc_link").css("text-decoration", "none");},
			onStop:		function() {jQuery('#tool_container_fixed').height(jQuery('#notice').height());jQuery('#notice_container_fixed').height(jQuery('#notice').height() );}	/* makes area undroppable when scrolled down, to use community side again*/
			}
		);


    jQuery('#tool_container_fixed').Droppable(
        {
            onDrop:         addProductToCart,
            accept :        'products',

            tolerance:        'intersect',
            onActivate:      function() { }
        }
    );

}

function hideHowTo(type)
{
	if (type == 'drag')
	{
		jQuery('#box_tool_0').hide();
		jQuery('#box_tool_1').show();
		jQuery('#view_list').show();
	}
	else
	{
		if (jQuery("#cartProducts .productCart").size() > 1) {
			jQuery('#box_tool_0').hide();
			jQuery('#box_tool_1').show();
			jQuery('#view_list').show();
		}
	}
}

var NOT_LOGGED = false;
function showNotlogged()
{
	//Störer wird angezeigt. Höhen der Tools werden angepasst, NOT_LOGGED gesetzt

	if ( jQuery.browser.msie ) //makes Tool visible in Opera <9
	{
		if (jQuery.browser.version < 7)
		{
			ge('must_login').style.bottom = '2';
		}
	}

	if ( jQuery.browser.safari ) //makes Tool visible in Opera <9
	{
		if (jQuery.browser.version < 3)
		{
			ge('must_login').style.bottom = '2';
		}
	}

	jQuery('#must_login').show();
	//onSmatchboxResize(newSize);										// Toolheight SETZEN mit der neuen Funktion, hier wenn der Login-Hinweis gezeigt wird  ;
	NOT_LOGGED = true;
	if (jQuery('#notice').height() < 180)
	{
	ge('notice').style.height = '180px';
	}
	ge('view_list').style.bottom ='70px';
	ge('community_side').style.marginTop ='20px';


}

function tools_resize (element) {
	// ÄNDERN der TOOLS-Höhe

	// Anpassen an Login-Stataus
     if  (NOT_LOGGED) {
		var	 add_to = 58;
	 } else {
		var	 add_to = 0;
	 }


	initToolsHeight();
    jQuery('#notice').Resizable(
        {
            minHeight: 125 + add_to,
            maxHeight: 450 + add_to,
            handlers: {s:'#notice_handle'},
            onStop:		function(){
            				jQuery('#notice').ResizableDestroy();
            				onSmatchboxResize(tool_height);				// Toolheight SETZEN mit der neuen Funktion  ;
            				
            				},
            onResize: adjustDisplayedListItems
        }
    );
}

function adjustDisplayedListItems() {
			   if  (NOT_LOGGED) {
			    var  add_to = 58;
			   } else {
			    var  add_to = 0;
			   }
          tool_height =  jQuery('#notice').height();
                    if (tool_height - add_to < '120')
                        {
                            max_products_in_Tool = 0;
                        }
                        else if (tool_height- add_to <= '175')
                        {
                            max_products_in_Tool = 2;
                        }
                        else if (tool_height- add_to <= '230')
                        {
                            max_products_in_Tool = 5;
                        }
                        else if (tool_height- add_to <= '285')
                        {
                            max_products_in_Tool = 8;
                        }
                        else if (tool_height- add_to <= '340')
                        {
                            max_products_in_Tool = 11;
                        }
                        else if (tool_height- add_to <= '395')
                        {
                            max_products_in_Tool = 14;
                        }
                        else if (tool_height- add_to <= '440')
                        {
                            max_products_in_Tool = 17;
                        }
                        else {
                            max_products_in_Tool = 20;
                        }
                        change_tool_count();
}

function getAbsolutSmatchboxsize(newSize) 		//(ihr ruft auf, wir implementieren)  	-> Aufrufen der Hoehe, die in den init-Funktionen dazu verwendet wird 
{
	var hoehe = 100;
	
	if (NOT_LOGGED)
	{
		hoehe = newSize+58;  	// jQuery('#notice').height() ersetzen durch den gespeicherten User-WERT
	}
	else
	{
		hoehe = newSize;		// jQuery('#notice').height() ersetzen durch den gespeicherten User-WERT
	}
	//console.debug('+'+newSize);
	return hoehe;

}                            


function onSmatchboxResize(newSize) // wird aufgerufen wenn der Benutzer die Smatchgoe�e aendert
{
	XMLHTTP.request("GET", LISTBOX_ADDRESS + ".setSmatchBoxSize/" + newSize, function(r){});	
}

function setSmatchboxSize(newSize) // ver�ndert die Gr��e der Smatchbox
{
	if ( newSize > 0 )
	 jQuery('#notice').height(getAbsolutSmatchboxsize(newSize));
}

function initToolsHeightif_Logged()
{
	var hoehe = getAbsolutSmatchboxsize(newSize);
	if (NOT_LOGGED)
	{       
	jQuery('#notice').height(hoehe);
	}
}

function initToolsHeight()
{
	var hoehe = getAbsolutSmatchboxsize();
	jQuery('#tool_container_fixed').height(jQuery('#notice').height());
	jQuery('#notice_container_fixed').height(jQuery('#notice').height());  
	//
	
}

function change_tool_count()
{
    /*
    Ändern der Anzahl der angezeigten Produkte im Tool
    */

    var numItems = jQuery('#box_tool_1 .productListItem').length;
   	jQuery('#currentListCount').html('(' + numItems + ')');

    for (var i = 0; i <  numItems ; i++)
    {
        if (i >= max_products_in_Tool)
        {
            jQuery('#cartProducts').children(".productListItem").get(i).style.display ="none";
        }
        else
        {
            jQuery('#cartProducts').children(".productListItem").get(i).style.display ="inline";
        }
    }

    hideHowTo();
}


var addProductToCart = function(dragged) {
    var cartItem;
    //var productId = dragged.alt;

    var productClasses = jQuery(dragged).attr('class');
    var regexp = /^.*id_([0-9]+)[^0-9]+.*$/;
    regexp.exec(productClasses);
    var productId = RegExp.$1;

    addProductIdToList(productId, "Drag and Drop");
};

function addProductIdToList(productId, addType) {

	getProductAjax(productId, function(r) {
    	var product = parseJsonWithErrorHandling(r);
    	if (!product) {
    		return;
   		}
    	
   		addProductToCurrentListAjax(productId, addType, function() {
   			
   	    	addProductToList(product);
   	    	
   		} );
    	
  	});
}

/**
 * Adds the given product to
 * the currently displayed product list
 */
function addProductToList(product) {
   	var productName = product.title;
    var productImage = product.verySmallThumbnailUrl;
    var productId = product.id;

    var isInCart = jQuery('#'  + 'cart_' + productId);

    if (isInCart.size() == 1) {
        change_tool_count();
    } else {
    	var productUrl = 'http://' + SHOP_SERVER_AND_PORT+SHOP_BASEURL + 'communityproductdetails' + '/' + product.id + '/byName/' + getProductListSelectionURIencoded();
        jQuery('#moveToProduct')
            .after('<div class="productCart productListItem" id="' +  'cart_' + productId + '" style="background-image:url('+ productImage +
            	')" title="'+ productName + '">' +
            	'<div style="width:33px; height:40px; background-color:transparent;" ' +
            		'onclick="javascript:window.location.href=\'' +  productUrl + '\'"/>' +
            	'<a href="javascript:removeProductFromList(\''+ productId + '\')"><img src="'+ STATIC_CONTENT_PREFIX + 'img/11x11_notice_delete.gif" width="11" height="11" align="Loeschen" title="Loeschen" id="' +
            	 'delete_'+ productId + '" style="" /></a></div>');
       	change_tool_count();
    }
}                  

function loadCurrentProductList() {
    getProductListAjax(getProductListSelectionURIencoded(),
        function(r) {
			displayProductList(r);
        }
    );
}

/**
 * Removes the current products from the displayed list
 * and adds the products from the given AJAX response.
 */
function displayProductList(r) {
    jQuery(".productListItem").remove();

    products = parseJsonWithErrorHandling(r);

    if (!products) {
        return;
    }


    for (i=0; i<products.length; i++) {
        addProductToList(products[i]);
    }

    if (products.length == 0) {
    	// set the correct number of products
    	// (change_tool_count will not be called if there are no products)
    	change_tool_count();
    }

    hideHowTo("drag");
}


function setAndReloadProductList() {
  if (getProductListSelection().indexOf("newStyleOpt") == 0) {
    changeProductListSelectionInProductListBox(lastSelectedList);
    createStyle('', '');
    return;
  } else if (getProductListSelection().indexOf("newList") == 0) {
		changeProductListSelectionInProductListBox(lastSelectedList);
		showNewProductListLayer();
		return;
	}
	toggleAddtoText(ge("productListSelection"));  // change text in ProductListAddProductSelection.html
    setCurrentProductList(getProductListSelectionURIencoded());
    loadCurrentProductList();
    lastSelectedList = getProductListSelection();
    changeProductListSelectionInProductDetails(getProductListSelection());
}

function toggleListSelection (element)
{
	var typeAndName = jQuery(element).val();
	if (typeAndName.indexOf("newList") == 0) {
		changeProductListSelectionInProductListBox(lastSelectedList);
		showNewProductListLayer();
		return;
	}
	toggleAddtoText (element);
}

function toggleAddtoText (element)
{
	var typeAndName = jQuery(element).val();
	if (typeAndName == "") {
		jQuery("#addToListButton").css('display', 'none');
		return;
	}

	var type = typeAndName.substr(0, typeAndName.indexOf("/"));

	var texts = new Object();
	texts["custom"] = "Ab auf:&nbsp;";
	texts["wardrobe"] = "Ab in den:&nbsp;";
	texts["notelist"] = "Ab auf den:&nbsp;";
	texts["wishlist"] = "Ab auf die:&nbsp;";
	texts["comparisonlist"] = "Ab auf die:&nbsp;";

	var listImages = new Object();
	listImages["custom"] = "box_list.gif";
	listImages["wardrobe"] = "box_kleid.gif";
	listImages["notelist"] = "box_merk.gif";
	listImages["wishlist"] = "box_wunsch.gif";
	listImages["comparisonlist"] = "box_vergl.gif";

	// Ändern des Anzeige-Textes 'ab auf den...' in seine verschiedenen Varianten
	// Änderung des BG_Bildes (Farbe)

	jQuery('#add_to_text').html(texts[type]);

	jQuery('#notice_switcher #mouse').css('background-image', 'url('+ STATIC_CONTENT_PREFIX + 'css/img/'+ listImages[type]+ ')');
	jQuery("#addToListButton").css('display', 'block');
}



function getProductListSelection() {
    return ge("productListSelection").value;
}

function getProductListSelectionURIencoded() {
    var raw = getProductListSelection();
    var typeIdx = raw.indexOf('/');
    return encodeURIComponent(raw.substring(0,typeIdx)) + '/' + encodeURIComponent(raw.substring(typeIdx + 1));
}

function removeProductFromList(productId) {
    if (productId == null) {
        return;
    }

    ge('delete_'+ productId).style.display ="none";
    jQuery("#"  + "cart_" + productId).Shrink(
        600,
        function() {
            jQuery(this).remove();
            change_tool_count();
        }
    );

    // only remove products from ListDetailView if this list is the same as the list
    // selected in the smatchbox
    if ( typeof selectedListId != "undefined"
            && selectedListId > 0
            && typeof viewedListId != "undefined"
            && viewedListId > 0
            && selectedListId == viewedListId ) {
        removeProductFromListDetailsPage(productId);
    }

    removeProductFromListAjax(getProductListSelectionURIencoded(), productId,
        function(r) {
        	parseJsonWithErrorHandling(r);
        });
}

function removeProductFromCertainList(listTypeAndName, productId) {
	if (productId == null) {
		alert("Falsche Produkt-ID");
		return;
	}

	if (getProductListSelection() == listTypeAndName) {
		removeProductFromList(productId);
	} else {
		removeProductFromListAjax(listTypeAndName, productId,
        function(r) {
        	parseJsonWithErrorHandling(r);
        });
	}

    //TODO feststellen von wo das Produkt tatsächlich gelöscht werden muss
	removeProductFromListDetailsPage(productId);
	removeProductFromComparePage(productId);
}

function removeProductFromListDetailsPage(productId) {
	productDiv = jQuery('#productlist_product_'+ productId);
	if (!productDiv) {
		return;
	}

	parentElem = productDiv.parent();
	productDiv.remove();

	// set margins for the products in the list.
	// Every 4th product has no right border.
	elems = parentElem.children("div");
	for (i=0; i<elems.size(); i++) {
		if ((i+1) % 4 == 0) {
			jQuery(elems.get(i)).css("margin-right", "0px");
		} else {
			jQuery(elems.get(i)).css("margin-right", "20px");
		}
	}
}

function removeProductFromComparePage(productId) {
	columns = jQuery(".compare_products_column_"+ productId);
	if (!columns) {
		return;
	}

	columns.remove();

	initTableMove();

	if (jQuery('#first_line').children("td").length == 0) {
		// table is empty
		jQuery('#compare_products_present_container').hide();
		jQuery('#no_compare_products_present_container').show();
	}

}

/**
 * This function is used by the dropdown box on the
 * productDetails page.
 */
function setCurrentProductListAndAddProduct(productId) {
	var productlist = jQuery('.addToListSelection_'+ productId).val();

	if (productlist != getProductListSelection()) {
		changeProductListSelectionInProductListBox(productlist);

		setCurrentProductListAjax(productlist, function(r) {
			getProductListAjax(getProductListSelectionURIencoded(),
		        function(r) {
					displayProductList(r);

					addProductIdToList(productId, "Konventionell");

					// This is needed for the search page only,
					// when there are more than one selection boxes on the page
					changeProductListSelectionInProductDetails(productlist);
		        }
	    	);
		});
	} else {
		addProductIdToList(productId, "Konventionell");
	}
}


function setCurrentProductList(listType) {
    setCurrentProductListAjax(listType, function(r) { });
}

function changeProductListSelectionInProductListBox(listType) {
	jQuery("#productListSelection > option[@value='"+ listType +"']").attr("selected", "selected");
}

function changeProductListSelectionInProductDetails(listType) {
	// If the is no addToListSelection on the current page,
	// do nothing
	if (jQuery(".addToListSelection").length == 0) {
		return;
	}

	forms = jQuery(".addToListSelection").get();

	for (i=0; i<forms.length; i++) {
		jQuery(forms[i]).children("option[@value='"+ listType +"']").attr("selected", "selected");
	}
}

/////////////////////////////////////////////
// Functions for adding a new product list //
/////////////////////////////////////////////

function showNewProductListLayer()  {
	jQuery('#newListName').val('');
	jQuery('#TB_overlay_list').bgiframe();
	jQuery("#TB_overlay_list").show();
	jQuery("#newListLayer").show();
	jQuery("#newListName").focus();
}

/**
  * Is called from the from in NewList.html.
  * For creating a style the page reload has to be
  * omitted.
  */
function newProductListNoAjax() {
  if (jQuery('#listtype_style').is(':checked')) {
    createStyle(jQuery('#new_productlist_name').val(), jQuery('#new_productlist_description').val());
    return false;
  }
  return true;
}

/**
  * Is called from the NewProductListLayer.
  * Creates a new list via ajax.
  */
function newProductList() {

	var listType = jQuery("#newProductListTypeSelection").val();
	var listName = jQuery("#newListName").val();

	if (listName == "") {
		jQuery("#newListErrorMessage").html("Der Name der Liste darf "+
		"nicht leer sein");
		return;
	}
	
	if (listName.indexOf('/') != -1) {
		jQuery("#newListErrorMessage").html("Der Name der Liste darf "+
		"kein / enthalten");
		return;
	}
	
	/**
	if ( listType == 'style' ) {
     jQuery("#newListLayer").hide();	
	   createStyle(listName, "");
	   return;
	}*/

	getProductListAjax(listType + "/" + encodeURIComponent(listName), function(r) {
		var res = XMLHTTP.parseJSON(r.responseText);
		if (!res.error) {
			// List already exists...
			jQuery("#newListErrorMessage").html("Es existiert schon eine"+
				" Liste dieses Typs mit dem angegebenen Namen");
		} else {
			createProductListAjax(listType + "/" + encodeURIComponent(listName),
				function(response) {
					res = XMLHTTP.parseJSON(response.responseText);
					if ( res.error ) {
						jQuery("#newListErrorMessage").html(res.error);
						return false;
					} else {
						jQuery("#newListLayer").hide();
						jQuery("#TB_overlay_list").hide();
            addListInSelectionBoxes(listType, listName);
            setAndReloadProductList();
            trackNewProductList();						
					}
			});
		}
	});
}

function trackNewProductList() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ProductListCreated";
        s.events="event15";
        s.eVar23="Liste erstellt";
        s.t();
        increaseNumberOfActions();
	}
}

function trackProductListDeleted() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ProductListDeleted";
        s.events="event16";
        s.eVar23="Liste geloescht";
        s.t();
        increaseNumberOfActions();
	}
}

function cancelNewProductList() {
	jQuery("#newListErrorMessage").html("");
	jQuery("#newListLayer").hide();
	jQuery("#TB_overlay_list").hide();
}

function addListInSelectionBoxes(type, name) {
	addListInSelectionBox(jQuery("#productListSelection").get(), type, name);

	// add-to-list-selections that may be on the current page
	var boxes = jQuery(".addToListSelection")
	for (i=0; i < boxes.length; i++) {
		addListInSelectionBox(boxes.get(i), type, name);
	}
}

/**
 * Adds a product list with the given name and type
 * to the given selection box.
 */
function addListInSelectionBox(box, type, name) {
	var options = jQuery(box).children("option");
	options.removeAttr('selected');
	var lastOption = options.get(options.length-1);
	jQuery(lastOption).before('<option selected="selected" value="'+ type + '/' + name +
		'">'+ name + '</option>');
}

/**
 * Sets the visibility status to the given value.
 * It first tries to get the list name from the span#list_name_span,
 * because this may contain a, via ajax updated, name. 
 */
function setListStatus(listName, listType, index, status) {
	var localListName = jQuery('#list_name_span').text(); 
	var finalName;
	if (localListName == '') {
		finalName = listName;
	} else {
		finalName = localListName;
	}
	
    var listTypeAndName = listType + '/' + encodeURIComponent(finalName);
	setListStatusAjax(listTypeAndName, status, function(r) {
		if (parseJsonWithErrorHandling(r) == false) {
			return;
		}
		jQuery("#statusChangeOkImage_"+ index).show();

		trackListStatusChanged(status);
	});
}

/**
* This was moved here from ProductListEditHeader.html - which previously inserted
* it every time it was rendered.
* @param element
* @param listId
* @return
*/
function handleListOps(element, listId) {
	var f = element.form;
	var submit = false;
	if (f.listOperations.value == 'NEW') {
		showNewProductListLayer();
	} else if (f.listOperations.value == 'NEW_STYLE') {
		createStyle('','');
	} else if (f.listOperations.value == 'EMPTY') {
		submit = confirm("Liste leeren, bist du sicher?");
	} else if (f.listOperations.value == 'CONVERT_TO_STYLE') {
		convertListToStyle(listId);
	} else if (f.listOperations.value == 'WECH') {
		submit = confirm("Liste löschen, bist du sicher?");
		if (submit) {
			trackProductListDeleted();
		}
	} else if (f.listOperations.value == 'WIDGET') {
		submit = true;
	} else if (f.listOperations.value == 'EDIT') {
		submit = false;
		editStyle(listId);
	}
	if (submit) {
		f.submit();
	}
}

function trackListStatusChanged(status) {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ProductListStatusChanged";
        if (status == 'public') {
	        s.events="event15";
	        s.eVar23="Liste veroeffentlicht";
        } else {
        	s.events="event16"
        	s.eVar23="Liste privat gemacht";
        }
        s.t();
        increaseNumberOfActions();
	}
}




function trackProductListDescriptionChanged() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ProductListDescriptionChanged";
        s.events="event15";
        s.eVar23="Liste beschrieben";
        s.t();
        increaseNumberOfActions();
	}
}




function trackProductListNameChanged() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ProductListNameChanged";
        s.events="event15";
        s.eVar23="Liste benannt";
        s.t();
        increaseNumberOfActions();
	}
}

// Functions with AJAX calls

var LISTBOX_ADDRESS = SHOP_BASEURL + "productdetails.maintemplate.productlistbox";
var LISTEDIT_ADDRESS = SHOP_BASEURL + "productlists/showlist";

/**
 * Makes an AJAX call for the product with the given ID.
 * The product is returned as
 * a JSON string in the attribute responseText of
 * the parameter of the given callback function.
 *
 */
function getProductAjax(productId, callbackFunction) {
    XMLHTTP.request("GET", LISTBOX_ADDRESS + ".getproduct/" + productId,
        callbackFunction);
}



function addProductToCurrentListAjax(productId, addType, successCallback) {
	XMLHTTP.request("GET", LISTBOX_ADDRESS + ".addProductToList/" + getProductListSelectionURIencoded()
        + "/" + productId,
        function(r) {
        	answer = parseJsonWithErrorHandling(r);
        	if (!answer) {
        		return;
        	}
        	else {
        		successCallback();
        	}

        	trackAddProductToList(productId, addType);

        	if (answer.state == "unsaved") {
        		showNotlogged();
        	}
        	
       	});
}

function trackAddProductToList(productId, addType) {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "AddProductToList";
        s.events="event10";
        s.eVar14=productId;
        s.eVar15 = addType;
        s.t();
        increaseNumberOfActions();
	}
}

function createProductListAjax(listTypeAndName, callbackFunction) {
	XMLHTTP.request("GET", LISTBOX_ADDRESS + ".createProductList/" + listTypeAndName,
	callbackFunction);
}

function setListStatusAjax(listTypeAndName, status, callbackFunction) {
	XMLHTTP.request("GET", LISTEDIT_ADDRESS + ".setListStatus/" + listTypeAndName +
		"/"+ status,
	callbackFunction);
}

/**
 * Makes an AJAX call for the product list with the
 * given type name. The product list is returned as
 * a JSON string in the attribute responseText of
 * the parameter of the given callback function.
 *
 */
function getProductListAjax(listTypeAndName, callbackFunction) {
    XMLHTTP.request("GET", LISTBOX_ADDRESS + ".getProductsForListTypeAndName/" + listTypeAndName,
            callbackFunction);
}

/**
 * Sets the list with the given list type as the currently
 * displayed list on the server.
 *
 * Over the callback function, the http retugetProductsrn code can be
 * checked in order to see if the call succeeded. The responseText
 * is empty on success.
 */
function setCurrentProductListAjax(listTypeAndName, callbackFunction) {
    XMLHTTP.request("GET", LISTBOX_ADDRESS + ".setSelectedList/"+ listTypeAndName,
        callbackFunction);
}

/**
 * Removes the product from the list with the given type on the server.
 *
 * Over the callback function, the http return code can be
 * checked in order to see if the call succeeded. The responseText
 * is empty on success.
 */
function removeProductFromListAjax(listTypeAndName, productId, callbackFunction) {
    XMLHTTP.request("GET", LISTBOX_ADDRESS + ".removeProductFromList/"+
        listTypeAndName + "/" + productId,
        function(r) { });
}

/**
 * Parses the given ajax response as JSON code.
 * Returns true, if an error object was found
 * in the JSON code or if there was a HTTP error.
 * In the case of an error object, alerts the message.
 */
function parseJsonWithErrorHandling(r) {
	if (r.status != 200) {
        alert("Ein Fehler ist aufgetreten. Die Aktion konnte nicht durchgeführt werden.");
        return false;
    }

    var res = XMLHTTP.parseJSON(r.responseText);

    if (res.error) {
        alert(res.error);
        return false;
    }

    return res;
}

// shopping25 JavaScript Document
jQuery(document).ready(function() {
   // put all your jQuery goodness in here.
   mouse_down = false;
   document.onmousedown = function(){mouse_down = true;};
   document.onmouseup   = function(){mouse_down = false;};

   //var ms = new Date();
   //debugOutput(ms.getSeconds()+" "+ms.getMilliseconds());
   if(jQuery('#compare_products_present_container').size()>0 && ge('TableMove_container')){
    initTableMove();
   }
   //initPicBrowser(); << noch nicht abgenommenes Feature, daher zurückgestellt
   initSearchValue();

   if(jQuery('#showlist').size()>0 || jQuery('#prod_detail').size()>0){
    draggableTag();
    initTagSuggest();
   }
   if(jQuery('#dashboard').size()>0 || ge('homepage_compare')){
    init_dashboard_compareMove();
   }
   /* Jobs- and Help-page*/
   /*if(jQuery('#jobs').size()>0){
       init_jobs_change ()
      }
      */

      if(jQuery('#around_invite_user').size()>0){
          initaddFriendInvitation()
    }
    
    
    // Style Pager
    if(jQuery("#resultContainer").size()>0){
          initStylePager();
    }

                                                     
           
   mouse_pos();
   hide_quickview();
   initQuickview();
   //initHomepageHeadline();
   initBrowserChanges();
   initSuggest();
   
   if(jQuery('#profile').size()>0){
    initFavs();
   }
   // var ms = new Date();
   //debugOutput(ms.getSeconds()+" "+ms.getMilliseconds());
 });

var allredyCleared = false;
var allredyCleared_Extra = false;
var client_id = 1; /* für Preis-Schieber*/
var lowPrice = 0;
var highPrice = 1200;

var tableMove_counter_left = 0 ,tableMove_counter_right = 0, tableMove_max_counter = 0;         /* Vergleichsliste*/
var PicBrowser_counter_left = 0, PicBrowser_counter_right = 0, PicBrowser_counter_max = 0;      /* Pic-Browser auf Promosite*/

var SubNav = undefined  // var fuer die Subnavi
var ActiveSubNav ='';
var active_timer = null;
var active_navigation = null;
var main_nav = null;
var mouse_down = false;

// IE6 Smatch Variablen
var lastY=0;
var YOffset=0;
var staticYOffset=28;
var smatchVisible = true;
var flag =true;
var pixelTopSmooth=134;
// Ende IE6 Smatch Variable

var TIMEOUT_SUGGEST = 150; // Delay nachdem eine Suchanfrage ausgeführt wird
var TIMEOUT_FIRST_SUGGEST = 300; // Name ist Programm
var TIMEOUT_SUGGEST_HIDE = 2500; // Nach 2500ms wird die Suggest bei mouseout geschlossen

var ENTER_TAGS_MESSAGE = "Gebe hier deine Tags ein";

function position_left(obj) {
 if (obj.offsetParent == null) {
  return obj.offsetLeft;
 } else {
  return obj.offsetLeft + position_left(obj.offsetParent);
 }
}

/**
 * Initialization of Fav pull containers, escpecially concerning blur();
 */
function initFavs(){
    jQuery('#profile #from_shops a,#profile #from_colors a,#profile  #from_brands a').focus(function(){this.blur();});
}

function change_imgsrc (element, img){
    jQuery(element).attr("src", STATIC_CONTENT_PREFIX + img);
}
/* send2HTML  -> change_jobheader(element)
function init_jobs_change (){

    jQuery(".job_header").click( function() {
        jQuery(this).toggleClass("active_job")
        var neighbour = jQuery(this).next('.job_desc');
        jQuery(neighbour).toggle();

    });

}
*/
function change_jobheader(element)
{
        jQuery(element).toggleClass("active_job")
        var neighbour = jQuery(element).next('.job_desc');
        jQuery(neighbour).toggle();
}

function hidenav(long){

    for (var i=1; i<=3; i++){
            jQuery('#category_menu_'+i).hide();
            //jQuery('#level_1_navigation .navi_'+i).removeClass("active");
    }
    if(long){
        var navi1 = jQuery('#level_1_navigation li a.navi_1');
        var navi2 = jQuery('#level_1_navigation li a.navi_2');
        var navi3 = jQuery('#level_1_navigation li a.navi_3');

        // The if-tests are for assuring that permanently active
        // items are not made unactive
        if ( navi1.length > 0 && navi1.attr("class").indexOf("active") == -1) {
            navi1.css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/mode_01.gif)", 'color': '#666666' });
        }
        if ( navi2.length > 0 && navi2.attr("class").indexOf("active") == -1) {
            navi2.css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/wohn_01.gif)", 'color': '#666666' });
        }
        if ( navi3.length > 0 && navi3.attr("class").indexOf("active") == -1) {
            navi3.css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/life_01.gif)", 'color': '#666666' });
        }
    }
}

function position_top(obj) {
 if (obj.offsetParent == null) {
  return obj.offsetTop;
 } else {
  return obj.offsetTop + position_top(obj.offsetParent);
 }
}
/*Tag Suggest suche BEGIN */

function trim (str) {
    
    return str.replace(/^\s+/,"");
}

function removeStripes(str){
    var ret = "";
    for(i=0;i<str.length;i++){
        if(str.charAt(i)!='\'')
            ret += str.charAt(i);
        else
            ret+="\\"+str.charAt(i);       
    
    }
    return ret;
}

var tagsuggest_words_left=0; // Wieviel Tags stehen auf der linken Seite
var tagsuggest_words_right =0; // Wieviele auf der rechten
var tag_arrowCounter =-1; // Stelle des gehighlighteten Tags bei der Pfeil Navigation
var tag_site = "left"; // Startseite der Pfeil Navi
var tag_suggestResultCount = 0; // Anzahl der Tags, wird in der Add Methode hochgez�hlt
var f_hideTagsuggest = false; // true, wenn der Tagsuggest Layer ausgefahren ist
var TAG_SUGGEST_TIMER =0; //Timer, um zu viele Requeat abzufangen 
var TAG_SUGGEST_TIME_FIRST = 0 // Frage, ob Abfrage zum ersten mal
var lastCursorPos = 0
var untrimmedTagPrefix = "";

// Muss auf allen Seiten aufgerufen werden, wo Tag Suggest vorkommt
function initTagSuggest(){
    // Tag-Suggest wird erstmal nicht mit deployed
    return;
    
    if (!ge('tagging_field')) {
        return;
    }        
    jQuery('#tagging_field').unbind('keyup');

    // Bei Tastendruck 1:tagsuggest layer einblenden 2: Abfragen ueber Ajax 3: Handling von Pfeiltasten Navigation
    jQuery('#tagging_field').keyup(function(event){
        
        // Pfeiltasten verarbeiten
        if(event.keyCode == 13 || event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39|| event.keyCode==40) 
            tag_handleArrow(event.keyCode);
        else if(event.keyCode ==32) // spaces ignorieren
            ;
        else if(event.keyCode == 188){
            f_hideTagsuggest = true;
            window.setTimeout(hideTagsuggest,300);
        }
        
        else{    
            ge('tagsuggest').style.display = "block";
            jQuery('#tagsuggest').bgiframe();  
            tagsuggest_words_left=0; // Wieviel Tags stehen auf der linken Seite    
            tagsuggest_words_right =0; // Wieviele auf der rechten
            jQuery('#tagsuggest_inner_left ul').empty();
            jQuery('#tagsuggest_inner_right ul').empty();  
            
            
            //cursorposition zum einfuegen merken
            lastCursorPos = getCursorPos(); 
            if (TAG_SUGGEST_TIME_FIRST == 0) // Abfrage, ob Ausfuerung zum ersten MAl
            {
                TAG_SUGGEST_TIME_FIRST = 1;
                TAG_SUGGEST_TIMER = window.setTimeout("performTagSuggestSearch ( '"+trim(calcTagPrefix(true))+"' )",0);
            }
            else
            { 
                window.clearInterval(TAG_SUGGEST_TIMER);  
                TAG_SUGGEST_TIMER = window.setTimeout("performTagSuggestSearch ( '"+trim(calcTagPrefix(true))+"' )",500);
            }
        }
    });
}

function calcTagPrefix(stripes){        
        var str = trim(jQuery('#tagging_field').val());
        if(stripes){
            str = removeStripes(str);
        }
        
        var tagPrefix = "";
        //Es gibt ein Komma       
        if(str.indexOf(',')!=-1){
            //debugOutput(getCursorPos());
            var begin = 0;
            for(i=getCursorPos()-1;i>0;i--){
               begin = i+1;
               //debugOutput(i+": "+str.charAt(i));
               if(str.charAt(i)==','){
                   break;
               }   
               //debugOutput(i);
            }
            if(begin<3)
               begin=0;
            
            var end = str.indexOf(',',getCursorPos());
            if(end==-1)
               end = str.length;
            var cursorPosition = getCursorPos();
            tagPrefix = str.substring(begin,end);    
            //debugOutput (tagPrefix+" "+begin+" "+end+" "+cursorPosition);       
        }
        //Kein Komma, also einzelnes Wort
        else{
            tagPrefix = str;
        }         
        return tagPrefix; 
}
/*
 */
(function() {
    var fieldSelection = {
        getSelection: function() {
            var e = this.jquery ? this[0] : this;
            return (
                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    var l = e.selectionEnd - e.selectionStart;
                    return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
                }) ||
                /* exploder */
                (document.selection && function() {

                    e.focus();

                    var r = document.selection.createRange();
                    if (r == null) {
                        return { start: 0, end: e.value.length, length: 0 }
                    }
                    var re = e.createTextRange();
                    var rc = re.duplicate();
                    re.moveToBookmark(r.getBookmark());
                    rc.setEndPoint('EndToStart', re);

                    return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
                }) ||

                /* browser not supported */
                function() {
                    return { start: 0, end: e.value.length, length: 0 };
                }
            )();
        }
        
    };
    jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();

/**
 * This function is invoked with the results of an AJAX request, that was performed because
 * the user entered some chars into the box for tagging.
 *
 * @param communityTags: an array of tags (strings) of all community users,
 *                       or an empty array if there are no matching tags
 * @param ownTags:  an array of tags (strings) of the current user if the user is logged in,
 *                  or an empty array if the user is not logged in or if there are no matching tags
 * @param userLoggedIn: a boolean that specified, if the current user is logged in
 */
function fillTagSuggestSearch( communityTags, ownTags, userLoggedIn ) {   
    if (communityTags.length == 0){
        tag_noResultsLeft();
    
    }
    else{
        for(i=0;i<communityTags.length;i++){
            add_tagsuggest_keyword(communityTags[i],'left', true);
        }
    }
    if (userLoggedIn == true){
        if (ownTags.length == 0){
            tag_noResultsRight()
        
        }
        else{
            for(i=0;i<ownTags.length;i++){          
                add_tagsuggest_keyword(ownTags[i],'right', true);
            }
       }
    }
    else {// wenn userLoggedIn = false -> Man beachte den extra Übergabe-Wert
         jQuery('#tagsuggest_inner_right ul').append('<li class="no_border_bottom no_border_top text">Um eigene Tags als Vorschläge zu sehen, musst du dich <a href="#" onclick="showLoginAndRegisterBox();return false;" class="underline">einloggen</a> oder <a href="#" onclick="showLoginAndRegisterBox();return false;" class="underline">registrieren</a></li>');
            
    }   
}

// Wenn es keine Community Tags gibt, diese Funktion aufrufen
function tag_noResultsRight(){
    var dots = ""; // ans trunc ranh�ngen
   if(calcTagPrefix(false).length>11)
    var dots = '...';
    jQuery('#tagsuggest_inner_right ul').append('<li class="no_border_bottom no_border_top text">&Uuml;bernimm einen Tag (Schlagwort) oder gib einen neuen an:<br /><a href="javascript:applyLastTag();" class="underline">Jetzt "'+calcTagPrefix(false).substring(0,10)+''+dots+'" als neuen Tag &uuml;bernehmen.</a></li>');
}

// Wenn es keine "Meine Tags" gibt, diese Funktion aufrufen
function tag_noResultsLeft(){
    jQuery('#tagsuggest_inner_left ul').append('<li class="no_border_bottom no_border_top text">Keine Tags (Schlagw&ouml;rter) der Community vorhanden.</li>');
}

// Wenn es weder noch gibt, diese Funktion aufrufen
function tag_noResultsBoth(){
    tag_noResultsLeft();
    jQuery('#tagsuggest_inner_right ul').append('<li class="no_border_bottom no_border_top text">Leg einen neuen Tag (Schlagwort) an:<br /><a href="javascript:applyLastTag();" class="underline">Jetzt Eingabe als Tag &uuml;bernehmen.</a></li>');    
}

/* Einfach ein Item uebergeben, diese Funktion sortiert das automatisch korrekt ein.
 * Bei mehr als 5 Woerter auf einer Seite, werden weitere nicht mehr ber�cksichtigt 
 * @tag: Das Schlagwort als String
 * @ site: left,right => je nachdem, auf welche Seite es soll    
 */
function add_tagsuggest_keyword(tag,site, logged_in){
   var dots = ""; // ans trunc ranhaengen
   var escapedTag = escape(tag);
   if(tag.length>12)
    var dots = '...';
   if(site == 'left' && tagsuggest_words_left<5){
        if(tagsuggest_words_left==0){
            jQuery('#tagsuggest_inner_left ul').append('<li class="no_border_top" id="tag_left_'+tagsuggest_words_left+'"><a href=javascript:applyTagsuggest("'+escapedTag+'"); title="'+tag+'">'+tag.substring(0,11)+''+dots+'</a></li>');
        }
        else if(tagsuggest_words_left==4){
            jQuery('#tagsuggest_inner_left ul').append('<li class="no_border_bottom" id="tag_left_'+tagsuggest_words_left+'"><a href=javascript:applyTagsuggest("'+escapedTag+'");  title="'+tag+'">'+tag.substring(0,11)+''+dots+'</a></li>');
        }
        else{
             jQuery('#tagsuggest_inner_left ul').append('<li id="tag_left_'+tagsuggest_words_left+'"><a href=javascript:applyTagsuggest("'+escapedTag+'"); title="'+tag+'">'+tag.substring(0,11)+''+dots+'</a></li>');
        }
        tagsuggest_words_left++;
        tag_suggestResultCount ++;
   }
   else if(site == 'right' && tagsuggest_words_right<5){
        if (logged_in == true)
        {
            if(tagsuggest_words_right==0){
                jQuery('#tagsuggest_inner_right ul').append('<li class="no_border_top" id="tag_right_'+tagsuggest_words_right+'"><a href=javascript:applyTagsuggest("'+escapedTag+'"); title="'+tag+'">'+tag.substring(0,11)+''+dots+'</a></li>');
            }
            else if(tagsuggest_words_right==4){
                jQuery('#tagsuggest_inner_right ul').append('<li class="no_border_bottom" id="tag_right_'+tagsuggest_words_right+'"><a href=javascript:applyTagsuggest("'+escapedTag+'"); title="'+tag+'">'+tag.substring(0,11)+''+dots+'</a></li>');
            }
            else{
                 jQuery('#tagsuggest_inner_right ul').append('<li id="tag_right_'+tagsuggest_words_right+'"><a href=javascript:applyTagsuggest("'+escapedTag+'"); title="'+tag+'">'+tag.substring(0,11)+''+dots+'</a></li>');
            }           
            tagsuggest_words_right++;
             tag_suggestResultCount ++;
        }
        else{
             jQuery('#tagsuggest_inner_right ul').append('<li class="no_border_top" id="tag_right_'+tagsuggest_words_right+'">'+tag+'</li>')
        }
   }
   else{
        return; // Seite ist schon voll
   }
}

function getCursorPos(){
    return jQuery('#tagging_field').getSelection().end;
}

function lockCursor(){
    if(jQuery.browser.msie){
          var range = ge('tagging_field').createTextRange(); 
          range.collapse(true); 
          range.moveEnd('character', jQuery('#tagging_field').val().length); 
          range.moveStart('character', jQuery('#tagging_field').val().length); 
          range.select(); 
    }
    else{
        ge('tagging_field').setSelectionRange(lastCursorPos,lastCursorPos);
    } 
    
}

/** Implementiert die Pfeil Tasten Navigation 
 * Keycodes
 * 13: Return
 * 37: left
 * 38: top
 * 39: right
 * 40: bottom
 */
function tag_handleArrow(keyCode){
    if(ge('tagsuggest').style.display=="block")
        lockCursor();
    
    if(keyCode==40 && tag_arrowCounter<10 ){
       tag_dehighlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
       tag_arrowCounter++;
       if(tag_arrowCounter<10 && (tag_arrowCounter<tag_suggestResultCount)){
          tag_highlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
       }
       else{
          tag_arrowCounter = -1;
          ge('tagging_field').focus();
       }
    }
    else if(keyCode==37 && tag_arrowCounter>4){
        tag_dehighlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
        tag_arrowCounter-=5;
        tag_highlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
    }
    else if(keyCode==38 && tag_arrowCounter>-1){
        tag_dehighlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
        tag_arrowCounter--;
        if(tag_arrowCounter>-1){
            tag_highlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
        }
        else{
            ge('tagging_field').focus();
        }
    }
    else if(keyCode==39 && tag_arrowCounter<5 && (tag_arrowCounter+5<tag_suggestResultCount)){
        tag_dehighlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
        tag_arrowCounter+=5;
        tag_highlightArrow(tag_determineSite(tag_arrowCounter),tag_arrowCounter%5);
    }
    else if(keyCode==13){
        jQuery('#tagging_field').val(jQuery('#tagging_field').val().replace(/\n/,"")); // Zeilenumbrueche loeschen
         if(jQuery('#tagsuggest_inner .suggest_hover').size()!=0){
            applyTagsuggest(escape(jQuery('#tagsuggest_inner .suggest_hover').attr('title'))); //Tag appenden
         }
         else{
            applyLastTag();
         }
        ge('tagging_field').focus();
    }

}
// Highlightet ein Tag
function tag_highlightArrow(site,counter){
    jQuery('#tagsuggest_inner_'+site+' ul #tag_'+site+'_'+counter+' a').addClass('suggest_hover');
}
//Dehighlightet ein Tag
function tag_dehighlightArrow(site,counter){
    jQuery('#tagsuggest_inner_'+site+' ul #tag_'+site+'_'+counter+' a').removeClass('suggest_hover');
}

//Bestimmt die Seite, wo man mit den Pfeiltasten hinspringt
function tag_determineSite(counter){
    return tag_site = tag_arrowCounter<5?"left":"right";
}

// Versteckt den Tagsuggest Layer und leert ANSCHLIESSEND die beiden Spalten mit Tags
function hideTagsuggest(){
    if(f_hideTagsuggest){
       // ge('tagsuggest').style.display = "none";
        tagsuggest_words_left=0; // Wieviel Tags stehen auf der linken Seite    
        tagsuggest_words_right =0; // Wieviele auf der rechten
       jQuery('#tagsuggest_inner_left ul').empty();
       jQuery('#tagsuggest_inner_right ul').empty(); 
    }
    f_hideSuggest = false;
    tag_arrowCounter = -1;
}
//zuletzt eingetippte Buchstaben bis zum letzten Komma als Tag uebernehmen
function applyLastTag(){
    //erster eintrag ?
    if(ge('tagging_field').value.indexOf(',')==-1)
        var str = ge('tagging_field').value.substring(0,ge('tagging_field').value.length);
    //Folge eintrag wegen Kommata anders behandeln
    else
        var str = ge('tagging_field').value.substring(ge('tagging_field').value.lastIndexOf(',')+1,ge('tagging_field').value.length);
    //@freiheit AJAX Add eines Tags
    applyTagsuggest(str);    
}

//uebernimmt eine Auswahl in die Tag area
function applyTagsuggest(dies){
    ge('tagging_field').focus();
    lockCursor();
     dies = unescape(dies);
    //Wort bis zum Zeilenanfang oder letztem Komma loeschen
    var str = jQuery('#tagging_field').val();
    //Es gibt ein Komma
    if(str.indexOf(',')!=-1){
        
        //debugOutput("lastCursor: "+lastCursorPos+" "+ jQuery('#tagging_field').val().length);
        //Der User aenderte inmitten der Textarea Worte
        if(lastCursorPos < jQuery('#tagging_field').val().length){
              var begin = 0;
              var end = 0;
              for(i=lastCursorPos-1;i>0;i--){
                   begin = i+1;           
                   if(str.charAt(i)==','){
                       break;
                   }   
                   //debugOutput(i);
              }
              for(i=lastCursorPos;i<str.length;i++){
                   end = i+1;              
                   if(str.charAt(i)==','){
                       break;
                   }
              }    
              var offset = 0;
              if(begin<3)              
               var substring_1 = "";
              else
               var substring_1 = str.substring(0,begin)+" ";
              var substring_2 = str.substring(end,str.length);
              //debugOutput("begin "+begin+" end:"+end+" s1:"+substring_1+" s2:"+substring_2);
              jQuery('#tagging_field').val(substring_1+" "+dies+", "+substring_2);
        }
        else{
            str = str.substring(0,str.lastIndexOf(','))+',';
            jQuery('#tagging_field').val(str+" "+dies+',');
        }
    }
    //Kein Komma, also einzelnes Wort
    else{
        str = "";
        jQuery('#tagging_field').val(dies+',');
    }
    startHideTagsuggest();
    tag_arrowCounter = -1;
    
}
// Zeitversetzter Aufruf der hideTagsuggest zum Schliessen des Tagsuggest Layers
function startHideTagsuggest(){
    f_hideTagsuggest = true;
    window.setTimeout("hideTagsuggest()",1000);
}
// Obiger Zeitversetzter Aufruf kann widerrufen werden, falls der Nutzer mit Maus in den entsprechenden Bereich zur�ckkehrt
function stopHideTagsuggest(){
    f_hideTagsuggest = false;
}

/* Tag Suggest Suche ENDE*/


/* Suggest Suche im Header Bereich */
var suggestsearch_out = true;
var suggestsearch_was_disabled = false;
var suggest_words_left=0;
var suggest_words_right =0;
var activeSuggest = -1; //-1: startzustand, 0: keine aktive Suche,1: es wird gerade eine suche durchgeführt und der timeout läuft
var failedSearchQuery = "";
var failedSelectQuery = "";
var searchResultEmpty = false;
var suggestsearch_out_of_focus = true;
var suggestResultCount = 0; // Anzahl der Suchergebnisse
function initSuggest(isMinimized){
    if (!ge('search')) {
        return;
    }
    ge('search').onsubmit = function (){
        searchValue = jQuery('#suggestsearch_inner .suggest_hover').text();
        //searchValue = searchValue.substring(0,searchValue.indexOf('(')-1);
        if(searchValue!="")
            jQuery('#textfield').val(searchValue);
    };
    if(isMinimized){

        minimizeSuggest( false );
        enableSuggest();
        suggestsearch_out = false;
        disableSuggest();
    }
    jQuery('#textfield').unbind('keyup');

    // TBD
    jQuery('#textfield').keyup(function(event){
        handleArrow(event.keyCode);
        processEvent(event.keyCode);
    });

    //TBD
    jQuery('#select').change(function(event){
        processEvent("");
    });
}



function set_suggest_out_of_focus()  //jQuery('#account_nav, #filter_side,#level_1_navigation,#main_content,#logo img')
{
    suggestsearch_out_of_focus = true;
    window.setTimeout('timeoutHideSuggest()',TIMEOUT_SUGGEST_HIDE);
}

function clickOut_suggest_links()  //#suggestsearch_inner .ausblenden_img,#suggestsearch_inner .ausblenden
{
      if(suggestsearch_out){
          minimizeSuggest( true );
          disableSuggest();
      }
      else{
          maximizeSuggest();
          enableSuggest();
      }
}


function processEvent (keyCode) {
    //console.log('processEvent');
    if(jQuery('#textfield').val()==""){
       disableSuggest();
    }

    // disable suggest search for list search
    if (jQuery('#select').val().indexOf('LISTS') != -1) {
        //console.log('disable for list search');
        disableSuggest();
        return;
    }

    if(searchResultEmpty){
        if(keyCode == 8){
            searchResultEmpty =false;
            return;
        }
        if(failedSelectQuery != jQuery('#select').val()){
          searchResultEmpty = false;
        }
        else if(jQuery('#textfield').val().indexOf(failedSearchQuery)!=0){
          searchResultEmpty = false;
        }
    }

    if(!searchResultEmpty && (keyCode<36 || keyCode>41)){
        // erste Query
        if(activeSuggest==-1 && jQuery('#textfield').val()!=""){
            activeSuggest = 1;
            window.setTimeout("suggestSearch()",TIMEOUT_FIRST_SUGGEST);
        }
        // nachfolgende Queries
        if(activeSuggest==0 && jQuery('#textfield').val()!=""){
            activeSuggest = 1;
            window.setTimeout("suggestSearch()",TIMEOUT_SUGGEST);
        }
    }
}
var arrowCounter =-1;
var site = "left";
/**
 * 37: left
 * 38: top
 * 39: right
 * 40: bottom
 */
function handleArrow(keyCode){
    if(keyCode==40 && arrowCounter<10 ){
       dehighlightArrow(determineSite(arrowCounter),arrowCounter%5);
       arrowCounter++;
       if(arrowCounter<10 && (arrowCounter<suggestResultCount)){
          highlightArrow(determineSite(arrowCounter),arrowCounter%5);
       }
       else{
          arrowCounter = -1;
          jQuery('#textfield').focus();
       }
    }
    else if(keyCode==37 && arrowCounter>4){
        dehighlightArrow(determineSite(arrowCounter),arrowCounter%5);
        arrowCounter-=5;
        highlightArrow(determineSite(arrowCounter),arrowCounter%5);
    }
    else if(keyCode==38 && arrowCounter>-1){
        dehighlightArrow(determineSite(arrowCounter),arrowCounter%5);
        arrowCounter--;
        if(arrowCounter>-1){
            highlightArrow(determineSite(arrowCounter),arrowCounter%5);
        }
        else{
            jQuery('#textfield').focus();
        }
    }
    else if(keyCode==39 && arrowCounter<5 && (arrowCounter+5<suggestResultCount)){
        dehighlightArrow(determineSite(arrowCounter),arrowCounter%5);
        arrowCounter+=5;
        highlightArrow(determineSite(arrowCounter),arrowCounter%5);
    }



}

function highlightArrow(site,counter){
    jQuery('#suggestsearch_inner_'+site+' #keyword_'+site+'_'+counter+' a').addClass('suggest_hover');
}

function dehighlightArrow(site,counter){
    jQuery('#suggestsearch_inner_'+site+' #keyword_'+site+'_'+counter+' a').removeClass('suggest_hover');
}

function determineSite(counter){
    return site = arrowCounter<5?"left":"right";
}

function timeoutHideSuggest(){
    if(suggestsearch_out_of_focus){
        disableSuggest();
    }
}
function stopTimeoutHideSuggest(){
    suggestsearch_out_of_focus = false;
}

function suggestSearch () {

    var keyString = jQuery('#textfield').val();
    var searchSelection = jQuery('#select').val()

    performSuggestSearch( keyString, searchSelection );
}

/**
 * Hier ajax request abschicken und die ergenisse an 'add_suggest_keyowrd()' verfüttern
 */
function performSuggestSearch( input, searchSelection ){
    //enableSuggest();
    if(suggestsearch_was_disabled  && searchResultEmpty){
       suggestsearch_out = false;
    }
    else {
        //debugOutput("Input: " + encodeURIComponent(input) + " selection: " + encodeURIComponent(searchSelection));

        var body = "input=" + input
                + "&selection=" + searchSelection;


        var pageName = "start";
        if ( ge('pageNameForSuggest') ) {
            var tmpPageName = ge('pageNameForSuggest').innerHTML
            if ( tmpPageName && tmpPageName.length > 0 ) {
                pageName = tmpPageName;
            }
        }

        XMLHTTP.request (
            "POST",
            SHOP_BASEURL + "Start.maintemplate.getSuggestion",
            function (r) {
                //debugOutput(r.responseText);
                fillSuggestSearch(eval(r.responseText));
            },
            body
        );
    }
    activeSuggest = 0; // activeSuggest zuröcksetzen, damit die nächste Abfrage bearbeitet werden kann.
}
/**
 * suggestItemArray: array der Form [["Hose","122"],["Hosen","145"],["Hosenblubb","14"]];
 * iteriert suggestItemArray durch und übergibt je Iteration ein Tupel an add_suggest_keyowrd()
 */
function fillSuggestSearch(suggestItemArray){
    suggestResultCount = suggestItemArray.length;
    reset_suggest_keywords();

    if( suggestItemArray.length == 0 ){
        searchResultEmpty = true;
        failedSearchQuery = jQuery('#textfield').val();
        failedSelectQuery = jQuery('#select').val();
        no_suggest_available();
    }
    else{
        enableSuggest();
        searchResultEmpty = false;
        for(i=0;i<suggestItemArray.length;i++){
            add_suggest_keyword(suggestItemArray[i][0]);
        }
    }
}

function submitSuggest(dies){
    jQuery('#textfield').val(dies);
    ge('search').submit();
}

function no_suggest_available(){
    disableSuggest();
}

/**
 * name: Name des Keywords
 * count: Trefferanzahl zur Anzeige hinter des Keywords
 * Könnte zb öber eine for schleife aufgerufen werden. Wenn alle 10 Plätze belegt sind, gibts n return.
 * Heißt: Nr. 11 wird garantiert nicht angezeigt
 * Zuerst wird die linke Seite von oben nach unten gefüllt, dann die rechte.
 */
function add_suggest_keyword(name){
    var submitLink;
    if (name.indexOf('\'') >= 0) {
        submitLink = '<a href=\'javascript:submitSuggest("' + escape(name) + '");\'>' + name + '</a>';
    } else {
        submitLink = '<a href="javascript:submitSuggest(\'' + name + '\');">' + name + '</a>';
    }
    
    if(suggest_words_left<5){
        if(suggest_words_left==0){
            jQuery('#suggestsearch_inner_left').append('<li class="no_border_top" id="keyword_left_'+suggest_words_left+'">' + submitLink + '</li>');
        }
        else if(suggest_words_left==4){
            jQuery('#suggestsearch_inner_left').append('<li class="no_border_bottom" id="keyword_left_'+suggest_words_left+'">' + submitLink + '</li>');
        }
        else{
             jQuery('#suggestsearch_inner_left').append('<li id="keyword_left_'+suggest_words_left+'">' + submitLink + '</li>');
        }
        suggest_words_left++;
   }
   else if(suggest_words_right<5){
        if(suggest_words_right==0){
            jQuery('#suggestsearch_inner_right').append('<li class="no_border_top" id="keyword_right_'+suggest_words_right+'">' + submitLink + '</li>');
        }
        else if(suggest_words_right==4){
            jQuery('#suggestsearch_inner_right').append('<li class="no_border_bottom" id="keyword_right_'+suggest_words_right+'">' + submitLink + '</li>');
        }
        else{
             jQuery('#suggestsearch_inner_right').append('<li id="keyword_right_'+suggest_words_right+'">' + submitLink + '</li>');
        }
        suggest_words_right++;
   }
   else{
        return;
   }
}

/**
 * Löscht die ganze Liste
 */
function reset_suggest_keywords(id){
     jQuery('#suggestsearch_inner_left').empty();
     jQuery('#suggestsearch_inner_right').empty();
     suggest_words_left = 0;
     suggest_words_right=0;
}
/**
 * Die Suggestsuche wird zum kleinen Balken
 */
function minimizeSuggest( send ){
    jQuery('#suggestsearch_inner ul').css('display', "none");
    ge('suggestsearch_inner_footer').style.display ="none";
    jQuery('#suggestsearch').css({"height":"39px","background-image":"url("+ STATIC_CONTENT_PREFIX  +"css/img/bg_suggestsearch_small.gif)"});
    suggestsearch_out = false;
    jQuery('#suggestsearch_inner .ausblenden_img').attr('src',STATIC_CONTENT_PREFIX  +'img/15x15_triangle_down.gif');
    jQuery('#suggestsearch_inner .ausblenden').text('anzeigen');
    jQuery('#suggestsearch').show();
    if ( send ) {
        suggestDialogMinimized();//Freiheit
    }
}
/**
 * Die Suggestsuche wird voll ausgefahren
 */
function maximizeSuggest(){
    jQuery('#suggestsearch').css({"height":"189px","background-image":"url("+ STATIC_CONTENT_PREFIX  +"css/img/bg_suggestsearch.gif)"});
    jQuery('#suggestsearch_inner ul').css("display","block");
    ge('suggestsearch_inner_footer').style.display ="block";
    suggestsearch_out = true;
    jQuery('#suggestsearch_inner .ausblenden_img').attr('src',STATIC_CONTENT_PREFIX  +'img/15x15_triangle_up.gif');
    jQuery('#suggestsearch_inner .ausblenden').text('ausblenden');
    jQuery('#suggestsearch').show();
    suggestsearch_was_disabled = false;
    suggestDialogMaximized();//Freiheit
}
/**
 * Der gesamte Suggestbereich wird unsichtbar
 */
function disableSuggest(){
    //suggestsearch_out=false;
    suggestsearch_was_disabled = true;
    activeSuggest = 0;
    jQuery('#suggestsearch').hide();
}
/**
 * Der gesamte Suggestbereich wird sichtbar
 */
function enableSuggest(){
    //suggestsearch_out = true;
    jQuery('#suggestsearch').bgiframe();
    ge('suggestsearch').style.display ="block";
}

function suggestDialogMinimized () {
   // debugOutput("minimized");
    setStringProperty( "suggestDialogMinimized", "true" );
}
function suggestDialogMaximized () {
    debugOutput("maximized");
    setStringProperty( "suggestDialogMinimized", "false" );
}

// ========= Suggest-Suche End =========


function set_url_focus()
{
    ge('url_2_copy').focus();
    document.url_copyform.url_2_copy.select();
    document.url_copyform.url_2_copy.focus();

}

function show_navigation(nav, menu) {
    disableSuggest();

    hide_navigation_total();

    var number = menu;
    var sub_menu = 'category_menu_'+number;

    active_navigation = sub_menu;
    //alert (active_navigation);


     main_nav = jQuery("#level_1_navigation .navi_"+ number);



    switch (number)
    {
        case 1:
        jQuery(main_nav).css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/mode_02.gif)",'color': '#F02914'  });
        break;
        case 2:
        jQuery(main_nav).css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/wohn_02.gif)",'color': '#A5B514'  });
        break;

        case 3:
        jQuery(main_nav).css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/life_02.gif)",'color': '#E626AD' });
        break;

    }

    jQuery('#'+sub_menu).bgiframe();
    jQuery('#'+sub_menu).show();
}

function hide_navigation(nav) {


    active_navigation = 'category_menu_'+nav;
    active_timer = window.setTimeout("hide_navigation_total()", 500);
}

function hide_navigation_total() {
     if (active_navigation != null)
     {

        var navi1 = jQuery('#level_1_navigation li a.navi_1');
        var navi2 = jQuery('#level_1_navigation li a.navi_2');
        var navi3 = jQuery('#level_1_navigation li a.navi_3');

        // The if-tests are for assuring that permanently active
        // items are not made unactive
        if (navi1.attr("class").indexOf("active") == -1) {
            navi1.css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/mode_01.gif)", 'color': '#666666' });
        }
        if (navi2.attr("class").indexOf("active") == -1) {
            navi2.css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/wohn_01.gif)", 'color': '#666666' });
        }
        if (navi3.attr("class").indexOf("active") == -1) {

            navi3.css({"background-image": "url("+ STATIC_CONTENT_PREFIX  +"css/img/nav/life_01.gif)", 'color': '#666666' });
        }

        //jQuery(main_nav).removeClass("active");
         jQuery('#'+active_navigation).hide();
     }
}

function keep_navigation(menu) {
    window.clearTimeout(active_timer);
    jQuery('#'+menu).show();
}


function initBrowserChanges(){
    if (!ge('tool_container')) {
        // If we are not in mainTemplate
        return;
    }

    if ( jQuery.browser.opera ){ //makes Tool visible in Opera <9
        if (jQuery.browser.version < 9){
            ge("tool_container").style.position = 'static';

            ge('tool_container_fixed').style.left = (jQuery("body").width()/2)+ 308;
        }
    }

    

         if(jQuery.browser.safari){

         jQuery('#validate_mailmessage').css({'width': '300', 'text-align':'right'});
         jQuery('#tagsuggest').css('top', '81px');
         jQuery('.clickoutButtonContainer img').css('margin-top','1px');
        
         
         }

        var link_text ="";
        /*  no use
        jQuery('.bottom_link').mouseover(function() {
          window.status =  jQuery(this).html();
        });
        */




        if(jQuery.browser.msie && jQuery.browser.version <= 6){

            /* .TB_overlay h�he und breite setzten */

            var weite = '100%';/*document.body.scrollWidth > document.body.offsetWidth ? document.body.scrollWidth : document.body.offsetWidth + 'px';*/
            var hoehe = document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px';
            jQuery('.TB_overlay').css({'width': weite,  'height': hoehe});

           /* Statuszeilentext im IE 6*/
            if(jQuery('.bottom_link').size()>0){}

           makeStatic();
           try {
               document.execCommand("BackgroundImageCache", false, true);
            } catch(err) {}

            if(jQuery.browser.msie && jQuery.browser.version <= 6){
                //smatchbox
                makeStatic();
               try {
                   document.execCommand("BackgroundImageCache", false, true);
                } catch(err) {}

                /* send2HTML -> add_remove_BorderClass
                small_pic =  jQuery('.small_pic');
                small_pic.mouseover(function(){
                    jQuery(this).addClass('bordered_small_pic');
                }
                );
               small_pic.mouseout(function(){
                    jQuery(this).removeClass('bordered_small_pic');
                }

                );
                 */
             }
         }
}

function add_remove_BorderClass(element, val)
{
    if (val == 1)
    {
        jQuery(element).addClass('bordered_small_pic');
    }
    else
    {
         jQuery(element).removeClass('bordered_small_pic');
    }
}


// Returns matching body object to the view mode in IE
function truebody(){
    return (document.compatMode!="BackCompat")? document.documentElement : document.body
}

// Makes the smatch appear static in M$ IE6
function makeStatic(){
    winY = truebody().scrollTop; // get Scroll Position

     // Case:
     if(winY==lastY &&  !smatchVisible  && flag ){
            document.getElementById("notice_container_fixed").style.pixelTop -= 132
            jQuery("#notice_container_fixed").show(0);
            setTimeout("display_smatch()",900);
            while(smatchVisible);
            jQuery('#mouse form').css('margin-left','24px');
            flag=false;
            pixelTopSmooth = 130;
    }

     else if(winY!=lastY  && smatchVisible){
        jQuery("#notice_container_fixed").hide();
        smatchVisible = false;
        mouse_down = false;
    }
    if (winY != lastY && winY>YOffset-staticYOffset) {
        smooth = .2 * (winY - lastY - YOffset + staticYOffset-staticYOffset);
    }
    else if (YOffset-staticYOffset+lastY > YOffset-staticYOffset && winY != lastY) {
        smooth = .2 * (winY - lastY - (YOffset-(YOffset-winY)));
    }
    else {
        smooth=0;
    }
    if(smooth > 0)
        smooth = Math.ceil(smooth);
    else
        smooth = Math.floor(smooth);
    document.getElementById("notice_container_fixed").style.pixelTop+=smooth;
    lastY = lastY+smooth;
    setTimeout('makeStatic()', 1)
}

function display_smatch(){

    document.getElementById("notice_container_fixed").style.pixelTop += 4;
    pixelTopSmooth -=4;
    if(pixelTopSmooth>0)
        setTimeout('display_smatch()', 1);

    smatchVisible = true;
    flag = true;
}

function ge(id){
    /*
    um das ewige document.getElementById() zu unterlaufen
    */
    return document.getElementById(id);
}


function initHomepageHeadline()
{
    if (!ge('main_teaser_right_1')) {
        // If we are not on the home page...
        return;
    }

    window.setTimeout("showHomepageHeadline('#main_teaser_right_1')", 0);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_1')", 2500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_2')", 3000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_2')", 4500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_3')", 5000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_3')", 6500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_4')", 7000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_4')", 8500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_1')", 9000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_1')", 10500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_2')", 11000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_2')", 12500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_3')", 13000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_3')", 14500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_4')", 15000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_4')", 16500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_1')", 17000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_1')", 18500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_2')", 19000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_2')", 20500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_3')", 21000);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_3')", 22500);
    window.setTimeout("showHomepageHeadline('#main_teaser_right_4')", 23000);




}

function showHomepageHeadline(element)
{
    jQuery(element).animate({opacity: 'toggle'}, "200");
}


function tooglelogininfo()
{

    window.setTimeout("showHomepageHeadline('#login_info1')", 2500);
    window.setTimeout("showHomepageHeadline('#login_info2')", 3000);
    window.setTimeout("showHomepageHeadline('#login_info2')", 4200);
    window.setTimeout("showHomepageHeadline('#login_info1')", 5000);
    window.setTimeout("showHomepageHeadline('#login_info1')", 6200);
    window.setTimeout("showHomepageHeadline('#login_info2')", 7000);
    window.setTimeout("showHomepageHeadline('#login_info2')", 8200);
    window.setTimeout("showHomepageHeadline('#login_info1')", 9000);
}


function showShopDetails(shop_id)
{

    shopInfo = window.open(SHOP_BASEURL + "shop/details/" + shop_id, "Info", "width=470,height=550,left=100,top=200, scrollbars=yes, toolbar=no");
      shopInfo.focus();


}

var POS_TYPE = '1'; // typ für die Quickview
var IS_OVERVIEW = false; // WENN über Pic oder Quickview-box true; default: false
var quickViewLoading = false;
var quickViewProductId = "";
var active_timer = null;
var qvTimer = 0;

function quickview_time(productId)
{
    //Aufruf nach Timeraufruf und wenn über .product oder #quickview
    
    
    if (IS_OVERVIEW == true && !quickViewLoading)
    {
        quickViewLoading = true;

        if (quickViewProductId == productId) {
            
            // don't make a new ajax request
            // if the quick view is already displayed
            jQuery('#quickview').bgiframe();
            jQuery('#quickview').show();
            quickViewLoading = false;
           // debugOutput('PID alt'+quickViewProductId);
            
        } else {
            
            XMLHTTP.request("GET", SHOP_BASEURL + "productquickviewcontent/"+
            productId,
            function(r) {
                jQuery('#quickview_inner_content').html(r.responseText);
                quickViewProductId = productId;
                jQuery('#quickview').bgiframe();
                jQuery('#quickview').show();
                if (WEBTRACKING_ENABLED) {
                    trackShowQuickView();
                }
                quickViewLoading = false;
               
            });
             //debugOutput('PID neu'+quickViewProductId);
        }
      
    }
}

function initQuickview(parentElement){
    if (!ge('quickview')) {
        // if not in mainTemplate...
        return;
    }
    //send2HTML
    initProductsForQuickview("");

    quickview_content_inner = jQuery("#quickview_content_inner");
    quickview_content_inner.mouseout( function() {IS_OVERVIEW = false; } );
    quickview_content_inner.mouseover( function() { IS_OVERVIEW = true; show_quickview(this);});
    //debugOutput ('+'+this+'-'+parentElement+'+');

}


function quickview_inner_mouseout()
{
    IS_OVERVIEW = false;
        window.clearTimeout(qvTimer); // Zurechtsetzen des Timers, damit nicht die Produkte w�hrend der Anzeige geladen werden
}

function quickview_inner_mouseover()
{
    IS_OVERVIEW = true;
}

function initProductsForQuickview(parentElement) {
    // Initialisierung der Quickview; alle .products sind quickviewable ;O)
    //debugOutput (parentElement+' - ');
    /*products = jQuery(parentElement + " .products");
    products.mouseout( function() { productImageOut(this) } );
    products.mouseover( function() { productImageOver(this) });        
    */
}

function productImageOver(element) {
    IS_OVERVIEW = true;
    //show_quickview(element);
}

function productImageOut(element) {
    IS_OVERVIEW = false;
   // window.clearTimeout(qvTimer); // Zurechtsetzen des Timers, damit nicht die Produkte w�hrend der Anzeige geladen werden
}

var testQV = false;

function testQv(element){
    if(testQV != true){
        jQuery('div.qv').removeClass('qv_activ2');
        //jQuery(this).removeClass('qv_activ');
    }
    
}


function hide_quickview(){

    if (!ge('main_content_inner')) {
        // If not in mainTemplate...
        return;
    }

    // Quickview ausblenden, wenn nicht über .product oder #quickview

    // send2HTML
    jQuery("#main_content_inner").mouseover( function(){
            if (IS_OVERVIEW != true){
                jQuery('#quickview').hide();
                IS_OVERVIEW = false;
            }
        }
    );
  
}

function hide_main_inner()
{
    if (IS_OVERVIEW != true){
              jQuery('#quickview_inner_content div').hide();
                jQuery('#quickview').hide();
                jQuery('div.qv').removeClass('qv_activ');
                if(testQV){
                    jQuery('div.qv').removeClass('qv_activ2');
                }
                testQV = false;
                IS_OVERVIEW = false;
                window.clearTimeout(qvTimer); // Zurechtsetzen des Timers, damit nicht die Produkte waehrend der Anzeige geladen werden
            }
}

/*#######################
Einblenden der QuickView - new version
########################*/


function qv_show(element, view){
    jQuery(element).addClass('qv_activ');
    //console.log(jQuery(element).parent().parent().find('img.products'));
    var productClasses = jQuery(element).parent().find('img.products').attr('class');;
    
    
    //var productClasses = jQuery(element).prev().attr('class');
    var regexp = /^.*id_([0-9]+)[^0-9]+.*$/;
    regexp.exec(productClasses);
    var productId = RegExp.$1;
    //ajaxRequest
    XMLHTTP.request("GET", SHOP_BASEURL + "productquickviewcontent/"+productId,function(r) {
        jQuery('#quickview_inner_content').html(r.responseText);
        quickViewProductId = productId;
        jQuery('#quickview').bgiframe();
        jQuery('#quickview').show();
            if (WEBTRACKING_ENABLED) {
                trackShowQuickView();
            }
        quickViewLoading = false;
       
    });
    show_quickview(jQuery(element).parent().parent().find('img.products'));
    
}
function show_quickview(element)
{
    //return;
    //Anzeige-Optionen der Quickview; Laden des richtigen BGs, setzen der Position relativ zum Bild etc
    window.clearTimeout(qvTimer); // Zurechtsetzen des Timers, damit nicht die Produkte w�hrend der Anzeige geladen werden
    //debugOutput('raus');
    IS_OVERVIEW = true;
    jQuery("#navtest").text(IS_OVERVIEW);
    for (var i=1; i<=4; i++ ) // BG setzen
    {
        if (i == POS_TYPE)
        {
            jQuery('#quickview_box').addClass('quickview_box_type_' + POS_TYPE);
            jQuery('#quickview_shadow').addClass('quickview_shadow_type_' + POS_TYPE);
        }
        else
        {
            jQuery('#quickview_box').removeClass('quickview_box_type_' + i);
            jQuery('#quickview_shadow').removeClass('quickview_shadow_type_' + i);
        }
    }

    // Position von element, um von dort die Position des overviews zu berechnen
    var result = eval(jQuery(element).offset({ border: true, padding: true }));
    elemTop  = result['top'];
    elemLeft = result['left'];

    jQuery(element).removeAttr('title');

    var from_left=0, from_top = 0; // Positions-VAR
    switch (POS_TYPE)
    {
        case '2':
            // nupsi links oben
            from_left   =  elemLeft+ (jQuery(element).width()-10);
            from_top    =   elemTop;
        break;

        case '3':
            // nupsi rechts unten
            from_left   =   elemLeft-285;
            from_top    =   elemTop-(290-(jQuery(element).height()-20));
        break;

        case '4':
            // nupsi rechts oben
            from_left   =   elemLeft-285 ;
            from_top    =   elemTop;

        break;

        default:
            // nupsi links unten
            from_left   =   elemLeft+ (jQuery(element).width()-10);
            from_top    =   elemTop-(290-(jQuery(element).height()-20));
        break;
    }
    if(jQuery.browser.msie && !(jQuery(element).parents('.prod_container_l,.prod_container_m,.prod_container_s').size()>0)){
        from_left-= 10;}


    jQuery('#quickview').css({left: from_left, top: from_top});

   /* var productClasses = jQuery(element).attr('class');
    var regexp = /^.*id_([0-9]+)[^0-9]+.*$/;
    regexp.exec(productClasses);
    var productId = RegExp.$1;*/

   // var parent = jQuery(element).parent('div'); // check parent
    
   
    
 /*   if ( productClasses.indexOf('no_quickview') == -1 ) // Check if the quickview should be shown or not
    {
        if (ge('quickview').style.display == 'none') {
            qvTimer = window.setTimeout("quickview_time("+ productId + ")", 1500); // aufrufen der Quickview anzeige nach 1.5 sekunden                      
        } else {
            // If the quickview is already shown, load the new product immediately
             qvTimer = window.setTimeout("quickview_time("+ productId + ")", 1500); // aufrufen der Quickview anzeige nach 1.5 sekunden         
            //quickview_time(productId);
        }
    }*/
}



function mouse_pos(){
    if (!ge('quickview')) {
        // if not in mainTemplate...
        return;
    }

    // Entschlüsseln der mouse-position relativ für viewport; setzen des BGs und der damit verbundenen Positionierung (POS_TYPE)
    var type;
    jQuery().mousemove(function(e){
        var x_pos='', y_pos='';

        if (e.pageX < jQuery(window).width()/2){
            x_pos = '1'; //left
        }
        else{
            x_pos = '2'; // right
        }

        if ( e.clientY <=300){
            y_pos = '2'; // top
        }
        else{
            y_pos = '1';    //bottom
        }

        if (x_pos == '1' && y_pos== '1'){
            POS_TYPE = '1';
        }
        if (x_pos == '2' && y_pos== '1'){
            POS_TYPE = '3';
        }
        if (x_pos == '1' && y_pos== '2'){
            POS_TYPE = '2';
        }
        if (x_pos == '2' && y_pos== '2'){
            POS_TYPE = '4';
        }
    })
}




/* Spinner-Aufrufe*/

function showSpinnerForSearchContent() {    
    jQuery("#headline_spinner").show(); 
    jQuery("#footerline_spinner").show(); 
}

function hideSpinnerForSearchContent() {
    jQuery("#headline_spinner").hide(); 
    jQuery("#footerline_spinner").hide(); 
}

function showSpinnerForMoreFacets() {
    jQuery("#moreless_facets_spinner").show(); 
    jQuery("#moreless_facets_spinner").next().css('margin-left','0')
}

function hideSpinnerForMoreFacets() {
    jQuery("#moreless_facets_spinner").hide(); 
    jQuery("#moreless_facets_spinner").next().css('margin-left','17px')
}


var bigSpinner ='<div id="bigSpinnerContainer"><img src="' + STATIC_CONTENT_PREFIX +'img/progress_ani_gr.gif" width="32" height="32" /></div>';
function  showSpinnerForMoreOptions(element) {
    jQuery('#facet_content_'+element).css('background-color','rgb(256, 256, 256)');
    jQuery('#categoryToFold_'+element).css('position','relative');
    
    jQuery(bigSpinner).prependTo('#categoryToFold_'+element); // 
    jQuery('#bigSpinnerContainer').css('height',jQuery('#categoryToFold_'+element).height() );
                                 
    jQuery('#bigSpinnerContainer img').css('margin-top',(jQuery('#categoryToFold_'+element).height()/2) -24);
    
    jQuery('#categoryToFold_'+element + ' .category_changer').css('overflow', 'hidden'); 
}

function  hideSpinnerForMoreOptions(element) {

    jQuery('#facet_content_'+element).css('background-color','transparent');
    jQuery('#categoryToFold_'+element + ' .category_changer').css('overflow', 'auto');
    jQuery("#bigSpinnerContainer").remove();
}
                                         

/* pers HP */

function toggle_pers_hp()
{
    jQuery('#todo_teaser').toggle();
 
    if (jQuery('#toggle_pers_hp_link').html() == 'ausblenden')
    {
        XMLHTTP.request("GET", SHOP_BASEURL + "user/community.personalizedhp.setstatus/" + 'false', function(r){});  
        jQuery('#toggle_pers_hp_img').attr('src', STATIC_CONTENT_PREFIX +'img/15x15_triangle_down.gif');
        jQuery('#toggle_pers_hp_link').html('einblenden');
    }
    else
    {
        XMLHTTP.request("GET", SHOP_BASEURL + "user/community.personalizedhp.setstatus/" + 'true', function(r){});  
        jQuery('#toggle_pers_hp_img').attr('src', STATIC_CONTENT_PREFIX +'img/15x15_triangle_up.gif');
        jQuery('#toggle_pers_hp_link').html('ausblenden');

    }



}


function clear_value (element, text)
{
    jQuery(element).addClass('write_color');
    // Leeren von Inputs, wenn Text = default-Text
    if (element.value == text)
    {
        element.value='';
        

    }
}

DEFAULT_SEARCH_TEXT = "Ich suche...";

function initSearchValue(){
    if (!ge('query')){
        // may occur if no mainTemplate is present
        return;
    }

    // Ausgabe des Default-Textes, wenn kein Text im Suchfeld
    if(ge('query').value == ''){
        ge('query').value = DEFAULT_SEARCH_TEXT;
    }
}

function linkToSearch(params) {
    window.location.href = SHOP_BASEURL + "search/" + params;
}

function shopping_slider(min, max)
{
    //alert(min + " - " + max);
     /*
    Preis-Schieber
    min und max per body-load übergeben und sind dadurch variabel
    */
    if (!ge('price_changer_d_1')) {
        // If we are on the wrong page,
        // then leave this function
        return;
    }

    //alert(min + " - " + max);

    ge('minPrice').value = min;
    ge('maxPrice').value = max;

    //alert("2 - " + min + " - " + max);

    //alert("3 - " + min + " - " + max);

    jQuery('.slider4').Slider(
        {
            accept: '.indicator',
            restricted: true,
            opacity: 0.8,
            values: [
                [0,0],
                [55540,0]
            ],
            onSlide : function(procx, procy, x, y) {
                /*var tempLowPrice=0;
                var tempHighPrice=1200;*/
                //price = ((min + parseInt(max * procx/100))/100) * 100;
                price = ((max-min)/100)*procx;
                //price = procx;
                ge(this.SliderIteration == 0 ? 'minPrice' : 'maxPrice').value = Math.round(price + min) ;
                //this.SliderIteration == 0 ? tempLowPrice=price : tempHighPrice=price;
                /*if(tempLowPrice!=lowPrice){
                    if(tempLowPrice < lowPrice)
                        filterContent(1,"block");
                    else
                        filterContent(1,"none");
                }
                else if(tempHighPrice!=highPrice){
                }*/
                //lowPrice = tempLowPrice;
                //highPrice = tempHighPrice;
                //ge('linkForPriceFacet').href = "[" + ge('minPrice').value + " TO " + ge('maxPrice').value + "]";
            }
        }
    );
}


function toogleBox (element)
{
    /*
    Ändert das Anzeigen einer Ebene von Block auf none

    */
    if (ge(element).style.display =="none")
    {
        ge(element).style.display = "block";
    }
    else
    {
        ge(element).style.display ="none";
    }

}


function toogle_communityBox (element, type)
{
    /* Toogle für die CommunityBox : taggen, bookmarken, weitersagen.... */

    justHide_communityBox ();

    /* highlights setzen*/
    var papa =jQuery(element).parent('div');
    jQuery(papa).addClass("active");
    jQuery(element).addClass("active");
    jQuery("#" + type).css ("display", "block");
    jQuery('#tagging_field').css('visibility','visible');
    jQuery('#tagging p').css('visibility','visible');
    jQuery('#product_tagging_field').css('visibility','visible'); 
    jQuery('#tagging button').css('visibility','visible');
    jQuery("#tagsSpinner").hide();
    jQuery("#tagsSpinner").css('visibility','visible');
}

function justHide_communityBox ()
{
    /* alles in den Ursprungszustand*/
    jQuery(".liststyle_link").removeClass("active");
    jQuery(".liststyle_link a").removeClass("active");
    jQuery(".communityBox").css ("display", "none");

}


function toogleSelectBox(element)
{
    /*
    Ändert das Anzeigen einer Ebene von Block auf none, hier speziell für die Pseudo-Selectboxen

    */
    if (ge('box_' + element).style.display =="none")
    {
        ge('box_' + element).style.display = "block";
        ge('triangle_' + element).src = STATIC_CONTENT_PREFIX + "img/triangle_up_topsearch.png";

    }
    else
    {
        ge('box_' + element).style.display ="none";
        ge('triangle_' + element).src = STATIC_CONTENT_PREFIX + "img/triangle_down_topsearch.png";
    }

}



function change_bg_color (element, color)
{
    // allgemeines Ändern der BG-Color bei bestimmten Events in übergebenen Wert
    jQuery(element).css ('background-color', color);
}


function switch_multiselect(element,the_class,number)
{
    /*
    Ändern der Multiselectanzeige
    */
    var count = ge('box_'+the_class).childNodes.length;

    for (i = 1; i <= count; i++)
    {
        if (i== number)
        {
            ge('multiselect_' + the_class).innerHTML = element.innerHTML;  /* Namen in der Leiste oben ändern*/

            ge(the_class + '_' + i).style.display = 'block'; /* Ebene Anzeigen*/

            element.style.display = "none"; /* Namen im Auswahlfeld 'löschen'*/
            ge('box_' + the_class).style.display ="none";    /* Select schließen*/
            ge('triangle_' + the_class).src = STATIC_CONTENT_PREFIX + "img/triangle_down_topsearch.png"; /* Pfeil-Grafik änder*/

        }
        else{

            element.style.display = "block"; /* Namen im Auswahlfeld anzeigen*/
        }
    }

}


function change_triple_tab(element)
{
    /*
    Ändert die sichtbare Ebene der 3 Tab-Reiter unten im Produktdetail
    */

    var count = 3;
    for (i = 1; i <= count; i++)
    {
        if (i== element)
        {
            ge('triple_tab').style.backgroundImage = 'url('+ STATIC_CONTENT_PREFIX + 'css/img/triple_tab_' + element + '.gif)';  /* BG in der Leiste oben ändern*/
            ge('triple_tab_box_' + i).style.display = 'block'; /* Ebene Anzeigen*/
             ge('change_triple_l_' + i).className = "active";
               ge('change_triple_l_' + i).style.color = "#006EC0";
        }
        else{
            ge('triple_tab_box_' + i).style.display = 'none'; /* Ebene NICHT Anzeigen*/
            ge('change_triple_l_' + i).className = "active";
               ge('change_triple_l_' + i).style.color = "#92BDDD";
        }
    }
}

function change_multi_tab_simple(element, tab)
{

  //  alert(jQuery(element).parent('li'));
    jQuery("#"+ tab +" li").removeClass('active');
    jQuery(element).parent('li').addClass('active'); 
}

function change_multi_tab(element, tab, number)
{
    /*
    Ändert die sichtbare Ebene der 3 Tab-Reiter unten im Produktdetail
    */
    //alert("#"+ tab +" li" + ":" + jQuery("#"+ tab +" li"));
    jQuery("#"+ tab +" li").removeClass('active');
       jQuery("#"+ tab +" li a").removeClass('active');

    var count = ge(tab).childNodes.length;
    for (i = 1; i <= count; i++) {
        if (i== number) {
            ge(tab + '_container_' + i).style.display = 'block'; /* Ebene Anzeigen*/
            jQuery(element).addClass('active');
            var papa =jQuery(element).parent('li');
            jQuery(papa).addClass('active');
        } else {
            ge(tab + '_container_' + i).style.display = 'none'; /* Ebene NICHT Anzeigen*/
        }
    }
}

function loadTeaserBoxAjax(element, tab, number,
    query, queryName, linkText, linkQuery, teaserImage,
    sortField, sortAsc, maxResults) {
    change_multi_tab(element, tab, number);

    var innerDiv = jQuery("#"+ tab + '_container_' + number+ " div");
    if (innerDiv.size() > 0) {
        // Tab is already loaded
        return;
    }

    // load content per ajax
    var body = "query=" + encodeURIComponent( query )
             + "&queryName=" + encodeURIComponent( queryName )
             + "&pageName=" + CURRENT_PAGE_NAME;
    if (linkText) {
        body += "&linkText=" + encodeURIComponent( linkText);
    }
    if (linkQuery) {
        body += "&linkQuery=" + encodeURIComponent(linkQuery);
    }
    if (teaserImage) {
        body += "&teaserImage=" + encodeURIComponent(teaserImage);
    }
    if (sortField) {
        body += "&sortField=" + encodeURIComponent(sortField);
    }
    if (sortAsc) {
        body += "&sortAsc=" + encodeURIComponent(sortAsc);
    }
    if (maxResults) {
        body += "&maxResults=" + encodeURIComponent(maxResults);
    }

    XMLHTTP.request(
        "POST",
        SHOP_BASEURL + "teaserBoxContentAjaxWrapper",
        function(r) {
            jQuery("#"+ tab + '_container_' + number).html(r.responseText);
            make_drag ("#" + tab + '_container_' + number + ' .products');
        },
        body
    );
}


function change_multi_tab_l(element, tab, number)
{
    /*
    Ändert die sichtbare Ebene der 3 Tab-Reiter unten im Produktdetail
    */

    jQuery("#"+ tab +" li").css({ height:"20px",  marginBottom:"1px" });
    jQuery("#"+ tab +" li").removeClass('active');
       jQuery("#"+ tab +" li a").css({ height:'20px', color:'#9C9C9C', marginBottom:'1px', fontWeight: 'normal' });

    var count = ge(tab).childNodes.length;
    for (i = 1; i <= count; i++)
    {
        if (i== number)
        {
            ge(tab + '_container_' + number).style.display = 'block'; /* Ebene Anzeigen*/
            jQuery(element).addClass('active');
            jQuery(element).css({ height:"21px", color:"#006EC0", marginBottom:"0px" , fontWeight: 'bold'});
            var dad =jQuery(element).parent('li');
            dad.css({ height:"21px", marginBottom:"0px" });
        }
        else{
            ge(tab + '_container_' + i).style.display = 'none'; /* Ebene NICHT Anzeigen*/

        }
    }
}

function show_detail_btn(element){
    jQuery("." + element + ".details").show();
}

function hide_detail_btn(element){
    jQuery("." + element + ".details").hide();
}

function highlight_prod_m (element)
{
    /* Gleichzeitiges Ändern von Produktrand-Farbe und Unterstrich zu den dazugehörigen Produktnamen und -preis*/
    jQuery("#" + element + " .prod_img").css("border", "1px solid #006EC0");

    var link = jQuery("#" + element + " .prod_desc_link");
    if (link.size() > 0) {
        link.css("text-decoration", "underline");
    }

}

function Dehighlight_prod_m (element)
{
    /* Gleichzeitiges Ändern von Produktrand-Farbe und Unterstrich zu den dazugehörigen Produktnamen und -preis in Ursprung*/
    jQuery("#" + element + " .prod_img").css("border", "1px solid #CCC");
    jQuery("#" + element + " a.prod_desc_link").css("text-decoration", "none");
}


function voting_text (number, color)
{
    if (color =="or")
        {
            var the_color = "#de5a1e";
        }
        else
        {
            var the_color = "#006ec0";
        }

    switch(number)
            {
                case 'star_vote_PRODUCT_1':
                jQuery('#text_voting').text('nicht mein Geschmack');

                break;

                case 'star_vote_PRODUCT_2':
                jQuery('#text_voting').text('ganz ok');
                break;

                case 'star_vote_PRODUCT_3':
                jQuery('#text_voting').text('das gefällt mir');
                break;

                case 'star_vote_PRODUCT_4':
                jQuery('#text_voting').text('find ich super');
                break;

                case 'star_vote_PRODUCT_5':
                jQuery('#text_voting').text('fantastisch!!!');
                break;


                case 'star_vote_PRODUCTLIST_1':
                jQuery('#text_voting').text('nicht mein Geschmack');

                break;

                case 'star_vote_PRODUCTLIST_2':
                jQuery('#text_voting').text('ganz ok');
                break;

                case 'star_vote_PRODUCTLIST_3':
                jQuery('#text_voting').text('das gefällt mir');
                break;

                case 'star_vote_PRODUCTLIST_4':
                jQuery('#text_voting').text('find ich super');
                break;

                case 'star_vote_PRODUCTLIST_5':
                jQuery('#text_voting').text('fantastisch!!!');
                break;



                default:
                jQuery('#text_voting').text('');
                break;
            }
    ge('text_voting').style.color = the_color;

}

function stars_vote (element, color)
{
    /* Sterne für Produktbewertung bei Mouseover highlighten oder de-highlighten sowie setzen des Values für ein input hidden -> Übermittlung in der Form */
    for (var i =1; i <= 5; i++)
    {
        if (color =="or")
        {
            var the_color = "#de5a1e";
        }
        else
        {
            var the_color = "#006ec0";
        }

        if (i <= element)
        {
            ge('star_vote_' + i).src = STATIC_CONTENT_PREFIX +"img/17x16_proddet_star_" + color + "_full.gif";

            switch(i)
            {
                case 1:
                jQuery('#text_voting').text('solala');
                ge('text_voting').style.color = the_color;
                break;

                case 2:
                jQuery('#text_voting').text('gut');
                ge('text_voting').style.color = the_color;
                break;

                case 3:
                jQuery('#text_voting').text('sehr schön');
                ge('text_voting').style.color = the_color;
                break;

                case 4:
                jQuery('#text_voting').text('ein Highlight');
                ge('text_voting').style.color = the_color;
                break;

                case 5:
                jQuery('#text_voting').text('Der Knaller !!!');
                ge('text_voting').style.color = the_color;
                break;

                default:
                jQuery('#text_voting').text('Zum Bewerten über die Sterne fahren');
                ge('text_voting').style.color = "#A7A7A7";
                break;
            }
        }
        else
        {
            ge('star_vote_' + i).src = STATIC_CONTENT_PREFIX +"img/17x16_proddet_star_" + color + "_null.gif";
        }
        ge('number_stars').value = element;
    }
}


function tools_resize_disable(element)
{
    //element.childNodes[1].style.display = 'none';
}

function change_tab_filter(element, name)
{
    /*
    Ebenen-Wechsel für den Farbwähler -> Farbfelder oder Farbname
    */
    var count =2;
    for (i = 1; i <= count; i++)
    {
        if (i== element)
        {
            ge(name).style.backgroundImage ="url("+ STATIC_CONTENT_PREFIX +"css/img/bg_tab_" + i +".gif)";

            ge(name + '_l_' + i).className = "active";
            ge(name + '_a_' + i).className = "active";
            ge(name + '_a_' + i).style.color = "#006EC0";
            ge(name + '_d_' + i).style.display = 'block';


        }
        else{
            ge(name + '_l_' + i).className = "disabled";
            ge(name + '_a_' + i).className = "disabled";
            ge(name + '_a_' + i).style.color = "#92BDDD";
            ge(name + '_d_' + i).style.display = 'none';
        }
    }

}

function show_stat_dsc(element)
{
    /* Anzeigen der Zusatz-Infos im Produktdetails -> Statistiken links*/
    element.childNodes[1].style.display='inline';
}

function hide_stat_dsc (element)
{
    /* Ausblenden der Zusatz-Infos im Produktdetails -> Statistiken links*/
    element.childNodes[1].style.display='none';
}


function change_mainpic(element, url)
{

    /* Ändern des Hauptbildes im Produktdetails -> */
    jQuery(".small_pic").css('border-color', '#CCC');
    jQuery(".small_pic_last").css('border-color', '#CCC');
    element.parentNode.style.borderColor ="#006ec0";
    ge('main_pic_img').src= url;

}

function change_mainpic_and_change_shop ( element, productId, url, imagePosition ) {
    
    change_mainpic( element, url );
    
    var body = "imagePosition=" + encodeURIComponent( imagePosition )
            + "&productId=" + encodeURIComponent( productId );

    XMLHTTP.request( "POST", SHOP_BASEURL + "productDetails.productDetailsBody.getShopAttributes",
        function(r) {
            
            var response = XMLHTTP.parseJSON( r.responseText );
            
            // setzen des Shoplogos. Wenn keines existiert wird ein default-Bild gezeigt
            var logo = ge('smatchTippProductImage');
            
            if ( response.shopImageUrl == null ) {
                logo.setAttribute( "src", STATIC_CONTENT_PREFIX + "img/shop_no_logo.gif", false );
            } else {
                logo.setAttribute( "src", response.shopImageUrl, false );
            }
            logo.setAttribute( "alt", response.shopName, false );
            logo.setAttribute( "title", response.shopName, false );
            
            // Setzen des Preises im 'smatch-Tipp'-Feld
            ge('smatchTippProductPrice').innerHTML = response.price;
            
            // Setzen des Lieferpreises im 'smatch-Tipp'-Feld
            if ( response.shippingPrice == null ) {
                ge('smatchTippShippingPrice').innerHTML = "Kein Preis verfügbar";
            } else {
                ge('smatchTippShippingPrice').innerHTML = "ab " + response.shippingPrice;
            }
            
            // Setzen der Werte des ClickoutForms im 'smatch-Tipp'-Feld
            document.clickoutForm.shopId.value = response.shopId;
            document.clickoutForm.productPrice.value = response.priceForClickout;
            document.clickoutForm.shopProductId.value = response.shopProductId;
            
            // Setzen der Werte des ClickoutForms in der Liste der Shops. Es wird nur
            // der Shop gupdated dessen Produkt gerade angezeigt wird.
            input = ge( 'shopsShopProductId_' + response.shopId );
            if ( input != null ) {
                input.value = response.shopProductId;tool_container_fixed
            }
        },
        body);
    
}

function bookmarkLink(url)
{
    //Bookmarking
    url = url.replace(/\$TITLE/, encodeURIComponent(document.title));
    url = url.replace(/\$URL/, encodeURIComponent(location.href));
    window.open(url);
    trackBookmarking();
}

function trackBookmarking() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "BookmarkPage";
        s.events = "event15";
        s.eVar23 = "Bookmark erstellt";
        s.t();
        increaseNumberOfActions();
    }
}

function initPicBrowser()
{
    if (jQuery(".pic_browser_container").size() <= 0) {
        // if not on promo page
        return;
    }

    /* Initialisierung Pic-browser auf der Promo-Site*/
    var number = jQuery(".pic_browser_container table td").size();

    jQuery(".pic_browser_container table").width(number*264);

    PicBrowser_counter_left = 0;
    PicBrowser_counter_right = number-1;
    PicBrowser_counter_max = number;
    var picbrowser_id = jQuery(".pic_browser_container table").attr('id');
    jQuery('#'+ picbrowser_id +'_counter_max').html(number);

    jQuery('#'+ picbrowser_id).css('left',  0);
}

function movePicBrowser(dir, element)
{
    // Bewegen der Bilder innerhalb des Picbrowsers
    var to_left = parseInt(jQuery('#'+element).css("left"));
    var new_left =1 ;

    if (dir =='left')
    {
        if (PicBrowser_counter_left > 0)
        {
            new_left =  to_left+264;
            PicBrowser_counter_left--;
            PicBrowser_counter_right++;
        }
        else
        {
            new_left =  1;
        }
    }
    else
    {
        if (PicBrowser_counter_right >0)
        {

            new_left =  to_left-264;
            PicBrowser_counter_left++;
            PicBrowser_counter_right--;
        }
        else
        {
            new_left =  to_left;
        }
    }

    jQuery('#'+ element +'_counter').html(PicBrowser_counter_left+1);
    jQuery('#'+element).animate({left:  new_left}, 264);
}

function initTableMove (){
    /* Initialisierung, um eine Vergleichliste durchblättern zu können*/
    var move_number= 3;

    if ( jQuery('body').attr('class') == 'homepage'){
        move_number= 4;
    }

    tableMove_counter_left = 0 ;
    tableMove_counter_right = jQuery(ge("first_line")).children("td").length - move_number;

    if (tableMove_counter_right < 0) {
        tableMove_counter_right = 0;
    }

    tableMove_max_counter = tableMove_counter_right;

    var tableMove = ge('TableMove');
    if ( tableMove != null ) {
        ge('TableMove').style.left =  0;
        jQuery('#TableMove_container').height(jQuery('#TableMove').height()) ;
        ge('TableMove_counter_topleft').innerHTML = tableMove_counter_left;
        ge('TableMove_counter_topright').innerHTML = tableMove_counter_right;
        ge('TableMove_counter_bottomleft').innerHTML = tableMove_counter_left;
        ge('TableMove_counter_bottomright').innerHTML = tableMove_counter_right;

        jQuery('#TableMove').tableHover();
        var number_rows = jQuery('#TableMove tr').size;
        jQuery("#TableMove tr").each(
            function(i){
                tab_val = jQuery('#tab_val_' + i);
                if(jQuery.browser.msie  ){
                    if (tab_val.attr('class') == 'double_td'){
                         tab_val.height(3);
                     }
                    else{
                         tab_val.height(jQuery(this).height()-1);
                     }
                }
                else if (jQuery.browser.safari){
                    if (tab_val.attr('class') == 'double_td'){
                         tab_val.height(3);
                     }
                    else{
                        var td =jQuery(this).children('td');
                        var padding = 2*(parseInt(jQuery(td).css('padding-top')));
                        tab_val.height(jQuery(td).height()+padding);
                    }
                }
                else{
                    if (tab_val.attr('class') == 'double_td'){
                         tab_val.height(3);
                     }
                    else{
                        tab_val.height(jQuery(this).height());
                    }
                }
            }
            );
            jQuery('#TableValues .last_line').height(200);
    }
}


function tableMove (dir, element)
{
    /* Vergleichsliste (auf Vergleichsseite) durchblättern  und entsprechende Werte setzen*/
    var to_left = parseInt(jQuery('#'+element).css("left"));
    var new_left =0 ;

    var move_size= 151;




    if (dir =='left')
    {
        if (tableMove_counter_left > 0)
        {
            new_left =  to_left+move_size;
            tableMove_counter_left--;
            tableMove_counter_right++;
        }
        else
        {
            new_left =  0;
        }
    }
    else
    {
        if (tableMove_counter_right >0)
        {
            new_left =  to_left-move_size;
            tableMove_counter_left++;
            tableMove_counter_right--;
        }
        else
        {
            new_left =  to_left;
        }


    }
    ge('TableMove_counter_topleft').innerHTML = tableMove_counter_left;
    ge('TableMove_counter_topright').innerHTML = tableMove_counter_right;
    ge('TableMove_counter_bottomleft').innerHTML = tableMove_counter_left;
    ge('TableMove_counter_bottomright').innerHTML = tableMove_counter_right;

    jQuery('#'+element).animate({left:  new_left}, 500);

    var range_left =tableMove_counter_left +1;
    var range_right =tableMove_counter_left + 3 ;
    ge('tableMove_range').innerHTML = range_left + ' bis ' + range_right;
}


function init_dashboard_compareMove()
{
    // Vergleich initialisieren
    jQuery(".dashboard_compare_list_item").each(function(i)
    {

           if (ge('dashboard_compare_inner_'+ i +'_left')) {
            ge('dashboard_compare_inner_'+ i +'_left').innerHTML = 0;
            //FIXME: absolute product count (5) will break components with other product count
            ge('dashboard_compare_inner_'+ i +'_right').innerHTML = jQuery('#dashboard_compare_inner_' + i + ' table tbody tr td').length - 5;
        }
     }
    );
}

function dashboard_compareMove (dir, element)
{
    // Vergleich bewegen
    var this_left = parseInt(jQuery('#'+element).css("left"));
    var counter_left = ge(element +'_left').innerHTML, counter_right = ge(element +'_right').innerHTML;
    var new_left =0 ;

    var move_size =100;
    if ( jQuery('body').attr('class') == 'homepage' || jQuery('#desc_support').length >=1 || jQuery('.desc_supp').length >=1)         
    {
        move_size= 109;
    }

    if (dir =='left')
    {
        if (counter_left > 0)
        {
            new_left =  this_left+move_size;
            counter_left--;
            counter_right++;
        }
        else
        {
            new_left =  0;
        }
    }
    else
    {
        if (counter_right >0)
        {
            new_left =  this_left-move_size;
            counter_left++;
            counter_right--;
        }
        else
        {
            new_left =  this_left;
        }
    }
    jQuery('#'+element).animate({left:  new_left}, 500);
    ge(element +'_left').innerHTML = counter_left;
    ge(element +'_right').innerHTML = counter_right;
}


function change_pricerange (number,element){
    /*
     * Aendert die Preis-Auswahl
     */
    var count =6;
    for (var i = 1; i < count; i++)
    {
        if (i == number)
        {
             ge('price_changer_al_' + i).style.color = "#000";
            ge('price_changer_al_' + i).style.fontWeight = "bold";

        }
        else
        {
            ge('price_changer_al_' + i).style.color = "#666";
            ge('price_changer_al_' + i).style.fontWeight = "normal";
        }
    }

}


function edit_headline (element)
{
    var text = jQuery(element).prev('span');
    var headline_text = jQuery(text).text();
    var parent= jQuery(element).parent();
    var parent_id = jQuery(parent).attr("id");

    jQuery(element).after('<form action="#" method="post"><fieldset><input type="text" id="' + parent_id + '_name" name="' + parent_id + '_name" value="' + headline_text + '" class="edit_headline_field"  /><br class="clearall" /><button class="button_s_g"><span class="outerspan"><span class="innerspan">Abbrechen</span></span></button> <button  class="button_s"><span class="outerspan"><span class="innerspan">Speichern</span></span></button><br class="clearall" /><br /></fieldset></form>');

    jQuery(text).css('display', 'none');
    jQuery(element).css('display', 'none');
    jQuery(parent).css('height', '60px');
    jQuery('#' + parent_id + '_name').focus();
}

function edit_bodytext (element)
{
    var text = jQuery(element).prev('span');
    var parent_text = jQuery(text).text();
    var parent= jQuery(element).parent();
    var parent_id = jQuery(parent).attr("id");

    jQuery(element).after('<form action="#" method="post"><fieldset><textarea rows="5" cols="25" name="' + parent_id + '_bodytext" class="edit_headline_field"  />' + parent_text + '</textarea><br class="clearall" /><button class="button_s_g"><span class="outerspan"><span class="innerspan">Abbrechen</span></span></button> <button  class="button_s"><span class="outerspan"><span class="innerspan">Speichern</span></span></button><br class="clearall" /><br /></fieldset></form>');

    jQuery(parent_text).css('display', 'none');
    jQuery(element).css('display', 'none');
    jQuery(text).css('display', 'none');
    jQuery(parent).css('height', '100px');
}

function edit_gender (element)
{
    var text = jQuery(element).prev('span');
    var parent= jQuery(element).parent();

    jQuery(element).after('<form action="#" method="post"><fieldset><label><input type="radio" name="gender" value="male" class="v_middle"  /> männlich</label>&nbsp;&nbsp; &nbsp;&nbsp;<label><input type="radio" name="gender" value="female" class="v_middle"  /> weiblich</label><br /><br /> <button class="button_s_g"><span class="outerspan"><span class="innerspan">Abbrechen</span></span></button> <button  class="button_s"><span class="outerspan"><span class="innerspan">Speichern</span></span></button><br /></fieldset></form>');

    jQuery(text).css('display', 'none');
    jQuery(element).css('display', 'none');
    jQuery(parent).css('height', '60px');
}

function edit_bday (element)
{
    var text = jQuery(element).prev('span');
    var parent= jQuery(element).parent();
    var parent_id = jQuery(parent).attr("id");
    jQuery(element).after('<form action="#" method="post"><fieldset><select name="' + parent_id + '_day"><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option></select> .   <select name="' + parent_id + '_month"><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option></select> . <select name="' + parent_id + '_year"><option>2001</option><option>2002</option><option>2003</option><option>2004</option><option>2005</option><option>2006</option><option>2007</option></select>(TT.MM.JJJJ)<br /><button class="button_s_g"><span class="outerspan"><span class="innerspan">Abbrechen</span></span></button> <button  class="button_s"><span class="outerspan"><span class="innerspan">Speichern</span></span></button><br /></fieldset></form>');

    jQuery(text).css('display', 'none');
    jQuery(element).css('display', 'none');
    jQuery(parent).css('height', '60px');
}


function edit_mytext (element)
{
    var text = jQuery(element).prev('span');
    var parent_text = jQuery(text).text();
    var parent= jQuery(element).parent();
    var parent_id = jQuery(parent).attr("id");
    ge("mytext_img").style.display = "block";

    jQuery(element).after('<form action="#" method="post"><fieldset><textarea rows="3" cols="25" name="' + parent_id + '_bodytext" class="edit_headline_field" style="width: 140px; height: 100px;">' + parent_text + '</textarea><button class="button_s_g"><span class="outerspan"><span class="innerspan">Abbrechen</span></span></button> <button  class="button_s"><span class="outerspan"><span class="innerspan">Speichern</span></span></button><br /></fieldset></form>');

    jQuery(parent_text).css('display', 'none');
    jQuery(element).css('display', 'none');
    jQuery(text).css('display', 'none');

}


function get_text_entries(id) {
    var spans = jQuery("#" + id + " .float_l").get();
    var names = "";
    for (var i = 0; i < spans.length; i++) {
        if (names != "") {
            names += ";";
        }
        names += jQuery(spans[i]).text();
    }
    return names;
}

function get_color_entries() {
    var names = "";
    var color = "";
    var spans = jQuery("#to_colors" + " .my_color").get();
    var names = "";
    for (var i = 0; i < spans.length; i++) {
        color = jQuery(spans[i]).css("background-color");
        // don't change this! IE6's regex parser crashes with the second RX
        // but it delivers the background color as #RGB, so we actually don't
        // need the second RX anyway.
        if (!color.match(/#[0-9][0-9][0-9][0-9][0-9][0-9]/)) {
            var match = color.match(/rgb *[(]([0-9]+), *([0-9]+), *([0-9]+)[)]/)
            if (match != null && match.length == 4) {
                color = "#";
                var tmp;
                for (var k = 1; k < 4; ++k) {
                    tmp = parseInt(match[k], 10).toString(16).toUpperCase();
                    while (tmp.length < 2) {
                        tmp = '0' + tmp;
                    }
                    color += tmp;
                }
            }
        }
        if (names != "") {
            names += ";";
        }
        names += color;
    }
    return names;
}


function edit_favos(element)
{
    // Favos editieren - ebenen Anzeigen / ausblenden
    jQuery('#fav_'+element).hide();
    jQuery('#edit_'+element).show();
}


function toggle_pull(element)
{
    // Favos  active / inactive
    jQuery(element).toggleClass("active_pull");
}

function toggle_contact_label(element)
{
    // Favos  active / inactive
    var dad = jQuery(element).parent();
    jQuery(dad).toggleClass("active_pull");

}

function pull_active_2container (type)
{
    // favos gesammelt hinzufügen
    jQuery('#no_item_' + type).hide();
    jQuery('#edit_'+ type + ' .active_pull').each(function(i) {
        jQuery(this).removeClass("active_pull");
        var names = "";
           switch (type) {
            case 'colors':
                change_my_color (jQuery(this));
                var container ='<div class="my_color" ><img src="'+ STATIC_CONTENT_PREFIX + 'img/41x41_rounded_color.gif" width="41" height="41" alt="Farbe" title="Farbe" class="my_color db" style="'+ jQuery(this).attr('style')+'" /><img  class="delete" width="11" height="11" align="Delete"  title="Delete" src="'+ STATIC_CONTENT_PREFIX + 'img/11x11_notice_delete.gif"  onclick="remove_pull(this)" /></div>';
                jQuery('#to_'+ type +' .pull_container_inner').append(container);
                
                names = get_color_entries();
                //alert("Colors: " + names);
                break;

            default:
                jQuery('#to_'+ type).append('<p><span class="float_l">' + jQuery(this).text() + '</span> <img  class="float_r" width="11" height="11" alt="Delete"  title="Delete" src="'+ STATIC_CONTENT_PREFIX + 'img/11x11_notice_delete.gif" onclick="remove_pull(this)" /><br class="clearall" /></p>');
                names = get_text_entries("to_" + type);
                //alert("Brands: " + names);
                break;
        }
        jQuery(this).hide();
    });

}

function pull_this_2container (element, type)
{
        jQuery(element).removeClass("active_pull");
        var names = "";
        jQuery('#no_item_' + type).hide();

           switch (type) {
            case 'colors':
                //change_my_color (jQuery(element));

                var container ='<div class="my_color" ><img src="'+ STATIC_CONTENT_PREFIX + 'img/41x41_rounded_color.gif" width="41" height="41" alt="Farbe" title="Farbe" class="my_color db" style="background-color:'+ jQuery(element).css("background-color")+'" onclick="remove_pull(this)" /><img  class="delete" width="11" height="11" align="Delete"  title="Delete" src="'+ STATIC_CONTENT_PREFIX + 'img/11x11_notice_delete.gif"  onclick="remove_pull(this)" /></div>';

                jQuery('#to_'+ type +' .pull_container_inner').append(container);
                names = get_color_entries();
                //alert("Colors: " + names);
                var kind = jQuery(element).prev('img');
                jQuery(kind).removeClass("active_pull");
                break;

            default:
                jQuery('#to_'+ type).append('<p><span class="float_l">' + jQuery(element).text() + '</span> <img  class="float_r" width="11" height="11" alt="Delete"  title="Delete" src="'+ STATIC_CONTENT_PREFIX + 'img/11x11_notice_delete.gif" onclick="remove_pull(this)" /><br class="clearall" /></p>');
                names = get_text_entries("to_" + type);
                //alert("Brands: " + names);
                break;
        }
        jQuery(element).hide();
}

function remove_pull (element, type)
{
    // favos delete
    var dad = jQuery(element).parent();
    jQuery(dad).remove();
}

function change_my_color(element)
{
    // FAvos Farben anklicken
    var kind = jQuery(element).next('img');
    jQuery(element).toggle();
    jQuery(kind).toggle();
}


var addFriendNo ='';
var clony = '';
function initaddFriendInvitation(){
    clony = jQuery('#invite_user_1').clone();
    invite_user_container = jQuery(".invite_user_container");
    if(invite_user_container.length > 1){
        addFriendNo = invite_user_containerlength-1;
    }
    else{
        addFriendNo = 0;
    }
}


function addFriendInvitation()
{
    var formerNo =addFriendNo;
    addFriendNo ++;

    var buttons =  jQuery('#adding_button').clone();
    jQuery('#adding_button').remove();

    var round_container = '<div class="invite_user_container" id="invite_user_controller_' + addFriendNo +'">'+ clony.html() +'</div>';


    jQuery(round_container).insertAfter(jQuery('#invite_user_controller_'+ formerNo));
    jQuery('#around_invite_user').append(buttons);





}




function removeFriendInvitation()
{
        if (addFriendNo >0)
        {
         var before = jQuery("#invite_user_controller_" + addFriendNo);

             var buttons =  jQuery('#adding_button').clone();
            jQuery('#adding_button').remove();
             jQuery(before).remove();
            addFriendNo --;
            jQuery('#around_invite_user').append(buttons);

        }


}

function removeFriendInvitationAftersend(element)
{


        jQuery(element).parents(".invite_user_container").next().remove();
        jQuery(element).parents(".invite_user_container").remove();


}




function submit_favourites(type)
{
    var names = "";
    switch (type) {
    case 'brands':
        names = get_text_entries("to_" + type);
        //alert("Brands: " + names);
        document.forms["EditBrands"].selectedBrands.value = names;
        //alert("Brands: " + document.forms["EditBrands"].selectedBrands.value);
        document.forms["EditBrands"].submit();
        break;

    case 'colors':
        names = get_color_entries();
        //alert("Colors: " + names);
        document.forms["EditColors"].selectedColors.value = names;
        document.forms["EditColors"].submit();
        break;

    case 'shops':
        names = get_text_entries("to_" + type);
        document.forms["EditShops"].selectedShops.value = names;
        document.forms["EditShops"].submit();
        //alert("Brands: " + names);
        break;
    }
}





function showMessagelayer()
{
    jQuery('#TB_overlay_messageLayer').bgiframe();
    jQuery("#TB_overlay_messageLayer").show();
    jQuery("#messageLayer_container").show();
}

function cancelMessagelayer()
{
    jQuery("#TB_overlay_messageLayer").hide();
    jQuery("#messageLayer_container").hide();
}


var CREATE_RATING_ADDRESS = new Object();
CREATE_RATING_ADDRESS['PRODUCT'] =  SHOP_BASEURL + "productdetails.productdetailsbody.CreateProductRating";
CREATE_RATING_ADDRESS['PRODUCTLIST'] =  SHOP_BASEURL + "productlists/showlist.CreateProductListRating";
CREATE_RATING_ADDRESS['PARTNERSHOP'] =  SHOP_BASEURL + "shop/details.CreateShopRating";

var alreadyRated = new Object();

function selectRatingImage(what, id, user, n) {
    if (!alreadyRated[what]) {
        XMLHTTP.request("GET", CREATE_RATING_ADDRESS[what]
            + ".setRating/" + what + "/"+  id + "/" + user + "/" + n,
            function(r) {
                if (r.status != 200 || r.responseText != "OK") {
                    alert ("Die Bewertung konnte nicht gespeichert werden: "
                        + r.responseText);
                } else {
                    alreadyRated[what] = true;
                    jQuery("#rate_"+ what + "_" + id + "_text").html("Die Bewertung wurde abgegeben.");

                    if (what == 'PRODUCT') {
                        trackProductRating(id);
                    } else if (what == 'PRODUCTLIST') {
                        trackListRating();
                    }
                }
            });
    }
}

function trackListRating() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "RateProductList";
        s.events="event14";
        s.t();
        increaseNumberOfActions();
    }
}

function trackProductRating(productId) {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "RateProduct";
        s.events="event13";
        s.eVar14=productId;
        s.t();
        increaseNumberOfActions();
    }
}


function mouseOverForInvalidRating(what, maxElems, element, nullImage, fullImage) {
}


function mouseOverRatingImage(what, maxElems, element, nullImage, fullImage) {
    if (!alreadyRated[what]) {
        for (var i =1; i <= maxElems; i++) {
            if (i <= element) {
                ge('star_vote_' + what + '_' + i).src = STATIC_CONTENT_PREFIX + fullImage;
            } else {
                ge('star_vote_' + what + '_' + i).src = STATIC_CONTENT_PREFIX + nullImage;
            }
        }
        voting_text('star_vote_' + what + '_' + element, 'bl');
    }
}

function mouseOutClearStars(what, maxElems, nullImage, fullImage) {
    if (!alreadyRated[what]) {
        for (var i =1; i <= maxElems; i++) {
            ge('star_vote_' + what + '_' + i).src = STATIC_CONTENT_PREFIX + nullImage;
        }
        voting_text(0,0);
    }
}

function showShopRating(shopProductId) {
    jQuery('#shopRating_'+ shopProductId).toggle();
}

function sendCertainProductTags(productId, communityUserId, tags) {
    if ( tags == ENTER_TAGS_MESSAGE ) {
        tags = null;
    }
    if ( tags.match(/^\s+$/) || tags.match(/^$/) ) {
        XMLHTTP.request(
            "GET",
            SHOP_BASEURL + "productdetails.tagProductForm.clearUserTags/" + productId + "/" + communityUserId,
            function(r) {
                updateProductTagLists(r, productId, communityUserId)
              //  trackProductTagging(productId);
            } );
    }
    else {
        XMLHTTP.request(
            "GET",
            SHOP_BASEURL + "productdetails.tagProductForm.tagProduct/" + productId + "/" + communityUserId + "/" + encodeURIComponentForTapestry(tags),
            function(r) {
                updateProductTagLists(r, productId, communityUserId);
                //trackProductTagging(productId);
                if ( r.status != 200 || r.responseText != "") {
                    alert ("Die Tags "+r.responseText+" sind reserviert und können nicht verwendet werden.");
                } else {
                    flashTagsStoredMessage ();
                }
            } );
    }
    return false;
}

/**
 * Removes the tag with the given value (string) from the product with the specified id. 
 * This is done even if the current user didn't provide the tag for this product.
 * This method is intended to allow users to cleanup the tags for products.
 * @param productId the id of the product
 * @param tagValue the value of the tag to remove
 * @param communityUserId the if of the user, is required to update tags on the product details page
 * @return
 */
function removeProductTag( productId, tagValue, communityUserId ) {
    XMLHTTP.request(
        "POST",
        SHOP_BASEURL + "productdetails.tagProductListBottom.removeProductTag/" + productId + "/" + encodeURIComponentForTapestry(tagValue),
        function(r) {
            if ( r.status != 200 ) {
                alert ("Der Tag konnte nicht gelöscht werden (Status "+ r.status+"): " + r.responseText);
            }
            else {
                updateProductTagLists(r, productId, communityUserId);
            }
        } );
}

/*
entfernt, da diese events jetzt fuer die bounce-rate-messung benutzt werden
function trackProductTagging(productId) {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "TagProduct";
        s.events="event11";
        s.eVar14=productId;
        s.t();
        increaseNumberOfActions();
    }
}

function trackListTagging() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "TagProductList";
        s.events="event12";
        s.t();
        increaseNumberOfActions();
    }
}
*/

function sendProductTags(productId, communityUserId) {
    return sendCertainProductTags(productId, communityUserId,
        ge("tagging_field").value);
}

function tagProductAfterLogin(productId) {

    // store values for after login
    params = "{ \"productId\" : \""+ productId + "\", "+
        " \"tags\" : \""+ ge("tagging_field").value + "\" }";

    showLoginAndRegisterBox(function() {
        setAfterLoginParameters(params, "tagProduct");
    });

    return false;
}

function tagListAfterLogin(listId) {
    // store values for after login
    params = "{ \"listId\" : \""+ listId + "\", "+
        " \"tags\" : \""+ ge("tagging_field").value + "\" }";

    showLoginAndRegisterBox(function() {
        setAfterLoginParameters(params, "tagList");
    });

    return false;
}

function setAfterLoginParameters(params, action) {
    jQuery('#jsonLoginActionParameters').val(params);
    jQuery('#jsonLoginActionParametersRegister').val(params);
    jQuery('#afterLoginAction').val(action);
    jQuery('#afterLoginActionRegister').val(action);
}

// Auf der Produkt-Datailseite finden sich 5 Stellen auf die das Tagging eine Auswirkung hat.
// Sobald ein CommunityUser eigene Tags geändert (also neu hinzugefügt, oder bestehende gelöscht) hat,
// dann ändern sich die Folgenden 5 Sachen (in der angegebenen Reihenfolge):
//      1. Liste aller Tags des Produktes, denn es kann ja sein, dass sich durch die Angabe des Nutzers die Reihenfolge
//         der Tags geändert hat oder sogar einer hinzugekommen ist. Es handelt sich hierbei um die Liste, die oben
//         zu sehen ist (sie ist auf x Zeichen limitiert).
//      2. Tags des CommunityUsers im Textarea in dem er sie bearbeitet, so werden Falscheingaben berichtigt.
//      3. Liste aller Tags des Produktes. Dabei handelt es sich um die Liste, die unten zu sehen ist.
//      4. Liste aller Tags, die der Benutzer zu einem Produkt vergeben hat.
//      5. Anzahl der Tags eines Produktes. Dies wird unten im Reiter TAGS(x) angezeigt.
// Dies geschieht über die vier untenstehenden XMLHTTP.requests UND (WICHTIG) den Request der Funktion
// sendProductTags(productId, communityUserId) der die anderen vier anstößt.
function updateProductTagLists (r, productId, communityUserId) {
    if (r.status != 200) {
        alert ("Tags konnten leider nicht gespeichert werden.");
    }
    // 1.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productdetails.tagProductListTop.updateLimitedProductTagListTop/" + productId + "/" + communityUserId,
        function(rr) {
            ge("productTags").innerHTML = rr.responseText;
            draggableTag();// Damit nach dem Speichern die Tags draggable bleiben
        } );
    // 2.
    getTagsByProductAndUserAjax(productId, communityUserId, function(rr) {
            ge('tagging_field').value = rr.responseText+", ";
        } );
    // 3.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productdetails.tagProductListBottom.tagProductListBottom/" + productId + "/" + communityUserId,
        function(rr) {
            ge("tagProductBottom").innerHTML = rr.responseText;
            draggableTag();// Damit nach dem Speichern die Tags draggable bleiben
        } );
    // 4.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productdetails.tagProductListTop.userProductTags/" + productId + "/" + communityUserId,
        function(rr) {
            ge("ownProductTags").innerHTML = rr.responseText;
            draggableTag();// Damit nach dem Speichern die Tags draggable bleiben
        } );
    // 5.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productdetails.tagProductForm.tagsAmount/" + productId,
        function (rr) {
            ge("productTagsAmount").innerHTML = rr.responseText;
        } );
}

function getTagsByProductAndUserAjax(productId, communityUserId, callback) {
    XMLHTTP.request( "GET", SHOP_BASEURL + "productdetails.tagProductForm.userTags/" + productId + "/" + communityUserId,
        callback);
}

function draggableTag() {
    if (!ge('tagging_field')) {
        // may occur if no mainTemplate is present
        return;
    }

    jQuery('.prod_tag').Draggable( {
        revert      :   true,
        ghosting    :   true,
        zIndex      :   1000,
        opacity     :   0.6,
        autoSize    :   true
    } )

    jQuery('#tagging_field').Droppable( {
        accept      :   'prod_tag',
        tolerance   :   'intersect',
        onDrop      :   function(dropped) {
                            tagging_field = ge('tagging_field');
                            if ( tagging_field.value == ENTER_TAGS_MESSAGE) {
                                clearTagInput(tagging_field);
                            }
                            else if (tagging_field.value == "" ) {
                                tagging_field.value = dropped.innerHTML;
                            }
                            else {
                                tagging_field.value = tagging_field.value + ", " + dropped.innerHTML;
                            }
                        }
    } )
}

function sendListTags(listId, communityUserId) {
    var productTagsTextArea = ge("product_tagging_field");
    var productTags = productTagsTextArea != null ? productTagsTextArea.value : null;
    return sendCertainListTags(listId, communityUserId, ge("tagging_field").value, productTags);
}

function sendCertainListTags(listId, communityUserId, listTags) {
    return sendCertainListTags( listId, communityUserId, listTags, null);
}
function sendCertainListTags(listId, communityUserId, listTags, productTags) {
    
    if ( listTags == ENTER_TAGS_MESSAGE ) {
        listTags = "";
    }
    
    if ( listTags.match(/^\s+$/) || listTags.match(/^$/) ){
        var contextParams = listId + "/" + communityUserId;
        var productTagUpdate = false;
        if ( productTags != null && productTags != "" ) {
            contextParams += "/" + encodeURIComponentForTapestry( productTags );
            productTagUpdate = true;
        }
        XMLHTTP.request(
            "GET",
            SHOP_BASEURL + "productlists/showlist.tagListForm.clearUserTags/" + contextParams,
            function(r) {
                updateListTagLists(r, listId, communityUserId);
                if (productTagUpdate) {
                    flashTagsStoredMessage ();
                }
              //  trackListTagging();
            } );
    }
    else {
        var contextParams = listId + "/" + communityUserId + "/" + encodeURIComponentForTapestry(listTags);
        if ( productTags != null && productTags != "" ) {
            contextParams += "/" + encodeURIComponentForTapestry( productTags );
        }
        XMLHTTP.request(
            "GET",
            SHOP_BASEURL + "productlists/showlist.tagListForm.tagList/" + contextParams,
            function(r) {
                updateListTagLists(r, listId, communityUserId);
                flashTagsStoredMessage ();
             //   trackListTagging();
            } );
    }
    return false;
}

function updateListTagLists (r, listId, communityUserId) {
    if (r.status != 200) {
        alert ("Tags konnten leider nicht gespeichert werden.");
    }
    // 1.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productlists/showlist.tagListListTop.updateLimitedListTagListTop/" + listId + "/" + communityUserId,
        function(rr) {
            ge("listTags").innerHTML = rr.responseText;
            draggableTag();// Damit nach dem Speichern die Tags draggable bleiben
        } );
    // 2.
    getTagsByListAndUserAjax(listId, communityUserId,
        function(rr) {
            ge('tagging_field').value = rr.responseText;
        });
    // 3.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productlists/showlist.tagListListBottom.tagListListBottom/" + listId + "/" + communityUserId,
        function(rr) {
            ge("tagListBottom").innerHTML = rr.responseText;
            draggableTag();// Damit nach dem Speichern die Tags draggable bleiben
        } );
    // 4.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productlists/showlist.tagListListTop.userListTags/" + listId + "/" + communityUserId,
        function(rr) {
            ge("ownListTags").innerHTML = rr.responseText;
            draggableTag();// Damit nach dem Speichern die Tags draggable bleiben
        } );
    // 5.
    XMLHTTP.request( "GET", SHOP_BASEURL + "productlists/showlist.tagListForm.listTagsAmount/" + listId,
        function (rr) {
            ge("lTagsAmount").innerHTML = rr.responseText;
        } );
}

function getTagsByListAndUserAjax(listId, communityUserId, callback) {
    XMLHTTP.request( "GET", SHOP_BASEURL + "productlists/showlist.tagListForm.userListTags/" + listId + "/" + communityUserId,
        callback);
}

// Funktion kann von zwei Ereignisen aus aufgerufen werden cleard das Feld aber nur einmal
function clearTagInput(tagInput) {
    if (!allredyCleared && ENTER_TAGS_MESSAGE == tagInput.value){
        tagInput.value = '';
        allredyCleared = true;
    }
}


// Funktion kann von zwei Ereignisen aus aufgerufen werden cleard das Feld aber nur einmal
function clearTagInput_extra(tagInput) {
    if (!allredyCleared_Extra){
        tagInput.value = '';
        allredyCleared_Extra = true;
    }
}

         

function flashTagsStoredMessage () {
        setStringProperty('testKey', 'testValue');
        
        
        //jQuery('#tagging_field').css('visibility','hidden');
        //jQuery('#tagging p').css('visibility','hidden');
      //  jQuery('#product_tagging_field').css('visibility','hidden');
      //    jQuery('#tagging button').css('visibility','hidden');
        jQuery('#tagsSpinner').css('visibility','visible');
        jQuery('#tagsSpinner').show();
        
        window.setTimeout('jQuery("#tagsSpinner").hide();jQuery(".liststyle_link").removeClass("active"); jQuery(".liststyle_link a").removeClass("active");jQuery(".communityBox").css("display", "none");', 1500);
        /*
        jQuery('#tagsStoredMessage').show(500,
        function () { 
            jQuery('#tagsStoredMessage').fadeTo( 1000, 1,
            function () { jQuery('#tagsStoredMessage').hide(500,
                function () {
                    jQuery('.liststyle_link').removeClass('active');
                    jQuery('.liststyle_link a').removeClass('active');
                    jQuery('.communityBox').css('display', 'none');
                }
            )
            }
        )
        }
        
    );*/
}


//////////////////////////////
// Buddys / Freunde //////////
//////////////////////////////

function addUserAsFriend(userId, loggedIn) {
    if (!loggedIn) {
        addUserAsFriendAfterLogin(userId);
        return;
    }

    XMLHTTP.request( "GET", SHOP_BASEURL + "user/AddAFriendForm/" + userId + "/" + Math.random(), // random is for preventing caching
        function(rr) {
            jQuery("#add_a_friend_layer").html(rr.responseText);
            jQuery('#TB_overlay_messageLayer').bgiframe();
            jQuery("#TB_overlay_messageLayer").show();
            jQuery("#add_a_friend_layer").show();
        } );
}

function cancelAddAFriend(successful) {
    if (successful) {
        jQuery("#add_a_friend_link").hide();
        trackBuddyRequest();
    }

    jQuery("#add_a_friend_layer").hide();
    jQuery("#TB_overlay_messageLayer").hide();
}

function submitAddAFriend(userId) {
    var mailCopy = 0;
    if (ge("addAFriendMessageCopy").checked) {
        mailCopy = 1;
    }

    var body = "subject=" + encodeURIComponent( jQuery("#addAFriendSubject").val() )
                 + "&message=" + encodeURIComponent( jQuery("#addAFriendMessage").val() )
                 + "&mailCopy=" + mailCopy;

    XMLHTTP.request( "POST", SHOP_BASEURL + "user/AddAFriendForm/" + userId,
        function(rr) {
            jQuery("#add_a_friend_layer").html(rr.responseText);
            jQuery("#TB_overlay_messageLayer").show();
            jQuery('#TB_overlay_messageLayer').bgiframe();
            jQuery("#add_a_friend_layer").show();
        },
        body);
}

function confirmBuddyRequestRejection(username) {
    var res = confirm("Freundesanfrage von " + username + " wirklich ablehnen?");

    if (res) {
        trackBuddyRequestRejected();
    }

    return res;
}

function confirmBuddyReport(username) {
    return confirm("Freundesanfrege von " + username + " wirklich melden?");
}

function confirmEndFriendship(username) {
    var res = confirm("Freundschaft mit " + username + " wirklich beenden?");

    if (res) {
        trackBuddyRemoved();
    }

    return res;
}

function addUserAsFriendAfterLogin(userId) {
    // store values for after login
    params = "{ \"userId\" : \""+ userId + "\" }";

    showLoginAndRegisterBox(function() {
        setAfterLoginParameters(params, "addFriend");
    });

    return false;
}

function handleBuddyRequestAction(selectElem, username) {
    var selected = jQuery(selectElem).val();

    if (selected) {
        if (selected == 'REJECT') {
            if (!confirmBuddyRequestRejection(username)) {
                selectElem.selectedIndex = 0;
                return;
            }
        } else if (selected == 'ACCEPT') {
            trackBuddyAdded();
        } else if (selected == 'REPORT_USER') {
            if ( !confirmBuddyReport (username) ) {
                selectElem.selectedIndex = 0;
                return;
            }
        }

        selectElem.form.submit();
    }
}

function handleBuddyAction(selectElem, username) {
    var selected = jQuery(selectElem).val();

    if (selected) {
        if (selected == 'END_FRIENDSHIP') {
            if (!confirmEndFriendship(username)) {
                selectElem.selectedIndex = 0;
                return;
            }
        }

        selectElem.form.submit();
    }
}

function showBuddyRequests(bigView) {
    var body = "bigView=" + bigView;

    XMLHTTP.request( "POST", SHOP_BASEURL + "buddy/BuddyRequestsAjaxWrapper",
        function(rr) {
            jQuery("#buddyRequestsDiv").html(rr.responseText);
        },
        body);
}

// tracking of buddy actions:

function trackBuddyRemoved() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "BuddyRemoved";
        s.events="event16";
        s.eVar23="Buddy entfernt";
        s.t();
        increaseNumberOfActions();
    }
}

function trackBuddyRequestRejected() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "BuddyRequestRejected";
        s.events="event16";
        s.eVar23="Buddy Anfrage abgelehnt";
        s.t();
        increaseNumberOfActions();
    }
}

function trackBuddyAdded() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "BuddyAdded";
        s.events="event15";
        s.eVar23="Buddy Anfrage angenommen";
        s.t();
        increaseNumberOfActions();
    }
}

function trackBuddyRequest() {
    if (WEBTRACKING_ENABLED) {
        resetSiteCatalystVariables();
        s.pageName = "BuddyRequest";
        s.events="event15";
        s.eVar23="Buddy Anfrage";
        s.t();
        increaseNumberOfActions();
    }
}


// ENDE Buddys / Freunde /////


//////////////////////////////
/// Newsletter: //////////////
/////////////////////////////

/**
 * value must be "yes" or "no"
 */
function changeUserNewsletterSubscription(value) {
    var body = "value=" + encodeURIComponent(value);

    XMLHTTP.request( "POST", SHOP_BASEURL + "user/Home.changeNewsletterSubscription",
        function(rr) {
            ge("newsletterSubscriptionChangeMessage").style.display = 'block';
        },
        body);
}

//var USER_LOGGED_IN = false;
function onAddNewsletter() {
   if (USER_LOGGED_IN) {
          // redirect a logged in user to the newsletter administration in his/her profile
          window.location.href = SHOP_BASEURL + "user/home";
       return false;
   }

   var email = ge("newsletter_field").value;

   var body = "email=" + encodeURIComponent( email );

   XMLHTTP.request("POST",
        SHOP_BASEURL + "newsletter/subscribe",
        function(r) {
            jQuery("#newsletter_field").val("Deine Email-Adresse");

            jQuery("#subscribe_newsletter_layer").html(r.responseText);
            jQuery("#TB_overlay_messageLayer").show();
            jQuery("#subscribe_newsletter_layer").show();
       }, body );

   return false;
}

function submitSubscribeNewsletter() {
   var body = "submitted=true&email=" + encodeURIComponent( jQuery("#newsletterEmail").val() ) +
           "&firstName=" + encodeURIComponent( jQuery("#newsletterFirstName").val() ) +
           "&lastName=" + encodeURIComponent( jQuery("#newsletterLastName").val() );

   var gender = null;
   if (ge('newsletterGenderFemale').checked) {
       gender = "female";
   }
   if (ge('newsletterGenderMale').checked) {
       gender = "male";
   }
   if (gender != null) {
           body += "&gender=" + encodeURIComponent(gender);
   }


   XMLHTTP.request("POST",
        SHOP_BASEURL + "newsletter/subscribe",
        function(r) {
            jQuery("#subscribe_newsletter_layer").html(r.responseText);
            jQuery("#TB_overlay_messageLayer").show();
            jQuery('#TB_overlay_messageLayer').bgiframe();
            jQuery("#subscribe_newsletter_layer").show();
       }, body );

   return false;
}

function cancelSubscribeNewsletter(successful) {
    if (successful) {
        // we could track a successful newsletter subscription here...
    }

    jQuery("#subscribe_newsletter_layer").hide();
    jQuery("#TB_overlay_messageLayer").hide();
}

function unsubscribeNewsletter() {
   if (USER_LOGGED_IN) {
          // redirect a logged in user to the newsletter administration in his/her profile
          window.location.href = SHOP_BASEURL + "user/home";
       return;
   }

   XMLHTTP.request("POST",
       SHOP_BASEURL + "newsletter/signoff",
       function(r) {
           jQuery("#subscribe_newsletter_layer").html(r.responseText);
           ge("TB_overlay_messageLayer").style.display = 'block';
           jQuery('#TB_overlay_messageLayer').bgiframe();
           ge("subscribe_newsletter_layer").style.display = 'block';
      }, "" );
}

function cancelUnsubscribeNewsletter(successful) {
    if (successful) {
        // we could track a successful newsletter unsubscription here...
    }

    jQuery("#subscribe_newsletter_layer").hide();
    jQuery("#TB_overlay_messageLayer").hide();
}

function submitUnsubscribeNewsletter() {
   var body = "submitted=true&email=" + encodeURIComponent( jQuery("#newsletterUnsubscribeEmail").val() );

   XMLHTTP.request("POST",
        SHOP_BASEURL + "newsletter/signoff",
        function(r) {
            jQuery("#subscribe_newsletter_layer").html(r.responseText);
               ge("TB_overlay_messageLayer").style.display = 'block';
               jQuery('#TB_overlay_messageLayer').bgiframe();
               ge("subscribe_newsletter_layer").style.display = 'block';
       }, body );

   return false;
}

//////////////////////////////
/// END Newsletter////////////
//////////////////////////////

function makeFormActionSecure(formElement) {
    var form = jQuery(formElement);
    form.attr("action", getSecureUrlFromUrl(form.attr("action")));
}



function encodeTwice(uri) {
    // no double encoding is needed any longer - so this
    // function returns single encoding now

    return encodeURI(uri);
    //res = res.replace(new RegExp("/", "g"), SLASH_REPLACEMENT_STRING);
    return res;

//  return encodeURI(encodeURI(uri));
}

function encodeURIComponentForTapestry(uri) {
    var res = encodeURIComponent(uri);
    res = res.replace(/%2F/g, SLASH_REPLACEMENT_STRING);
    res = res.replace(/%0A/g, ","); // replace \n with , as tag separator
    return res;
}

function encodeURIForTapestry(uri) {
    var res = encodeURI(uri);
    res = res.replace(new RegExp("/", "g"), SLASH_REPLACEMENT_STRING);
    return res;
}

function decodeTapestryURIComponent(uri) {
    var res = decodeURIComponent(uri);
    res = res.replace(new RegExp(SLASH_REPLACEMENT_CHAR, "g"), "/");
    return res;
}


function trackClickoutQuickView(formToSubmit, minPrice) {

    if (WEBTRACKING_ENABLED) {
        webtrackingTrackClickoutQuickView(minPrice);
        trackRemarketing("IlodCKeCxwEQvaOW-QM");
    }

    formToSubmit.submit();
}

function trackClickToShop(shopId) {
    if (WEBTRACKING_ENABLED) {
        webtrackingTrackClickToShop(shopId);
        trackRemarketing("IlodCKeCxwEQvaOW-QM");
    }
}

function trackRemarketing(conversion_label) {
	var google_conversion_id = 1059426749;
	var google_conversion_language = "en";
	var google_conversion_format = "3";
	var google_conversion_color = "666666";
	var google_conversion_label = conversion_label;
	var google_conversion_value = 0;
	
	importJS('http://www.googleadservices.com/pagead/conversion.js');
}

// load js
function importJS(src, look_for, onload) {
	var s = document.createElement('script');
	s.setAttribute('type', 'text/javascript');
	s.setAttribute('src', src);
	if (onload) wait_for_script_load(look_for, onload);
	var head = document.getElementsByTagName('head')[0];
	// wenn Head-Tag im DOM vorhanden ist, JavaScript in den Head schreiben, ansonsten in den body bereich
	if (head) {
		head.appendChild(s);
	} else {
		document.body.appendChild(s);
	}
}

// wait for a js
function wait_for_script_load(look_for, callback) {
	var interval = setInterval(function() {
		if (eval("typeof " + look_for) != 'undefined') {
			clearInterval(interval);
			callback();
		}
	}, 50);
}

function debugOutput(debugString) {
    if (typeof console != "undefined") {
        console.debug(debugString);
    }
}

function setStringProperty (key, value) {
    var body = "key=" + key + "&value=" + value;
    XMLHTTP.request(
        "POST",
        SHOP_BASEURL + "start.maintemplate.setstringProperty",
        function (r) {},
        body);
    return false;
}

function getStringProperty (key) {
    var body = "key=" + key;
    XMLHTTP.request(
        "POST",
        SHOP_BASEURL + "start.maintemplate.getstringProperty",
        function (r) { return r.responseText; },
        body);
    return false;
}

// This function submits a form if the calling object is a 'select' and the
// the selected item has an index greater than or equals nthItem
function submitForm ( callingItem, nthItem ) {
    if ( typeof callingItem.selectedIndex != "undefined"
            && callingItem.selectedIndex >= nthItem ) {
        callingItem.form.submit()
    }
    return false;
}

// Invite external friends - begin //

function showWebmailerThickbox( name ) {
    jQuery('#TB_overlay_messageLayer').bgiframe();
    jQuery("#TB_overlay_messageLayer").show();
    jQuery('#test_2_layer').show();
    
    jQuery('#test_2_layer .adressBookString').html(name);
}

function showSelectedWebmailerThickboxFromOption( callingSelect, nthItem ) {

    if ( typeof callingSelect.selectedIndex != "undefined"
            && callingSelect.selectedIndex >= nthItem ) {
        var webmailerNameTmp = callingSelect.options[callingSelect.selectedIndex].text;
        showSelectedWebmailerThickbox( webmailerNameTmp );
    }

}

function showSelectedWebmailerThickbox( name ) {

    if ( webmailerName.length == 0 ) {
        webmailerName = name;
        showWebmailerThickbox( webmailerName );
        jQuery('#emailForm').append('<input type="hidden" name="webmailerName" value="' + name + '" id="webmailerName">');
    }
    
    ge('email').focus();
    
    makeFormActionSecure(ge('emailForm'));
    
}

function moveWebmailerThickbox () {
    ge('inviteExternalFriendsThickboxContainer').innerHTML = ge('thickboxContent').innerHTML;
    ge('thickboxContent').innerHTML = "";
}

function hideWebmailerThickBox() {
    jQuery("#TB_overlay_messageLayer").hide();
    jQuery('#test_2_layer').hide();
    webmailerName = "";
}

function showSelectedSocialNetworkThickboxFromOption( callingSelect, nthItem ) {

    if ( typeof callingSelect.selectedIndex != "undefined"
            && callingSelect.selectedIndex >= nthItem ) {
        var socialNetworkNameTmp = callingSelect.options[callingSelect.selectedIndex].text;
        var socialNetworkTypeTmp = callingSelect.options[callingSelect.selectedIndex].value;
        showSelectedSocialNetworkThickbox( socialNetworkNameTmp, socialNetworkTypeTmp );
    }

}

function showSelectedSocialNetworkThickbox( name, type ) {

    socialNetworkName = name;
    socialNetworkTypeName = type;
    jQuery('#socialNetworkForm').append('<input type="hidden" name="socialNetworkName" value="' + socialNetworkName + '" id="socialNetworkName">');
    jQuery('#socialNetworkForm').append('<input type="hidden" name="socialNetworkTypeName" value="' + socialNetworkTypeName + '" id="socialNetworkTypeName">');
    showSocialNetworkThickBox( socialNetworkName );
    
    ge('socialNetworkUid').focus();
    
    makeFormActionSecure(ge('socialNetworkForm'));
    
}

function showSocialNetworkThickBox ( name ) {
    jQuery('#TB_overlay_messageLayer').bgiframe();
    jQuery("#TB_overlay_messageLayer").show();
    jQuery('#test_3_layer').show();
    
    
    if(name == 'Xing')
    {
         jQuery('#xing_text').show();       
    }
    else
    {
        jQuery('#xing_text').hide();
    }
    
    
    jQuery('#test_3_layer .socialNetworkString').html( name );
}

function hideSocialNetworkThickBox () {
    jQuery("#TB_overlay_messageLayer").hide();
    jQuery('#test_3_layer').hide();
    socialNetworkName = "";
}

function moveSocialNetworkThickbox () {
    ge('sendSocialNetworkMessangesThickboxContainer').innerHTML = ge('SocialNetworkThickboxContent').innerHTML;
    ge('thickboxContent').innerHTML = "";
}

// Invite external friends - end //

//////////////////////////////
// tag Suggestions ///////////
//////////////////////////////

function performTagSuggestSearch ( tagPrefix ) {

    var tagSuggestionsResponse;
    
    var body = "prefix=" + encodeURIComponent( tagPrefix );
    var url = SHOP_BASEURL + "productdetails.tagProductForm.getTagSuggestions";
    
    
    XMLHTTP.request(
            "POST",
            url,
            function(r) {
            var suggestions = XMLHTTP.parseJSON( r.responseText );
                 // rufe fillTagSuggestSearch mit entsprechenden Arrays auf
                 fillTagSuggestSearch( suggestions.communityTags, suggestions.userTags, suggestions.userLoggedIn );
            },
            body
    );
}

function showThickBox(id) {
  jQuery("#TB_overlay_list").show();
  jQuery("#" + id).show();
}

function hideThickBox(id) {
  jQuery("#" + id).hide();
  jQuery("#TB_overlay_list").hide();
}

function createStyle(name, description) {
  showEditor('title=' + escape(name) + '&description=' + escape(description));
}

function editStyle(id) {
  showEditor('styleId=' + id);
}

function convertListToStyle(convertId) {
  showEditor('convertId=' + convertId);
}

function getCookie(name) {
   var start = document.cookie.indexOf(name+"="); 
   var len = start+name.length+1; 
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
   if (start == -1) return null; 
   var end = document.cookie.indexOf(";",len); 
   if (end == -1) end = document.cookie.length; 
   return unescape(document.cookie.substring(len,end)); 
}


                             
var STYLE_EDITOR_APP_ID = 'wg13iur5';
var styleeditor_initialized = false;
//var demoMode = 'true'; // demoMode isnt in use anymore, since we have temp users now
//var userN = "Stylemaster";
var editorParams ='';
var slideshow ='';
function showEditor(params) {
    editorParams = params;
    if (!styleeditor_initialized) {
        //userN = USERNAME;
        //demoMode = 'false';
        writeStyleEditor(editorParams);
          
        styleeditor_initialized = true;
        window.scrollTo(0,0);
        jQuery("#TB_overlay_list").show();
        jQuery("#styleeditor").show();
    } else {
        window.scrollTo(0,0);
        jQuery("#TB_overlay_list").show();
        jQuery("#styleeditor").show();
        document.getElementById("styleeditor").style.visibility=null;
    }
}

/* tagBox in Thickbox öffnen */
function tagProductinTB(){                  
    var testContent = jQuery('.taggingBox');
    jQuery('#container').prepend(testContent);
    jQuery('.taggingBox').show();
    jQuery('#tagsuggest').show();
    jQuery('.taggingBox').find('form.communityBox').show();
    jQuery('#tagging_field').focus();
    hideTagsuggest();
    showTagBoxinTB(); 
}   

function showTagBoxinTB(){
    jQuery("#TB_overlay_list").show();
    return false;
}

function hideTagBoxinTB(){
    jQuery("#TB_overlay_list").hide();
    jQuery('#taggingBox').hide();
    /*console.log('hide');*/
    jQuery('.taggingBox').hide();
    //jQuery('#taggingBox').find('form.communityBox').hide();
    return false;
}

/* open InviteMail in Thickbox */
/* tagBox in Thickbox öffnen */
function openInviteMailInTB(){                  
    var testContent = jQuery('.inviteBox'); 
    jQuery('#container').prepend(testContent);
    jQuery('.inviteBox').show();
    //jQuery('#tagsuggest').show();
    jQuery('.inviteBox').find('form.communityBox').show();
    //jQuery('#tagging_field').focus();
    //hideTagsuggest();
    showTagBoxinTB(); 
}   

function writeStyleEditor(editorParams) {
    jQuery("#no_flash_text").show();
    jQuery("#demo_editor_info").hide();
  
    if (jQuery('#noflash_image').size() > 0 && jQuery("#no_flash_text").css('display') != 'none') {
       slideshow = window.setInterval("change_noflash_img('noflash_image')", 2000);
    } else {
       window.clearInterval(slideshow);
    }
    
    if ((typeof USERNAME == 'undefined') && ( getCookie('TEMP_USER_COOKIE') == null )) { 
        XMLHTTP.request(
            "POST",
            SHOP_BASEURL + CURRENT_PAGE_NAME + ".maintemplate.getTempUser",
            function( r ) {// r.responseText;
                writeStyleEditorDetails(editorParams);
            });
       return;
    } else {
       writeStyleEditorDetails(editorParams);   
    }
}

function writeStyleEditorDetails(params) {
    var userToken = getCookie('SHOPPING24_SHOP_REMEMBER_ME_COOKIE');
    var username = ""
    var demoMode = false;
    if (typeof USERNAME != 'undefined') { 
        username = USERNAME;
    }
    if ( userToken == null ) {
        userToken = getCookie('TEMP_USER_COOKIE');
        username = getCookie('TEMP_USER_NAME_COOKIE');
        demoMode = true;
    }
    if ( userToken == null ) {
        alert('Entschuldigung, der Styleeditor lässt sich momentan nicht nutzen, versuche es später noch einmal.');
    }    
    var constantParams = 'stopper&appId=' + STYLE_EDITOR_APP_ID + '&' +
                             'userToken=' + userToken + '&' +
                             'username=' + escape(username).replace(/\+/g, '%2B') + '&' + 
                             'baseUrl=' + escape(API_BASE_URL) + '&' +
                             'baseMediaUrl=' + escape(STATIC_CONTENT_PREFIX);
    if (demoMode) {
        constantParams += '&tempUser=true';
    }

    var editor = new SWFObject( STATIC_CONTENT_PREFIX+'img/styles/styleeditor.swf" ', 'styleeditor_flash', "970", "690", "9.0.124", "#F6F6F6");
    editor.addVariable("FlashVars", constantParams + '&' + params );
    editor.addParam("allowScriptAccess", "always");
    //editor.addParam("wmode", "transparent");
    editor.write("styleeditor_content");

}


var noflash_counter_mx = 5;
var noflash_counter_mn = 1;

function change_noflash_img(element)
{
        
        if ( noflash_counter_mn < noflash_counter_mx)
        {
                noflash_counter_mn++;
                
        }
        else
        {
                noflash_counter_mn = 1;
                
        }
        var src = jQuery('#'+element).attr('src');
        var new_src= src.replace(/[0-9]+/, noflash_counter_mn);
        jQuery('#'+element).attr('src', new_src);
}

function exitFromEditStyle() {
  //hideThickBox('styleeditor');
  window.clearInterval(slideshow);
  hideStyleeditor();
}

/**
 * dirty hack for ff2/windows,mac closing crash: just hide, not clean up
 */
function hideStyleeditor() {
  document.getElementById("styleeditor").style.visibility="hidden";
  jQuery("#TB_overlay_list").hide();
}

function redirectAfterEditStyle(redirectURL) {
  //hideThickBox('styleeditor');
  hideStyleeditor();
  location.href = redirectURL;
}

function showWhatToolTip() {
    jQuery('#what').removeClass( 'what' ).addClass( 'what_active' );
    jQuery('#what_header').removeClass( 'what_header' ).addClass( 'what_header_active' );
    jQuery('#tool-tip').show();
}

function hideWhatToolTip() {
    jQuery('#what').removeClass( 'what_active' ).addClass( 'what' );
    jQuery('#what_header').removeClass( 'what_header_active' ).addClass( 'what_header' );
    jQuery('#tool-tip').hide();
}

/**
 * This is a really weird hack to display the special option in the register
 * form when opened from the styleeditor.
 * It sets the global (argh) variable _displaySpecialOptionInRegisterForm which is
 * then read by displayLoginAndRegisterBoxAndStyleEditorAfterwards
 * 
 * This var should be set by the demo-style-editor panel, which is right now in
 * the maintemplate. This also should be changed to be loaded on demand, then we
 * can pass this variable to the loading function.
 * 
 * @param displaySpecialOptionInRegisterBox if <code>true</code>, then the registration panel
 *                              (which might be opened from the demo-style-editor panel)
 *                              also provides the checkbox "special option", e.g. for subscribing
 *                              to some special newsletter.
 * @return
 */
var _displaySpecialOptionInRegisterForm = false;
function showStyleEditor( displaySpecialOptionInRegisterForm ) {
    _displaySpecialOptionInRegisterForm = displaySpecialOptionInRegisterForm;
    showEditor();
}

/**
 * Hide the element with id "styleeditor", display the login/register box
 * and open the styleeditor after successful login/registration.
 * 
 * @param showRegistrationPanel if <code>true</code> then the registration panel is shown
 *                              initially, otherwise the login panel is shown.
 */
function hideStyleEditorDemoInfoAndShowLoginRegisterBox( showRegistrationPanel ) {
    jQuery( "#styleeditor" ).hide();
    jQuery( "#TB_overlay_list" ).fadeOut( 200 );
    displayLoginAndRegisterBoxAndStyleEditorAfterwards( showRegistrationPanel, _displaySpecialOptionInRegisterForm );
}

/**
 * Display the login/register box and open the styleeditor after successful login/registration.
 * 
 * @param showRegistrationPanel if <code>true</code> then the registration panel is shown
 *                              initially, otherwise the login panel is shown.
 * @param displaySpecialOptionInRegisterBox if <code>true</code>, then the registration panel
 *                              also provides the checkbox "special option", e.g. for subscribing
 *                              to some special newsletter.
 */
function displayLoginAndRegisterBoxAndStyleEditorAfterwards( showRegistrationPanel, displaySpecialOptionInRegisterBox ) {

    showLoginAndRegisterBox(function() {
        setAfterLoginParameters( "showEditor();", "invokeJavascript" );
    }, showRegistrationPanel, displaySpecialOptionInRegisterBox );

    return false;
}

/* fuer pepsi */
function showHideTab(obj){
    var tabContent = new Array("multitab_container_1", "multitab_container_2", "multitab_container_3");
    for (var i = 0; i < tabContent.length; i++){
        el = document.getElementById(tabContent[i]);
        el.style.display = 'none';
    }
    document.getElementById("multitab_container_"+obj).style.display = 'block';
}

//Clickout auf Listenansicht ueber Title und ProdImage                  
function submitFormForClickout(obj, fromWhere){
    switch (fromWhere)
    {
        /* Listenansicht - Produktimage */
        case 'searchListFromImage':
            jQuery(obj).parent().find('.cc_searchListFromProdImg').find('button').trigger('click');
        break;
        /* Produktdetailansicht - Produktimage */
        case 'prodDetailFromCPImage':
            jQuery(obj).parent().find('.cc_productDetailFromProdImg').find('button').trigger('click');
        break;
        /* Produktdetailansicht - Produktimage SP */
        case 'prodDetailFromSPImage':
            jQuery(obj).parent().find('.cc_productDetailFromSPProdImg').find('button').trigger('click');
        break;      
        /* Galerieansicht ProduktImage */
        case 'searchMediumFromProdImg':
            jQuery(obj).parent().find('.cc_searchMediumFromProdImg').find('button').trigger('click');
        break;  
        case 'searchListFromTitle':
            jQuery(obj).parent().parent().find('form').find('button.clickoutButton').trigger('click');
        break;      
        case 'prodDetailFromSPTitle':
                jQuery(obj).parent().parent().parent().children().eq(2).find('form').find('button.clickoutButton').trigger('click');
                
            break;
        case 'searchResultListBigView':
            jQuery(obj).parent().parent().find('form').find('button.clickoutButton').trigger('click');
        break;  
        default:
            return false;
    }                           
}

/* openSocial Bookmarks */
function openSocialBookMarks(what){
    u=location.href;
    t=document.title;
    switch (what)
    {
        case 'facebook':
            window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&amp;t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
            break;
        case 'delicious':
            window.open('http://delicious.com/save?v=5&noui&jump=close&amp;url='+encodeURIComponent(u)+encodeURIComponent(t),'delicious','toolbar=no,width=626,height=436');
            break;
        case 'wong':
            window.open('http://www.mister-wong.de/index.php?action=addurl&bm_url='+encodeURIComponent(u)+'&bm_description='+encodeURIComponent(t), 'wong','toolbar=no,width=626,height=436');
		case 'studivz':
            window.open('http://www.studivz.net/Suggest/Selection/?u='+encodeURIComponent(u)+'&bm_description='+encodeURIComponent(t), 'studivz','toolbar=no,width=800,height=460');
                   
            break;
        default:
            return false;
    }
    return false;
}

/* toggle the description text between long and short description text - productdetailpage  */
function toogleDescText(hide, show){
    /*console.log('toogleDescText: '+ hide);*/
    jQuery('#'+show).show();
    jQuery('#'+hide).hide();
    return;
}


function subselect(id, w) {
    w = w.toLowerCase();
    var lis = jQuery(id +' > li > a');
    var matches = 0;
    var tit,idx,li,foo = 0;
    for (var i=0; i < lis.length; ++i) {
        li = lis[i]
        tit = li .getAttribute('title')
        idx = tit.indexOf(w);
        if (idx < 0) {
            li.parentNode.style.display = 'none';
            ++foo;
        } else {
            li.parentNode.style.display = 'block';          
        }
    }
}
function browserCanAddBookmarks() {
    if (window.sidebar || window.external) {
        return true;
    }
    return false;
}

function addSearchPageAsBookmark() {
    if (window.sidebar) { // Mozilla Firefox
        window.sidebar.addPanel(document.title, window.location.href, '');
    } else if( window.external ) { // IE Favorite
        window.external.AddFavorite( window.location.href, document.title);
    }
}


function toggle_copyUrl (element, type) {
    if (ge('copy_url').style.display =="none") {
        if (browserCanAddBookmarks()) {
            ge('bookmarkSearchPageLink').style.display='inline';
        } else {
            ge('bookmarkSearchPageLink').style.display='none';
        }
        jQuery("#url_2_copy").val(window.location.href);

        toogle_communityBox (element, type);
        set_url_focus();
    }
    else {
        justHide_communityBox ();
    }
}

function filterPrice(a) {
    var orig = a.href;
    var min = ge('minPrice').value;
    var max = ge('maxPrice').value;
    a.href = orig + '/preis-[' + min + ' TO ' + max + ']';
}
/**
 * Validation for the register page
 */

/**
 * For avoiding unneccessary AJAX calls
 */
var lastUsername = "";
var lastEmail = "";

/**
 * If true, then all fields are always
 * validated, else only non-empty fields
 */
var validateEverything = false;


function reloadCaptcha() {
    var oldsrc = jQuery("#captcha").attr("src");
    jQuery("#captcha").attr("src", oldsrc + "/reload");
    jQuery("#captchaText").val("");
    jQuery("#captchaText").focus();
}

function computePasswordStrengthFromForm() {
	password = jQuery('#password').val();
	username = jQuery('#username').val();
	if (!password) {
		password = "";
	}
	if (!username) {
		username = "";
	}

	jQuery('#reg_result2').css("width",
		passwordStrength(password,username));
}

function computePasswordStrength(password, username) {
	jQuery('#reg_result2').css("width",
		passwordStrength(password,
		username));
}

function usernameInRange(username) {
    return username.length >= 6 && username.length <=24;
}

function usernameInBlacklist(username) {
	if (username.indexOf("@") != -1 || username.indexOf("smatch") != -1) {
		return true;
	}

	return false;
}

function passwordInRange(password) {
    return password.length >= 8;
}

function validate() {
    username = document.getElementById("username").value;
    password = document.getElementById("password").value;
    repeatedPassword = document.getElementById("repeatedPassword").value;
    email = document.getElementById("email").value;

    if (username || validateEverything) {
        validateUsername(username);
    }
    if (password || validateEverything) {
        validatePassword(password);
    }
    if (repeatedPassword || validateEverything) {
        validateRepeatedPassword(password, repeatedPassword);
    }
    if (email || validateEverything) {
        validateEmail(email);
    }
    validateEnabled = true;
    //hideFormErrors();
}

function validatePassword(password, repeatedPassword) {
    if (passwordInRange(password)) {
        setFormError("password", false, "<br />");
    } else {
        setFormError("password", true, "Bitte min. 8 Zeichen");
    }
}

function validateRepeatedPassword(password, repeatedPassword) {
    if (password == repeatedPassword) {
        setFormError("repeatedPassword", false, "<br />");
    } else {
        setFormError("repeatedPassword", true, "Stimmt nicht überein");
    }
}

function validateUsername(username) {
    if (lastUsername != "" && lastUsername == username) {
        // don't check if the user name did
        // not change: prevent unneccessary AJAX calls
        return;
    }


    if (usernameInRange(username) && !usernameInBlacklist(username)) {
        XMLHTTP.request("GET", SHOP_BASEURL +
            "user/register.registerForm.checkUsernamePresent/" + username,
            function(r) {
                if (r.responseText == "no") {
                    setFormError('username', false, "<br />");
                } else {
                    setFormError('username', true, "Name schon vergeben");
                }

            }
        );
    } else {
    	if (!usernameInRange(username)) {
        	setFormError('username', true, "Bitte 6 bis 24 Zeichen");
        } else {
        	setFormError('username', true, "Bitte kein @ oder smatch");
        }
    }

    lastUsername = username;
}



function validateEmail(email) {
    if (isValidEmail(email)) {
    	if (email == lastEmail) {
    		return;
    	}
    	lastEmail = email;

        XMLHTTP.request("GET", SHOP_BASEURL +
            "user/register.registerForm.checkEmailPresent/" + email,
            function(r) {
                if (r.responseText == "no") {
                    setFormError('email', false, "<br />");
                } else {
                    setFormError('email', true, "Es existiert schon ein Benutzer mit dieser E-Mail-Adresse.");
                }
            }
        );
    } else {
        setFormError('email', true, "ungültig");
    }
}

function hideFormErrors() {
    errorDiv = document.getElementById("RegisterForm:errors");
    if (errorDiv) {
    	jQuery(errorDiv).hide();
   	}
}

function setFormError(elementid, on, message) {
    field = document.getElementById(elementid);
    errormsg = document.getElementById(elementid + "-error");
    error_img = document.getElementById(elementid + "-error_img");

    if (on) {
        jQuery(field).addClass('alert');
        jQuery(error_img).show();
    } else {
        jQuery(field).removeClass('alert');
        jQuery(error_img).hide();
    }

	jQuery(errormsg).html(message);

}

function isValidEmail(email) {
    return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/i.test(email);
}


// Functions for the login and register thickbox

function showLoginAndRegisterBox( callbackFunction ) {
	showLoginAndRegisterBox( callbackFunction, false, false );
}

function showLoginAndRegisterBox(callbackFunction, showRegistrationPanel, displaySpecialOptionInRegisterBox) {
	trackLoginRegisterStart();

	loadLoginAndRegisterBoxAjax(callbackFunction, showRegistrationPanel, displaySpecialOptionInRegisterBox);
	
}

function makeLoginAndRegisterBoxVisible( showRegistrationPanel ) {
	jQuery('#TB_overlay_reg').bgiframe();
	jQuery("#TB_overlay_reg").show();
	jQuery("#loginAndRegisterBox").show();

	// the login panel is displayed by default, therefore we only have to
	// act if we shall display the registration panel
	if ( showRegistrationPanel ) {
		change_multi_tab_l( "#multitab_reg_2", "multitab_reg", 2 );
	}

	if(jQuery.browser.msie ) {
          if (jQuery.browser.version <7) {
              window.location.href="#";
          }
    }
}

function loadLoginAndRegisterBoxAjax(callbackFunction, showRegistrationPanel, displaySpecialOptionInRegisterBox) {
	if (ge('loginAndRegisterBox_inner')) {
		// box is already loaded
		makeLoginAndRegisterBoxVisible( showRegistrationPanel );
		callbackFunction();
		return;
	}

	if ( typeof displaySpecialOptionInRegisterBox == "undefined" ) {
		displaySpecialOptionInRegisterBox = false;
	}

	var body = "requestUri=" + encodeURIComponent(REQUEST_URI)
			 + "&displaySpecialOptionInRegisterBox=" + displaySpecialOptionInRegisterBox;

	XMLHTTP.request(
		"POST",
		SHOP_BASEURL + "user/LoginAndRegisterBoxAjaxWrapper/" +
				Math.random() * 10000, // random is for forcing that the response is not cached!,
		function(r) {
			jQuery("#loginAndRegisterBox").html(r.responseText);
			makeLoginAndRegisterBoxVisible( showRegistrationPanel );
			callbackFunction();
		},
		body
	);
}

function trackLoginRegisterStart() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
		s.pageName = "LoginRegisterBox";
		s.prop22 = "overlay";
		s.t();
	}
}

function trackRegisterFormShown() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
		s.pageName = "RegisterThickbox";
		s.events="event1";
		s.t();
		increaseNumberOfActions();
	}
}

function cancelLoginOrRegister() {
	jQuery("#TB_overlay_reg").hide();
	jQuery("#loginAndRegisterBox").hide();
}


My_Url = function() {}

My_Url.parse = function(url) {
    this.url = url;
    result = this.url.match(this.regexp);
    this.scheme = result[1];
    this.host = result[2];
    this.port = result[3];
    this.path = result[4];
    return this;
}

My_Url.prototype.parse = My_Url.parse
My_Url.prototype.regexp = /(https?:\/\/)([a-zA-Z0-9_\-\.]+)(:[0-9]+)?\/?(.*)?/

function getSecureUrlFromUrl(url) {
	if (url.indexOf("http") != 0) {
		return SECURE_URL_PREFIX + url;
	} else {
		urlObject = new My_Url();
		urlObject.parse(url);

		return SECURE_URL_PREFIX + "/"+ urlObject.path;
	}
}



// Functions for editing the about-me-text

function hideUserDescriptionTeaser() {
	jQuery("#edit_user_description_teaser").hide();
	showEditUserDescriptionForm();
}

function showEditUserDescriptionForm() {
	jQuery('#user_description_edit_icon').hide();
	jQuery("#user_description_text").hide();
	jQuery('#user_description_textarea').val(jQuery('#user_description_text').html().replace(/<br>/gi, "\n").replace(/&amp\;/gi, "&").replace(/&gt\;/gi, ">").replace(/&lt\;/gi, "<"));
	jQuery("#user_description_form").show();
}

function changeUserDescription() {
	changeUserDescriptionAjax();
	return false;
}

function changeUserDescriptionAjax() {
	XMLHTTP.request("POST", SHOP_BASEURL +
            "user/editprofile.communitypagetemplate.infobox.changeUserInfoText/",
            function(r) {
                if (parseJsonWithErrorHandling(r)) {
                	jQuery('#user_description_text').html(jQuery('#user_description_textarea').val().replace(/(\r\n)|(\n\r)|\r|\n/g,"<br>"));
                }

                hideUserDescriptionForm();
            }, 
            "text=" + encodeURIComponent(jQuery('#user_description_textarea').val())
    );
}

function hideUserDescriptionForm() {
	jQuery("#user_description_form").hide();
	jQuery('#user_description_edit_icon').show();
	jQuery("#user_description_text").show();
}






var SHOUTBOX_SUBMIT_ABORTED=false;

function submitShoutbox() {
	var text = jQuery('#shoutbox').val();
	if (!text) {
		alert("Gib bitte etwas ein");
		return;
	}
	
	var userId = jQuery('#shoutboxOwnerId').val();
	
	if (jQuery('#shoutboxIsLoggedIn').val() == 'false') {
		submitShoutboxAfterLogin(userId, text);
		return;
	}

	addShoutboxEntryAndRefreshView(userId, text);
}

function addShoutboxEntryAndRefreshView(userId, text) {
	addShoutboxEntryAjax(userId,
		text, 
		function(r) {
			if (!parseJsonWithErrorHandling(r)) {
				return;
			}
			
			XMLHTTP.request(
				"GET",
				SHOP_BASEURL + "user/shoutboxcontentsajaxwrapper/"+ userId +
					"/" + Math.random() * 10000, // random is for forcing that the response is not cached!
				function(r) {
					jQuery('#shoutboxContentsContainer').html(r.responseText);
					jQuery("#shoutbox").val("");
					
					trackShoutboxEntryAdded();
				}
			);
			
		}
	);
}

function trackShoutboxEntryAdded() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ShoutboxEntryAdded";
        s.events="event15";
        s.eVar23="Shoutbox-Eintrag";
        s.t();
        increaseNumberOfActions();
	}
}

function submitShoutboxAfterLogin(userId, text) {
	// store values for after login
	params = "{ \"userId\" : \""+ userId + "\", "+
		" \"text\" : \""+ text + "\" }";
	
	showLoginAndRegisterBox(function() {
		setAfterLoginParameters(params, "submitShoutbox");
	});
}

function abortShoutboxEntry(inform) {
	var ta = jQuery(inform).find("textarea");
	if (ta.val() && confirm("Text wirklich löschen?")) {
		ta.val("");	
	}
}

function shoutboxDeleteConfirmation(elem) {       
	if (confirm("Eintrag wirklich löschen?")) {
		trackShoutboxEntryDeleted();
		elem.submit();
	}
}

function trackShoutboxEntryDeleted() {
	if (WEBTRACKING_ENABLED) {
		resetSiteCatalystVariables();
        s.pageName = "ShoutboxEntryDeleted";
        s.events="event16";
        s.eVar23="Shoutbox entfernt";
        s.t();
        increaseNumberOfActions();
	}
}

function addShoutboxEntryAjax(receiverUserId, text, callback) {
	var body = "receiverUserId=" + receiverUserId
				 + "&text=" + encodeURIComponent( text );
	XMLHTTP.request(
		"POST",
		SHOP_BASEURL + "user/editshoutbox.communitypagetemplate.infobox.addShoutboxEntry",
		callback,
		body
	);
}

function move_smatch_widget_left(widgetId) {
	var currentImageNumber = currentSmatchWidgetImages["widget_" + widgetId];
	var images = jQuery("#smatch_widget_product_images_"+ widgetId).find("a");
	
	if ((currentImageNumber-1) <= 0) {
		return;
	}
	
	currentSmatchWidgetImages["widget_" + widgetId] = currentImageNumber - 1;
	show_smatch_widget_picture(currentImageNumber - 1, widgetId);
}


function move_smatch_widget_right(widgetId) {
	var currentImageNumber = currentSmatchWidgetImages["widget_" + widgetId];
	var images = jQuery("#smatch_widget_product_images_"+ widgetId).find("a");
	
	if ((currentImageNumber+1) >= images.size()-1) {
		return;
	}
	
	currentSmatchWidgetImages["widget_" + widgetId] = currentImageNumber + 1;
	show_smatch_widget_picture(currentImageNumber + 1, widgetId);
}

function show_smatch_widget_picture(pictureNo, widgetId) {

	var images = jQuery("#smatch_widget_product_images_"+ widgetId).find("a");
	jQuery("#smatch_widget_center_"+ widgetId).html(jQuery(images.get(pictureNo)).clone());
	
	var texts = jQuery("#smatch_widget_product_texts_"+ widgetId).find("div");
	jQuery("#smatch_widget_center_product_text_" + widgetId).html(jQuery(texts.get(pictureNo-1)).html());
	
	var leftPic = jQuery(images.get(pictureNo-1)).clone();
	jQuery(leftPic).find("img").height(55);
	jQuery(leftPic).find("img").width(40);
	jQuery("#smatch_widget_first_small_"+ widgetId).html(leftPic);
	
	var rightPic = jQuery(images.get(pictureNo+1)).clone();
	jQuery(rightPic).find("img").height(55);
	jQuery(rightPic).find("img").width(40);
	jQuery("#smatch_widget_last_small_"+ widgetId).html(rightPic);
	
}

function addWidgetParameter(link) {
	jQuery(link).attr("href", jQuery(link).attr("href") + "?cid=W");
}

function ge(id) {
    /*
    um das ewige document.getElementById() zu unterlaufen
    */
    return document.getElementById(id);
}
/*
Plugin cmspvincamp V1.0 20100209FR�
Wem dient der gral?
singlepage visits werden ausgeschlossen in theeventtoreportsecondpageswith
lassen sich nun durch theeventtoreportVisitswith-theeventtoreportsecondpageswith
berechnen. zus�tzlich setzen und lesen von cookies f�r interne kampagnen
*/
var cmspvfinalmarker='CMSPVFINALMARKER';
var cmspvcookiename='cm_spv';
var cmspvreportvisits=true;
var cmspveventlist="event11,event12";//TheEventToReportVisitsWith,TheEventToReportSecondPageWith
var cmspvUseLinkInternalFilters=true;
var cmspvPagenameMustBeDifferent=false;
var cmspvPagenameATClickOut="Zum_Shop";

function cmspvgetReportVisits(){
	return cmspvreportvisits;
}

function cmspvgetTheEventToReportVisitsWith(){
	var l=cmspveventlist.split(',');
	if(l.length) return l[0];
	return '';
}
	
function cmspvgetTheEventToReportSecondPagesWith(){
	var l=cmspveventlist.split(',');
	if(l.length>1) return l[1];
	return '';
}	

function cmspvgetThePageNameToReportInCookie(){
	var pn="";
	if(typeof(s.pageName)!='undefined')pn=s.pageName;
	if(pn==""){
		if(s.linkLeaveQueryString==true){
			pn=document.location.url;
		} else {
			pn=document.location.pathname;		
		}
	}
	return pn;	
}

function cmspvgetcookie(){
	////alert('getting cookie');
	return s.c_r(cmspvcookiename);
}	

function cmspvsetcookie(v){
	document.cookie=cmspvcookiename+"="+v+"; path=/;";	
	//alert('setting cookie: '+v);
}

function cmspvFromInternalDomain(){
	//alert('domcheck')
	if(cmspvPagenameATClickOut==s.pageName){
		//alert('pn clickout');
		return false;
	}	
	var dom=getdomain(document.domain);
	var dr=document.referrer;
	var refdom=getdomain(dr);
	////alert(dom)
	////alert(refdom)
	if(cmspvUseLinkInternalFilters){
		////alert('use')
		lif=s.linkInternalFilters;
		////alert(lif)
		l=lif.split(',');
		for(i=0;i<l.length;i++){
			str=l[i];
			if(str!=""){
				pos=refdom.indexOf(str);
				////alert(str)
				////alert(pos)
				if(pos>-1){
					tail=refdom.substr(pos);
					////alert(tail)
					if(tail.length==0) return true;
				}
			}		
		}
		return false;			
	} else {
		//alert('jeeehah')
		return refdom==dom;
	}
}
	
function cmspvdoit(){
	cmspvcookie=cmspvgetcookie();
	//alert('got cookie: '+cmspvcookie);
	if(cmspvcookie!=cmspvfinalmarker){
		if(cmspvcookie==''){
			//alert('cookie empty');
			if(!cmspvFromInternalDomain()){
				//alert('externaldomain');
				cmspvsetcookie(cmspvgetThePageNameToReportInCookie());
				if(cmspvgetReportVisits()){
					cm_addEvent(cmspvgetTheEventToReportVisitsWith());
					//alert(cmspvgetTheEventToReportVisitsWith()+ ' added');
				}		
			}
			//alert('internaldomain');
		} else {
			if(cmspvPagenameMustBeDifferent && cmspvgetThePageNameToReportInCookie()==cmspvcookie) return; 
			//alert('cookie!=pagename');
			cm_addEvent(cmspvgetTheEventToReportSecondPagesWith());	
			//alert(cmspvgetTheEventToReportSecondPagesWith()+ ' added');
			cmspvsetcookie(cmspvfinalmarker);
		}
	}	
	//alert('finalmarker')
}//doit



function getdomain(url){
	var url=url.toLowerCase().split('/');
	if(url[0].substr(0,4)=='http')return(url[2]);
	return(url[0]);
}
function cm_varIsSet(vn){//variable vn ist gesetzt und nicht leer
	if(typeof(vn)!="undefined"&&vn!="")return true;
	return false;
}
function cm_eventIsSet(ev){//event ev ist gesetzt
	if(!cm_varIsSet(s.events))return false;
	var events=''+s.events;
	if(events.indexOf(ev)>-1)return true;
	return false;
}
function cm_addEvent(ev){//setzt einen event ev einmalig pro seite
	if(!cm_varIsSet(s.events)){//1.fall events nicht definiert oder leer
		s.events=ev;
		return;
	}	
	if(cm_eventIsSet(ev)) return;//2.fall nicht leer aber schon drin
	s.events+=','+ev;//3.fall nicht leer aber nicht drin
}
function setcookie_werbemittel(w_id) {
	s.c_w('intwerbemittel',w_id);
	
}
function getcookie_werbemittel() {
	s.eVar22=s.c_r('intwerbemittel');
	var a=new Date;
	a.setTime(a.getTime()-1);
	s.c_w('intwerbemittel','leer',a);
}
/* SiteCatalyst code version: H.13.
Copyright 1997-2007 Omniture, Inc. More info available at
http://www.omniture.com */
/* Specify the Report Suite ID(s) to track here */
s_account='shopping24smatchdev';
var domain = document.domain;

switch (domain) {
	case "www.smatch.com":
	    s_account='shopping24smatchlive';
	    break;
  	case "test-bugfix.smatch.com":
	    s_account='shopping24test-bugfix';
	    break;
 	default:
	    s_account='shopping24smatchdev';
	    break;
}
    
var s=s_gi(s_account);
/************************** CONFIG SECTION **************************/
/* You may add or alter any code config here. */
s.charSet="UTF-8";
/* Conversion Config */
s.currencyCode="EUR";
/* Link Tracking Config */
s.trackDownloadLinks=true;
s.trackExternalLinks=true;
s.trackInlineStats=true;
s.linkDownloadFileTypes="exe,zip,wav,mp3,mov,mpg,avi,wmv,doc,pdf,xls";
s.linkInternalFilters="javascript:,suchenundshoppen.de,smatch.com,#,";
s.linkLeaveQueryString=false;
s.linkTrackVars="None";
s.linkTrackEvents="None";
s.usePlugins=true;
/* WARNING: Changing any of the below variables will cause drastic
changes to how your visitor data is collected.  Changes should only be
made when instructed to do so by your account manager.*/

s.dc=112;
s.PluginsDone=false;

function s_doPlugins(s) {
    //Handling event4 to count searches precisely
    if(s.prop1){
        var stcval=s.c_r('stc');
        if (stcval != s.prop1){
            if(s.events && s.events.indexOf("event4")<0){
                s.events+=",event4";
            } else {
                s.events="event4";
            }
        }
        s.c_w('stc',s.prop1,0);
        if(cm_getQueryParam('cid')){
            s.prop23='Ext';
            s.eVar31='Ext';
        } else if(s.eVar22){
            s.prop23='Int';
            s.eVar31='Int';
        } else {
            s.prop23='User';
            s.eVar31='User';
        }//if
    }//if s.prop1
    if(typeof s.events!='undefined' && s.events.indexOf('purchase')>-1 && s.c_r('direktkonversion')=='1'){s.events+=',event20';}
    var ref=s.getValOnce(document.referrer,'ref',0);
    if(!ref && s.c_r('ref')){//this is an AJAX call with s.t()
        s.referrer=document.location.href;
        s.campaign='';
    }else{
        if(!s.eVar22){s.eVar22=cm_getQueryParam('intcid');}//fr20080128
             var cid=cm_getQueryParam('cid');//fr20080901
           s.campaign=cid;//fr20080826
           s.c_w('direktkonversion','1',0);
           if(cid){
              cm_addEvent('event19');//fr20080523
            if(cid!=s.c_r('cidx')){
                var a=new Date();
                a.setTime(a.getTime()+300000);
                s.c_w('cidx',cid,a);//fr20080826 300sek=5min
                cm_addEvent('event9');//fr20080826
               }
        }//if(cid)  
           var kid=cm_getQueryParam('kid');
        if(kid && document.referrer){
            kid+='_'+cm_getQueryParam(cm_getParam(document.referrer),'',document.referrer);//wenn ref=google=>getQueryParam(q)
            if(kid.length>255){
                kid='X'+kid.substr(0,254);
            }
            s.eVar38=kid;
        }//if(kid)
    }//else
    if (s.prop7 && s.pageName) {
        s.prop13 = s.prop7 + ":" + s.pageName;
    }
    if(!s.PluginsDone){
        //holt oldsprops aus cookie
        eval(s.c_r('oldsprops'));
        //vergleicht aktuelle mit alten werten und setzt evars bei Aenderungen
        var startVar = 1;
        var endVar = 13;
        var ex='';
        for(sc_n=startVar;sc_n<=endVar;sc_n++){
            ex+='if(typeof(s.prop'+sc_n+')!="undefined" && s.prop'+sc_n+'!=s.propold'+sc_n+')s.eVar'+sc_n+'=s.prop'+sc_n+';\n';
        }
        eval(ex);
        ex='';
        var v=''; 
        //speichert variablen in v
        for(sc_n=startVar;sc_n<=endVar;sc_n++){
            ex+='if(typeof(s.prop'+sc_n+')!="undefined" && s.prop'+sc_n+'!="") v+="s.propold'+sc_n+'=\'"+s.prop'+sc_n+'+"\';";';
        }
        eval(ex);
        //schreibt oldsprops in cookie
        s.c_w('oldsprops',v,0);
        cmspvdoit();
		getcookie_werbemittel();
    } 
    if(!s.prop4)s.prop4=s.pageName;
    s.PluginsDone=true;
	
	if(typeof s.events!='undefined' && s.events.indexOf("purchase")>-1){
		s.eVar12=s.pageName;
	}
}

s.doPlugins=s_doPlugins;

/*Plugin cm_getQueryParam V1.1 20080901FRÄ
calls s.getQueryParam if installed, if doesn't return anything
tries to split document.location.search at separator sep,
finds the parameter name case-insensitive and returns the value
*/
function cm_getQueryParam(n){
	if(typeof(n)=='undefined')return '';
	var ret='';
	if(typeof(s)!='undefined'&&s.getQueryParam!='undefined')ret=s.getQueryParam(n);
	if(ret)return cm_removeHashmarkFromUrlParamValue(ret);
	n=n.toLowerCase();
	var sep='&';
	var qstr=document.location.search.substr(1);
	var qs=qstr.split(sep);
	var pair;
	var p;
	for(i=0;i<qs.length;i++){
		pair=qs[i];
		p=pair.split('=');
		if(p[0].toLowerCase()==n)return cm_removeHashmarkFromUrlParamValue(p[1]);	
	}
	return '';	
}
/*Plugin cm_removeHashmarkFromUrlParamValue V1.0 20080901FRÄ
removes hashmark and the following anchor name from querystring parameters.
*/
function cm_removeHashmarkFromUrlParamValue(v){
	if(typeof(v)!="string")return v;
	if(v[v.length-1]=='#')return v.substr([v.length-1]); 
	return v;
}

/*
 * Copyright (c) contentmetrics GmbH, 2008
 * THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
 * APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
 * HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
 * IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
 * ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 *
 * Autor: Frank Räther, 2008-09-05
 * Code: JavaScript Library zum Tracken von SEM/SEO Keywords
 * Kunde: Shopping24
 * Version: V1, last changed 05.09.2008, F.Raether
 * Einziger Parameter: URL (meist aus Referrer)
 * Rückgabewert: Leer wenn keine Suchmaschine, 
 * sonst Name des URL Parameters, der das Suchwort enthält.
 */


//BEGIN 20080905 
function cm_getParam(url){
	urll=url.split('?');
	if(urll.length==1)return;	
	var sEng=new Array();
	var sPar=new Array();
	sEng[0]="google";			sPar[0]="q";
	sEng[1]="yahoo";			sPar[1]="p";
	sEng[2]="msn";				sPar[2]="q";
	sEng[3]="aol";				sPar[3]="query";
	sEng[4]="aol";				sPar[4]="encquery";
	sEng[5]="lycos";			sPar[5]="query";
	sEng[6]="ask";				sPar[6]="q";
	sEng[7]="altavista";		sPar[7]="q";
	sEng[8]="netscape";			sPar[8]="query";
	sEng[9]="cnn";				sPar[9]="query";
	sEng[10]="looksmart";		sPar[10]="qt";
	sEng[11]="about";			sPar[11]="terms";
	sEng[12]="mamma";			sPar[12]="query";
	sEng[13]="alltheweb";		sPar[13]="q";
	sEng[14]="gigablast";		sPar[14]="q";
	sEng[15]="voila";			sPar[15]="rdata";
	sEng[16]="virgilio";		sPar[16]="qs";
	sEng[17]="live";			sPar[17]="q";
	sEng[18]="baidu";			sPar[18]="wd";
	sEng[19]="alice";			sPar[19]="qs";
	sEng[20]="yandex";			sPar[20]="text";
	sEng[21]="najdi";			sPar[21]="q";
	sEng[22]="aol";				sPar[22]="q";
	sEng[23]="club-internet"; 	sPar[23]="query";
	sEng[24]="mama";			sPar[24]="query";
	sEng[25]="seznam";			sPar[25]="q";
	sEng[26]="search";			sPar[26]="q";
	sEng[27]="wp";				sPar[27]="szukaj";
	sEng[28]="onet";			sPar[28]="qt";
	sEng[29]="netsprint";		sPar[29]="q";
	sEng[30]="google.interia";	sPar[30]="q";
	sEng[31]="szukacz";			sPar[31]="q";
	sEng[32]="yam";				sPar[32]="k";
	sEng[33]="pchome";			sPar[33]="q";
	sEng[34]="kvasir";			sPar[34]="searchExpr";
	sEng[35]="sesam";			sPar[35]="q";
	sEng[36]="ozu"; 			sPar[36]="q";
	sEng[37]="terra";	 		sPar[37]="query";
	sEng[38]="nostrum"; 		sPar[38]="query";
	sEng[39]="mynet"; 			sPar[39]="q";
	sEng[40]="ekolay";	 		sPar[40]="q";
	sEng[41]="search.ilse"; 	sPar[41]="search_for";
	for (var i = 0; i < sEng.length; i++) {
		if (urll[0].indexOf('.'+sEng[i]+'.')>-1){
			if(urll[1].indexOf(sPar[i])>-1){
				return sPar[i];
			}
		}	 
	}
	return "";
}	
//END 20080905  

/*
 * Plugin: getQueryParam 2.1 - return query string parameter(s)
 */
s.getQueryParam=new Function("p","d","u",""
+"var s=this,v='',i,t;d=d?d:'';u=u?u:(s.pageURL?s.pageURL:s.wd.locati"
+"on);if(u=='f')u=s.gtfs().location;while(p){i=p.indexOf(',');i=i<0?p"
+".length:i;t=s.p_gpv(p.substring(0,i),u+'');if(t)v+=v?d+t:t;p=p.subs"
+"tring(i==p.length?i:i+1)}return v");
s.p_gpv=new Function("k","u",""
+"var s=this,v='',i=u.indexOf('?'),q;if(k&&i>-1){q=u.substring(i+1);v"
+"=s.pt(q,'&','p_gvf',k)}return v");
s.p_gvf=new Function("t","k",""
+"if(t){var s=this,i=t.indexOf('='),p=i<0?t:t.substring(0,i),v=i<0?'T"
+"rue':t.substring(i+1);if(p.toLowerCase()==k.toLowerCase())return s."
+"epa(v)}return ''");

/*
 * Plugin: getValOnce 0.2 - get a value once per session or number of days
 */
s.getValOnce=new Function("v","c","e",""
+"var s=this,k=s.c_r(c),a=new Date;e=e?e:0;if(v){a.setTime(a.getTime("
+")+e*86400000);s.c_w(c,v,e?a:0);}return v==k?'':v");
/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code='',s_objectID;function s_gi(un,pg,ss){var d="function s_dr"
+"(x,o,n){var i=x.indexOf(o);if(i>=0&&x.split)x=(x.split(o)).join(n);"
+"else while(i>=0){x=x.substring(0,i)+n+x.substring(i+o.length);i=x.i"
+"ndexOf(o)}return x}function s_d(x) {var t='`^@$#',l='0123456789ABCD"
+"EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',d,n=0,b,k,w,i=x.l"
+"astIndexOf('~~');if(i>0){d=x.substring(0,i);x=x.substring(i+2);whil"
+"e(d){w=d;i=d.indexOf('~');if(i>0){w=d.substring(0,i);d=d.substring("
+"i+1)}else d='';b=parseInt(n/62);k=n-b*62;k=t.substring(b,b+1)+l.sub"
+"string(k,k+1);x=s_dr(x,k,w);n++}for(i=0;i<5;i++){w=t.substring(i,i+"
+"1);x=s_dr(x,w+' ',w)}}return x}",c=".substring(~.indexOf(~return ~="
+"f`K(~){`Ms=^u~';`At`h~;$2~.toLowerCase()~`ZF`K('e`z`Ms=s_c_il['+@g+"
+"']~};s.~`s $2~.length~`ZObject~.toUpperCase~s.wd~.location~')q='~li"
+"nk~s.apv~$f$U~unction~)$2x^W!Object||!Object.prototype||!Object.pro"
+"totype[x])~var ~s.pt(~ookieDomainPeriods~,`z,'~while(~);s.~.protoco"
+"l~){$2~:'')~=''~;@F^Us[k],255)}~javaEnabled~connection^E~=new ~.las"
+"tIndexOf('~tm.get~@5\"$Os.b.addBehavior('# default# ~onclick~ternal"
+"Filters~entElement~Name~=='~javascriptVersion~=parseFloat(~=s.dynam"
+"icAccount~s_c_il['+@g+'].mrq(\"'+un+'\")'~visitor~cookie~parseInt(~"
+"s.^I~o@6oid~browser~else~referrer~colorDepth~String~.host~s.rep(~}c"
+"atch(e){~','~r=s.m(f)?s[f](~}$2~s.un~s.eo~s.sq~t=s.ot(o)~track~j='1"
+".~)?'Y':'N'~$ZURL~@6c_i~s.ismac~lugins~;for(~Type~s.rc[un]~s.b.addE"
+"ventListener~Download~tfs~resolution~.get@I()~s.eh~s.isie~s.vl_l~s."
+"vl_t~Height~t,h){t=t?t~isopera~escape(~screen.~s.fl(~harCode~&&(~va"
+"riableProvider~s.gg('objectID')~&&s.~:'';h=h?h~e&&l$eSESSION'~');~f"
+"',~_'+~Date~name~home$Z~s_c2~s.c_r(~s.rl[u~o.href~Lifetime~Width~sE"
+"nabled~'){q='~transactionID~b.attachEvent~&&l$eNONE'){~ExternalLink"
+"s~this~charSet~onerror~currencyCode~s=s_gi(~e$QElement~;s.gl(s.vl_g"
+"~.parent~Array~lnk~Opera~eval(~.s_~Math.~s.fsg~s.ns6~docum~s.oun~In"
+"lineStats~Track~'0123456789~s[k]=~window~onload~Time~s.epa(~s.c_w(~"
+"(s.ssl~n=s.oid(o)~LeaveQuery~')>=~&&t~'=')~){n=~+1))~' '+~s.t()}~\""
+",''),~=s.oh(o);~+(y<1900?~ingServer~true~sess~campaign~lif~s_gs(~,1"
+"00)~s.co(~s._in~x in ~='s_~ffset~s.c_d~'&pe~s.gv(~s.qav~s.pl~=(apn~"
+"Sampling~sqs',q);~Year(~=s.n.app~(''+~)+'/~',s~'||t~s()+':'+~a):f(~"
+"){v=s.n.~channel~if(~un)~.target~o.value~\".tl(\")~etscape~(ns?ns:~"
+"s_')t=t~omePage~++}~&&!~')<~){x~1);~e))~'+n~height~events~trk~rando"
+"m~code~un,~try{~'MSIE ~.src~floor(~s.pg~s.num(~s.ape(~s.c_gd~s.dc~."
+"inner~Events~page~.set~.fromC~++){~?'':~!='~='+~?'&~+';~(f){~){p=~>"
+"=5)~&&i>~[b](~=l[n];~~f`K ^ife$i`Mx`V,s=0,e,a,b,c;`Q1){e=f`1'\"@w);"
+"b=f`1'\\\\',s);c=f`1\"\\n\",s)`6e<0||(b>=0&&b<$Ge=b`6e<0||(c>=0&&c<"
+"$Ge=c`6e>=0$E+=(e>s?f`0s,e)`U+(e==c?'\\\\n':'\\\\'+f`0e,e@S;s=e+1}`"
+"s `2x+f`0s)}`2f}f`K ^ifa$i`Ms=f`1'(')+1,e=f`1')'),a`V,c;`Qs>=0&&s<e"
+"){c=f`0s,s+1)`6c`h,')a+='\",\"';`A(\"\\n\\r\\t \")`1c)<0)a+=c;s$B`2"
+"a?'\"'+a+'\"':a}f`K ^if(cc){cc`V+cc;`Mfc='`Mf`ZF`K(@w=cc`1';',cc`1'"
+"{')),e=cc`a}'),o,a,d,q,c,f,h,x;fc+=^ifa(cc)+',\"`Ms`C;';c=cc`0s+1,e"
+");s=c`1'f`K^c`Qs>=0){d=1;q`V;x=0;f=c`0s);a=^ifa(f);e=o=c`1'{@w);e++"
+";`Qd>0){h=c`0e,e+1)`6q`Th==q$Cx)q`V`6h`h\\\\')x=x?0:1;`s x=0}`s{$2h"
+"`h\"'||h==\"'\")q=h`6h`h{')d++`6h`h}')d--^1d>0)e$Bc=c`00,s)+'new F`"
+"K('+(a?a+`z`U+'\"'+^ife(c`0o+1,$G+'\")'+c`0e+$Fs=c`1'f`K')}fc+=^ife"
+"(c)$h`2s\");';@5fc);`2f}f`K s_co(o){`M^y\"^ \",1,$F`2@fo)}f`K @d$3{"
+"`M^y$N1,$F`2@Uf`K s_dc($3{`M^y$N$F`2@Uf`K s_c($Npg,ss`4;s._c@ic';`E"
+"=@G`6!`E^An){`E^Al`Z@2;`E^An=0;}s._il=`E^Al;@g=`E^An;s._il[@g]=s;`E"
+"^An++;s.m`3m){`2@um)`1'{$D0`9fl`3x,l){`2x?@ux)`00,l):x`9co`3o`T!o)`"
+"2o;`Mn`C,x^D@ho)$2x`1'select$D0&&x`1'filter$D0)n[x]=o[x];`2n`9num`3"
+"x$E`V+x^D`Mp=0;p<x`B;p++)$2(@E')`1x`0p,p@S<0)`20;`21`9rep`3x,o,n){`"
+"Mi=x`1o);`Qx$l=0$E=x`00,i)+n+x`0i+o`B);i=x`1o,i+n`B)}`2x`9ape`3x`4,"
+"h=@EABCDEF',i,c=s.^v,n,l,e,y`V;c=c?c`D():''`6x$E`V+x`6c`hAUTO'^W'')"
+".c^VAt){for(i=0;i<x`B;i$cc=x`0i,i+$Fn=x.c^VAt(i)`6n>127){l=0;e`V;`Q"
+"n||l<4){e=h`0n%16,n%16+1)+e;n=`on/16);l$By+='%u'+e}`Ac`h+')y+='%2B'"
+";`s y+=^Sc)}x=y}`s{x=x?`x^S''+x),'+`z%2B'):x`6x&&c^Zem==1&&x`1'%u$D"
+"0&&x`1'%U$D0){i=x`1'%^c`Qi>=0){i++`6h`08)`1x`0i,i+1)`D())>=0)`2x`00"
+",i)+'u00'+x`0i);i=x`1'%',i)}}}}`2x`9epa`3x`4;`2x?un^S`x''+x,'+`z ')"
+"):x`9pt`3x,d,f,a`4,t=x,z=0,y,r;`Qt){y=t`1d);y=y<0?t`B:y;t=t`00,y);^"
+"0t,@zt,a)`6r)`2r;z+=y+d`B;t=x`0z,x`B);t=z<x`B?t:''}`2''`9isf`3t,a){"
+"`Mc=a`1':')`6c>=0)a=a`00,c)`6t`00,2)`h$9`02);`2(t!`V@P==a)`9fsf`3t,"
+"a`4`6`Na`Pis^dt))@8+=(@8!`V?`z`U+t;`20`9fs`3x,f`4;@8`V;`Nx`Pfs^df);"
+"`2@8`9c_d`V;$Vf`3t,a`4`6!$Tt))`21;`20`9c_gd`3`4,d=`E`F`w^g,n=s.fpC`"
+"O,p`6!n)n=s.c`O`6d$C@k@Rn?`on):2;n=n>2?n:2;p=d`a.')`6p>=0){`Qp>=0&&"
+"n>1$jd`a.',p-$Fn--}@k=p>0&&`Nd,'.`zc_gd^d0)?d`0p):d}}`2@k`9c_r`3k`4"
+";k=$Uk);`Mc=@Ts.d.`n,i=c`1@Tk+@Q,e=i<0?i:c`1';',i),v=i<0$d@Jc`0i+2+"
+"k`B,e<0?c`B:$G;`2v$e[[B]]'?v:''`9c_w`3k,v,e`4,d=$V(),l=s.`n^m,t;v`V"
+"+v;l=l?@ul)`D():''`6^b^st=(v!`V?`ol?l:0):-60)`6t){e`Z^f;e$a@I(e^K+("
+"t*1000))}^1k^ss.d.`n=k+'`Jv!`V?v:'[[B]]')$h path=/;'+(^b?' expires$"
+"fe.toGMT`v()$h'`U+(d?' domain$fd$h'`U;`2^jk)==v}`20`9eh`3o,e,r,f`4,"
+"b='s^ee+'^e@g,n=-1,l,i,x`6!^Ll)^Ll`Z@2;l=^Ll^Di=0;i<l`B&&n<0;i++`Tl"
+"[i].o==o&&l[i].e==e)n=i^1n<0@Ri;l[n]`C}x$nx.o=o;x.e=e;f=r?x.b:f`6r|"
+"|f$E.b=r?0:o[e];x.o[e]=f^1x.b$E.o[b]=x.b;`2b}`20`9cet`3f,a,t,o,b`4,"
+"r`6`I>=5^W!s.^R||`I>=7))@5'$O^0@za)`yr=s.m(t)?s[t](e):t(e)}^c`s{$2^"
+"B^Zu`1$P4@O0)r=s.m(b)?s$ma):b(a);`s{^L(`E,'^w',0,o);^0@za`Reh(`E,'^"
+"w',1)}}`2r`9g^Iet`3e`4;`2`p`9g^Ioe`8;^L(@G,\"^w\",1`Re^I=1;`Mc=s.t("
+")`6c)s.d.write(c`Re^I=0;`2@Z'`Rg^Ifb`3a){`2@G`9g^If`3w`4,p=w@1,l=w`"
+"F;`p=w`6p&&p`F!=l&&p`F`w==l`w){`p=p;`2s.g^If(`p)}`2`p`9g^I`3`4`6!`p"
+"){`p=`E`6!s.e^I)`p=s.cet('g^I^d`p,'g^Iet@w.g^Ioe,'g^Ifb')}`2`p`9mrq"
+"`3u`4,l=^k],n,r;^k]=0`6l)for(n=0;n<l`B;n$cr$ns.mr(0,0,r.t,r.u,r.r)}"
+"`9mr`3@a,q,ta,u,rs`4,dc=$W,t1=s.^6@Y,t2=s.^6@YSecure,ns=s.`m`gspace"
+",un=u?u:$8s.f$3,unc=`x$N'_`z-'),r`C,l,imn@ii^e($3,im,b,e`6!rs){rs='"
+"http'+@L?'s'`U+'://'+(t1?@L@P2?t2:t1):($8@L?'102':unc))+'.'+($W?$W:"
+"112)+'.2o7.net')@vb/ss/'+^2+'/1/H.13-pdv-2/'+@a+'?[AQB]&ndh=1'+(q?q"
+"`U+'&[AQE]'`6^M$C^B`T`I>5.5)rs=^Urs,4095);`s rs=^Urs,2047)}^1s.d.im"
+"ages&&`I>=3^W!s.^R||`I>=7)^W@9<0||`I>=6.1)`T!s.rc)s.rc`C`6!^F){^F=1"
+"`6!s.rl)s.rl`C;^kn]`Z@2;set@Iout('`l,750)}`s{l=^kn]`6l){r.t=ta;r.u="
+"un;r.r=rs;l[l`B]=r;`2''}imn+='^e^F;^F$Bim=`E[imn]`6!im)im=`E[imn]`Z"
+"Image;im@6l=0;im.@H`ZF`K('e`z^u@6l=1;`l);im$Q=rs`6rs`1@l=@O0^W!ta||"
+"ta`h_self@xa`h_top'||(`E.^g@Pa==`E.^g))){b=e`Z^f;`Q!im@6l&&e^K-b^K<"
+"500)e`Z^f}`2''}`2'<im'+'g sr'+'c=\"'+rs+'\" width=1 $I=1 border=0 a"
+"lt=\"\">'`9gg`3v`4`6!`E['s^ev])`E['s^ev]`V;`2`E['s^ev]`9glf`3t,a`Tt"
+"`00,2)`h$9`02);`Ms=^u,v=s.gg(t)`6v)s[t]=v`9gl`3v`4`6$S)`Nv`Pgl^d0)`"
+"9gv`3v`4;`2s['vpm^ev]?s['vpv^ev]:(s[v]?s[v]`U`9havf`3t,a`4,b=t`00,4"
+"),x=t`04),n=`ox),k='g^et,m='vpm^et,q=t,v=s.`H@DVars,e=s.`H@D$Y;@F@m"
+"t)`6s.@3||^3){v=v?v+`z+^N+`z+^N2:''`6v$C`Nv`Pis^dt))s[k]`V`6t`h$J'&"
+"&e)@Fs.fs(s[k],e)}s[m]=0`6t`h`mID`Gvid`5^9^pg'`W`At`h`t^pr'`W`At`hv"
+"mk`Gvmt`5^v^pce'`6s[k]&&s[k]`D()`hAUTO')@F'ISO8859-1';`As[k]^Zem==2"
+")@F'UTF-8'}`At`h`m`gspace`Gns`5c`O`Gcdp`5`n^m`Gcl`5^X`Gvvp`5^x`Gcc`"
+"5$1`Gch`5^q`Gxact`5@b`Gv0`5^J`Gs`5`u`Gc`5`i`Gj`5`X`Gv`5`n^o`Gk`5`r^"
+"n`Gbw`5`r^P`Gbh`5`Y`Gct`5^h`Ghp`5p^C`Gp';`A$Tx)`Tb`hprop`Gc$H;`Ab`h"
+"eVar`Gv$H;`Ab`hhier^ph$H`W^1s[k]@P$e`H`g'@P$e`H^E')@n+='&'+q+'`Js[k"
+"]);`2''`9hav`3`4;@n`V;`N^O`Phav^d0);`2@n`9lnf`3^Q`7^a`7:'';`Mte=t`1"
+"@Q`6t@Pe>0&&h`1t`0te@S>=0)`2t`00,te);`2''`9ln`3h`4,n=s.`H`gs`6n)`2`"
+"Nn`Pln^dh);`2''`9ltdf`3^Q`7^a`7:'';`Mqi=h`1'?^ch=qi>=0?h`00,qi):h`6"
+"t&&h`0h`B-(t`B@S`h.'+t)`21;`20`9ltef`3^Q`7^a`7:''`6t&&h`1t)>=0)`21;"
+"`20`9lt`3h`4,lft=s.`H^HFile^Es,lef=s.`HEx`e,@c=s.`HIn`e;@c=@c?@c:`E"
+"`F`w^g;h=h`7`6s.^6^HLinks&&lft&&`Nlft`Pltd^dh))`2'd'`6s.^6^t^Wlef||"
+"@c)^W!lef||`Nlef`Plte^dh))^W!@c||!`N@c`Plte^dh)))`2'e';`2''`9lc`8,b"
+"=^L(^u,\"`d\"`R@3=@f^u`Rt(`R@3=0`6b)`2^u$me);`2@Z'`Rbc`8,f`6s.d^Zd."
+"all^Zd.all.cppXYctnr)return;^3=^z?^z:e$4;@5\"$O$2^3^W^3.tag`g||^3.p"
+"ar`f||^3@1Nod$G@Ucatch$i}\"`Reo=0'`Roh`3o`4,l=`E`F,h=^l?^l:'',i,j,k"
+",p;i=h`1':^cj=h`1'?^ck=h`1'/')`6h^Wi<0||(j>=0$lj)||(k>=0$lk))$jo`S&"
+"&o`S`B>1?o`S:(l`S?l`S`U;i=l.path^g`a/^ch=(p?p+'//'`U+(o`w?o`w:(l`w?"
+"l`w`U)+(h`00,1)$e/'?l.path^g`00,i<0?0:i@v'`U+h}`2h`9ot`3o){`Ma=o.ty"
+"pe,b=o.tag`g;`2(a&&a`D?a:b&&b`D?b:^l?'A'`U`D()`9oid`3o`4,^5,p=o`S,c"
+"=o.`d,n`V,x=0`6!`q`T^l^Wt`hA@x`hAREA')^W!c||!p||p`7`1'javascript$D0"
+"))n@W`Ac@R`xs.rep(`xs.rep@uc,\"\\r@V\"\\n@V\"\\t@V' `z^cx=2}`A$5^Wt"
+"`hINPUT@x`hSUBMIT')@R$5;x=3}`Ao$Q@P`hIMAGE')n=o$Q`6n){`q=^Un@e;`qt="
+"x}}`2`q`9rqf`3t,un`4,e=t`1@Q,u=e>=0?`z+t`00,e)+`z:'';`2u&&u`1`z+un+"
+"`z)>=0?@Jt`0e@S:''`9rq`3un`4,c=un`1`z),v=^j's_sq'),q`V`6c<0)`2`Nv,'"
+"&`zrq^d$3;`2`Nun`Prq',0)`9sqp`3t,a`4,e=t`1@Q,q=e<0$d@Jt`0e+1)`Rsqq["
+"q]`V`6e>=0)`Nt`00,e)`P@r`20`9sqs`3$Nq`4;^4u[un]=q;`20`9sq`3q`4,k@is"
+"q',v=^jk),x,c=0;^4q`C;^4u`C;^4q[q]`V;`Nv,'&`zsqp',0);`N^2`P@rv`V^D@"
+"h^4u`L)^4q[^4u[x]]+=(^4q[^4u[x]]?`z`U+x^D@h^4q`L&&^4q[x]^Wx==q||c<2"
+")){v+=(v$g'`U+^4q[x]+'`Jx);c$B`2@Kk,v,0)`9wdl`8,r=@Z,b=^L(`E,\"@H\""
+"),i,o,oc`6b)r=^u$me)^Di=0;i<s.d.`Hs`B;i$co=s.d.`Hs[i];oc=o.`d?\"\"+"
+"o.`d:\"\"`6(oc`1\"@d\")<0||oc`1\"@6oc(\")>=0)&&oc`1$6<0)^L(o,\"`d\""
+",0,s.lc);}`2r^c`Es`3`4`6`I>3^W!^M||!^B||`I$k`Ts.b^Z^r)s.^r('`d@w.bc"
+");`As.b&&^G)^G('click@w.bc,false);`s ^L(`E,'@H',0,`El)}`9vs`3x`4,v="
+"s.`m@q,g=s.`m@qGroup,k@ivsn^e^2+(g?'^eg`U,n=^jk),e`Z^f,y=e.get@s);e"
+"$a@sy+10@X1900:0))`6v){v*=100`6!n`T!@Kk,x,$G`20;n=x^1n%10000>v)`20}"
+"`21`9dyasmf`3t,m`Tt&&m&&m`1t)>=0)`21;`20`9dyasf`3t,m`4,i=t?t`1@Q:-1"
+",n,x`6i>=0&&m){`Mn=t`00,i),x=t`0i+1)`6`Nx`Pdyasm^dm))`2n}`20`9uns`3"
+"`4,x`kSelection,l`kList,m`kMatch,n,i;^2=^2`7`6x&&l`T!m)m=`E`F`w`6!m"
+".toLowerCase)m`V+m;l=l`7;m=m`7;n=`Nl,';`zdyas^dm)`6n)^2=n}i=^2`1`z`"
+"Rfun=i<0?^2:^2`00,i)`9sa`3un`4;^2=un`6!@B)@B=un;`A(`z+@B+`z)`1$3<0)"
+"@B+=`z+un;^2s()`9t`3`4,$K=1,tm`Z^f,sed=Math&&@7$L?@7$R@7$L()*100000"
+"00000000):`b@I(),@a='s'+@7$R`b@I()/10800000)%10+sed,y=`b@s),vt=`b^f"
+"(@v'+`bMonth(@v'@Xy+1900:y)+@T`bHour@y`bMinute@y`bSeconds()+@T`bDay"
+"()+@T`b@IzoneO@j(),^I=s.g^I(),ta`V,q`V,qs`V@0`Runs()`6!s.td){`Mtl=^"
+"I`F,a,o,i,x`V,c`V,v`V,p`V,bw`V,bh`V,^70',k=@K's_cc`z@Z',0^8,hp`V,ct"
+"`V,pn=0,ps`6`v&&`v.prototype){^71'`6j.match){^72'`6tm$aUTC^f){^73'`"
+"6^M&&^B&&`I$k^74'`6pn.toPrecision){^75';a`Z@2`6a.forEach){^76';i=0;"
+"o`C;@5'$Oi`ZIterator(o)`y}')`6i&&i.next)^77'}}}}^1`I>=4)x=^Twidth+'"
+"x'+^T$I`6s.isns||s.^R`T`I>=3$0`X(^8`6`I>=4){c=^TpixelDepth;bw=`E$X^"
+"n;bh=`E$X^P}}@o=s.n.p^C}`A^M`T`I>=4$0`X(^8;c=^T`u`6`I$k{bw=s.d.@A`f"
+".o@j^n;bh=s.d.@A`f.o@j^P`6!^B^Zb){`ch$A^chp=s.b.isH$A(tl^8`y}\");`c"
+"clientCaps^cct=s.b.`Y`y}\")}}}`s r`V^1@o)`Qpn<@o`B&&pn<30){ps=^U@o["
+"pn].^g@e$h'`6p`1ps)<0)p+=ps;pn$Bs.^J=x;s.`u=c;s.`i=j;s.`X=v;s.`n^o="
+"k;s.`r^n=bw;s.`r^P=bh;s.`Y=ct;s.^h=hp;s.p^C=p;s.td=1^1s.useP^C)s.do"
+"P^C(s);`Ml=`E`F,r=^I.@Aent.`t`6!s.^9)s.^9=l`6!s.`t)s.`t=r`6s.@3||^3"
+"){`Mo=^3?^3:s.@3`6!o)`2'';`Mp=@m'$Z`g'),w=1,^5,@M,x=`qt,h,l,i,oc`6^"
+"3&&o==^3){`Qo$Cn@P$eBODY'){o=o.par`f?o.par`f:o@1Node`6!o)`2'';^5;@M"
+";x=`qt}oc=o.`d?''+o.`d:''`6(oc`1\"@d\")>=0&&oc`1\"@6oc(\")<0)||oc`1"
+"$6>=0)`2''}ta=n?o$4:1;h@Wi=h`1'?^ch=s.`H@N`v||i<0?h:h`00,i);l=s.`H`"
+"g?s.`H`g:s.ln(h);t=s.`H^E?s.`H^E`7:s.lt(h)`6t^Wh||l))q+=@l=@3^e(t`h"
+"d@x`he'?$Ut):'o')+(h?@lv1`Jh)`U+(l?@lv2`Jl)`U;`s $K=0`6s.^6@C`T!p$j"
+"@m'^9^cw=0}^5;i=o.sourceIndex`6^Y@R^Y;x=1;i=1^1p&&n@P)qs='&pid`J^Up"
+",255))+(w$gpidt$fw`U+'&oid`J^Un@e)+(x$goidt$fx`U+'&ot`Jt)+(i$goi$fi"
+"`U}^1!$K$Cqs)`2''`6s.p_r)s.p_r();`M$M`V`6$K^Zvs(sed))$M=s.mr(@a,(vt"
+"$gt`Jvt)`U+s.hav()+q+(qs?qs:s.rq(^2)),ta`Rsq($K$dqs`R@3=^3=s.`H`g=s"
+".`H^E=`E@6objectID=s.ppu`V`6$S)`E@6@3=`E@6eo=`E@6`H`g=`E@6`H^E`V;`2"
+"$M`9tl`3o,t,n`4;s.@3=@fo`R`H^E=t;s.`H`g=n;s.t()`9ssl=(`E`F`S`7`1'ht"
+"tps@O0`Rd=@Aent;s.b=s.d.body;s.n=navigator;s.u=s.n.userAgent;@9=s.u"
+"`1'N$76/^c`Mapn@t`g,v@tVersion,ie=v`1$P'),o=s.u`1'@4 '),i`6v`1'@4@O"
+"0||o>0)apn='@4';^M@p`hMicrosoft Internet Explorer'`Risns@p`hN$7'`R^"
+"R@p`h@4'`Rismac=(s.u`1'Mac@O0)`6o>0)`I`js.u`0o+6));`Aie>0){`I=`oi=v"
+"`0ie+5))`6`I>3)`I`ji)}`A@9>0)`I`js.u`0@9+10));`s `I`jv`Rem=0`6`v$b^"
+"V){i=^S`v$b^V(256))`D(`Rem=(i`h%C4%80'?2:(i`h%U0100'?1:0))}s.sa(un`"
+"Rvl_l='`mID,vmk,ppu,^v,`m`gspace,c`O,`n^m,$Z`g,^9,`t,^x';^O=^N+',^X"
+",$1,server,$Z^E,^q,purchaseID,@b,state,zip,$J,products,`H`g,`H^E'^D"
+"`Mn=1;n<51;n++)^O+=',prop$H+',eVar$H+',hier$H;^N2='^J,`u,`i,`X,`n^o"
+",`r^n,`r^P,`Y,^h,p^C';^O+=`z+^N2;s.vl_g=^O+',^6^HLinks,^6^t,^6@C,`H"
+"@N`v,`H^HFile^Es,`HEx`e,`HIn`e,`H@DVars,`H@D$Y,`H`gs,@3';$S=pg@0)`6"
+"!ss)`Es()}",
w=window,l=w.s_c_il,n=navigator,u=n.userAgent,v=n.appVersion,e=
v.indexOf('MSIE '),m=u.indexOf('Netscape6/'),a,i,s;if(un){un=
un.toLowerCase();if(l)for(i=0;i<l.length;i++){s=l[i];if(s._c=='s_c'){
if(s.oun==un)return s;else if(s.fs(s.oun,un)){s.sa(un);return s}}}}
w.eval(d);c=s_d(c);i=c.indexOf("function s_c(");w.eval(c.substring(0,i
));if(!un)return 0;c=c.substring(i);if(e>0){a=parseInt(i=v.substring(e
+5));if(a>3)a=parseFloat(i)}else if(m>0)a=parseFloat(u.substring(m+10)
);else a=parseFloat(v);if(a>=5&&v.indexOf('Opera')<0&&u.indexOf(
'Opera')<0){eval(c);return new s_c(un,pg,ss)}else s=s_c2f(c);return s(
un,pg,ss)}s_gi()
function resetSiteCatalystVariables() {
	// s.prop7 and s.prop8 are not reset, since the login information
    // will typically not change within an ajax request
    // The same is true for s.server and s.hier1.
    
	s.pageName=""
    
    s.channel=""
    s.pageType=""
    s.prop1=""
    s.prop2=""
    s.prop3=""
    s.prop4=""
    s.prop5=""
    s.prop6=""
    
    for (i=9; i<=29; i++) {
    	s["prop" + i] = "";
    }
    
    /* Conversion Variables */
    s.campaign=""
    s.state=""
    s.zip=""
    s.events=""
    s.products=""
    s.purchaseID=""
    
    for (i=1; i<=28; i++) {
    	s["eVar" + i] = "";
    }
    
    // s.eVar29 and s.eVar30 can remain the same, too (inventory data)
    
    s.eVar31="";
}


function getGroup( value, values, titles ){
	if( typeof(value)=='string' ) value=parseInt(value);
	vals = values.split(';');
	if( titles ){
		names = titles.split(';');
	} else {
		names = vals;	
	}	
	for(var pair=0; pair<vals.length; pair++) {
		
		v = vals[pair].split('-');
		if( v.length==2 ){//has -
		if( v[0]=='' && parseInt(v[1])>=value ){
				return names[pair];
			}	
			if( parseInt(v[0])<=value && (v[1]=='' || parseInt(v[1])>=value) ){
				return names[pair];
			}
		} else {//is max or min
			if( v[0].indexOf('<')==0 ){
				if( parseInt(v[0].substr(1))>value ){
					return names[pair];
				}					
			} else if( v[0].indexOf('>')==0 ){
				if( parseInt(v[0].substr(1))<value ){
					return names[pair];
				}
			} else {//no match
				return '';	
			} 
		}			
	}
}	

function addToSEvents(event) {
	if (s.events) {
		s.events = s.events + "," + event;
	} else {
		s.events = event;
	}
}


//Clustering of search result amount. Clusters: 0,1-10,11-25,26-50,51-100,101-500,>500
function numberOfSearchResults(number_of_results){
	return getGroup(number_of_results,'<1;1-5;6-10;11-25;26-50;51-100;101-250;251-500;>500','0;1-5;6-10;11-25;26-50;51-100;101-250;251-500;>500');  
}

function getPriceDeviationClustered(priceDeviation) {
	return getClusteredValues100(priceDeviation);
}

function getClusteredValues100(value) {
	return getGroup(value, '<1;1-2;3-4;5-6;7-8;9-10;11-15;16-20;21-25;26-50;51-100;>100', '0;1-2;3-4;5-6;7-8;9-10;11-15;16-20;21-25;26-50;51-100;>100');
}

function getClusteredLargeValues(value) {
	if (value >= 100000) {
		var base = parseInt(value / 100000) * 100000;
		return ''+ base + '-' + (base + 100000 - 1);
	} else {
		return getGroup(value, '0-9;10-19;20-29;30-39;40-49;50-59;60-69;70-79;80-89;90-99;100-199;200-299;' +
		 	'300-399;400-499;500-599;600-699;700-799;800-899;900-999;'+
		 	'1000-1999;2000-2999;3000-3999;4000-4999;5000-5999;6000-6999;'+
		 	'7000-7999;8000-8999;9000-9999;'+
		 	'10000-19999;20000-29999;30000-39999;40000-49999;50000-59999;'+
		 	'60000-69999;70000-79999;80000-89999;90000-99999;>99999');
	}
}

function getPriceDeviation(lowPrice, highPrice) {
    if (lowPrice == 0) {
        return 0;
    }
    
    return Math.round(((highPrice / lowPrice) * 100) - 100);
} 

function increaseNumberOfActions() {
	var nac = getNumberOfActions() + 1;
	
	// cookie 50 days valid
	var validUntil = new Date()
	var days = validUntil.getTime() + (50 * 24 * 60 * 60 * 1000);
	validUntil.setTime(days);
	
	s.c_w("nac", nac, validUntil);
}

function resetNumberOfActions() {
	// cookie 50 days valid
	var validUntil = new Date()
	var days = validUntil.getTime() + (50 * 24 * 60 * 60 * 1000);
	validUntil.setTime(days);
	
	s.c_w("nac", 0, validUntil);
}

function getNumberOfActions() {
	var nac = s.c_r("nac");
	if (!nac) {
		return 0;
	} else {
		return parseInt(nac);
	}
}

function trackShowQuickView() {
	resetSiteCatalystVariables();
    s.pageName = "ProductQuickView";
    s.events = "prodView,event7";
    s.prop10 = jQuery('#quickview_s_prop10').text();
    s.prop11 = numberOfSearchResults(jQuery('#quickview_number_of_ratings').text());

    s.eVar14= jQuery('#quickview_product_id').text();

    s.prop18 = numberOfSearchResults(jQuery('#quickview_number_of_shop_products').text());
    s.eVar18 = s.prop18;

    s.prop19 = jQuery('#quickview_s_prop_19').text();
    s.eVar19 = s.prop19;

    s.products = ";"+ s.prop19;
    s.t();
}


/**
 * Generates a unique ID with the current timestamp and
 * a random value, all in all with the length of 20 chars.
 * This ID must be reported in s.purchaseID with every clickout
 * (see bug #0032766)
 */
function getPurchaseIdForClickout() {
	var timestamp = ""+ new Date().getTime(); // make a string of it
	var randomPart = (""+ Math.random()).substr(3, 20 - timestamp.length);
	return timestamp + randomPart;
}

function webtrackingTrackClickToShop(shopId) {
    var clickPos = "0";
    var productId = s.eVar14;

    resetSiteCatalystVariables();
    s.pageName = "ClickoutShopDetails";
    s.events="purchase";
    s.prop12 = "ShopDetails_" + clickPos;
    s.purchaseID = getPurchaseIdForClickout();
    s.products = ";"+ shopId + ";1;-1"; // last number is product price -> not known here 
    s.t();
}


function webtrackingTrackClickoutFromSearch(clickoutForm, priceMin, priceMax, productId) {
    var shopId = jQuery(clickoutForm).find("input[@name='shopId']").val();
    var productPrice = jQuery(clickoutForm).find("input[@name='productPrice']").val();
    var clickPos = jQuery(clickoutForm).find("input[@name='clickPos']").val();
    var minPrice = priceMin;
    var maxPrice = priceMax;
    submitClickout("ClickoutSearchListView", shopId, productId, productPrice, priceMin, priceMax);
}

function submitClickout(pageName, shopId, productId, productPrice, minPrice, maxPrice) {
	submitClickoutAll(pageName, shopId, productId, productPrice, minPrice, maxPrice, '-1', '-1', '-1', '-1', '');
}

function submitClickoutAll(pageName, shopId, productId, productPrice, minPrice, maxPrice, numOfRatings, ratingVal, shopProductCount, shopWithLowestPrice, campaignId) {
    var deviationMaxPrice = getPriceDeviation(productPrice, maxPrice);
    var deviationMinPrice = getPriceDeviation(minPrice, productPrice);
    resetSiteCatalystVariables();
    s.pageName = pageName;
    s.prop10 = ratingVal; // in percent
    s.prop11 = numOfRatings;
    s.prop12 = pageName + "_0";
    s.events="purchase";
    s.eVar14=productId;
    s.eVar16 = getPriceDeviationClustered(deviationMinPrice);
    s.eVar17 = getPriceDeviationClustered(deviationMaxPrice);
    s.campaign = campaignId;
    s.purchaseID = getPurchaseIdForClickout();

    s.products = ";"+ shopId + ";1;"+ productPrice;
    s.t();
    // google remarketing
	trackRemarketing("IlodCKeCxwEQvaOW-QM");
}


function trackClickoutFromSearch(clickoutForm, priceMin, priceMax, productId) {
    if (WEBTRACKING_ENABLED) {
        webtrackingTrackClickoutFromSearch(clickoutForm, priceMin, priceMax, productId);
    } 
}


/*
 * Autor: Frank R�ther, 23-05-2008
 * Code: JavaScript Library zum Hinzufuegen von events
 */
function cm_varIsSet(vn){//variable vn ist gesetzt und nicht leer
	if(typeof(vn)!="undefined"&&vn!="")return true;
	return false;
}
function cm_eventIsSet(ev){//event ev ist gesetzt
	if(!cm_varIsSet(s.events))return false;
	var events=''+s.events;
	if(events.indexOf(ev)>-1)return true;
	return false;
}
function cm_addEvent(ev){//setzt einen event ev einmalig pro seite
	if(!cm_varIsSet(s.events)){//1.fall events nicht definiert oder leer
		s.events=ev;
		return;
	}	
	if(cm_eventIsSet(ev)) return;//2.fall nicht leer aber schon drin
	s.events+=','+ev;//3.fall nicht leer aber nicht drin
}

/*
 * Copyright (c) contentmetrics GmbH, 2008
 * THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
 * APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
 * HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
 * IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
 * ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 *
 * Autor: Frank Räther, 01-09-2008
 * Code: JavaScript Library zum Auslesen von URL Parametern mit belibigen Trennzeichen
 * 		und unter Entfernung angehängter Anchor Tags mit '#'
 * Kunde: Shopping24
 * Version: V1.1, last changed 11.09.2008, F. Raether
 */

/*Plugin cm_getQueryParam V1.1 20080901FRÄ
calls s.getQueryParam if installed, if doesn't return anything
tries to split document.location.search at separator sep,
finds the parameter name case-insensitive and returns the value
*/
function cm_getQueryParam(n){
	var ret='';
	if(typeof(s)!='undefined'&&s.getQueryParam!='undefined')ret=s.getQueryParam(n);
	if(ret)return cm_removeHashmarkFromUrlParamValue(ret);
	n=n.toLowerCase();
	var sep='&';
	var qstr=document.location.search.substr(1);
	var qs=qstr.split(sep);
	var pair;
	var p;
	for(i=0;i<qs.length;i++){
		pair=qs[i];
		p=pair.split('=');
		if(p[0].toLowerCase()==n)return cm_removeHashmarkFromUrlParamValue(p[1]);	
	}
	return '';	
}
/*Plugin cm_removeHashmarkFromUrlParamValue V1.0 20080901FRÄ
removes hashmark and the following anchor name from querystring parameters.
*/
function cm_removeHashmarkFromUrlParamValue(v){
	if(typeof(v)!="string")return v;
	if(v[v.length-1]=='#')return v.substr([v.length-1]); 
	return v;
}

/*
 * Copyright (c) contentmetrics GmbH, 2008
 * THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
 * APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
 * HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
 * IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
 * ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 *
 * Autor: Frank Räther, 2008-09-05
 * Code: JavaScript Library zum Tracken von SEM/SEO Keywords
 * Kunde: Shopping24
 * Version: V1, last changed 05.09.2008, F.Raether
 * Einziger Parameter: URL (meist aus Referrer)
 * Rückgabewert: Leer wenn keine Suchmaschine, 
 * sonst Name des URL Parameters, der das Suchwort enthält.
 */


//BEGIN 20080905 
function cm_getParam(url){
	urll=url.split('?');
	if(urll.length==1)return;	
	var sEng=new Array();
	var sPar=new Array();
	sEng[0]="google";			sPar[0]="q";
	sEng[1]="yahoo";			sPar[1]="p";
	sEng[2]="msn";				sPar[2]="q";
	sEng[3]="aol";				sPar[3]="query";
	sEng[4]="aol";				sPar[4]="encquery";
	sEng[5]="lycos";			sPar[5]="query";
	sEng[6]="ask";				sPar[6]="q";
	sEng[7]="altavista";		sPar[7]="q";
	sEng[8]="netscape";			sPar[8]="query";
	sEng[9]="cnn";				sPar[9]="query";
	sEng[10]="looksmart";		sPar[10]="qt";
	sEng[11]="about";			sPar[11]="terms";
	sEng[12]="mamma";			sPar[12]="query";
	sEng[13]="alltheweb";		sPar[13]="q";
	sEng[14]="gigablast";		sPar[14]="q";
	sEng[15]="voila";			sPar[15]="rdata";
	sEng[16]="virgilio";		sPar[16]="qs";
	sEng[17]="live";			sPar[17]="q";
	sEng[18]="baidu";			sPar[18]="wd";
	sEng[19]="alice";			sPar[19]="qs";
	sEng[20]="yandex";			sPar[20]="text";
	sEng[21]="najdi";			sPar[21]="q";
	sEng[22]="aol";				sPar[22]="q";
	sEng[23]="club-internet"; 	sPar[23]="query";
	sEng[24]="mama";			sPar[24]="query";
	sEng[25]="seznam";			sPar[25]="q";
	sEng[26]="search";			sPar[26]="q";
	sEng[27]="wp";				sPar[27]="szukaj";
	sEng[28]="onet";			sPar[28]="qt";
	sEng[29]="netsprint";		sPar[29]="q";
	sEng[30]="google.interia";	sPar[30]="q";
	sEng[31]="szukacz";			sPar[31]="q";
	sEng[32]="yam";				sPar[32]="k";
	sEng[33]="pchome";			sPar[33]="q";
	sEng[34]="kvasir";			sPar[34]="searchExpr";
	sEng[35]="sesam";			sPar[35]="q";
	sEng[36]="ozu"; 			sPar[36]="q";
	sEng[37]="terra";	 		sPar[37]="query";
	sEng[38]="nostrum"; 		sPar[38]="query";
	sEng[39]="mynet"; 			sPar[39]="q";
	sEng[40]="ekolay";	 		sPar[40]="q";
	sEng[41]="search.ilse"; 	sPar[41]="search_for";
	for (var i = 0; i < sEng.length; i++) {
		if (urll[0].indexOf('.'+sEng[i]+'.')>-1){
			if(urll[1].indexOf(sPar[i])>-1){
				return sPar[i];
			}
		}	 
	}
	return "";
}	
//END 20080905 
jQuery(document).ready(function() {
//	 MultiSelectFacet.init();
});

var MultiSelectFacet = {

	selectedFacetConstraints : {},
	deselectedFacetConstraints : {},
	facetItemIndex : {},
	facetPositionIndex : {},
	hidden : false,
	activateLinkPart : '',
	inactivateLinkPart : '',
	activeImage : '',
	inactivImage : '',
	
//	facetItemTemplateArray : ['<a id="facet_item_',null,'_',null,'" class="clearfix facet_item_',null,'" onclick="MultiSelectFacet.toggleFacetConstraint( ',"'",null,"', '",null,"' ); MultiSelectFacet.toggleFacetItemCheckboxImage(this); return false;",'" href="javascript:;"><img title="Check" src="',STATIC_CONTENT_PREFIX,'img/8x8_checkbox_off.gif" /><span class="cat_name" title="',null,'">',null,'<span class="cat_no">(',null,')</span></span><br class="clearall"/></a>'],
    //                        0                    1    2   3    4                               5    6                                                     7   8    9      10   11                                                                        12                                               13                    14                                                          15   16   17   18                       19   20
    facetItemTemplateArray : ['<li><a id="facet_item_',null,'_',null,'" class="facet_item_',null,' ',null,'" onclick="addParamsToLink( this );" href="',null,'/',null,'/',null,'">',null,'<span title="',null,'"><span id="facet_item_content_',null,'_',null,'" class="category_name">',null,'</span><span class="cat_no">(',null,')</span></span></a></li>'],
    //                        0                        1    2   3    4                      5    6   7    8                                             9    10  11   12  13   14   15   16              17   18                                19   20  21   22   23   24                              25   26
    buildFacetItem : function (facetName, index, linkPart, image, title, content, amount, activeClass) {
        MultiSelectFacet.facetItemTemplateArray[1] = facetName;
        MultiSelectFacet.facetItemTemplateArray[3] = index;
        MultiSelectFacet.facetItemTemplateArray[5] = facetName;
        MultiSelectFacet.facetItemTemplateArray[7] = activeClass;
        MultiSelectFacet.facetItemTemplateArray[9] = linkPart;
        MultiSelectFacet.facetItemTemplateArray[11] = facetName;
        MultiSelectFacet.facetItemTemplateArray[13] = title;
        MultiSelectFacet.facetItemTemplateArray[15] = image;
        MultiSelectFacet.facetItemTemplateArray[17] = title;
        MultiSelectFacet.facetItemTemplateArray[19] = facetName;
        MultiSelectFacet.facetItemTemplateArray[21] = index;
        MultiSelectFacet.facetItemTemplateArray[23] = content
        MultiSelectFacet.facetItemTemplateArray[25] = amount;
        
        return MultiSelectFacet.facetItemTemplateArray.join('');
    },
	
	initSearch: function ( invertedIndex, positionIndex, activateLinkPart, inactivateLinkPart, activeImage, inactiveImage ) {
	   MultiSelectFacet.facetItemIndex = invertedIndex;
	   MultiSelectFacet.facetPositionIndex = positionIndex;
	   MultiSelectFacet.activateLinkPart = activateLinkPart;
	   MultiSelectFacet.inactivateLinkPart = inactivateLinkPart;
	   MultiSelectFacet.activeImage = activeImage;
	   MultiSelectFacet.inactiveImage = inactiveImage;
	},
	
	toggleFacetConstraint: function( facetConstraint, facetName ) {
		var selectedField = "selectedField";
		var deSelectedField = "deSelectedField";
	
		var URI = window.location.href;
		/*
		 * DAmit Facetconstraints in der Query nicht mitgelöscht werden...
		 */
		var filter = /\/query\/.*?\/(.*)/;
		var tmpURI = filter.exec(URI);
		var facetAlreadyConstrained;
		if ( tmpURI != null && tmpURI.length > 1 ) {
			facetAlreadyConstrained = URI.indexOf( facetConstraint ) > -1;
		}
		else {
			facetAlreadyConstrained = false;
		}
		
		var div = jQuery( '#hidden_div_' + facetName );
		
		var selected = !facetAlreadyConstrained ? 
			!(facetConstraint in MultiSelectFacet.selectedFacetConstraints)
			: facetConstraint in MultiSelectFacet.deselectedFacetConstraints;
			
		if ( selected ) {
			if ( !facetAlreadyConstrained ) {
				MultiSelectFacet.selectedFacetConstraints[facetConstraint] = facetConstraint;
				div.append('<input type="hidden" name="' + selectedField + '" value="' + decodeTapestryURIComponent(facetConstraint) + '" id="' + facetConstraint + '_' + selectedField + '">');
			}
			if ( facetConstraint in MultiSelectFacet.deselectedFacetConstraints ) {
				delete MultiSelectFacet.deselectedFacetConstraints[facetConstraint];
				ge(facetConstraint + '_' + deSelectedField).parentNode.removeChild(ge(facetConstraint + '_' + deSelectedField));
			}
		}
		else {
			if (facetAlreadyConstrained) {
				MultiSelectFacet.deselectedFacetConstraints[facetConstraint] = facetConstraint;
				div.append('<input type="hidden" name="' + deSelectedField + '" value="' + decodeTapestryURIComponent(facetConstraint) + '" id="' + facetConstraint + '_' + deSelectedField + '">');
			}
			if ( facetConstraint in MultiSelectFacet.selectedFacetConstraints ) {
				delete MultiSelectFacet.selectedFacetConstraints[facetConstraint];
				ge(facetConstraint + '_' + selectedField).parentNode.removeChild(ge(facetConstraint + '_' + selectedField));
			}
		}
	},
    
    showLess: function ( facetName ) {
        jQuery('#facet_item_div_' + facetName).hide();
        jQuery('#searched_facet_item_div_' + facetName).show();
    },
	
	showMore: function ( facetName ) {
        jQuery('#facet_item_div_' + facetName).show();
        jQuery('#searched_facet_item_div_' + facetName).hide().empty();
	},
	
	showLessAdvanced: function ( facetName, entries ) {
	    
	    var ItemArray = [];
	    var counter = 0;
	    
        jQuery('#searched_facet_item_div_' + facetName).empty();
        for ( entryKey in entries ) {
            //var element = jQuery('#facet_item_' + facetName + '_' + entryKey).clone();
            
            //var content = element.find('#facet_item_content_' + facetName + '_' + entryKey);
            
            var contentText = MultiSelectFacet.facetPositionIndex[entryKey][2];
            
            var spanB = '<span style="font-weight:bolder; color:#006EC0">';
            var spanE = '</span>';
            
            //var newContentText = "";
            var index = 0;
            
            var counter2 = 0;
            var newContentArray = [];
            
            for ( var i = 0; i < entries[entryKey].length; i++ ) {
                if ( entries[entryKey][i]['start'] == 0 ) {
                    newContentArray[counter2 ++] = spanB;
                    newContentArray[counter2 ++] = contentText.substring (0, entries[entryKey][i]['length']);
                    newContentArray[counter2 ++] = spanE;
                    //newContentText += spanB + contentText.substring (0, entries[entryKey][i]['length']) + spanE;
                    index = entries[entryKey][i]['length'];
                } else {
                    newContentArray[counter2 ++] = contentText.substring (index, entries[entryKey][i]['start']);
                    newContentArray[counter2 ++] = spanB;
                    newContentArray[counter2 ++] = contentText.substring (entries[entryKey][i]['start'], entries[entryKey][i]['start'] + entries[entryKey][i]['length']);
                    newContentArray[counter2 ++] = spanE;
	                //newContentText += contentText.substring (index, entries[entryKey][i]['start']);
	                //newContentText += spanB + contentText.substring (entries[entryKey][i]['start'], entries[entryKey][i]['start'] + entries[entryKey][i]['length']) + spanE;
	                index = entries[entryKey][i]['start'] + entries[entryKey][i]['length'];
                }
            }
            
            newContentArray[counter2 ++] = contentText.substr (index);
            //newContentText += contentText.substr (index);
            
            
            ItemArray[counter ++] = MultiSelectFacet.buildFacetItem(
                    facetName,
                    entryKey,
                    MultiSelectFacet.facetPositionIndex[entryKey][5] ? MultiSelectFacet.inactivateLinkPart : MultiSelectFacet.activateLinkPart,
                    MultiSelectFacet.facetPositionIndex[entryKey][5] ? MultiSelectFacet.activeImage : MultiSelectFacet.inactiveImage,
                    MultiSelectFacet.facetPositionIndex[entryKey][2],
                    newContentArray.join(''),
                    MultiSelectFacet.facetPositionIndex[entryKey][4],
                    MultiSelectFacet.facetPositionIndex[entryKey][5] ? 'list_selected' : '' );
        }
        //debugOutput(speedTest);
        
        ge('searched_facet_item_div_' + facetName).innerHTML = ItemArray.join('');
        
    },
	
	search: function ( facetName ) {
	   
		var start = new Date();
		
		var entries = {};
		
		var input = jQuery( '#category_search_field_' + facetName ).val().toLowerCase();
		
        var inputs = jQuery.trim(input).split(' ');
        
        // Bestimmung aller betroffenene Einträge AND
        var firstChar = inputs[0].charAt(0);
        var facetItemArray = MultiSelectFacet.facetItemIndex[firstChar];
        if ( facetItemArray ) {
            for ( var j = 0; j < facetItemArray.length; j++ ) {
                
                var index = facetItemArray[j][1];
                var multipleMatched = true;
                var positions = [];
                
                for ( var i = 0; i < inputs.length; i++ ) {
                    var matched = false;
                    for ( var k = 0; k < MultiSelectFacet.facetPositionIndex[index][0].length; k++ ) {
                        if ( MultiSelectFacet.facetPositionIndex[index][0][k].indexOf(inputs[i]) == 0 ) {
                            matched = true;
                            var position = {};
                            position['start'] = MultiSelectFacet.facetPositionIndex[index][1][k];
                            position['length'] = inputs[i].length;
                            positions.push(position);
                            break;
                        }
                    }
                    if ( ! matched ) {
                        multipleMatched = false;
                        break;
                    }
                }
                if ( multipleMatched && ! entries[facetItemArray[j][1]]) {
                    positions.sort(function(a, b){ return a['start'] - b['start'];});
                    entries[facetItemArray[j][1]] = positions;
                }
            }
        }
        
        if ( input.length >= 1 && ! MultiSelectFacet.hidden ) {
            MultiSelectFacet.hidden = true;
            MultiSelectFacet.showLess(facetName);
        }
		if ( input.length < 1 ) {
		   MultiSelectFacet.hidden = false;
		   MultiSelectFacet.showMore(facetName);
		}
		
		if ( input.length >= 1 ) {
            MultiSelectFacet.showLessAdvanced ( facetName, entries );
		}
        //debugOutput(entries);
		
		debugOutput(new Date().getTime() - start.getTime());
    },
	
	submitFacetConstraints: function() {
		debugOutput( "submitFacetConstraints invoked" );
		var targetUrl = window.location.href;
		for( var removedFacetConstraint in MultiSelectFacet.deselectedFacetConstraints ) {
			debugOutput( "removedFacetConstraint: " + removedFacetConstraint );
			if ( targetUrl.indexOf( removedFacetConstraint ) > -1 ) {
				debugOutput( "removing %o from targetUrl...", removedFacetConstraint );
				targetUrl = targetUrl.replace( "/" + removedFacetConstraint, '' );
				debugOutput( "targetUrl now is " + targetUrl );
			}
		}
		for( var addFacetConstraint in MultiSelectFacet.selectedFacetConstraints ) {
			debugOutput( "facetConstraint: " + addFacetConstraint );
			targetUrl += '/' + addFacetConstraint;
		}
		window.location.href = targetUrl;
	},
	
	submitRangeFacetConstraints: function (min, max) {
		var targetUrl = window.location.herf;
		targetUrl = targetUrl.replace ( /price.*/ , '/' );
		window.location.href = targetUrl;
	},
	
	showMoreFacets: function() {
		targetUrl += '/mf';
		window.location.href = targetUrl;
	},
	
	toggleFacetItemCheckboxImage: function(element) {
	    /*
	     * Aendert das Checkbox-Img bei dist echt ganz schön er Kategorie-Auswahl
	     */
		var img = jQuery(element).children("img").get(0);
		var last = img.src.lastIndexOf('/');
		var part = img.src.substring(last);
		
	    if (part.indexOf("/8x8_checkbox_off.gif") != -1){ // Do not test with ==, since there may be an additional query parameter at the image
	        img.src = STATIC_CONTENT_PREFIX + "img/8x8_checkbox_on.gif";
	        element.style.color = "#313131";
	        element.style.fontWeight = "bold";
	    }
	    else{
	        img.src = STATIC_CONTENT_PREFIX + "img/8x8_checkbox_off.gif";
	        element.style.color = "#666";
	        element.style.fontWeight = "normal";
	    }
    
	},
	
//	init: function() {
//    	MultiSelectFacet.initToggleImages();
//    },

/*	initToggleImages: function() {
	
		if (jQuery('.category_changer')) {
			/* this is for dynamic facets/filter, these cannot use
			 * ids but have to use style classes
			 *
		    var filterBoxes  = jQuery('.category_changer');
		    for( var i = 0; i < filterBoxes.length; i++ ) {
		    	var filterBox = filterBoxes[i];
			    MultiSelectFacet.initToggleImagesFor( filterBox );
		    }
		}
		
		if ( ge('color_picker_d_1') && ge('color_picker_d_2') ) {
			var color1  = ge('color_picker_d_1');
			var color2  = ge('color_picker_d_2');
			var color1Imgs  = color1.getElementsByTagName("img");
			var color2Imgs  = color2.getElementsByTagName("img");
			if ( color1Imgs.length != color2Imgs.length ) {
				throw "Different number of images in color filters," +
					" color picker: " + color1Imgs.length + 
					", color names: " + color2Imgs.length;
			}
			for( var i = 0; i < color1Imgs.length; i++ ) {
			
				var img1 = jQuery(color1Imgs[i]);
				var link2 = jQuery(color2Imgs[i]).parent();
				
				/* create the handler with additional data in the event,
				 * to be able to reference the according link in the other tab...
				 * see http://visualjquery.com/1.1.2.html / Events/bind(type, data, fn)
				 * for more...
				 *
				function handler1(event) {
					change_color_scheme(this);
					MultiSelectFacet.toggleFacetItemCheckboxImage( event.data.refLink.get(0) );
					return false;
				}
				img1.bind( "click", { refLink: link2 }, handler1 );
			    
				function handler2(event) {
					debugOutput( "refimg: " + event.data.refImg );
					change_color_scheme( event.data.refImg.get(0) );
					MultiSelectFacet.toggleFacetItemCheckboxImage( this );
					return false;
				}
			    link2.bind( "click", { refImg: img1 }, handler2 );
			}
		}
		
		/*
	    if ( jQuery('#color_picker_d_2') ) {
		    var filterBoxes  = jQuery('#color_picker_d_2');
		    for( var i = 0; i < filterBoxes.length; i++ ) {
		    	var filterBox = filterBoxes[i];
			    MultiSelectFacet.initToggleImagesFor( filterBox );
		    }
	    }
	    *
	    
	},*/
	
	initToggleImagesFor: function( filterBox ) {
		var aAs  = filterBox.getElementsByTagName("a");
	    for( var j = 0; j < aAs.length; j++ ) {
	    	if ( aAs[j].className != "single_select_facet" ) {
		        jQuery( aAs[j] ).click(
		        	function(){
		        		MultiSelectFacet.toggleFacetItemCheckboxImage(this);
		        		return false;
		        	}
		        );
		    }
	    }
	}
	
}
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
//////////////////////////////////////
//
//  Style-Pager
//
///////////////////////////////////////

function initStylePager() {
  if ( showMoreLinks )
    initStylePagerWithMoreLinks();
  else
    initStylePagerSimple();
    
}

/**
 * Pager Variablen
 * 
 * 
 * resultCount Anzahl des Suchergebnisse / Elenete insgesamt
 * @type {Number}
 */
var resultCount = 116;
/**
 * itemsPerRow Anzahl Elemente in einer Reihe 
 * @type {Number}
 */
var itemsPerRow = 3;
/**
 * rowCount Anzahl der Reihen
 * @type {Number}
 */
var rowCount = 5;
/**
 * pagerStyleChangeValue Wieviel Zahlen im Pager als Block dargestellt
 * @type {Number}
 */
var pagerStyleChangeValue = 3;

/**
 * automatische errechnete Werte
 */
var itemsPerPage = itemsPerRow * rowCount; 
var pageCount = Math.ceil(resultCount / itemsPerPage);


/**
 * globales array welches die einzelnen Pages als Subarray bekommt
 * @type {array}
 */
var resultPages = new Array();


/**
 * 
 * @param {int} pageNum
 */
function showPage(pageNum) {
  jQuery("#resultContainer").html("&nbsp;");
  var newHtml = "";
  for(var pageItem=1;pageItem<resultPages[pageNum].length; pageItem++) {
    newHtml += resultPages[pageNum][pageItem];
  }
  jQuery("#resultContainer").html(newHtml);
  showPagerHtml(pageNum);
}

/**
 * generiert html des Pager je nach aktueller Seitenzahl
 * @param {int} pageNum
 */
function showPagerHtml(pageNum) {
  var pagerElements = new Array();
  if(pageCount > 1) {
    if(pageNum > pageCount) {
      pageNum = pageCount;
    }
    var isFloatingPager = true;
    if(pageCount<2*pagerStyleChangeValue) {
      pagerStyleChangeValue =  pageCount;
      isFloatingPager = false;
    }
    var leftArrowImg = '<img style="margin-left:-1px;" alt="vorherige Seite" src="'+ STATIC_CONTENT_PREFIX +'/img/17x17_page_prev.png" title="vorherige Seite">';
    var leftArrow = leftArrowImg;
    if(pageNum > 1) {
      leftArrow = '<a style="margin-left:-1px;" href="javascript: ;" id="pagerLeftLink" onclick="showPage('+(pageNum-1)+')">'+leftArrowImg+'</a>';
    } 
    pagerElements.push(leftArrow);
    
    var firstBlock = new Array();
    var middleBlock = new Array();
    var lastBlock = new Array();
    
    

    if(pageNum < pagerStyleChangeValue || !isFloatingPager) {
      for(var i=1;i<=pagerStyleChangeValue;i++) {
        var firstBlockElement = '<span class="active">'+i+'</span>';
        if(i != pageNum) {
          firstBlockElement = '<a class="page_link" id="page_link_'+i+'" href="javascript:;" onclick="showPage('+i+')">'+i+'</a>';
        }
        firstBlock.push(firstBlockElement);
      }
      if(isFloatingPager) {
        middleBlock.push('<span>...</span>');
        lastBlockElement = '<a class="page_link" id="page_link_'+pageCount+'" href="javascript:;" onclick="showPage('+pageCount+')">'+pageCount+'</a>';
        lastBlock.push(lastBlockElement);
        
      }
    } else if(isFloatingPager && pageNum >= pagerStyleChangeValue && pageNum <= pageCount-(pagerStyleChangeValue-1)) {
      firstBlock.push('<a class="page_link" id="page_link_1" href="javascript:;" onclick="showPage(1)">1</a>');
      firstBlock.push('<span>...</span>');
      var cStart = pageNum - (Math.floor(pagerStyleChangeValue/2)); 
      for(var i=cStart;i<=cStart+pagerStyleChangeValue-1;i++) {
        var middleBlockElement = '<span class="active">'+i+'</span>';
        if(i != pageNum) {
          middleBlockElement = '<a class="page_link" id="page_link_'+i+'" href="javascript:;" onclick="showPage('+i+')">'+i+'</a>';
        }
        middleBlock.push(middleBlockElement);
      }
      lastBlock.push('<span>...</span>');
      lastBlock.push('<a class="page_link" id="page_link_'+pageCount+'" href="javascript:;" onclick="showPage('+pageCount+')">'+pageCount+'</a>');

    } else if(isFloatingPager && pageNum > pageCount-pagerStyleChangeValue && pageNum <= pageCount) {

      firstBlockElement = '<a class="page_link" id="page_link_1" href="javascript:;" onclick="showPage(1)">1</a>';
      firstBlock.push(firstBlockElement);
      middleBlock.push('<span>...</span>');
      for(var i=pageCount-pagerStyleChangeValue+1; i<=pageCount;i++) {
        var lastBlockElement = '<span class="active">'+i+'</span>';
        if(i != pageNum) {
          lastBlockElement = '<a class="page_link" id="page_link_'+i+'" href="javascript:;" onclick="showPage('+i+')">'+i+'</a>';
        }
        lastBlock.push(lastBlockElement);
      }
    }
    
    pagerElements = pagerElements.concat(firstBlock);
    pagerElements = pagerElements.concat(middleBlock);
    pagerElements = pagerElements.concat(lastBlock);

    var rightArrowImg = '<img alt="vorherige Seite" src="'+ STATIC_CONTENT_PREFIX +'/img/17x17_page_next.png" title="vorherige Seite">';
    var rightArrow = rightArrowImg;
    if(pageNum < pageCount) {
      rightArrow = '<a href="javascript: ;" id="pagerRightLink" onclick="showPage('+(pageNum+1)+')">'+rightArrowImg+'</a>';
    } 
    pagerElements.push(rightArrow);
    var htmlString = "";
    for(var i=0;i<pagerElements.length;i++) {
      htmlString += pagerElements[i];
    }
    var pager = jQuery(htmlString)
    
    jQuery(".search_result_header_page").html(htmlString);
    

  }
  else
  {
  jQuery(".search_result_header_page").html('<div style="height: 20px" />');
  }
    
}



function initStylePagerSimple()
{
          // Serverseitig setzen, Wert wird zum berechnen der Seitenanzahl benötigt
          resultCount = style_products.length;
          // Einstellung Elemente per Zeile
          itemsPerRow = 3;
          // Einstellung Anzahl Zeile
          rowCount = 5;
          // Eintellung Zahlenblock im Pagermanü
          pagerStyleChangeValue = 3;
          // Elemente pro Seite und Seitenanzahl berechnen
          itemsPerPage = itemsPerRow * rowCount; 
          pageCount = Math.ceil(resultCount / itemsPerPage);
                           
          var elementCounter = 0;
          for(var page=1; page<=pageCount; page++) {
            resultPages[page] = new Array(); // resultElements per Page
            
            for(var pageElement = 1;pageElement<=itemsPerPage;pageElement++) {
              var htmlString = "";
              resultPages[page][pageElement] = "";
              if(elementCounter < resultCount) {
                var styleExtension = "";
                if(pageElement % itemsPerRow == 0) {
                  styleExtension = 'style="margin-right:0;"';
                }
                if(pageElement % itemsPerRow == 1) {
                  styleExtension = 'style="clear:both;"';
                }
          
                htmlString += '<div id="page_'+page+'_item_'+pageElement+'_element_'+elementCounter+'" class="prod_container_s" '+styleExtension+'>';
                htmlString += '<a class="small_pic" rel="nofollow" href="' + SHOP_BASEURL + 'communityproductdetails/' + style_products[elementCounter][0] + '/' + watchedStyle +'"><img  t:type="t5x/imgVersionSupport" style="margin: 0pt;" src="' + style_products[elementCounter][1] + '" height="55" width="40"></a>';
                htmlString += '</div>';
                resultPages[page][pageElement] = htmlString;
              }
              elementCounter++;
            }
          }
          
          showPage(1);    
} 


function initStylePagerWithMoreLinks()
{

  // init pager
        // Pager Variable deklariert, dokumentiert und initialisiert in style_pager.js
          
          // Serverseitig setzen, Wert wird zum berechnen der Seitenanzahl benötigt
          resultCount = style_products.length;
          // Einstellung Elemente per Zeile
          itemsPerRow = 1;
          // Einstellung Anzahl Zeile
          rowCount = 6;
          // Eintellung Zahlenblock im Pagermanü
          pagerStyleChangeValue = 3;
          // Elemente pro Seite und Seitenanzahl berechnen
          itemsPerPage = itemsPerRow * rowCount; 
          pageCount = Math.ceil(resultCount / itemsPerPage);
          
          
          
          // hier serverseitig images und links einfügen
          // globales ergebnis array vom server wird hier mit dem elementCounter durchgezählt
          var elementCounter = 0;
          for(var page = 1; page <= pageCount; page++) {
            resultPages[page] = new Array(); // resultElements per Page
            
            for(var pageElement = 1; pageElement <= itemsPerPage; pageElement++) {
              var htmlString = "";
              resultPages[page][pageElement] = "";
              if(elementCounter < resultCount) {
                 
                var styleExtension = (pageElement == itemsPerPage-1)? 'style="height: 71px;"':'';

                htmlString += '<div class="prod_container_List" '+styleExtension+'>';
                htmlString += '<div id="page_'+page+'_item_'+pageElement+'_element_'+elementCounter+'" class="prod_container_s">';
                htmlString += '<a class="small_pic" href="' + SHOP_BASEURL + 'communityproductdetails/' + style_products[elementCounter][0]  + '/' + watchedStyle +'"><img style="margin: 0pt;" src="' + style_products[elementCounter][1] + '" height="55" width="40"></a></div>';
                htmlString += '<a class="listLink" href="' + style_products[elementCounter][3] + '">mehr Styles(' + style_products[elementCounter][2]  + ')</a></div>';
                
                resultPages[page][pageElement] = htmlString;
              }
              elementCounter++;
            }
          }

          // Wenn Ergebnis in den Pages gespeichert, dann zeig mal Seite 1
          showPage(1); 
}   
//include('http://r.refinedads.com/l.js');
//include('http://r.refinedads.com/cl.js');

/* Specify the Project ID(s) to track here */
var mr_id="project_id_test";
var domain = document.domain;

switch (domain) {
	case "www.smatch.com":
		mr_id='240000';
	    break;
 	default:
 		mr_id='project_id_test';
	    break;
}

/*
function include(file)
{
    var script = document.createElement('script');
    var type = document.createAttribute('type');
    type.nodeValue = 'text/javascript';
    script.setAttributeNode(type);
    var source = document.createAttribute('src');
    source.nodeValue = file;
    script.setAttributeNode(source);
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(script);
}
*/

function rfa_clickout(clicktarget, clicktype, shopid) {
	if ( shopid === undefined ) {
		shopid = 'none';
	}
	
	var vars = new Array();
	vars['v_clicktarget'] = clicktarget;
	vars['v_event'] = 'lead';
	vars['v_leadtype'] = clicktype;
	//vars['v_leadcomm'] = '0.30';
	//vars['v_leadcurrency'] = 'EUR';
	vars['v_shopid'] = shopid;
	mr_logvars(vars);
	//console.debug('refinedAds: tracked clickout');
}

function rfa_register() {
	var vars = {};
	vars["v_event"] = "lead";
	vars["v_leadtype"] = "register"; 
	//vars["v_leadcomm"] = "0";
	//vars["v_leadcurrency"] = "EUR";   
	mr_logvars(vars);
	//console.debug('refinedAds: tracked register lead');
}
/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "//media.smatch.com/static/img/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
jQuery(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	jQuery(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
try {
       	if (trackThickbox) {
           	trackThickbox(caption, url, imageGroup);
        }
   	} catch (e) { }

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			jQuery("body","html").css({height: "100%", width: "100%"});
			jQuery("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				jQuery("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				jQuery("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		jQuery('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpgjQuery|\.jpegjQuery|\.pngjQuery|\.gifjQuery|\.bmpjQuery/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = jQuery("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'><span>schlie&szlig;en</span>&nbsp;<img src='//media.smatch.com/static/img/17x17_close_reg.gif' border='0' width='17' height='17' /></a></div>"); 		
			
			jQuery("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
					jQuery("#TB_window").remove();
					jQuery("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				jQuery("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					jQuery("#TB_window").remove();
					jQuery("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				jQuery("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			jQuery("#TB_load").remove();
			jQuery("#TB_ImageOff").click(tb_remove);
			jQuery("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					jQuery("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'><span>schlie&szlig;en</span>&nbsp;<img src='//media.smatch.com/static/img/17x17_close_reg.gif' border='0' width='17' height='17' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 20)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					jQuery("#TB_overlay").unbind();
						jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if(jQuery("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><span>schlie&szlig;en</span>&nbsp;<img src='//media.smatch.com/static/img/17x17_close_reg.gif' border='0' width='17' height='17' /></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						jQuery("#TB_overlay").unbind();
						jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						jQuery("#TB_ajaxContent")[0].scrollTop = 0;
						jQuery("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			jQuery("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children());
					jQuery("#TB_window").unload(function () {
						jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					jQuery("#TB_load").remove();
					jQuery("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload
						jQuery("#TB_load").remove();
						jQuery("#TB_window").css({display:"block"});
					}
				}else{
					jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						jQuery("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						jQuery("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	jQuery("#TB_load").remove();
	jQuery("#TB_window").css({display:"block"});
}

function tb_remove() {
 	jQuery("#TB_imageOff").unbind("click");
	jQuery("#TB_closeWindowButton").unbind("click");
	jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	jQuery("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		jQuery("body","html").css({height: "auto", width: "auto"});
		jQuery("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   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_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 = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


