

/*
 * Definition der Pfade als JS-Variablen
 */
var filterPath = '/json_services/artist_filter';
var listPath   = '/concert/archive';
var favoriteSetPath = '/json_services/set_favourite';
var favoriteGetPath = '/json_services/get_favourites';
var timezonesGetPath   = '/json_services/timezones';
var timezonesSetPath   = '/json_services/set_timezone';
var timeformatSetPath = '/json_services/set_time_format';
var bandwidthtestSetPath   = '/json_services/send_porttest_result';
var passwordrecoveryPath = '/json_services/send_password';
var videolistPath = '/concert/search';
var videoAutocompletePath = '/json_services/autocomplete';
var recommendTokenGetPath = '/json_services/get_recommend_token';
var statesGetPath = '/json_services/provinces';

var videosearchCachePath = 'http://dchbe-dev-lb1.berliner-philharmoniker.de/sites/default/files/cachedcontent/dch_searchindex_'+dch_currentlanguage+'.json';

var dch_cookie_domain = 'digitalconcerthall.com';

var dchcontent_flash_expressinstall = 'http://cdn4.digitalconcerthall.com/img/flash_intro/expressInstall.swf';
var dchcontent_flashintro_flashfile = 'http://cdn4.digitalconcerthall.com/img/flash_intro/DCHPreloader.swf';
var dchcontent_flashintro_videourl = 'http://cdn4.digitalconcerthall.com/img/flash_intro/intro_animation.mp4';
var dchcontent_flashintro_imagefirst = 'http://cdn4.digitalconcerthall.com/img/flash_intro/videoImageFirst.jpg';
var dchcontent_flashintro_imagelast = 'http://cdn4.digitalconcerthall.com/img/flash_intro/videoImageLast.jpg';
var dchcontent_flashintro_homepagebackground = 'http://cdn4.digitalconcerthall.com/img/layout/bg_body_00.jpg';
var dchcontent_bandwidthtest_testurls = 'http://cdn2.digitalconcerthall.com/speedtest/bin_test_1.flv,http://cdn2.digitalconcerthall.com/speedtest/bin_test_2.flv,http://cdn2.digitalconcerthall.com/speedtest/bin_test_3.flv';
var dchcontent_bandwidthtest_flashfile = 'http://cdn4.digitalconcerthall.com/img/bandwidth/BandWidthDetectionMain.swf';


/* globaler debug-Schalter */
var debug = false;

/**/
/**/


/**/
if(window.location.toString().search(/\/#\/en\/help\/streamtest\//) != -1) {
	window.location = window.location.protocol.toString()+'//'+window.location.host.toString()+'/en/help/bandwidth';
}
if(window.location.toString().search(/\/#\/de\/help\/streamtest\//) != -1) {
	window.location = window.location.protocol.toString()+'//'+window.location.host.toString()+'/de/hilfe/bandwidth';
}

/**/
if(window.location.toString().search(/\/#\/de\//) != -1) {
	window.location = window.location.protocol.toString()+'//'+window.location.host.toString()+window.location.hash.toString().replace(/#\/de\/concertarchiv\/archiv\/([0-9]{4})\/([0-9]{1,2})\/([a-z]{1})([0-9]{1,4})\//,'/de/konzert/$4/');
}
if(window.location.toString().search(/\/#\/en\//) != -1) {
	window.location = window.location.protocol.toString()+'//'+window.location.host.toString()+window.location.hash.toString().replace(/#\/en\/concertarchiv\/archiv\/([0-9]{4})\/([0-9]{1,2})\/([a-z]{1})([0-9]{1,4})\//,'/en/concert/$4/');
}
		
/**/

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};/**/
function showOldbrowsermessage(){
	$('#wrapper').addClass('hasbrowseralert');
	$('#browseralertmessage').html(dchjslanguage_errors_oldbrowsermessage);
	$('#browseralertlink').html(dchjslanguage_errors_oldbrowsermessagelink);
	$('#browseralert-wrapper').show();
}

/**/
/**/

$(document).ready(function() {
	/**/
	BrowserDetect.init();
	if (BrowserDetect.browser == "Firefox" && BrowserDetect.version < 2) showOldbrowsermessage();
	if (BrowserDetect.browser == "Opera" && BrowserDetect.version < 9.8) showOldbrowsermessage();
	if (BrowserDetect.browser == "Explorer" && BrowserDetect.version < 7) showOldbrowsermessage();
	if (BrowserDetect.browser == "Safari" && BrowserDetect.version < 3) showOldbrowsermessage();
	if (BrowserDetect.browser == "Chrome" && BrowserDetect.version < 5) showOldbrowsermessage();

	/**/
	if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
		$('#wrapper').addClass('hasbrowseralert');
		$('#browseralertmessage').html(dchjslanguage_errors_noflashmessage);
		$('#browseralertlink').html(dchjslanguage_errors_noflashmessagelink);
		$('#browseralert-wrapper').show();
	}
});

/*!
 * jQuery UI 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
(function(c){c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.2",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==
"hidden")return false;b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,
NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect",
"none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",
1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");return(/input|select|textarea|button|object/.test(b)?
!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery);/*!
 * jQuery UI Widget 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Widget
 */
(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend({},c.options);b[e][a].prototype=
b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==undefined){h=i;return false}}):this.each(function(){var g=
b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();
this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);/*!
 * jQuery UI Mouse 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&
this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();
return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&
this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-
a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);/*
 * jQuery UI Position 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Position
 */
(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h=
0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+=
g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k,
elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"?
-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position=
"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);/*
 * jQuery UI Autocomplete 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */

/* TPUPPE.LLH: "Konstanten", die irgendwo gebraucht werden */
if(typeof characterHellip == 'undefined') {
	var characterHellip = String.fromCharCode(8230);
}

(function( $ ) {

$.widget( "ui.autocomplete", {
	options: {
		minLength: 2,
		delay: 300
	},
	_create: function() {
		var self = this,
			doc = this.element[ 0 ].ownerDocument;
		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" )
			// TODO verify these actually work as intended
			.attr({
				role: "textbox",
				"aria-autocomplete": "list",
				"aria-haspopup": "true"
			})
			.bind( "keydown.autocomplete", function( event ) {
				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
					self._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					self._move( "nextPage", event );
					break;
				case keyCode.UP:
					self._move( "previous", event );
					// prevent moving cursor to beginning of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.DOWN:
					self._move( "next", event );
					// prevent moving cursor to end of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.ENTER:
				case keyCode.NUMPAD_ENTER:
					// when menu is open or has focus
					if ( self.menu.active ) {
						event.preventDefault();
					}
					//passthrough - ENTER and TAB both select the current element
				case keyCode.TAB:
					if ( !self.menu.active ) {
						return;
					}
					self.menu.select( event );
					break;
				case keyCode.ESCAPE:
					self.element.val( self.term );
					self.close( event );
					break;
				case keyCode.LEFT:
				case keyCode.RIGHT:
				case keyCode.SHIFT:
				case keyCode.CONTROL:
				case keyCode.ALT:
				case keyCode.COMMAND:
				case keyCode.COMMAND_RIGHT:
				case keyCode.INSERT:
				case keyCode.CAPS_LOCK:
				case keyCode.END:
				case keyCode.HOME:
					// ignore metakeys (shift, ctrl, alt)
					break;
				default:
					// keypress is triggered before the input value is changed
					clearTimeout( self.searching );
					self.searching = setTimeout(function() {
						self.search( null, event );
					}, self.options.delay );
					break;
				}
			})
			.bind( "focus.autocomplete", function() {
				self.selectedItem = null;
				self.previous = self.element.val();
			})
			.bind( "blur.autocomplete", function( event ) {
				clearTimeout( self.searching );
				// clicks on the menu (or a button to trigger a search) will cause a blur event
				self.closing = setTimeout(function() {
					self.close( event );
					self._change( event );
				}, 150 );
			});
		this._initSource();
		this.response = function() {
			return self._response.apply( self, arguments );
		};
		this.menu = $( "<ul></ul>" )
			.addClass( "ui-autocomplete" )
			.insertAfter($(this.element)) // LLH.TPUPPE
			.wrap("<div class=\"autocomplete-choice\"><div class=\"rc-b\"><div class=\"rc-c\"></div></div></div>") //  LLH:TPUPPE
			// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
			.mousedown(function() {
				// use another timeout to make sure the blur-event-handler on the input was already triggered
				setTimeout(function() {
					clearTimeout( self.closing );
				}, 13);
			})
			.menu({
				focus: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" );
					if ( false !== self._trigger( "focus", null, { item: item } ) ) {
						// use value to match what will end up in the input, if it was a key event
						if ( /^key/.test(event.originalEvent.type) ) {
							self.element.val( item.value );
						}
					}
				},
				selected: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" );
					if ( false !== self._trigger( "select", event, { item: item } ) ) {
						self.element.val( item.value );
					}
					self.close( event );
					// only trigger when focus was lost (click on menu)
					var previous = self.previous;
					if ( self.element[0] !== doc.activeElement ) {
						self.element.focus();
						self.previous = previous;
					}
					self.selectedItem = item;
				},
				blur: function( event, ui ) {
					if ( self.menu.element.is(":visible") ) {
						self.element.val( self.term );
					}
				}
			})
			//.zIndex( this.element.zIndex() + 1 ) // LLH.TPUPPE
			// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
			//.css({ top: 0, left: 0 }) // LLH.TPUPPE
			//.hide() // LLH.TPUPPE
			.data( "menu" );
			$('.autocomplete-choice').hide();

		if ( $.fn.bgiframe ) {
			 this.menu.element.bgiframe();
		}
	},

	destroy: function() {
		this.element
			.removeClass( "ui-autocomplete-input" )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-autocomplete" )
			.removeAttr( "aria-haspopup" );
		this.menu.element.remove();
		$.Widget.prototype.destroy.call( this );
	},

	_setOption: function( key ) {
		$.Widget.prototype._setOption.apply( this, arguments );
		if ( key === "source" ) {
			this._initSource();
		}
	},

	_initSource: function() {
		var array,
			url;
		if ( $.isArray(this.options.source) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter(array, request.term) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				$.getJSON( url, request, response );
			};
		} else {
			this.source = this.options.source;
		}
	},

	search: function( value, event ) {
		value = value != null ? value : this.element.val();
		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		clearTimeout( this.closing );
		if ( this._trigger("search") === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.term = this.element
			.addClass( "ui-autocomplete-loading" )
			// always save the actual value, not the one passed as an argument
			.val();

		this.source( { term: value }, this.response );
	},

	_response: function( content ) {
		if ( content.length ) {
			content = this._normalize( content );
			this._suggest( content );
			this._trigger( "open" );
		} else {
			this.close();
		}
		this.element.removeClass( "ui-autocomplete-loading" );
	},

	close: function( event ) {
		clearTimeout( this.closing );
		if ( this.menu.element.is(":visible") ) {
			this._trigger( "close", event );
			//this.menu.element.hide(); // LLH.TP
			$('.autocomplete-choice').hide(); // LLH.TP
			this.menu.deactivate();
		}
		this.element.removeClass('open'); // LLH.TP
	},
	
	_change: function( event ) {
		if ( this.previous !== this.element.val() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[0].label && items[0].value ) {
			return items;
		}
		return $.map( items, function(item) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend({
				label: item.label || item.value,
				value: item.value || item.label
			}, item );
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element
				.empty(),
				/*.zIndex( this.element.zIndex() + 1 ), // LLH.TPUPPE*/
			menuWidth,
			textWidth;
		this.element.addClass('open'); // LLH.TPUPPE
		this._renderMenu( ul, items );
		// TODO refresh should check if the active item is still in the dom, removing the need for a manual deactivate
		this.menu.deactivate();
		this.menu.refresh();

		// besser: niemals hiden
		//this.menu.element.show(); // LLH.TPUPPE

		/*
		this.menu.element.show().position({
			my: "left top",
			at: "left bottom",
			of: this.element,
			collision: "none"
		});
		*/ // LLH.TPUPPE

	   this.element.parent().find('.autocomplete-choice').show(); // LLH.TPUPPE
	   
		menuWidth = ul.width( "" ).width();
		textWidth = this.element.width();
		//ul.width( Math.max( menuWidth, textWidth ) ); // LLH.TPUPPE
	},
	
	_renderMenu: function( ul, items ) {
		var self = this;
		// tpuppe.llh: Zahl der angezeigten Vorschläge reduzieren
		var renderItemCounter = 0;
		$.each( items, function( index, item ) {
			if(renderItemCounter<20){
				self._renderItem( ul, item );
				renderItemCounter++;
			}
		});
	},

	_renderItem: function( ul, item) {

		// TPUPPE.LLH: Kürzung bei x Zeichen, weil sonst häßliche Umbrüche entstehen.
		var itemShortLabel = item.label
		if(itemShortLabel.length>20) {
			itemShortLabel = jQuery.trim(itemShortLabel.substring(0,19))+characterHellip;
		}
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( "<a title=\"" + item.label + "\"><span class=\"rc-l\"><span class=\"rc-r\"><span class=\"rc-m\">" + itemShortLabel + "</span></span></span></a>" ) // LLH.JLEIST
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is(":visible") ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.first() && /^previous/.test(direction) ||
				this.menu.last() && /^next/.test(direction) ) {
			this.element.val( this.term );
			this.menu.deactivate();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	}
});

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1" );
	},
	filter: function(array, term) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
		return $.grep( array, function(value) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

}( jQuery ));

/*
 * jQuery UI Menu (not officially released)
 * 
 * This widget isn't yet finished and the API is subject to change. We plan to finish
 * it for the next release. You're welcome to give it a try anyway and give us feedback,
 * as long as you're okay with migrating your code later on. We can help with that, too.
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Menu
 *
 * Depends:
 *	jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function($) {

$.widget("ui.menu", {
	_create: function() {
		var self = this;
		this.element
			.addClass("ui-menu ui-widget ui-widget-content ui-corner-all")
			.attr({
				role: "listbox",
				"aria-activedescendant": "ui-active-menuitem"
			})
			.click(function( event ) {
				if ( !$( event.target ).closest( ".ui-menu-item a" ).length ) {
					return;
				}
				// temporary
				event.preventDefault();
				self.select( event );
			});
		this.refresh();
	},
	
	refresh: function() {
		var self = this;

		// don't refresh list items that are already adapted
		var items = this.element.children("li:not(.ui-menu-item):has(a)")
			.addClass("ui-menu-item")
			.attr("role", "menuitem");
		
		items.children("a")
			.addClass("ui-corner-all")
			.attr("tabindex", -1)
			// mouseenter doesn't work with event delegation
			.mouseenter(function( event ) {
				self.activate( event, $(this).parent() );
			})
			.mouseleave(function() {
				self.deactivate();
			});
	},

	activate: function( event, item ) {
		this.deactivate();
		if (this.hasScroll()) {
			var offset = item.offset().top - this.element.offset().top,
				scroll = this.element.attr("scrollTop"),
				elementHeight = this.element.height();
			if (offset < 0) {
				this.element.attr("scrollTop", scroll + offset);
			} else if (offset > elementHeight) {
				this.element.attr("scrollTop", scroll + offset - elementHeight + item.height());
			}
		}
		this.active = item.eq(0)
			.children("a")
				.addClass("ui-state-hover")
				.attr("id", "ui-active-menuitem")
			.end();
		this._trigger("focus", event, { item: item });
	},

	deactivate: function() {
		if (!this.active) { return; }

		this.active.children("a")
			.removeClass("ui-state-hover")
			.removeAttr("id");
		this._trigger("blur");
		this.active = null;
	},

	next: function(event) {
		this.move("next", ".ui-menu-item:first", event);
	},

	previous: function(event) {
		this.move("prev", ".ui-menu-item:last", event);
	},

	first: function() {
		return this.active && !this.active.prev().length;
	},

	last: function() {
		return this.active && !this.active.next().length;
	},

	move: function(direction, edge, event) {
		if (!this.active) {
			this.activate(event, this.element.children(edge));
			return;
		}
		var next = this.active[direction + "All"](".ui-menu-item").eq(0);
		if (next.length) {
			this.activate(event, next);
		} else {
			this.activate(event, this.element.children(edge));
		}
	},

	// TODO merge with previousPage
	nextPage: function(event) {
		if (this.hasScroll()) {
			// TODO merge with no-scroll-else
			if (!this.active || this.last()) {
				this.activate(event, this.element.children(":first"));
				return;
			}
			var base = this.active.offset().top,
				height = this.element.height(),
				result = this.element.children("li").filter(function() {
					var close = $(this).offset().top - base - height + $(this).height();
					// TODO improve approximation
					return close < 10 && close > -10;
				});

			// TODO try to catch this earlier when scrollTop indicates the last page anyway
			if (!result.length) {
				result = this.element.children(":last");
			}
			this.activate(event, result);
		} else {
			this.activate(event, this.element.children(!this.active || this.last() ? ":first" : ":last"));
		}
	},

	// TODO merge with nextPage
	previousPage: function(event) {
		if (this.hasScroll()) {
			// TODO merge with no-scroll-else
			if (!this.active || this.first()) {
				this.activate(event, this.element.children(":last"));
				return;
			}

			var base = this.active.offset().top,
				height = this.element.height();
				result = this.element.children("li").filter(function() {
					var close = $(this).offset().top - base + height - $(this).height();
					// TODO improve approximation
					return close < 10 && close > -10;
				});

			// TODO try to catch this earlier when scrollTop indicates the last page anyway
			if (!result.length) {
				result = this.element.children(":first");
			}
			this.activate(event, result);
		} else {
			this.activate(event, this.element.children(!this.active || this.first() ? ":last" : ":first"));
		}
	},

	hasScroll: function() {
		return this.element.height() < this.element.attr("scrollHeight");
	},

	select: function( event ) {
		this._trigger("selected", event, { item: this.active });
	}
});

}(jQuery));/*
 * jQuery UI Slider 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var a=this,b=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");b.disabled&&this.element.addClass("ui-slider-disabled ui-disabled");
this.range=d([]);if(b.range){if(b.range===true){this.range=d("<div></div>");if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(b.range==="min"||b.range==="max")this.range.addClass("ui-slider-range-"+b.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");
if(b.values&&b.values.length)for(;d(".ui-slider-handle",this.element).length<b.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(b.disabled)d(this).blur();
else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),g,h,i;if(!a.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e=
false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");g=a._start(c,f);if(g===false)return}break}i=a.options.step;g=a.options.values&&a.options.values.length?(h=a.values(f)):(h=a.value());switch(c.keyCode){case d.ui.keyCode.HOME:h=a._valueMin();break;case d.ui.keyCode.END:h=a._valueMax();break;case d.ui.keyCode.PAGE_UP:h=a._trimAlignValue(g+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:h=a._trimAlignValue(g-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(g===
a._valueMax())return;h=a._trimAlignValue(g+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(g===a._valueMin())return;h=a._trimAlignValue(g-i);break}a._slide(c,f,h);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(c,e);a._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");
this._mouseDestroy();return this},_mouseCapture:function(a){var b=this.options,c,e,f,g,h,i;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c={x:a.pageX,y:a.pageY};e=this._normValueFromMouse(c);f=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(j){var k=Math.abs(e-h.values(j));if(f>k){f=k;g=d(this);i=j}});if(b.range===true&&this.values(1)===b.min){i+=1;g=d(this.handles[i])}if(this._start(a,
i)===false)return false;this._mouseSliding=true;h._handleIndex=i;g.addClass("ui-state-active").focus();b=g.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-g.width()/2,top:a.pageY-b.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)};e=this._normValueFromMouse(c);this._slide(a,i,e);return this._animateOff=true},_mouseStart:function(){return true},
_mouseDrag:function(a){var b=this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b;
if(this.orientation==="horizontal"){b=this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=
this.values(b);c.values=this.values()}return this._trigger("start",a,c)},_slide:function(a,b,c){var e;if(this.options.values&&this.options.values.length){e=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>e||b===1&&c<e))c=e;if(c!==this.values(b)){e=this.values();e[b]=c;a=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e});this.values(b?0:1);a!==false&&this.values(b,c,true)}}else if(c!==this.value()){a=this._trigger("slide",a,{handle:this.handles[b],
value:c});a!==false&&this.value(c)}},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("change",a,c)}},value:function(a){if(arguments.length){this.options.value=
this._trimAlignValue(a);this._refreshValue();this._change(null,0)}return this._value()},values:function(a,b){var c,e,f;if(arguments.length>1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(a):this.value();
else return this._values()},_setOption:function(a,b){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(a){case "disabled":if(b){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();
this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a)},_values:function(a){var b,c;if(arguments.length){b=this.options.values[a];
return b=this._trimAlignValue(b)}else{b=this.options.values.slice();for(c=0;c<b.length;c+=1)b[c]=this._trimAlignValue(b[c]);return b}},_trimAlignValue:function(a){if(a<this._valueMin())return this._valueMin();if(a>this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=a%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a=
this.options.range,b=this.options,c=this,e=!this._animateOff?b.animate:false,f,g={},h,i,j,k;if(this.options.values&&this.options.values.length)this.handles.each(function(l){f=(c.values(l)-c._valueMin())/(c._valueMax()-c._valueMin())*100;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](g,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(l===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},b.animate);if(l===1)c.range[e?"animate":"css"]({width:f-
h+"%"},{queue:false,duration:b.animate})}else{if(l===0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},b.animate);if(l===1)c.range[e?"animate":"css"]({height:f-h+"%"},{queue:false,duration:b.animate})}h=f});else{i=this.value();j=this._valueMin();k=this._valueMax();f=k!==j?(i-j)/(k-j)*100:0;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](g,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},
b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[e?"animate":"css"]({width:100-f+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.8.2"})})(jQuery);/*
 * jQuery UI Tabs 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function(d){function s(){return++u}function v(){return++w}var u=0,w=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'},_create:function(){this._tabify(true)},_setOption:function(c,e){if(c=="selected")this.options.collapsible&&
e==this.options.selected||this.select(e);else{this.options[c]=e;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+s()},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+v());return d.cookie.apply(null,[c].concat(d.makeArray(arguments)))},_ui:function(c,e){return{tab:c,panel:e,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var c=
d(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function e(g,f){g.css({display:""});!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}this.list=this.element.find("ol,ul").eq(0);this.lis=d("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);var a=this,b=this.options,h=/^#.+/;this.anchors.each(function(g,f){var j=d(f).attr("href"),l=j.split("#")[0],p;if(l&&(l===location.toString().split("#")[0]||
(p=d("base")[0])&&l===p.href)){j=f.hash;f.href=j}if(h.test(j))a.panels=a.panels.add(a._sanitizeSelector(j));else if(j!="#"){d.data(f,"href.tabs",j);d.data(f,"load.tabs",j.replace(/#.*$/,""));j=a._tabId(f);f.href="#"+j;f=d("#"+j);if(!f.length){f=d(b.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else b.disabled.push(g)});if(c){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");
this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(b.selected===undefined){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){b.selected=g;return false}});if(typeof b.selected!="number"&&b.cookie)b.selected=parseInt(a._cookie(),10);if(typeof b.selected!="number"&&this.lis.filter(".ui-tabs-selected").length)b.selected=
this.lis.index(this.lis.filter(".ui-tabs-selected"));b.selected=b.selected||(this.lis.length?0:-1)}else if(b.selected===null)b.selected=-1;b.selected=b.selected>=0&&this.anchors[b.selected]||b.selected<0?b.selected:0;b.disabled=d.unique(b.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(b.selected,b.disabled)!=-1&&b.disabled.splice(d.inArray(b.selected,b.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");
if(b.selected>=0&&this.anchors.length){this.panels.eq(b.selected).removeClass("ui-tabs-hide");this.lis.eq(b.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[b.selected],a.panels[b.selected]))});this.load(b.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else b.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[b.collapsible?"addClass":
"removeClass"]("ui-tabs-collapsible");b.cookie&&this._cookie(b.selected,b.cookie);c=0;for(var i;i=this.lis[c];c++)d(i)[d.inArray(c,b.disabled)!=-1&&!d(i).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");b.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(b.event!="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+g)};this.lis.bind("mouseover.tabs",
function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(b.fx)if(d.isArray(b.fx)){m=b.fx[0];o=b.fx[1]}else m=o=b.fx;var q=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._trigger("show",
null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},r=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};this.anchors.bind(b.event+".tabs",
function(){var g=this,f=d(this).closest("li"),j=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(this.hash));if(f.hasClass("ui-tabs-selected")&&!b.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}b.selected=a.anchors.index(this);a.abort();if(b.collapsible)if(f.hasClass("ui-tabs-selected")){b.selected=-1;b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){r(g,
j)}).dequeue("tabs");this.blur();return false}else if(!j.length){b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this));this.blur();return false}b.cookie&&a._cookie(b.selected,b.cookie);if(l.length){j.length&&a.element.queue("tabs",function(){r(g,j)});a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",
function(){return false})},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(b,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,
"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c,e,a){if(a===undefined)a=this.anchors.length;var b=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,e));c=!c.indexOf("#")?c.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",
true);var i=d("#"+c);i.length||(i=d(h.panelTemplate).attr("id",c).data("destroy.tabs",true));i.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);i.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);i.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");i.removeClass("ui-tabs-hide");
this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(c){var e=this.options,a=this.lis.eq(c).remove(),b=this.panels.eq(c).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=c}),function(h){return h>=c?--h:h});this._tabify();this._trigger("remove",
null,this._ui(a.find("a")[0],b[0]));return this},enable:function(c){var e=this.options;if(d.inArray(c,e.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=c});this._trigger("enable",null,this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){var e=this.options;if(c!=e.selected){this.lis.eq(c).addClass("ui-state-disabled");e.disabled.push(c);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}return this},
select:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));else if(c===null)c=-1;if(c==-1&&this.options.collapsible)c=this.options.selected;this.anchors.eq(c).trigger(this.options.event+".tabs");return this},load:function(c){var e=this,a=this.options,b=this.anchors.eq(c)[0],h=d.data(b,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(b,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-processing");
if(a.spinner){var i=d("span",b);i.data("label.tabs",i.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(b.hash)).html(k);e._cleanup();a.cache&&d.data(b,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.error(k,n,c,b)}catch(m){}}}));e.element.dequeue("tabs");return this}},
abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(c,e){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.2"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(c,e){var a=this,b=this.options,h=a._rotate||(a._rotate=
function(i){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=b.selected;a.select(++k<a.anchors.length?k:0)},c);i&&i.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(i){i.clientX&&a.rotate(null)}:function(){t=b.selected;h()});if(c){this.element.bind("tabsshow",h);this.anchors.bind(b.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(b.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery);/*
 * jQuery UI Accordion 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function($) {

$.widget("ui.accordion", {
	options: {
		active: 0,
		animated: 'slide',
		autoHeight: true,
		clearStyle: false,
		collapsible: false,
		event: "click",
		fillSpace: false,
		header: "> li > :first-child,> :not(li):even",
		icons: {
			header: "ui-icon-triangle-1-e",
			headerSelected: "ui-icon-triangle-1-s"
		},
		navigation: false,
		navigationFilter: function() {
			return this.href.toLowerCase() == location.href.toLowerCase();
		}
	},
	_create: function() {

		var o = this.options, self = this;
		this.running = 0;

		this.element.addClass("ui-accordion ui-widget ui-helper-reset");

		// in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix
		this.element.children("li").addClass("ui-accordion-li-fix");

		this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all")
			.bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); })
			.bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); })
			.bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); })
			.bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); });

		this.headers
			.next()
				.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");

		if ( o.navigation ) {
			var current = this.element.find("a").filter(o.navigationFilter);
			if ( current.length ) {
				var header = current.closest(".ui-accordion-header");
				if ( header.length ) {
					// anchor within header
					this.active = header;
				} else {
					// anchor within content
					this.active = current.closest(".ui-accordion-content").prev();
				}
			}
		}

		this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");
		this.active.next().addClass('ui-accordion-content-active');

		//Append icon elements
		this._createIcons();

		this.resize();

		//ARIA
		this.element.attr('role','tablist');

		this.headers
			.attr('role','tab')
			.bind('keydown', function(event) { return self._keydown(event); })
			.next()
			.attr('role','tabpanel');

		this.headers
			.not(this.active || "")
			.attr('aria-expanded','false')
			.attr("tabIndex", "-1")
			.next()
			.hide();

		// make sure at least one header is in the tab order
		if (!this.active.length) {
			this.headers.eq(0).attr('tabIndex','0');
		} else {
			this.active
				.attr('aria-expanded','true')
				.attr('tabIndex', '0');
		}

		// only need links in taborder for Safari
		if (!$.browser.safari)
			this.headers.find('a').attr('tabIndex','-1');

		if (o.event) {
			this.headers.bind((o.event) + ".accordion", function(event) {
				self._clickHandler.call(self, event, this);
				event.preventDefault();
			});
		}

	},

	_createIcons: function() {
		var o = this.options;
		if (o.icons) {
			$("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers);
			this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected);
			this.element.addClass("ui-accordion-icons");
		}
	},

	_destroyIcons: function() {
		this.headers.children(".ui-icon").remove();
		this.element.removeClass("ui-accordion-icons");
	},

	destroy: function() {
		var o = this.options;

		this.element
			.removeClass("ui-accordion ui-widget ui-helper-reset")
			.removeAttr("role")
			.unbind('.accordion')
			.removeData('accordion');

		this.headers
			.unbind(".accordion")
			.removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top")
			.removeAttr("role").removeAttr("aria-expanded").removeAttr("tabIndex");

		this.headers.find("a").removeAttr("tabIndex");
		this._destroyIcons();
		var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");
		if (o.autoHeight || o.fillHeight) {
			contents.css("height", "");
		}

		return this;
	},

	_setOption: function(key, value) {
		$.Widget.prototype._setOption.apply(this, arguments);

		if (key == "active") {
			this.activate(value);
		}
		if (key == "icons") {
			this._destroyIcons();
			if (value) {
				this._createIcons();
			}
		}

	},

	_keydown: function(event) {

		var o = this.options, keyCode = $.ui.keyCode;

		if (o.disabled || event.altKey || event.ctrlKey)
			return;

		var length = this.headers.length;
		var currentIndex = this.headers.index(event.target);
		var toFocus = false;

		switch(event.keyCode) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[(currentIndex + 1) % length];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[(currentIndex - 1 + length) % length];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				this._clickHandler({ target: event.target }, event.target);
				event.preventDefault();
		}

		if (toFocus) {
			$(event.target).attr('tabIndex','-1');
			$(toFocus).attr('tabIndex','0');
			toFocus.focus();
			return false;
		}

		return true;

	},

	resize: function() {

		var o = this.options, maxHeight;

		if (o.fillSpace) {

			if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); }
			maxHeight = this.element.parent().height();
			if($.browser.msie) { this.element.parent().css('overflow', defOverflow); }

			this.headers.each(function() {
				maxHeight -= $(this).outerHeight(true);
			});

			this.headers.next().each(function() {
    		   $(this).height(Math.max(0, maxHeight - $(this).innerHeight() + $(this).height()));
			}).css('overflow', 'auto');

		} else if ( o.autoHeight ) {
			maxHeight = 0;
			this.headers.next().each(function() {
				maxHeight = Math.max(maxHeight, $(this).height());
			}).height(maxHeight);
		}

		return this;
	},

	activate: function(index) {
		// TODO this gets called on init, changing the option without an explicit call for that
		this.options.active = index;
		// call clickHandler with custom event
		var active = this._findActive(index)[0];
		this._clickHandler({ target: active }, active);

		return this;
	},

	_findActive: function(selector) {
		return selector
			? typeof selector == "number"
				? this.headers.filter(":eq(" + selector + ")")
				: this.headers.not(this.headers.not(selector))
			: selector === false
				? $([])
				: this.headers.filter(":eq(0)");
	},

	// TODO isn't event.target enough? why the seperate target argument?
	_clickHandler: function(event, target) {

		var o = this.options;
		if (o.disabled)
			return;

		// called only when using activate(false) to close all parts programmatically
		if (!event.target) {
			if (!o.collapsible)
				return;
			this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
				.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
			this.active.next().addClass('ui-accordion-content-active');
			var toHide = this.active.next(),
				data = {
					options: o,
					newHeader: $([]),
					oldHeader: o.active,
					newContent: $([]),
					oldContent: toHide
				},
				toShow = (this.active = $([]));
			this._toggle(toShow, toHide, data);
			return;
		}

		// get the click target
		var clicked = $(event.currentTarget || target);
		var clickedIsActive = clicked[0] == this.active[0];

		// TODO the option is changed, is that correct?
		// TODO if it is correct, shouldn't that happen after determining that the click is valid?
		o.active = o.collapsible && clickedIsActive ? false : $('.ui-accordion-header', this.element).index(clicked);

		// if animations are still active, or the active header is the target, ignore click
		if (this.running || (!o.collapsible && clickedIsActive)) {
			return;
		}

		// switch classes
		this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
			.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
		if (!clickedIsActive) {
			clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top")
				.find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected);
			clicked.next().addClass('ui-accordion-content-active');
		}

		// find elements to show and hide
		var toShow = clicked.next(),
			toHide = this.active.next(),
			data = {
				options: o,
				newHeader: clickedIsActive && o.collapsible ? $([]) : clicked,
				oldHeader: this.active,
				newContent: clickedIsActive && o.collapsible ? $([]) : toShow,
				oldContent: toHide
			},
			down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] );

		this.active = clickedIsActive ? $([]) : clicked;
		this._toggle(toShow, toHide, data, clickedIsActive, down);

		return;

	},

	_toggle: function(toShow, toHide, data, clickedIsActive, down) {

		var o = this.options, self = this;

		this.toShow = toShow;
		this.toHide = toHide;
		this.data = data;

		var complete = function() { if(!self) return; return self._completed.apply(self, arguments); };

		// trigger changestart event
		this._trigger("changestart", null, this.data);

		// count elements to animate
		this.running = toHide.size() === 0 ? toShow.size() : toHide.size();

		if (o.animated) {

			var animOptions = {};

			if ( o.collapsible && clickedIsActive ) {
				animOptions = {
					toShow: $([]),
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: o.autoHeight || o.fillSpace
				};
			} else {
				animOptions = {
					toShow: toShow,
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: o.autoHeight || o.fillSpace
				};
			}

			if (!o.proxied) {
				o.proxied = o.animated;
			}

			if (!o.proxiedDuration) {
				o.proxiedDuration = o.duration;
			}

			o.animated = $.isFunction(o.proxied) ?
				o.proxied(animOptions) : o.proxied;

			o.duration = $.isFunction(o.proxiedDuration) ?
				o.proxiedDuration(animOptions) : o.proxiedDuration;

			var animations = $.ui.accordion.animations,
				duration = o.duration,
				easing = o.animated;

			if (easing && !animations[easing] && !$.easing[easing]) {
				easing = 'slide';
			}
			if (!animations[easing]) {
				animations[easing] = function(options) {
					this.slide(options, {
						easing: easing,
						duration: duration || 700
					});
				};
			}

			animations[easing](animOptions);

		} else {

			if (o.collapsible && clickedIsActive) {
				toShow.toggle();
			} else {
				toHide.hide();
				toShow.show();
			}

			complete(true);

		}

		// TODO assert that the blur and focus triggers are really necessary, remove otherwise
		toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur();
		toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus();

	},

	_completed: function(cancel) {

		var o = this.options;

		this.running = cancel ? 0 : --this.running;
		if (this.running) return;

		if (o.clearStyle) {
			this.toShow.add(this.toHide).css({
				height: "",
				overflow: ""
			});
		}

		// other classes are removed before the animation; this one needs to stay until completed
		this.toHide.removeClass("ui-accordion-content-active");

		this._trigger('change', null, this.data);
	}

});


$.extend($.ui.accordion, {
	version: "1.8.2",
	animations: {
		slide: function(options, additions) {
			options = $.extend({
				easing: "swing",
				duration: 300
			}, options, additions);
			if ( !options.toHide.size() ) {
				options.toShow.animate({height: "show"}, options);
				return;
			}
			if ( !options.toShow.size() ) {
				options.toHide.animate({height: "hide"}, options);
				return;
			}
			var overflow = options.toShow.css('overflow'),
				percentDone = 0,
				showProps = {},
				hideProps = {},
				fxAttrs = [ "height", "paddingTop", "paddingBottom" ],
				originalWidth;
			// fix width before calculating height of hidden element
			var s = options.toShow;
			originalWidth = s[0].style.width;
			s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - (parseInt(s.css("borderLeftWidth"),10) || 0) - (parseInt(s.css("borderRightWidth"),10) || 0) );

			$.each(fxAttrs, function(i, prop) {
				hideProps[prop] = 'hide';

				var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/);
				showProps[prop] = {
					value: parts[1],
					unit: parts[2] || 'px'
				};
			});
			options.toShow.css({ height: 0, overflow: 'hidden' }).show();
			options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{
				step: function(now, settings) {
					// only calculate the percent when animating height
					// IE gets very inconsistent results when animating elements
					// with small values, which is common for padding
					if (settings.prop == 'height') {
						percentDone = ( settings.end - settings.start === 0 ) ? 0 :
							(settings.now - settings.start) / (settings.end - settings.start);
					}

					options.toShow[0].style[settings.prop] =
						(percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit;
				},
				duration: options.duration,
				easing: options.easing,
				complete: function() {
					if ( !options.autoHeight ) {
						options.toShow.css("height", "");
					}
					options.toShow.css("width", originalWidth);
					options.toShow.css({overflow: overflow});
					options.complete();
				}
			});
		},
		bounceslide: function(options) {
			this.slide(options, {
				easing: options.down ? "easeOutBounce" : "swing",
				duration: options.down ? 1000 : 200
			});
		}
	}
});

})(jQuery);


$(function() {
	$(".accordion").accordion({ collapsible: true, active: false, autoHeight: false });
});/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

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

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.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
        }
        // CAUTION: 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;
    }
};/*

highlight v3

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};
(function($){$.fn.lazyload=function(options){var settings={threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};if(options){$.extend(settings,options);}
var elements=this;if("scroll"==settings.event){$(settings.container).bind("scroll",function(event){var counter=0;elements.each(function(){if($.abovethetop(this,settings)||$.leftofbegin(this,settings)){}else if(!$.belowthefold(this,settings)&&!$.rightoffold(this,settings)){$(this).trigger("appear");}else{if(counter++>settings.failurelimit){return false;}}});var temp=$.grep(elements,function(element){return!element.loaded;});elements=$(temp);});}
this.each(function(){var self=this;if(undefined==$(self).attr("original")){$(self).attr("original",$(self).attr("src"));}
if("scroll"!=settings.event||undefined==$(self).attr("src")||settings.placeholder==$(self).attr("src")||($.abovethetop(self,settings)||$.leftofbegin(self,settings)||$.belowthefold(self,settings)||$.rightoffold(self,settings))){if(settings.placeholder){$(self).attr("src",settings.placeholder);}else{$(self).removeAttr("src");}
self.loaded=false;}else{self.loaded=true;}
$(self).one("appear",function(){if(!this.loaded){$("<img />").bind("load",function(){$(self).hide().attr("src",$(self).attr("original"))
[settings.effect](settings.effectspeed);self.loaded=true;}).attr("src",$(self).attr("original"));};});if("scroll"!=settings.event){$(self).bind(settings.event,function(event){if(!self.loaded){$(self).trigger("appear");}});}});$(settings.container).trigger(settings.event);return this;};$.belowthefold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).height()+$(window).scrollTop();}else{var fold=$(settings.container).offset().top+$(settings.container).height();}
return fold<=$(element).offset().top-settings.threshold;};$.rightoffold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).width()+$(window).scrollLeft();}else{var fold=$(settings.container).offset().left+$(settings.container).width();}
return fold<=$(element).offset().left-settings.threshold;};$.abovethetop=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollTop();}else{var fold=$(settings.container).offset().top;}
return fold>=$(element).offset().top+settings.threshold+$(element).height();};$.leftofbegin=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollLeft();}else{var fold=$(settings.container).offset().left;}
return fold>=$(element).offset().left+settings.threshold+$(element).width();};$.extend($.expr[':'],{"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})","above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})","right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})","left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"});})(jQuery);/*
 * Lazy Display - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2010 Thomas Puppe
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Based on Lazyload Plugin by Mika Tuupola:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Problem ist, dass die Divs beim Ausblenden die Höhe 0 bekommen und dadurch
 * ganz schnell alle über dem Pagefold sind. Beim Einblenden liegen dann eben
 * alle über dem Pagefold und werden alle eingeblendet (durchsehen geht
 * schneller als das show()). Ich habe daher fürs Verstecken und Einblenden
 * den hiddenCounter und shownCounter eingeführt, der dies verzögert.
 * 
 * */
(function($) {

    $.fn.lazydisplay = function(options) {
        var settings = {
            threshold    : 0,
            failurelimit : 0,
            event        : "scroll",
            effect       : "show",
            container    : window
        };

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

        /**/
        var elements = this;
        if ("scroll" == settings.event) {
            $(settings.container).bind("scroll", function(event) {

                var counter = 0;
				var shownCounter = 0;
				
                elements.each(function() {
                    if ($.abovethetop(this, settings) ||
                        $.leftofbegin(this, settings)) {
                            /**/
                    } else if (!$.belowthefold(this, settings) &&
                        !$.rightoffold(this, settings)) {
                            //$(this).trigger("appear");
							$(this).show();
							shownCounter++;
							if(shownCounter>10){
								return false;
							}
                    } else {
                        if (counter++ > settings.failurelimit) {
                            return false;
                        }
                    }
                });
                /**/
                var temp = $.grep(elements, function(element) {
                    return !element.loaded;
                });
                elements = $(temp);
            });
        }

		var hiddenCounter = 0;
        this.each(function() {
            var self = this;

            if ("scroll" != settings.event ||
                    ($.abovethetop(self, settings) ||
                     $.leftofbegin(self, settings) ||
                     $.belowthefold(self, settings) ||
                     $.rightoffold(self, settings) )) {
				hiddenCounter++;
				if(hiddenCounter>5){
					$(self).hide();
					self.loaded = false;
				}
            } else {
                self.loaded = true;
            }


            /**/
            /**/
            if ("scroll" != settings.event) {
                $(self).bind(settings.event, function(event) {
                    if (!self.loaded) {
                        //$(self).trigger("appear");
						$(self).show();
                    }
                });
            }
        });

        /**/
        $(settings.container).trigger(settings.event);

        return this;

    };

    /**/
    /**/

    $.belowthefold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).width() + $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left + $(settings.container).width();
        }
        return fold <= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left;
        }
        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };
    /**/
    /**/

    $.extend($.expr[':'], {
        "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})",
        "right-of-fold"  : "$.rightoffold(a, {threshold : 0, container: window})",
        "left-of-fold"   : "!$.rightoffold(a, {threshold : 0, container: window})"
    });

})(jQuery);/**
*	swffit v2.3.3 (11/23/2009) <http://swffit.millermedeiros.com/>
*	Copyright (c) 2009 Miller Medeiros <http://www.millermedeiros.com/>
*	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swffit=function(){var win=window,doc=document,html=doc.getElementsByTagName("html")[0],AGENT=navigator.userAgent.toLowerCase(),WK=/webkit/.test(AGENT),IE=/msie/.test(AGENT)&&!win.opera,FF=/firefox/.test(AGENT)&&!win.opera,UNDEF="undefined",_ft,_re,_t,_mw,_mh,_xw,_xh,_hc,_vc,_ow,_oh;swfobject.createCSS("object","position:absolute; outline:none");function fit(t,mw,mh,xw,xh,hc,vc){mw=mw||_ow;mh=mh||_oh;xw=xw||null;xh=xh||null;hc=(hc||hc==null);vc=(vc||vc==null);configure({target:t,minWid:mw,minHei:mh,maxWid:xw,maxHei:xh,hCenter:hc,vCenter:vc});}function configure(o){var evalNum=function(v,p){return(typeof o[p]!=UNDEF)?o[p]:v;},evalBool=function(v,p){return(o[p]||(v&&typeof o[p]==UNDEF));};_mw=evalNum(_mw,"minWid");_mh=evalNum(_mh,"minHei");_xw=evalNum(_xw,"maxWid");_xh=evalNum(_xh,"maxHei");_hc=evalBool(_hc,"hCenter");_vc=evalBool(_vc,"vCenter");if(o.target&&(o.target!=_t)){_t=o.target;swfobject.addDomLoadEvent(initFit);if(IE){swfobject.addLoadEvent(initFit);}}else{startFit();}}function initFit(){if(!html.style.overflowX){controlScroll(0,0);}if(!html.style.overflowY){controlScroll(0,1);}html.style.height=doc.body.style.height="100%";doc.body.style.margin=doc.body.style.padding=0;var st="width:100%; height:100%";st+=(IE)?"; overflow:hidden":"";swfobject.createCSS("#"+_t,st);_ft=doc.getElementById(_t);_ft=(_ft!=UNDEF&&FF&&/object/.test(_ft.innerHTML))?doc.getElementById(_t).getElementsByTagName("object")[0]:_ft;_ow=_ft.width;_oh=_ft.height;_mw=_mw||_ow;_mh=_mh||_oh;startFit();}function startFit(){setSize();if(!_re){swffit.addResizeEvent(setSize);_re=1;}}function stopFit(w,h){if(_re){swffit.removeResizeEvent(setSize);_re=0;setStyle("top","auto");setStyle("left","auto");setStyle("marginTop",0);setStyle("marginLeft",0);w=w||"100%";h=h||"100%";setWidth(w);setHeight(h);forceRedraw();}}function forceRedraw(){if(WK){html.focus();}}function controlResizeEvent(a,fn){var p=(a)?["addEventListener","attachEvent"]:["removeEventListener","detachEvent"];if(win[p[0]]){win[p[0]]("resize",fn,false);}else{if(win[p[1]]){win[p[1]]("onresize",fn);}}}function setWidth(w){var v=(isNaN(w))?w:w+"px";setStyle("width",v);}function setHeight(h){var v=(isNaN(h))?h:h+"px";setStyle("height",v);}function setStyle(p,v){_ft.style[p]=v;}function setSize(){var iw=(win.innerWidth)?win.innerWidth:((doc.documentElement.clientWidth)?doc.documentElement.clientWidth:doc.body.clientWidth),ih=(win.innerHeight)?win.innerHeight:((doc.documentElement.clientHeight)?doc.documentElement.clientHeight:doc.body.clientHeight);iw-=(!IE&&ih<=_mh)?18:0;ih-=(!IE&&iw<=_mw)?18:0;if(_xw&&iw>=_xw){setWidth(_xw);setPosition(0,1);}else{if(iw>_mw&&(iw<_xw||!_xw)){setWidth("100%");}else{setWidth(_mw);}setPosition(0,0);}if(_xh&&ih>=_xh){setHeight(_xh);setPosition(1,1);}else{if(ih>_mh&&(ih<_xh||!_xh)){setHeight("100%");}else{setHeight(_mh);}setPosition(1,0);}forceRedraw();}function setPosition(t,x){var p,m;if(t){p=(x&&_vc)?"50%":"auto";m=(x&&_vc)?-(_xh*0.5)+"px":0;setStyle("top",p);setStyle("marginTop",m);}else{p=(x&&_hc)?"50%":"auto";m=(x&&_hc)?-(_xw*0.5)+"px":0;setStyle("left",p);setStyle("marginLeft",m);}}function controlScroll(s,v){var p=(v)?"overflowY":"overflowX";html.style[p]=(s)?"scroll":"auto";}function getValueOf(p){var o={target:_t,minWid:_mw,minHei:_mh,maxWid:_xw,maxHei:_xh,hCenter:_hc,vCenter:_vc};return o[p];}return{fit:fit,configure:configure,startFit:startFit,stopFit:stopFit,getValueOf:getValueOf,addResizeEvent:function(fn){controlResizeEvent(1,fn);},removeResizeEvent:function(fn){controlResizeEvent(0,fn);},showScrollH:function(){controlScroll(1,0);},showScrollV:function(){controlScroll(1,1);}};}();
/**/
$(document).ready(function() {
	$('div.choice', '#nav-lang').hide();
	$('div.title', '#nav-lang').click(function(){
		$('#nav-lang').toggleClass("opened");
		$("div.choice", '#nav-lang').toggle();
	});
});
/**/

$(document).ready(function() {
	/**/
	$("div.item:has(a), div.work:has(a), div.bonus:has(a), div.piece:has(a), div.full-movie:has(a), div.teaser:has(a), div.ticket-row:has(a)").hover(
		function () {
			$(this).addClass("hover");
		},
		function () {
			$(this).removeClass("hover");
		}
		);

	/**/
	var resultsDivs = $('#results');
	if(resultsDivs.length>0){
		$(resultsDivs).find('div.item:has(a)').live('mouseenter', function (event) {
			$(this).addClass("hover");
		});
		$(resultsDivs).find('div.item:has(a)').live('mouseleave', function (event) {
			$(this).removeClass("hover");
		});
	}

	/**/
	/**/
	$("div.item:has(a), div.work:has(a), div.bonus:has(a), div.full-movie:has(a), div.piece:has(a), div.teaser:has(a), div.ticket-row:has(a)").live('click',function(event){
		if($(this).find('a.ticketactivation').length==0){
			window.location.href = $(this).find("a.button").eq(0).attr("href");
			event.preventDefault();
		}
	});
});
$(document).ready(function(){

	//Hide (Collapse) the toggle containers on load
	$(".toggle .content").width($(".toggle .content").outerWidth());
	$(".toggle .content").hide();
	
	//Make the header closed
	$(".toggle").addClass("closed");

	//Switch the "Open" and "Close" state per click
	$(".toggle .head").toggle(function(){
			$(this).closest(".toggle").removeClass("closed").addClass("opened");
		}, function () {
		$(this).closest(".toggle").removeClass("opened").addClass("closed");
	});

	//Slide up and down on click
	$(".toggle .head").click(function(){
		$(this).next(".toggle .content").slideToggle('slow');
	});

});
$(document).ready(function(){

	/* Tooltips */
	$("div.tooltip div.tooltip-button").hover(
		function () {
			$(this).next("div.tooltip-t").fadeIn("fast");
		},
		function () {
			$(this).next("div.tooltip-t").fadeOut("fast");
		}
		);

});/**/
$(document).ready(function() {
	$(".nav-content-drop").addClass("closed").bind('click', function(event){
		$(this).toggleClass("closed").toggleClass("opened");
		event.preventDefault();
	});
});
	/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4265 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
	
		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 93 2010-06-01 08:17:28Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *								topCapHeight	-	The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *								bottomCapHeight	-	The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 *								observeHash		-	Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			var paneEle = this;
			var currentScrollPosition = 0;
			var paneWidth;
			var paneHeight;
			var trackHeight;
			var trackOffset = settings.topCapHeight;
			var $container;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				$container = $(this).parent();
				currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				paneWidth = $c.innerWidth();
				paneHeight = $c.outerHeight();
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
				$this.css({'top':0});
			} else {
				$this.data('originalStyleTag', $this.attr('style'));
				// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
				$this.css('overflow', 'hidden');
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				paneWidth = $this.innerWidth();
				paneHeight = $this.innerHeight();
				$container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				$this.wrap($container);
				$container = $this.parent();
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			trackHeight = paneHeight;
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;
			
			var isScrollable = percentInView < .99;
			$container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable');

			if (isScrollable) {
				$container.append(
					$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					),
					$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowUp', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'top':settings.topCapHeight + 'px'
									}
								)
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowDown', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'bottom':settings.bottomCapHeight + 'px'
									}
								)
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
				}
				
				if (settings.arrowSize) {
					trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
					trackOffset += settings.arrowSize;
				} else if ($upArrow) {
					var topArrowHeight = $upArrow.height();
					settings.arrowSize = topArrowHeight;
					trackHeight = paneHeight - topArrowHeight - $downArrow.height();
					trackOffset += topArrowHeight;
				}
				trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
				$track.css({'height': trackHeight+'px', top:trackOffset+'px'})
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll).bind('mouseleave', onStopDrag)
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					$container.scrollTop(0);
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
						// errors from the lookup...
						try {
							$e = $(pos, $this);
						} catch (err) {
							return;
						}
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						$container.scrollTop(0);
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						var preventInfiniteLoop = 100;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
							if (!preventInfiniteLoop--) {
								return;
							}
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (settings.observeHash) {
					if (location.hash && location.hash.length > 1) {
						setTimeout(function(){
							scrollTo(location.hash);
						}, $.browser.safari ? 100 : 0);
					}
					
					// use event delegation to listen for all clicks on links and hijack them if they are links to
					// anchors within our content...
					$(document).bind('click', function(e){
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function(){
									scrollTo(h, !settings.animateToInternalLinks);
								}, $.browser.safari ? 100 : 0);
							}
						}
					});
				}
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$this.attr('style', $this.data('originalStyleTag'));
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	topCapHeight: 0,
	bottomCapHeight: 0,
	observeHash: true
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);/**/
/**/

/**/
var view = 'dks';
var viewLevels = view.split('');
/**/
var d = null;
var k = null;
var s = null;
/**/
var resultsOrder = 'desc';
var resultsFrom = 0;
var resultsLimit = 20;

/**/
var filterHeadingArray = new Array();
filterHeadingArray['d'] = dchjslanguage_labels_filter_choice_conductor;
filterHeadingArray['k'] = dchjslanguage_labels_filter_choice_composer;
filterHeadingArray['s'] = dchjslanguage_labels_filter_choice_soloist;

/**/
if(typeof characterHellip == 'undefined') {
	var characterHellip = String.fromCharCode(8230);
}

/**/
var filterCookieName = 'dch_archivefilter';
/**/
var filterCookieOptions = { path: '/', domain: dch_cookie_domain };

var filterScaffold = '';
filterScaffold+= '<div class="choice-1"><div class="selection"></div><div class="options"><ul id="choicelist-1"></ul></div></div>';
filterScaffold+= '<div class="choice-2" style="display:none;"><div class="selection"></div><div class="options"><ul id="choicelist-2"></ul></div></div>';
filterScaffold+= '<div class="choice-3" style="display:none;"><div class="selection"></div><div class="options"><ul id="choicelist-3"></ul></div></div>';

/**/
var givenFilterParameters = new Array();

/**/
var filterCacheAllConcerts = null;
var filterCacheConductorList = null;
var filterCacheComposerList = null;
var filterCacheSoloistList = null;

/**/
function initButtons() {

/**/
$('body.archive #conductors').bind('click',function(){adaptView('d');initFilter('d');});
$('body.archive #composers').bind('click',function(){adaptView('k');initFilter('k');});
$('body.archive #soloists').bind('click',function(){adaptView('s');initFilter('s');});

$('body.archive .new-search a').bind('click', resetAllFilters, false);

}


/**/

$(document).ready(function() {

/**/
if($('body.archive.list').length>0) {

	filterCacheAllConcerts = $('#results').html();

	if(BrowserDetect.browser != "Explorer"){
		/**/
		$('img', '#results').lazyload();
		/**/
		$('div.item', '#results').lazydisplay();
	}

	/**/
	initButtons();

	/**/
	/**/

	/**/
	$('div.sort a', '#functions').bind('click', function(event){
		/**/
		if($(this).is('.up')) {
			resultsOrder = 'desc';
			$(this).hide();
			$('.sort .down', '#functions').show();
		} else {
			resultsOrder = 'asc';
			$(this).hide();
			$('.sort .up', '#functions').show();
		}
		updateResults();
		event.preventDefault();
	})
}

});
/**/



/**/
function initFilter(selectedFilter) {

	/**/
	var setFiltersClass = '';
	if(selectedFilter=='d'){
		setFiltersClass = 'conductors';
	} else if(selectedFilter=='k'){
		setFiltersClass = 'composers';
	} else if(selectedFilter=='s'){
		setFiltersClass = 'soloists';
	}
	$('#choices').removeClass().addClass(setFiltersClass);



	// Interface für Filter einblenden
	$('div.choice-all').empty().append(filterScaffold);

	/**/
	$('div.choice-1 div.selection').text(filterHeadingArray[selectedFilter]);

	/**/
	$('#choicelist-1').before('<span class="ajax-loader"></span>');

	/**/
	if(d!=null || k!=null || s!=null){
		// {d|k|s} zurücksetzen, für die Ajax-Requests
		d = null;
		k = null;
		s = null;
		updateResults();
	}

	fillFilter(1);

}


/**/
function updateFilter(e) {

	var thisFilterId = e.target.id;
	var thisFilterIdElements = thisFilterId.split("-");
	var thisFilterLevel = parseInt(thisFilterIdElements[1]);

	/**/
	eval(viewLevels[thisFilterLevel-1] + '="' + $('#'+thisFilterId).data('fullName') + '";');

	e.preventDefault();
	e.stopPropagation();

	/**/
	if(thisFilterLevel==1) {
		removeFilter(3);
	}

	/**/
	$('div.choice-'+thisFilterLevel).addClass('selected');

	/**/
	$('#choicelist-'+thisFilterLevel+' li').removeClass('active');
	$('#'+thisFilterId).addClass('active');

	// Überschrift für aktuelle Filterspalte setzten, Schließen-Link dazutun, und ihr den resetFilter() Event zuweisen
	var filterHeadlineName = $('#'+thisFilterId).data('fullName');
	var filterHeadlineFullName = filterHeadlineName;
	if(filterHeadlineName.length>18) {
		filterHeadlineName = jQuery.trim(filterHeadlineName.substring(0,17))+characterHellip;
	}
	$('div.choice-'+thisFilterLevel+' div.selection').text(filterHeadlineName).attr('title', filterHeadlineFullName).after('<div class="selection-delete"><span class="alt">x</span></div>');
	$('div.choice-'+thisFilterLevel+' div.selection-delete').one('click', function(){resetFilter(thisFilterLevel);});

	/**/
	if(thisFilterLevel<3) {

		var nextFilterLevel = parseInt(thisFilterLevel+1);
		var nextFilterId = parseInt(thisFilterIdElements[3]);

		/**/
		removeFilter(nextFilterLevel);
		$('div.choice-'+nextFilterLevel).css('display', 'block');
		$('#choicelist-'+nextFilterLevel).empty().before('<span class="ajax-loader"></span>');

		// Überschrift über nächsten Filter setzen (thisFilterLevel, weil viewLevels[] bei 0 beginnt)
		$('div.choice-'+nextFilterLevel+' div.selection').text(filterHeadingArray[viewLevels[thisFilterLevel]]);
		fillFilter(nextFilterLevel)
	} else {
		// ansonsten (für Klick auf Spalte 3) die nächste Filterstufe anschubsen,
		// damit der Server vom gewählten Filter weiß (und ihn bei der Rückkehr
		// zu den Suchergebnissen berücksichtigen kann)
		// -> ni9cht mehr nötig, wegen Einsatz von Cookies zu diesem Zweck
		//$.getJSON(createRequestUrl('filterlist'));
	}

	updateResults();
}


function injectFilterIntoPage(level, data, callbackFunction){

	$('div.choice-'+level+' .ajax-loader').remove();

	$.each(data.items, function(i,item){

		var itemName = item.label;
		if(item.label.length>21) {
			itemName = jQuery.trim(item.label.substring(0,20))+characterHellip;
		}

		/**/
		if(item.label=='Sir Simon Rattle') {
			if(data.count>1){
				$('<li>').attr('class', 'description').text(dchjslanguage_labels_guestconductor).prependTo('#choicelist-'+level);
			}
			$('<li>').attr('id', 'filter-'+level+'-option-'+i).attr('title', item.label).text(itemName+' ('+item.results+')').prependTo('#choicelist-'+level);
			$('<li>').attr('class', 'description').text(dchjslanguage_labels_chiefconductor).prependTo('#choicelist-'+level);
		}
		/**/
		else if(item.label=='Berliner Philharmoniker') {
			// ignore
		}
		else {
			$('<li>').attr('id', 'filter-'+level+'-option-'+i).attr('title', item.label).text(itemName+' ('+item.results+')').appendTo('#choicelist-'+level);
		}

		// Originalen langen Namen und Ergebnisanzahl mit beim Listenelement abspeichern. Wird später für die Requests gebraucht.
		$('#filter-'+level+'-option-'+i).data('fullName', item.label);
		$('#filter-'+level+'-option-'+i).data('results', item.results);
	});

	// Events für Listenelemente anlegen: updateFilter()
	$('#choicelist-'+level).bind('click', updateFilter, false);

	/**/
	$('div.choice-'+level+' .options').jScrollPane({showArrows:false, scrollbarWidth:5});


	/**/
	if(callbackFunction=='callbackActivateSelection')
	{
		eval('var selectedParam = '+viewLevels[level-1]+';');
		$('#choicelist-'+level+' li:contains('+selectedParam+')').addClass('active');
	}
	
}

/**/
function fillFilter(level, callbackFunction) {

	/**/
	if(level==1){
		var cachedFilterData = null;
		if(viewLevels[level-1]=='d' && filterCacheConductorList!=null){
			cachedFilterData = filterCacheConductorList;
		}else if(viewLevels[level-1]=='k' && filterCacheComposerList!=null){
			cachedFilterData = filterCacheComposerList;
		}else if(viewLevels[level-1]=='s' && filterCacheSoloistList!=null){
			cachedFilterData = filterCacheSoloistList;
		}else{
			// ignore
		}

		if(cachedFilterData!=null){
			injectFilterIntoPage(level, cachedFilterData, callbackFunction);
			return;
		}
	}

	/**/
	$.getJSON(createRequestUrl('filterlist'), function(data) {
		
		if(level==1){
			var cachedFilterData = null;
			if(viewLevels[level-1]=='d'){
				filterCacheConductorList = data;
			}else if(viewLevels[level-1]=='k'){
				filterCacheComposerList= data;
			}else if(viewLevels[level-1]=='s'){
				filterCacheSoloistList = data;
			}else{
				// ignore
			}
		}
		
		injectFilterIntoPage(level, data, callbackFunction);
	});
}



/**/
function removeFilter(level) {
	if(level<=3) {
		$('div.choice-'+level).removeClass('selected');
		$('div.choice-'+level).css('display', 'none');
		$('div.choice-'+level+' div.selection').empty();
		$('div.choice-'+level+' div.selection-delete').remove();
		$('#choicelist-'+level).empty();
		eval(viewLevels[level-1]+'=null;');
		$('#choicelist-'+level).unbind('click', updateFilter);
	}
}

/**/
function resetFilter(level) {
	/**/
	if(level==3) {
		// {d|k|s} zurücksetzen, für die Ajax-Requests
		eval(viewLevels[2]+'=null;');
	}
	if(level==2) {
		removeFilter(3);
		// {d|k|s} zurücksetzen, für die Ajax-Requests
		eval(viewLevels[2]+'=null;');
		eval(viewLevels[1]+'=null;');
	}
	if(level==1) {
		removeFilter(3);
		removeFilter(2);
		// {d|k|s} zurücksetzen, für die Ajax-Requests
		d = null;
		k = null;
		s = null;
	}

	/**/
	updateResults();
	
	/**/
	$('div.choice-'+level).removeClass('selected');
	$('#choicelist-'+level+' li').removeClass('active');
	$('div.choice-'+level+' div.selection-delete').remove();
	$('div.choice-'+level+' div.selection').text(filterHeadingArray[viewLevels[level-1]]);
}


function resetAllFilters(e) {

	e.preventDefault();
	e.stopPropagation();

	selectedFilter = '';

	// {d|k|s} zurücksetzen, für die Ajax-Requests
	d = null;
	k = null;
	s = null;

	/**/

	// Hauptfilter zur�cksetzen
	$('#choices').removeClass();
	// Filter löschen
	$('div.choice-all').empty();

	updateResults();

}


function adaptView(newView) {
	if(newView=='d') {
		view='dks';
	} else if(newView=='k') {
		view='kds';
	} else if(newView=='s') {
		view='sdk';
	}
	else {
		view='dks';
	}

	viewLevels = view.split('');
}

/**/
function polishResultsAfterCacheUpdate() {

	/**/
	var resultsCount = $('#results').children().length;
	if(resultsCount==1)
	{
		$('div.result-numbers', '#functions').html('<span class="number">1</span> '+dchjslanguage_labels_concert);
	} else {
		$('div.result-numbers', '#functions').html('<span class="number">'+resultsCount+'</span> '+dchjslanguage_labels_concerts);
	}

	/**/
	if(s!=null) {
		$('div.head div.stars:contains('+s+')').addClass('result').parents('#results').addClass('highlight');
		$('div.work:contains('+s+')').addClass('result').parents('#results').addClass('highlight');
		$('div.bonus:contains('+s+')').addClass('result').parents('#results').addClass('highlight');
	}

	/**/
	if(k!=null) {
		$('div.work:contains('+k+')').addClass('result').parents('#results').addClass('highlight');
		$('div.bonus:contains('+k+')').addClass('result').parents('#results').addClass('highlight');
	}

	if(resultsCount>10) {
		if(BrowserDetect.browser != "Explorer"){
			$('img', '#results').lazyload();
			$('div.item', '#results').lazydisplay();
		}
	}
}

/**/
function updateResults() {

	/**/
	/**/

	/**/
	if(view=='dks' && (d==''||d==null) && (k==''||k==null) && (s==''||s==null) && resultsOrder=='desc'){	
		$('#results').removeClass('highlight').html(filterCacheAllConcerts);
		polishResultsAfterCacheUpdate();
		return;
	}

	/**/
	$('#results').fadeTo(150, 0.1);
	
	$.ajax({
		url:      createRequestUrl('results'),
	    dataType: 'html',

	    success: function(data, status, request) {

			$('#results').removeClass('highlight').html(data).fadeTo(150, 1);

			/**/
			var resultsCount = $('#results').children().length;
			if(resultsCount==1)
			{
				$('div.result-numbers', '#functions').html('<span class="number">1</span> '+dchjslanguage_labels_concert);
			} else {
				$('div.result-numbers', '#functions').html('<span class="number">'+resultsCount+'</span> '+dchjslanguage_labels_concerts);
			}

			/**/
			if(s!=null) {
				$('div.head div.stars:contains('+s+')').addClass('result').parents('#results').addClass('highlight');
				$('div.work:contains('+s+')').addClass('result').parents('#results').addClass('highlight');
				$('div.bonus:contains('+s+')').addClass('result').parents('#results').addClass('highlight');
			}

			/**/
			if(k!=null) {
				$('div.work:contains('+k+')').addClass('result').parents('#results').addClass('highlight');
				$('div.bonus:contains('+k+')').addClass('result').parents('#results').addClass('highlight');
			}

			if(resultsCount>10) {
				if(BrowserDetect.browser != "Explorer"){
					$('img', '#results').lazyload();
					$('div.item', '#results').lazydisplay();
				}
			}

	    }
	});

}

/**/
function createRequestUrl(type) {

	var requestUrl = '';

	if(type=='filterlist') {
		requestUrl = filterPath + '?';
	} else if(type=='results') {
		requestUrl = listPath + '?';
	}

	/**/
	var paramsSet = 0;
	if(d!=null) {
		++paramsSet;
		requestUrl+= 'd=' + d + '&';
	}
	if(k!=null) {
		++paramsSet;
		requestUrl+= 'k=' + k + '&';
	}
	if(s!=null) {
		++paramsSet;
		requestUrl+= 's=' + s + '&';
	}

	/**/
	if(type=='results') {
		requestUrl+= 'sortby=date-'+resultsOrder+'&';
	}

	if(type=='filterlist') {
		requestUrl+= 'view=' + viewLevels[paramsSet];
		requestUrl+= '&order=' + view;
	}

	/**/
	var lastChar = requestUrl.substr(requestUrl.length-1, 1);
	if(lastChar=='?' || lastChar=='&') {
		requestUrl = requestUrl.substr(0, requestUrl.length-1);
	}

	return encodeURI(requestUrl);
}

/**/
function restoreFilter(paramArray) {
	 /**/
	if(typeof paramArray['view'] != 'undefined') {
		adaptView(paramArray['view'].charAt(0));
	}

	/**/

	/**/
	var setFiltersClass = '';
	if(viewLevels[0]=='d'){
		setFiltersClass = 'conductors';
	} else if(viewLevels[0]=='k'){
		setFiltersClass = 'composers';
	} else if(viewLevels[0]=='s'){
		setFiltersClass = 'soloists';
	}
	$('#choices').removeClass().addClass(setFiltersClass);
	$('div.choice-all').empty().append(filterScaffold);

	/**/
	activateFilterElement(1);

	/**/
	if(typeof paramArray[viewLevels[0]] != 'undefined' && paramArray[viewLevels[0]] != null && paramArray[viewLevels[0]] != 'null') {
		// d = paramArray['d'] // oder k, oder s
		eval(viewLevels[0]+' = \''+paramArray[viewLevels[0]]+'\'');
		// "geklickten" Filter als 'selected' setzen und seine Titelzeile einsetzen
		$('div.choice-1').addClass('selected');

		// Überschrift für aktuelle Filterspalte setzten, Schließen-Link dazutun, und ihr den resetFilter() Event zuweisen
		filterHeadlineName = paramArray[viewLevels[0]];
		if(filterHeadlineName.length>18) {
			filterHeadlineName = jQuery.trim(filterHeadlineName.substring(0,17))+characterHellip;
		}

		$('div.choice-1 div.selection').text(filterHeadlineName).after('<div class="selection-delete"><span class="alt">x</span></div>');
		$('div.choice-1 div.selection-delete').one('click', function(){resetFilter(1);});
		// Inhalt in den zweiten Filter laden
		activateFilterElement(2);
	}

	/**/
	if(typeof paramArray[viewLevels[1]] != 'undefined' && paramArray[viewLevels[1]] != null && paramArray[viewLevels[1]] != 'null') {
		// d = paramArray['d'] // oder k, oder s
		eval(viewLevels[1]+' = \''+paramArray[viewLevels[1]]+'\'');
		// "geklickten" Filter als 'selected' setzen und seine Titelzeile einsetzen
		$('div.choice-2').addClass('selected');

		// Überschrift für aktuelle Filterspalte setzten, Schließen-Link dazutun, und ihr den resetFilter() Event zuweisen
		filterHeadlineName = paramArray[viewLevels[1]];
		if(filterHeadlineName.length>18) {
			filterHeadlineName = jQuery.trim(filterHeadlineName.substring(0,17))+characterHellip;
		}

		$('div.choice-2 div.selection').text(filterHeadlineName).after('<div class="selection-delete"><span class="alt">x</span></div>');
		$('div.choice-2 div.selection-delete').one('click', function(){resetFilter(2);});
		// Inhalt in den dritten Filter laden
		activateFilterElement(3);
	}

	/**/
	if(typeof paramArray[viewLevels[2]] != 'undefined' && paramArray[viewLevels[2]] != null && paramArray[viewLevels[2]] != 'null') {
		// d = paramArray['d'] // oder k, oder s
		eval(viewLevels[2]+' = \''+paramArray[viewLevels[2]]+'\'');
		// "geklickten" Filter als 'selected' setzen und seine Titelzeile einsetzen
		$('div.choice-3').addClass('selected');

		// Überschrift für aktuelle Filterspalte setzten, Schließen-Link dazutun, und ihr den resetFilter() Event zuweisen
		filterHeadlineName = paramArray[viewLevels[2]];
		if(filterHeadlineName.length>18) {
			filterHeadlineName = jQuery.trim(filterHeadlineName.substring(0,17))+characterHellip;
		}

		$('div.choice-3 div.selection').text(filterHeadlineName).after('<div class="selection-delete"><span class="alt">x</span></div>');
		$('div.choice-3 div.selection-delete').one('click', function(){resetFilter(3);});
	}
	updateResults();
}


/**/
function activateFilterElement(level) {
	/**/
	$('div.choice-'+level).css('display', 'block');
	$('div.choice-'+level+' div.selection').text(filterHeadingArray[viewLevels[level-1]]);
	$('#choicelist-'+level).before('<span class="ajax-loader"></span>');

	/**/
	fillFilter(level, 'callbackActivateSelection');
}/**/
$(document).ready(function() {

/**/
if($('body.detail').length>0) {

/**/

/**/

	$('#infos').tabs();

}
});/**/
/**/

	/**/
	/**/
	var liveticker_verbleibendeZeit;
	var runningTimer;

	/**/
	function liveticker(){
		liveticker_verbleibendeZeit--;

		/**/
		if (liveticker_verbleibendeZeit > 0) {

			var tage = Math.floor(liveticker_verbleibendeZeit / (60*60*24));
			var stunden = Math.floor((liveticker_verbleibendeZeit-(tage*60*60*24)) / (60*60));
			var minuten = Math.floor((liveticker_verbleibendeZeit-(tage*60*60*24+stunden*60*60)) / 60);
			var sekunden = liveticker_verbleibendeZeit % 60;
			$('span.liveticker').html(dchjslanguage_labels_liveticker_prefix + ' ' + tage + dchjslanguage_labels_liveticker_day + ":" + stunden + dchjslanguage_labels_liveticker_hour + ":" + minuten + dchjslanguage_labels_liveticker_minute + ":" + sekunden + dchjslanguage_labels_liveticker_second);

			/**/
			$('.full-concert').find('a.button.watch-concert.play').hide();
			$('.full-concert').find('a.button.watch-concert.purchase').hide();
		} else {
			$('span.liveticker').html('<div>'+dchjslanguage_labels_liveticker_livenow + '</div>');
			/**/
			$('.full-concert').find('a.button.watch-concert.play').show();
			$('.full-concert').find('a.button.watch-concert.purchase').show();
		} 
		runningTimer = setTimeout('liveticker()',1000);
	}

/**/
$(document).ready(function() {
/**/
if($('span.liveticker').length>0) {

	/**/
	liveticker_verbleibendeZeit=$('span.liveticker').text();
	/**/
	liveticker_verbleibendeZeit = liveticker_verbleibendeZeit-900
	liveticker();
	$('span.liveticker').show();
}
});
/**/

/**/

$(document).ready(function() {
if($('a.pagefade').length) {
	/**/
	$('body').prepend('<div id="pagefade-overlay" style="position:absolute;width:100%;height:100%;z-index:9999;background-color:#000;display:none;"></div>');

/**/
$('a.pagefade').bind('click', function(event){
		var targetLink = $(this).attr("href");
		$('object').remove();
		$('#pagefade-overlay').height($(document).height()).fadeIn(2000, function(){
			window.location = targetLink;
		});
		return false;
	})
}
});/**/

$(document).ready(function() {
/**/
if($('#live-list-months').length) {
	
/**/
$('#live-list-months .options ul li a').bind('click', function(event){

	/**/
	event.preventDefault();
	event.stopPropagation();

	/**/
	$('#live-list-months div.selected').text($(this).text());
	$('#live-list-months').toggleClass("closed").toggleClass("opened");

	/**/
	$('#live-list-months .options ul li').removeClass('act');
	$(this).parent().addClass('act');

	var resultsCount = 0;
	/**/
	var searchTerm = $(this).attr('href');
	if(searchTerm=='all') {
		resultsCount = $('#results div.item').show().length;
	} else {
		$('#results div.item').hide();
		var searchTermClass = '#results div.item.'+searchTerm;
		resultsCount = $(searchTermClass).show().length;
	}

	if(resultsCount==1){
		$('#functions .result-numbers').empty().append('<span class="number">1</span> '+dchjslanguage_labels_concert);
	} else {
		$('#functions .result-numbers').empty().append('<span class="number">'+resultsCount+'</span> '+dchjslanguage_labels_concerts);
	}

});

}
});
/**/

/**/
function bindFavoriteAction() {

$('.actions .favorite a').bind('click', function (event) {

		event.preventDefault();
		event.stopPropagation();

		var favoriteAction = '';
		/**/
		var favoriteLinkReference = $(this);
		if ($(this).hasClass("remove")) {
			var unsetFavUrl = favoriteSetPath+'?product_id='+$(this).parents('.work, .bonus').attr('id')+'&remove=true';
			$.getJSON(unsetFavUrl, function(data) {
				if(data.success){
					favoriteLinkReference.removeClass('remove').addClass('add').html(dchjslanguage_labels_favorite_add);
				}
			});
		} else {
			var setFavUrl = favoriteSetPath+'?product_id='+$(this).parents('.work, .bonus').attr('id');
			$.getJSON(setFavUrl, function(data) {
				if(data.success){
					favoriteLinkReference.removeClass('add').addClass('remove').html(dchjslanguage_labels_favorite_remove);
				}
			});
		}

	}, false);
}

/**/
function bindFavoriteRemoveAction() {
	 $('.favorites a.remove').bind('click', function(event){

		event.preventDefault();
		event.stopPropagation();

		var favoriteElement = $(this).parents('div.item:eq(0)');
		var unsetFavUrl = favoriteSetPath+'?product_id='+$(favoriteElement).attr('id')+'&remove=true';
		$.getJSON(unsetFavUrl, function(data) {
			if(data.success){
				favoriteElement.slideUp();
				var result_numbers;
				$result_numbers = $('.result-numbers .number').text();
				if (!isNaN($result_numbers)){
					$('.result-numbers .number').text($result_numbers - 1);
				}
			}
		});
	 });
}

/**/
function updateAllFavorites() {
		$.getJSON(favoriteGetPath, function(data) {
			$.each(data.favourites, function(i,item){
				var pieceSelectorId = '#'+item+' .actions .favorite a';
				$(pieceSelectorId).removeClass('add').addClass('remove').text(dchjslanguage_labels_favorite_remove);
			});
		bindFavoriteAction();

		});
}

$(document).ready(function() {
/**/
if($('.actions .favorite').length) {
	updateAllFavorites();
	bindFavoriteRemoveAction();
}
});/**/
$(document).ready(function() {

/**/
if($('a.ticketactivation').length>0) {

	$(".item:has(.ticketactivation), .full-concert:has(.ticketactivation), .work:has(.ticketactivation), .bonus:has(.ticketactivation), .full-movie:has(.ticketactivation), .piece:has(.ticketactivation), .teaser:has(.ticketactivation), .ticket-row:has(.ticketactivation)").live('click',function(event){

		event.preventDefault();
		event.stopPropagation();

		var linkToConcerthall = $(this).find('a.ticketactivation').attr('href');

		/**/
		activationMessage = '';
		if($('body.archive').length>0){
			activationMessage = '<div id="status-overlay"><div id="status" class="alert ticketactivation-archive"><div class="rc-t"><div class="rc-b"><div class="rc-c">';
			activationMessage+= '<div class="head">'+dchjslanguage_labels_ticketactivation_archive_status_head+'</div>';
			activationMessage+= '<div class="content"><div class="description"><p>'+dchjslanguage_labels_ticketactivation_archive_status_descr+'</p>';
			activationMessage+= '<div class="buttons"><a class="cancel" href="#">'+dchjslanguage_labels_ticketactivation_archive_status_cancel+'</a><a class="button confirm" href="#"><span class="button-rc-l"><span class="button-rc-r"><span class="button-rc-c">'+dchjslanguage_labels_ticketactivation_special_status_confirm+'</span></span></span></a>';
			activationMessage+= '</div></div></div></div></div></div></div></div>';
		} else if($('body.account').length>0){
			activationMessage = '<div id="status-overlay"><div id="status" class="alert ticketactivation-archive"><div class="rc-t"><div class="rc-b"><div class="rc-c">';
			activationMessage+= '<div class="head">'+dchjslanguage_labels_ticketactivation_archive_status_head+'</div>';
			activationMessage+= '<div class="content"><div class="description"><p>'+dchjslanguage_labels_ticketactivation_archive_status_descr+'</p>';
			activationMessage+= '<div class="buttons"><a class="cancel" href="#">'+dchjslanguage_labels_ticketactivation_archive_status_cancel+'</a><a class="button confirm" href="#"><span class="button-rc-l"><span class="button-rc-r"><span class="button-rc-c">'+dchjslanguage_labels_ticketactivation_special_status_confirm+'</span></span></span></a>';
			activationMessage+= '</div></div></div></div></div></div></div></div>';
		} else if($('body.live').length>0) {
			activationMessage = '<div id="status-overlay"><div id="status" class="alert ticketactivation-live"><div class="rc-t"><div class="rc-b"><div class="rc-c">';
			activationMessage+= '<div class="head">'+dchjslanguage_labels_ticketactivation_live_status_head+'</div>';
			activationMessage+= '<div class="content"><div class="description"><p>'+dchjslanguage_labels_ticketactivation_live_status_descr+'</p>';
			activationMessage+= '<div class="buttons"><a class="cancel" href="#">'+dchjslanguage_labels_ticketactivation_live_status_cancel+'</a><a class="button confirm" href="#"><span class="button-rc-l"><span class="button-rc-r"><span class="button-rc-c">'+dchjslanguage_labels_ticketactivation_special_status_confirm+'</span></span></span></a>';
			activationMessage+= '</div></div></div></div></div></div></div></div>';
		} else if($('body.specials').length>0) {
			activationMessage = '<div id="status-overlay"><div id="status" class="alert ticketactivation-special"><div class="rc-t"><div class="rc-b"><div class="rc-c">';
			activationMessage+= '<div class="head">'+dchjslanguage_labels_ticketactivation_special_status_head+'</div>';
			activationMessage+= '<div class="content"><div class="description"><p>'+dchjslanguage_labels_ticketactivation_special_status_descr+'</p>';
			activationMessage+= '<div class="buttons"><a class="cancel" href="#">'+dchjslanguage_labels_ticketactivation_special_status_cancel+'</a><a class="button confirm" href="#"><span class="button-rc-l"><span class="button-rc-r"><span class="button-rc-c">'+dchjslanguage_labels_ticketactivation_special_status_confirm+'</span></span></span></a>';
			activationMessage+= '</div></div></div></div></div></div></div></div>';
		} else {
			activationMessage = '<div id="status-overlay"><div id="status" class="alert ticketactivation-archive"><div class="rc-t"><div class="rc-b"><div class="rc-c">';
			activationMessage+= '<div class="head">'+dchjslanguage_labels_ticketactivation_archive_status_head+'</div>';
			activationMessage+= '<div class="content"><div class="description"><p>'+dchjslanguage_labels_ticketactivation_archive_status_descr+'</p>';
			activationMessage+= '<div class="buttons"><a class="cancel" href="#">'+dchjslanguage_labels_ticketactivation_archive_status_cancel+'</a><a class="button confirm" href="#"><span class="button-rc-l"><span class="button-rc-r"><span class="button-rc-c">'+dchjslanguage_labels_ticketactivation_special_status_confirm+'</span></span></span></a>';
			activationMessage+= '</div></div></div></div></div></div></div></div>';
		}


		/**/
		$('object').hide();

		$('body').append(activationMessage);
		
		$('#pagebody, #meta, #footer, #nav-horiz-wrapper').fadeOut();

		$('#status-overlay').find('a.confirm').one('click', function(event){
			event.preventDefault();
			event.stopPropagation();
			$(this).replaceWith('<span class="ajax-loader"></span>');

			$('body').prepend('<div id="pagefade-overlay" style="position:absolute;width:100%;height:100%;z-index:9999;background-color:#000;display:none;"></div>');
			$('#pagefade-overlay').height($(document).height()).fadeIn(2000, function(){
				window.location = linkToConcerthall;
			});
			
		});
		$('#status-overlay').find('a.cancel').one('click', function(event){
			event.preventDefault();
			event.stopPropagation();
			$('#pagebody, #meta, #footer, #nav-horiz-wrapper').fadeIn();
			$('#status-overlay').remove(); $('object').show();
		});

	});

}
});/**/
$(document).ready(function(){


/**/
if($('body.account').length>0) {

/**/
	$(".user-data div.form, .recommend div.form").hide();


/**/
	$('.user-data .password .edit, .user-data .timezone .edit, .user-data .timeformat .edit').bind('click', function(event){
		event.preventDefault();
		$(this).parent().find('div.accent').remove(); // Bestätigungsmeldung vom letzzten Senden
		$(this).parent().next("div.form").show();
		$(this).hide();
	});


/**/
	$('.user-data .data .edit, .user-data .newsletter .edit, .recommend .edit').bind('click', function(event){
		event.preventDefault();
		$(this).parent().find('div.accent').remove(); // Bestätigungsmeldung vom letzzten Senden
		$(this).parent().next("div.form").show();
		$(this).hide();

		/**/
		$(this).parent().parent().find('input').each(function(i, item){
			jQuery.data(item, 'savedValue', $(item).val());
		});
		$(this).parent().parent().find('textarea').each(function(i, item){
			jQuery.data(item, 'savedValue', $(item).val());
		});
		$(this).parent().parent().find('select option:selected').each(function(i, item){
			jQuery.data(item, 'savedValue', 'selected');
		});
		$(this).parent().parent().find('input:checkbox:checked').each(function(i, item){
			jQuery.data(item, 'savedValue', 'checked');
		});
		$(this).parent().parent().find('input:radio:checked').each(function(i, item){
			jQuery.data(item, 'savedValue', 'checked');
		});

		/**/
	});

/**/
	$('.user-data .password .cancel, .user-data .timezone .cancel, .timeformat .cancel').bind('click', function(event){
		event.preventDefault();
		$(this).parents('div.form').hide();
		$(this).parents('div.form').parent().find('span.edit').show();
		
		/**/
		$(this).parents('form').find('span.error').remove();
		$(this).parents('form').find('div.row.error').removeClass('error');
});

/**/
	$('.user-data .data .cancel, .user-data .newsletter .cancel, .recommend .cancel').bind('click', function(event){
		event.preventDefault();
		$(this).parents('div.form').hide();
		$(this).parents('div.form').parent().find('span.edit').show();

		/**/
		$(this).parents('form').find('input').each(function(i, item){
			if($(item).attr('id')!='token') {
				$(item).val(jQuery.data(item, 'savedValue'));
			}
		});
		$(this).parents('form').find('textarea').each(function(i, item){
			$(item).val(jQuery.data(item, 'savedValue'));
		});
		$(this).parents('form').find('select option').each(function(i, item){
			if(jQuery.data(item, 'savedValue')=='selected'){
				$(item).attr('selected', 'selected');
				jQuery.data(item, 'savedValue', '');
			} else {
				$(item).attr('selected', false);
			}
		});
		$(this).parents('form').find('input:checkbox').each(function(i, item){
			if(jQuery.data(item, 'savedValue')=='checked'){
				$(item).attr('checked', 'checked');
				jQuery.data(item, 'savedValue', '');
			} else {
				$(item).attr('checked', false);
			}
		});
		$(this).parents('form').find('input:radio').each(function(i, item){
			if(jQuery.data(item, 'savedValue')=='checked'){
				$(item).attr('checked', 'checked');
				jQuery.data(item, 'savedValue', '');
			} else {
				$(item).attr('checked', false);
			}
		});
		/**/
		$(this).parents('form').find('span.error').remove();
		$(this).parents('form').find('div.row.error').removeClass('error');
	});

	

/**/
	$(".user-data div.form:has(.error)").show();
	$(".recommend div.form:has(.error)").show();


/**/

	/**/
	function accountLocalisationSelectTimezone(event) {

		/**/
		event.preventDefault();
		event.stopPropagation();

		var selectedTimezone = event.target.value;

		var timezonesSetUrl = timezonesSetPath+'?timezone='+selectedTimezone;
		$.getJSON(timezonesSetUrl, function(data, status) {
			location.reload();
		});

		/**/
		$('.user-data').find('.localisation').find('div.row.button').empty().prepend('<span class="ajax-loader"></span>');

	}

	/**/
	$('.user-data').find('.localisation').find('.edit').one('click', function(event){

		event.preventDefault();
		$(this).parent().next("div.form").show();
		$(this).hide();

		accountTimezoneCurrentTimezone = $('#account_timezone_current_timezone').val();
		accountTimezoneSelectbox = $('#useraccount-localisation').find('#timezone');
		$(accountTimezoneSelectbox).hide().after('<span class="ajax-loader"></span>');
		$.getJSON(timezonesGetPath, function(data) {
			var timezoneSelectorHtml = '';
			$.each(data, function(i,item){
				if(item==accountTimezoneCurrentTimezone) {
					timezoneSelectorHtml+= '<option value="'+item+'" selected="selected">'+item+'</option>';
				} else {
					timezoneSelectorHtml+= '<option value="'+item+'">'+item+'</option>';
				}
			});
			$(accountTimezoneSelectbox).html(timezoneSelectorHtml).show();
			$('.user-data').find('.localisation').find('.ajax-loader').remove();
			$(accountTimezoneSelectbox).bind('change', accountLocalisationSelectTimezone, false);
		});

		/**/
		$(this).bind('click', function(event){
			event.preventDefault();
			$(this).parent().next("div.form").show();
			$(this).hide();
		});

	});

	/**/
	$('.user-data .localisation .cancel').bind('click', function(event){
		event.preventDefault();
		$(this).parents('div.form').hide();
		$(this).parents('div.form').parent().find('span.edit').show();
	});

}
});/**/
var timezoneSelector;
var timezoneSelectorHtml = null;

/**/
function selectTimezone(event) {

	/**/
	event.preventDefault();
	event.stopPropagation();

	var selectedTimezone = event.target.value;

	var timezonesSetUrl = timezonesSetPath+'?timezone='+selectedTimezone;
	$.getJSON(timezonesSetUrl, function(data, status) {
		location.reload();
	});

	$('#useraccount-timezones').find('div.row.button').empty().prepend('<span class="ajax-loader"></span>');

}

function fillTimezoneSelector(timezoneSelectorTrigger){
	
	$('div.timezone-selector').remove();
	$(timezoneSelectorTrigger).after(timezoneSelector);

	/**/
	$('#timezone-selector').bind('click', function(event) {
		/**/
		event.preventDefault();
		event.stopPropagation();
	});
	
	/**/
	$('#timezone-selector').bind('change', selectTimezone, false);
	$('span.timezone-selector-close').bind('click', function(event) {
		/**/
		event.preventDefault();
		event.stopPropagation();
		$('div.timezone-selector').remove();
	});
}

/**/
function getAndBindTimezoneSelector(timezoneSelectorTrigger) {

	if(timezoneSelectorHtml==null){
		$.getJSON(timezonesGetPath, function(data) {
			timezoneSelectorHtml = '<div class="timezone-selector"><select id="timezone-selector" name="timezoneSelector">';
			$.each(data, function(i,item){
				timezoneSelectorHtml+= '<option value="'+item+'">'+item+'</option>';
			});

			timezoneSelectorHtml+= '</select><span class="timezone-selector-close"><span class="alt">x</span></span></div>';
			timezoneSelector = timezoneSelectorHtml;
			fillTimezoneSelector(timezoneSelectorTrigger);
		});
	} else {
		timezoneSelector = timezoneSelectorHtml;
		fillTimezoneSelector(timezoneSelectorTrigger);
	}
	
}

/**/
$(document).ready(function() {
	/**/
	if($('div.date-user').length>0) {
		$('span.change-timezone', 'div.date-user').bind('click', function(event){
			event.stopPropagation();
			getAndBindTimezoneSelector(this);
		});
	}
});
/**/
function onFlashintroStart(){
	$('body').css('background', "#0d0d0d url('"+dchcontent_flashintro_homepagebackground+"') no-repeat top center");
}

function onFlashintroEnd(){
	$('#wrapper').fadeIn('slow');
	$('#footer').fadeIn('slow');
	$('#flashintro').remove();
}

$(document).ready(function() {
if($('#flashintro').length>0) {

	if($.cookie('dch_flashintro')==null) {
		
		$('#wrapper').hide();
		$('#footer').hide();

		$('#flashintro').show();
		$.cookie('dch_flashintro', 'played', { path: '/', domain: dch_cookie_domain});

		var flashintro_flashvars = {
					videoUrl:dchcontent_flashintro_videourl,
					videoImageFirst:dchcontent_flashintro_imagefirst,
					videoImageLast:dchcontent_flashintro_imagelast,
					videoStartCallback: 'onFlashintroStart',
					videoEndCallback: 'onFlashintroEnd'
				};
		var flashintro_params = {
			menu:"false",
			AllowScriptAccess:"always",
			allowfullscreen:"true",
			bgcolor:"#000000",
			wmode:"transparent"
		};
		var flashintro_attributes = {};

		swfobject.embedSWF (dchcontent_flashintro_flashfile, "flashintro",
			"100%", "100%",
			"9.0.124", dchcontent_flash_expressinstall,
			flashintro_flashvars, flashintro_params, flashintro_attributes );
	} else {
		/**/
		$('body').css('background', "#0d0d0d url('"+dchcontent_flashintro_homepagebackground+"') no-repeat top center");
		$('#flashintro').remove();
	}
} else {
	/**/
	$.cookie('dch_flashintro', 'played', { path: '/', domain: dch_cookie_domain});
}

});/**/
/*
 * Search
 */

var searchcache = {};

var searchrequestfilter = {};

/* Suchergebnisse abfragen und anzeigen
 * Abfragen der Suche + Suchergebnisse für die Ergebnisliste vom Server
 * Befüllen #pagebody
 * Suchbegriff highlight
 */
function videolistsearch(selector,term){
	$(selector).find("#functions").empty();
	$(selector).find("#results").empty().prepend('<span class="ajax-loader"></span>');
	var requestterm = {
		"term": term
	};
	$.ajax({
		url:      videolistPath,
		dataType: 'html',
		data: $.extend(requestterm, searchrequestfilter),
		success: function(data, status, request) {
			$(selector).empty();
			$(selector).html(data);
			$('.item').highlight(term);
		}
	});
}

$(document).ready(function() {
	// concert/search: Input Feld initialisieren und mit Suchbegriff belegen
	var term_highlight = $("#searchboxinput").val();
	if (term_highlight) $('.item').highlight(term_highlight);

	// meta-nav/searchboxinput: Hinweistext in dem Input-Feld ausblenden
	var searchboxinputtext = $("#searchboxinput").val();
	$("#searchboxinput").focus(function(){
		if ($("#searchboxinput").val() == searchboxinputtext)
			$("#searchboxinput").val("")
	});


	$("#searchboxinput").one('focus', function(){
		var searchindexJSONScript = document.createElement('script');
		searchindexJSONScript.setAttribute('src', videosearchCachePath);
		document.getElementsByTagName('head')[0].appendChild(searchindexJSONScript);
	});
});

/*
 * Callback-Funktion für die JSON Anfrage (Auf fremder Domain. Deswegen die Mühe.)
 * */
function searchindexProcessJsonReturn(value){

	$("#searchboxinput").autocomplete({
		minLength: 2,
		select: function(event, ui) {
			window.location.href = "/concert/search?term=" + ui.item.value;
		},
		source: value
	});
}/**/

$(document).ready(function() {
/**/
if($('form').length) {

	/**/
	$('input').keyup(function(event) {
		if(event.which==13) {
			$(this).closest("form").submit();
		}
	});

	/**/
	$('form a.button.submit').bind('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$(this).closest("form").submit();
	});
	
	/**/
	$('form a.button.submit').after('<span class="ajax-loader" style="display:none;"></span>');

	/**/
	$('#user-register #a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d, #a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d').bind('blur', function(){
		var changingSubmitButton = $('form a.button.submit');
		/**/
		if(changingSubmitButton.data('originalButtonText')==null) {
			changingSubmitButton.data('originalButtonText', changingSubmitButton.text());
		}
		
		if(this.value!=''){
			changingSubmitButton.find('.button-rc-c').text(changingSubmitButton.data('originalButtonText') + ' ' +this.value);
		} else {
			changingSubmitButton.find('.button-rc-c').text(changingSubmitButton.data('originalButtonText'));
		}
	});
}
});/**/
function submitBandwidthtestResult(bandwidth) {

	/**/
	if(bandwidth>4000) {
		$('#bandwidthtest').removeClass().addClass('high');
	} else if(bandwidth>1200) {
		$('#bandwidthtest').removeClass().addClass('medium');
	} else {
		$('#bandwidthtest').removeClass().addClass('low');
	}
	$('#bandwidthtest').find('.indicator-text').text(bandwidth+' KBit/s');

	/**/
	var bandwidthtestSetUrl = bandwidthtestSetPath+'?result='+bandwidth;
	$.getJSON(bandwidthtestSetUrl, function(data, status) {
		// ignore
	});

	/**/
	if($('#bandwidthtest').parents('form').length>0) {
		bandwidthtestForm = $('#bandwidthtest').parents('form');
		$(bandwidthtestForm).find("div.row.button").show();
		$(bandwidthtestForm).find('input:submit').removeAttr('disabled');
	}
}

/**/
$(document).ready(function() {
if($('#bandwidthtest').length>0) {

	var flashvars = {};
	flashvars.maxduration = 10000; // in ms
	flashvars.js = "submitBandwidthtestResult";
	flashvars.nocache = true;
	flashvars.testurls = dchcontent_bandwidthtest_testurls;
	var params = {};
	params.allowscriptaccess = "always";
	var attributes = {};
	attributes.id = "bandwidthtestflash";

	/**/
	 if($('#bandwidthtest').parents('form').length>0) {

		bandwidthtestForm = $('#bandwidthtest').parents('form');

		$(bandwidthtestForm).one('focusin', function(event) {
			$(bandwidthtestForm).find("div.row.button").hide();
			$(bandwidthtestForm).find('input:submit').attr('disabled', 'disabled');
			$('#bandwidthtest').show();
			swfobject.embedSWF(dchcontent_bandwidthtest_flashfile, "bandwidthtest-flashfilm", "1", "1", "10.0.0", false, flashvars, params, attributes);
		});

	 } else {
		/**/
		$('#bandwidthtest').show();
		swfobject.embedSWF(dchcontent_bandwidthtest_flashfile, "bandwidthtest-flashfilm", "1", "1", "10.0.0", false, flashvars, params, attributes);

	 }
}
});
/*
 * jQuery validation plug-in 1.7
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

$.extend($.fn, {
	// http://docs.jquery.com/Plugins/Validation/validate
	validate: function( options ) {

		// if nothing is selected, return nothing; can't chain anyway
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
			return;
		}

		// check if a validator for this form was already created
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}

		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator);

		if ( validator.settings.onsubmit ) {

			// allow suppresing validation by adding a cancel class to the submit button
			this.find("input, button").filter(".cancel").click(function() {
				validator.cancelSubmit = true;
			});

			// when a submitHandler is used, capture the submitting button
			if (validator.settings.submitHandler) {
				this.find("input, button").filter(":submit").click(function() {
					validator.submitButton = this;
				});
			}

			// validate the form on submit
			this.submit( function( event ) {
				if ( validator.settings.debug )
					// prevent form submit to be able to see console output
					event.preventDefault();

				function handle() {
					if ( validator.settings.submitHandler ) {
						if (validator.submitButton) {
							// insert a hidden input as a replacement for the missing submit button
							var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
						}
						validator.settings.submitHandler.call( validator, validator.currentForm );
						if (validator.submitButton) {
							// and clean up afterwards; thanks to no-block-scope, hidden can be referenced
							hidden.remove();
						}
						return false;
					}
					return true;
				}

				// prevent submit for invalid forms or custom submit handlers
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}

		return validator;
	},
	// http://docs.jquery.com/Plugins/Validation/valid
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = true;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid &= validator.element(this);
            });
            return valid;
        }
    },
	// attributes: space seperated list of attributes to retrieve and remove
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function(index, value) {
			result[value] = $element.attr(value);
			$element.removeAttr(value);
		});
		return result;
	},
	// http://docs.jquery.com/Plugins/Validation/rules
	rules: function(command, argument) {
		var element = this[0];

		if (command) {
			var settings = $.data(element.form, 'validator').settings;
			var staticRules = settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				if (argument.messages)
					settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}

		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);

		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}

		return data;
	}
});

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

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

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

$.extend($.validator, {

	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		validClass: "valid",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: [],
		ignoreTitle: false,
		onfocusin: function(element) {
			this.lastActive = element;

			// hide error label and remove error class on focus if enabled
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
				this.errorsFor(element).hide();
			}
		},
		onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element) {
			// click on selects, radiobuttons and checkboxes
			if ( element.name in this.submitted )
				this.element(element);
			// or option elements, check parent select in that case
			else if (element.parentNode.name in this.submitted)
				this.element(element.parentNode);
		},
		highlight: function( element, errorClass, validClass ) {
			$(element).addClass(errorClass).removeClass(validClass);
		},
		unhighlight: function( element, errorClass, validClass ) {
			$(element).removeClass(errorClass).addClass(validClass);
			$(element).parent().parent().removeClass(errorClass).addClass(validClass); // llh.tpuppe
		}
	},

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

	messages: {
		required: "This field is required.",
		remote: "Please fix this field.",
		email: "Please enter a valid email address.",
		url: "Please enter a valid URL.",
		date: "Please enter a valid date.",
		dateISO: "Please enter a valid date (ISO).",
		number: "Please enter a valid number.",
		digits: "Please enter only digits.",
		creditcard: "Please enter a valid credit card number.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.validator.format("Please enter no more than {0} characters."),
		minlength: $.validator.format("Please enter at least {0} characters."),
		rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
		range: $.validator.format("Please enter a value between {0} and {1}."),
		max: $.validator.format("Please enter a value less than or equal to {0}."),
		min: $.validator.format("Please enter a value greater than or equal to {0}.")
	},

	autoCreateRanges: false,

	prototype: {

		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();

			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});

			function delegate(event) {
				var validator = $.data(this[0].form, "validator"),
					eventType = "on" + event.type.replace(/^validate/, "");
				validator.settings[eventType] && validator.settings[eventType].call(validator, this[0] );
			}
			$(this.currentForm)
				.validateDelegate(":text, :password, :file, select, textarea", "focusin focusout keyup", delegate)
				.validateDelegate(":radio, :checkbox, select, option", "click", delegate);

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

		// http://docs.jquery.com/Plugins/Validation/Validator/form
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			this.showErrors();
			return this.valid();
		},

		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid();
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/element
		element: function( element ) {
			element = this.clean( element );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				// Hide error containers on last error
				this.toHide = this.toHide.add( this.containers );
			}
			this.showErrors();
			return result;
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/showErrors
		showErrors: function(errors) {
			if(errors) {
				// add items to error list and map
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				// remove items from success list
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/resetForm
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},

		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},

		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},

		hideErrors: function() {
			this.addWrapper( this.toHide ).hide();
		},

		valid: function() {
			return this.size() == 0;
		},

		size: function() {
			return this.errorList.length;
		},

		focusInvalid: function() {
			if( this.settings.focusInvalid ) {
				try {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
					.filter(":visible")
					.focus()
					// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
					.trigger("focusin");
				} catch(e) {
					// ignore IE throwing errors when focusing hidden elements
				}
			}
		},

		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},

		elements: function() {
			var validator = this,
				rulesCache = {};

			// select all valid inputs inside the form (no submit or reset buttons)
			// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
			return $([]).add(this.currentForm.elements)
			.filter(":input")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);

				// select only the first element for each name, and only those with rules specified
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;

				rulesCache[this.name] = true;
				return true;
			});
		},

		clean: function( selector ) {
			return $( selector )[0];
		},

		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},

		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.currentElements = $([]);
		},

		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().add( this.containers );
		},

		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},

		check: function( element ) {
			element = this.clean( element );

			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name )[0];
			}

			var rules = $(element).rules();
			var dependencyMismatch = false;
			for( method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );

					// if a method indicates that the field is optional and therefore valid,
					// don't mark it as valid when there are no other rules
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;

					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}

					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method", e);
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},

		// return the custom message for the given element and validation method
		// specified in the element's "messages" metadata
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;

			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();

			return meta && meta.messages && meta.messages[method];
		},

		// return the custom message for the given element name and validation method
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},

		// return the first defined argument, allowing empty strings
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},

		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				// title is never undefined, so handle empty string as undefined
				!this.settings.ignoreTitle && element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},

		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method ),
				theregex = /\$?\{(\d+)\}/g;
			if ( typeof message == "function" ) {
				message = message.call(this, rule.parameters, element);
			} else if (theregex.test(message)) {
				message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);
			}
			this.errorList.push({
				message: message,
				element: element
			});

			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},

		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
			return toToggle;
		},

		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
		},

		validElements: function() {
			return this.currentElements.not(this.invalidElements());
		},

		invalidElements: function() {
			return $(this.errorList).map(function() {
				return this.element;
			});
		},

		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				// refresh error/success class
				label.removeClass().addClass( this.settings.errorClass );

				// check if we have a generated label, replace the message then
				label.attr("generated") && label.html(message);
			} else {
				// create label
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					// make sure the element is visible, even in IE
					// actually showing the wrapped element is handled elsewhere
					label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow = this.toShow.add(label);
		},

		errorsFor: function(element) {
			var name = this.idOrName(element);
    		return this.errors().filter(function() {
				return $(this).attr('for') == name;
			});
		},

		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},

		findByName: function( name ) {
			// select by name and filter by form for performance over form.find("[name=...]")
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},

		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},

		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},

		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},

		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},

		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},

		stopRequest: function(element, valid) {
			this.pendingRequest--;
			// sometimes synchronization fails, make sure pendingRequest is never < 0
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
				this.formSubmitted = false;
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
				this.formSubmitted = false;
			}
		},

		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}

	},

	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},

	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},

	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},

	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);

		for (method in $.validator.methods) {
			var value = $element.attr(method);
			if (value) {
				rules[method] = value;
			}
		}

		// maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}

		return rules;
	},

	metadataRules: function(element) {
		if (!$.metadata) return {};

		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},

	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},

	normalizeRules: function(rules, element) {
		// handle dependency check
		$.each(rules, function(prop, val) {
			// ignore rule when param is explicitly false, eg. required:false
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});

		// evaluate parameters
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});

		// clean number parameters
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});

		if ($.validator.autoCreateRanges) {
			// auto-create ranges
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}

		// To support custom messages in metadata ignore rule methods titled "messages"
		if (rules.messages) {
			delete rules.messages;
		}

		return rules;
	},

	// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/addMethod
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message != undefined ? message : $.validator.messages[name];
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},

	methods: {

		// http://docs.jquery.com/Plugins/Validation/Methods/required
		required: function(value, element, param) {
			// check if dependency is met
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				// could be an array for select-multiple or a string, both are fine this way
				var val = $(element).val();
				return val && val.length > 0;
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return $.trim(value).length > 0;
			}
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/remote
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";

			var previous = this.previousValue(element);
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			previous.originalMessage = this.settings.messages[element.name].remote;
			this.settings.messages[element.name].remote = previous.message;

			param = typeof param == "string" && {url:param} || param;

			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					data: data,
					success: function(response) {
						validator.settings.messages[element.name].remote = previous.originalMessage;
						var valid = response === true;
						if ( valid ) {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						} else {
							var errors = {};
							var message = (previous.message = response || validator.defaultMessage( element, "remote" ));
							errors[element.name] = $.isFunction(message) ? message(value) : message;
							validator.showErrors(errors);
						}
						previous.valid = valid;
						validator.stopRequest(element, valid);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/minlength
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) >= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/maxlength
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) <= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/rangelength
		rangelength: function(value, element, param) {
			var length = this.getLength($.trim(value), element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/min
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/max
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/range
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/email
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/date
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/number
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/digits
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/creditcard
		// based on http://en.wikipedia.org/wiki/Luhn
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

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

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

			return (nCheck % 10) == 0;
		},

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

		// http://docs.jquery.com/Plugins/Validation/Methods/equalTo
		equalTo: function(value, element, param) {
			// bind to the blur event of the target in order to revalidate whenever the target field is updated
			// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
			var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
				$(element).valid();
			});
			return value == target.val();
		}

	}

});

// deprecated, use $.validator.format instead
$.format = $.validator.format;

})(jQuery);

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

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

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
;(function($) {
	// only implement if not provided by jQuery core (since 1.4)
	// TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs
	if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) {
		$.each({
			focus: 'focusin',
			blur: 'focusout'
		}, function( original, fix ){
			$.event.special[fix] = {
				setup:function() {
					this.addEventListener( original, handler, true );
				},
				teardown:function() {
					this.removeEventListener( original, handler, true );
				},
				handler: function(e) {
					arguments[0] = $.event.fix(e);
					arguments[0].type = fix;
					return $.event.handle.apply(this, arguments);
				}
			};
			function handler(e) {
				e = $.event.fix(e);
				e.type = fix;
				return $.event.handle.call(this, e);
			}
		});
	};
	$.extend($.fn, {
		validateDelegate: function(delegate, type, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		}
	});
})(jQuery);/**/
$(document).ready(function() {

	/**/
	if($('form').length) {
		$('#couponform').bind('submit', function(event){
			$('#couponform').find('.row').remove();
			if ($('#couponform #code').val()=="") {
				event.preventDefault();
				event.stopPropagation();
				$('#couponform #code').addClass('error');
				$('#couponform').append('<div class="row" id="coupon_code_empty"><span class="label alert">'+dchjslanguage_form_errors_coupon_code_empty+'</span></div>')
				return false;
			}
		});
	}


	// http://docs.jquery.com/Plugins/Validation/validate

	if ($("#errormessages").children().length <= 0) {
		$("#errormessages").html('<div class="error"><ul></ul></div>');
		$("#errormessages").hide();
	}

	if ($("#errormessages2").children().length <= 0) {
		$("#errormessages2").html('<div class="error"><ul></ul></div>');
		$("#errormessages2").hide();
	}

	jQuery.validator.setDefaults({
		debug: false,
		errorContainer: "#errormessages",
		errorLabelContainer: "#errormessages div ul",
		/**/
		errorElement: "span",
		errorClass: "error",
		/**/
		/**/
		onkeyup: false,
		onsubmit: true,
		errorPlacement: function(label, element) {
			label.insertAfter( element.parent() );
			element.parent().parent().addClass('error');
		},
		submitHandler: function(form){
			/**/
			$(form).find('a.button.submit').parent().find('span.ajax-loader').show();
			$(form).find('a.button.submit').remove();
			$(form).find('input:submit').remove();
			form.submit();
		}
	});

	/**/

	// NEUE/VERSCHLUESSELTE BEZEICHNUNGEN
	/**/

	/**/
	var validator_user_login = $("#user-login").validate({
				rules: {
					/**/
					'username': {required: true, email: true},
					/**/
					'password': {required: true}
				}
			});

	/**/
	var validator_user_pwrecovery = $("#pw-recovery").validate({
			rules: {
				'pwrecovery-username': {required: true, email: true}
			},
			submitHandler: function(form) {
				passwordrecoveryAjaxSubmit(form);
			}
		});


	/**/
	var validator_user_register = $("#user-register").validate({
			rules: {
				/**/
				'0ece0e47ec5f1a1c21938eff3db8e60e0e1d1183': {required: true},
				/**/
				'e8108b821aa8165140b5f968d0a4f979f2d0b615': {required: true},
				/**/
				'4e2cdd3b204e1576631be15f94076c91440497e7': {required: true},
				/**/
				'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {required: true, email: true},
				/**/
				'5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8': {required: true},
				/**/
				'8e68b3e5af636475363c23b52ade8e6064b05806': {required: true},
				/**/
				'e11523c5ff23fc1600aca2d8ee5adb542c5ce4b3': {required: true},
				/**/
				'4f956f26eec05f8cb2ba8486384fd8fe70fd2ffd': {required: true}
			}
		});


	/**/
	var validator_user_purchaseregister = $("#user-purchaseregister").validate({
			rules: {
				/**/
				'0ece0e47ec5f1a1c21938eff3db8e60e0e1d1183': {required: true},
				/**/
				'e8108b821aa8165140b5f968d0a4f979f2d0b615': {required: true},
				/**/
				'4e2cdd3b204e1576631be15f94076c91440497e7': {required: true},
				/**/
				'd3a9fb075d49be97f6eaec99399d8cfdd38c7361': {required: true},
				/**/
				'f13e27693c85aed522df8c3fcb0bb0110ca54e14': {required: true},
				/**/
				'2c54892c40a1751663d9aca4e03e6a833056bc9f': {required: true},
				/**/
				'8e68b3e5af636475363c23b52ade8e6064b05806': {required: true},
				/**/
				'e11523c5ff23fc1600aca2d8ee5adb542c5ce4b3': {required: true},
				/**/
				'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {required: true, email: true},
				/**/
				'5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8': {required: true},
				/**/
				'4f956f26eec05f8cb2ba8486384fd8fe70fd2ffd': {required: true}
			}
		});


	/**/
	var validator_user_purchasecomplete= $("#user-purchasecomplete").validate({
			rules: {
				/**/
				'0ece0e47ec5f1a1c21938eff3db8e60e0e1d1183': {required: true},
				/**/
				'e8108b821aa8165140b5f968d0a4f979f2d0b615': {required: true},
				/**/
				'4e2cdd3b204e1576631be15f94076c91440497e7': {required: true},
				/**/
				'd3a9fb075d49be97f6eaec99399d8cfdd38c7361': {required: true},
				/**/
				'f13e27693c85aed522df8c3fcb0bb0110ca54e14': {required: true},
				/**/
				'2c54892c40a1751663d9aca4e03e6a833056bc9f': {required: true},
				/**/
				'8e68b3e5af636475363c23b52ade8e6064b05806': {required: true},
				/**/
				'e11523c5ff23fc1600aca2d8ee5adb542c5ce4b3': {required: true},
				/**/
				'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {required: true, email: true}
			}
		});



	/**/
	var validator_contact = $("#contactform").validate({
			rules: {
				/**/
				'6ae999552a0d2dca14d62e2bc8b764d377b1dd6c': {required: true},
				/**/
				'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {required: true, email: true},
				/**/
				'335ce16b3fe40346cc3af2a4efce2ef04bc4ea55': {required: true},
				/**/
				'6f9b9af3cd6e8b8a73c2cdced37fe9f59226e27d': {required: true}
			}
		});


	/**/
	var validator_studentdiscount = $("#studentdiscountform").validate({
			rules: {
				/**/
				'6ae999552a0d2dca14d62e2bc8b764d377b1dd6c': {required: true},
				/**/
				'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {required: true, email: true},
				/**/
				'335ce16b3fe40346cc3af2a4efce2ef04bc4ea55': {required: true},
				/**/
				'6f9b9af3cd6e8b8a73c2cdced37fe9f59226e27d': {required: true}
			}
		});


	/**/
	var validator_newsletter = $("#newsletterform").validate({
			rules: {
				/**/
				'6ae999552a0d2dca14d62e2bc8b764d377b1dd6c': {required: true},
				/**/
				'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {required: true, email: true}
			}
		});


	/**/
	var validator_useraccount_register = $("#useraccount-register").validate({
			rules: {
				'salutation': {required: true},
				'firstname': {required: true},
				'lastname': {required: true},
				'street': {required: true},
				'zip': {required: true},
				'city': {required: true},
				/**/
				'country': {required: true},
				'language': {required: true},
				'email': {required: true, email: true}
			}
		});

	/**/
	var validator_useraccount_password = $("#useraccount-password").validate({
			rules: {
				'password': {required: true},
				'password2':  {required: true, equalTo: "#password"}
			}
		});

	/**/
	var validator_useraccount_newsletter = $("#useraccount-newsletter").validate({
			rules: {
				'nl': {required: true}
			}
		});

	/**/

	/**/
	jQuery.validator.addMethod("emaillist", function(value, element) {

		valueArray = value.split(',');
		for(var i=0; i<valueArray.length; i++) {
			if(i>5){
				return false;
			}
			valueArray[i] = jQuery.trim(valueArray[i]);
			if(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(valueArray[i]) == false) {
				return false;
			}
		}
		return true;
	}, "Please enter a comma-seperated list of email addresses.");

	var validator_recommendation = $("#recommendform").validate({
			rules: {
				'message': {required: true},
				'email_list': {required: true, emaillist: true}
			}
		});
});/**/

jQuery.validator.setDefaults({ messages: {
	/**/
	'0ece0e47ec5f1a1c21938eff3db8e60e0e1d1183': dchjslanguage_form_errors_salutation_empty, 
	/**/
	'e8108b821aa8165140b5f968d0a4f979f2d0b615': dchjslanguage_form_errors_firstname_empty, 
	/**/
	'4e2cdd3b204e1576631be15f94076c91440497e7': dchjslanguage_form_errors_lastname_empty, 
	/**/
	'6ae999552a0d2dca14d62e2bc8b764d377b1dd6c': dchjslanguage_form_errors_name_empty, 
	/**/
	'a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d': {
		required: dchjslanguage_form_errors_email_empty, 
		email: dchjslanguage_form_errors_email_not_valid 
	},
	/**/
	'5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8': {
		required: dchjslanguage_form_errors_password_empty, 
		rangelength: $.format("Bitte geben Sie ein Passwort mit {0} bis {1} Zeichen ein")
	},
	/**/
	'8e68b3e5af636475363c23b52ade8e6064b05806': dchjslanguage_form_errors_country_empty, 
	/**/
	'e11523c5ff23fc1600aca2d8ee5adb542c5ce4b3': dchjslanguage_form_errors_language_empty, 
	/**/
	'4f956f26eec05f8cb2ba8486384fd8fe70fd2ffd': dchjslanguage_form_errors_tos_empty, 
	'salutation': dchjslanguage_form_errors_salutation_empty, 
	'firstname': dchjslanguage_form_errors_firstname_empty, 
	'lastname': dchjslanguage_form_errors_lastname_empty, 
	/**/
	'd3a9fb075d49be97f6eaec99399d8cfdd38c7361': dchjslanguage_form_errors_street_empty, 
	/**/
	'f13e27693c85aed522df8c3fcb0bb0110ca54e14': dchjslanguage_form_errors_zip_empty, 
	/**/
	'2c54892c40a1751663d9aca4e03e6a833056bc9f': dchjslanguage_form_errors_city_empty, 
	/**/
	'aa4a5f8125f234182e2dea92805afdfb747a86be': dchjslanguage_form_errors_state_empty, 
	/**/
	'f6be6ca910984ef05a237a180d464ceb8847c14a': dchjslanguage_form_errors_phone_empty, 
	/**/
	'83d6311e87d4775ca4b3a411e3a334581ad8951e': dchjslanguage_form_errors_mobile_empty, 
	'street': dchjslanguage_form_errors_street_empty, 
	'zip': dchjslanguage_form_errors_zip_empty, 
	'city': dchjslanguage_form_errors_city_empty, 
	'state': dchjslanguage_form_errors_state_empty, 
	'phone': dchjslanguage_form_errors_phone_empty, 
	'mobile': dchjslanguage_form_errors_mobile_empty, 
	/**/
	'adcc7cde3d36ca2fb1fb953cc85f6b59960d885b': dchjslanguage_form_errors_certificate_empty, 
	/**/
	'335ce16b3fe40346cc3af2a4efce2ef04bc4ea55': dchjslanguage_form_errors_subject_empty, 
	/**/
	'6f9b9af3cd6e8b8a73c2cdced37fe9f59226e27d': dchjslanguage_form_errors_message_empty, 
	'subject': dchjslanguage_form_errors_subject_empty, 
	'message': dchjslanguage_form_errors_message_empty, 
	'pwrecovery-username': {
		required: dchjslanguage_form_errors_email_empty, 
		email: dchjslanguage_form_errors_email_not_valid 
	},
	'username': dchjslanguage_form_errors_email_empty, 
	'password': dchjslanguage_form_errors_password_empty, 
	'password2': {
		empty: dchjslanguage_form_errors_password_repeat_empty,
		equalTo: dchjslanguage_form_errors_password_equalTo 
	},
	'email_list': {
		empty: dchjslanguage_form_errors_emaillist_empty,
		emaillist: dchjslanguage_form_errors_emaillist_emaillist
	}

}});
/**/

/**/
function bindPasswordrecoveryToggler() {
	$('div.pwrecovery-link a').bind('click', function(event) {
		event.preventDefault();
		event.stopPropagation();
		$('#pwrecovery-username').val($('#username').val());
		$('#loginform').hide();
		$('#pwrecoveryform').show();
	});
}


/**/
function bindPasswordrecoveryAction() {

	/**/
	$('#pw-recovery a.button.submit').unbind('click');

	$('#pw-recovery a.submit').bind('click', function(event) {

		event.preventDefault();
		event.stopPropagation();

		var passwordrecoveryEmail = $('#pwrecovery-username').val();
		var passwordrecoveryUrl = passwordrecoveryPath+'?email='+passwordrecoveryEmail;

		$.getJSON(passwordrecoveryUrl, function(data, textStatus) {
			if(data.success){
				pwrecoveryformBacklinkToLogin = $('#pwrecoveryform div.row.login-link').html();
				$('#pwrecoveryform').html(dchjslanguage_labels_passwordrecovery_affirmation + pwrecoveryformBacklinkToLogin);
			} else {
				$('#pwrecoveryform #pwrecovery-username').parent().append('<span class="error">'+dchjslanguage_labels_passwordrecovery_error+'</span>');
			}
		});
		
	});
	
}

/**/
function passwordrecoveryAjaxSubmit(form) {
	var passwordrecoveryEmail = $('#pwrecovery-username').val();
	var passwordrecoveryUrl = passwordrecoveryPath+'?email='+passwordrecoveryEmail;

	/**/
	$(form).find('a.button.submit').hide().after('<span class="ajax-loader"></span>');
	$(form).find('input:submit').remove();

	$.getJSON(passwordrecoveryUrl, function(data, textStatus) {
		if(data.success){
			pwrecoveryformBacklinkToLogin = $('#pwrecoveryform div.row.login-link').html();
			$('#pwrecoveryform').html(dchjslanguage_labels_passwordrecovery_affirmation + pwrecoveryformBacklinkToLogin);
		} else {
			$('#pwrecoveryform #pwrecovery-username').parent().append('<span class="error">'+dchjslanguage_labels_passwordrecovery_error+'</span>');
				/**/
				$(form).find('a.button.submit').show().after('<input type="submit" />');
				$(form).find('span.ajax-loader').remove();
		}
	});
}

$(document).ready(function() {
if($('#pwrecoveryform').length>0){
	bindPasswordrecoveryToggler();
}
});
	/**/

/**/
$(document).ready(function() {
if($('body.account').length>0) {

	$('#email_list').one('focus', function(event) {

		/**/
		var recommendForm = $('#recommendform');
		$(recommendForm).find("div.row.button").hide();
		$(recommendForm).find('input:submit').attr('disabled', 'disabled');

		$.getJSON(recommendTokenGetPath, function(data) {
			/**/
			$('#token').val(data.token);
			/**/
			$(recommendForm).find("div.row.button").show();
			$(recommendForm).find('input:submit').removeAttr('disabled');
		});
	});
}
});/**/
/**/

$(document).ready(function() {
/**/
if($('#state', 'body.account').length>0) {

	userdataForm = $('#useraccount-register');

	/**/
	function updateStateOptions() {

		var statesGetUrl = statesGetPath+'?cc='+$(userdataForm).find('#country').val();
		$.getJSON(statesGetUrl, function(data) {
			var stateSelectHtml = '';
			if(data!=null){
				$.each(data, function(i,item){
					stateSelectHtml+= '<option value="'+item+'">'+item+'</option>';
				});
			}
			if(stateSelectHtml == ''){
				$(userdataForm).find('#state').empty().parents('div.row').hide();
			} else {
				$(userdataForm).find('#state').empty().prepend(stateSelectHtml).parents('div.row').show();
			}
		});
	}

	/**/
	if($(userdataForm).find('#state option').length==0) {
		updateStateOptions();
	}

	/**/
	$(userdataForm).find('#country').bind('change', updateStateOptions, false);

}

/**/

if($('#user-purchaseregister').length>0) {

	userdataForm = $('#user-purchaseregister');

	/**/
	function updateStateOptions() {
		var statesGetUrl = statesGetPath+'?cc='+$(userdataForm).find('#8e68b3e5af636475363c23b52ade8e6064b05806').val();
		$.getJSON(statesGetUrl, function(data) {

			var stateSelectHtml = '';
			if(data!=null){
				$.each(data, function(i,item){
					stateSelectHtml+= '<option value="'+item+'">'+item+'</option>';
				});
			}
			if(stateSelectHtml == ''){
				$(userdataForm).find('#aa4a5f8125f234182e2dea92805afdfb747a86be').empty().parents('div.row').hide();
			} else {
				$(userdataForm).find('#aa4a5f8125f234182e2dea92805afdfb747a86be').empty().prepend(stateSelectHtml).parents('div.row').show();
			}
		});
	}

	/**/
	if($(userdataForm).find('#aa4a5f8125f234182e2dea92805afdfb747a86be option').length==0) {
		updateStateOptions();
	}

	/**/
	$(userdataForm).find('#8e68b3e5af636475363c23b52ade8e6064b05806').bind('change', updateStateOptions, false);
}

/**/

if($('#user-purchasecomplete').length>0) {

	userdataForm = $('#user-purchasecomplete');

	/**/
	function updateStateOptions() {
		var statesGetUrl = statesGetPath+'?cc='+$(userdataForm).find('#8e68b3e5af636475363c23b52ade8e6064b05806').val();
		$.getJSON(statesGetUrl, function(data) {
			var stateSelectHtml = '';
			if(data!=null){
				$.each(data, function(i,item){
					stateSelectHtml+= '<option value="'+item+'">'+item+'</option>';
				});
			}
			if(stateSelectHtml == ''){
				$(userdataForm).find('#aa4a5f8125f234182e2dea92805afdfb747a86be').empty().parents('div.row').hide();
			} else {
				$(userdataForm).find('#aa4a5f8125f234182e2dea92805afdfb747a86be').empty().prepend(stateSelectHtml).parents('div.row').show();
			}
		});
	}

	/**/
	if($(userdataForm).find('#aa4a5f8125f234182e2dea92805afdfb747a86be option').length==0) {
		updateStateOptions();
	}

	/**/
	$(userdataForm).find('#8e68b3e5af636475363c23b52ade8e6064b05806').bind('change', updateStateOptions, false);
}

});
	
