/**
 * Define constants here.
 */
var ClientSideConstants = {
	IE6HoverFix: {
		elements: ['.contentbox', '.imagebutton', '.product', '.instructionEl']
	},
	CachedSubmit: {
		elements: ['searchForm']
	},
	DropDownBox: {
		closeDelay: 3
	},
	MiniCart: {
		closeDelay: 3,
		maxShownItems: 5,
		firstItemCount: 2,
		secondItemCount: 3
	},
	ComponentsToInit: ['IE6HoverFix',
					   'InitialInputValueHandler', 
					   'SizeSliderLink',
					   'LinkedInputField',
					   'StatusWindow',
					   'DropDownBox',
					   'WishList',
					   'PrintButton',
					   'CheckFieldOnFocus',
					   'StatusWindowError',
					   'PopupLinkHandler',
					   'PasswordStrengthCheck',
					   'ConfirmDialogHandler',
					   'InfoLinkHandler',
					   'InfoSizeHandler',
					   'AjaxLinkSwapper',
					   'Captcha',
					   'ReturnKeySubmit',
					   'noHoverCursorFix',
					   'sweepstakesHandler'
					   /* 'MiniCart' */]
};

/**
 * Extend Prototype browser information
 */
Object.extend(Prototype.Browser, {
     WebKit419: Prototype.Browser.WebKit && (Prototype.BrowserFeatures.XPath),
     WebKit420: Prototype.Browser.WebKit && (!Prototype.BrowserFeatures.XPath),
     IE6: Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined"),
     IE7: Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object") && (typeof window.XDomainRequest == "undefined"),
	 IE8: Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object") && (typeof window.XDomainRequest == "object"),
	 IE9: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false
});

var Comment = Class.create({
	node: null,
	
	initialize: function(node) {
		this.node = node;
	},
	
	getNode: function() {
		return this.node;
	},
	
	getText: function() {
		return this.node.nodeValue;
	},
	
	toObject: function() {
		var obj = null;
		eval('obj=' + this.getText());
		return obj;
	},
	
	getObjectForComponent: function(componentName) {
		return this.toObject()[componentName];
	}
});

Element.addMethods({
	comments: function(element, first) {
		var comments = [];
		var childs = element.childNodes;
		for (var i = 0; i < childs.length; i++) {
			var node = childs[i];
			if (node.nodeType == Node.COMMENT_NODE) {
				if (first) {
					return new Comment(node);
				} else {
					comments.push(new Comment(node));
				}
			}
		}
		return first ? null : comments;
	},
	
	nextSiblingComment: function(element) {
		var sibling = element.nextSibling;
		if (sibling && sibling.nodeType == Node.COMMENT_NODE) {
			return new Comment(sibling);
		}
		return null;
	},
	
	removeSelection: function(element) {
		if (element.selectedIndex) {
			element.selectedIndex = '';
		}
		if (element.value) {
			element.value = '';
		} 	
		element.fire('dom:changed');
	},
	
	getConfiguration: function(element, component, nextSibling) {
		var comment = null;
		var config = null;
		comment = nextSibling ? element.nextSiblingComment() : element.comments(true);
		if (comment) {
			if (!nextSibling && comment.getText().strip().indexOf('dwMarker') != -1) {
				var comments = element.comments();
				comment = comments[1];
			}
			if (comment) {
				config = comment.getObjectForComponent(component);
			}
		}
		return config;
	},
	
	getOuterHTML: function(el) {
		if (el.outerHTML) {
			return el.outerHTML;
		} else {
			var element = document.createElement("div");
			element.appendChild(el.cloneNode(true));
			return element.innerHTML;
		}
	}
});

/**
 * Event.simulate(@element, eventName[, options]) -> Element
 *
 * - @element: element to fire event on
 * - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
 * - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
 *
 * $('foo').simulate('click'); // => fires "click" event on an element with id=foo
 *
 * @see http://github.com/kangax/protolicious/blob/e5091a8051d57d62ae54bb906b16435fa638d75d/event.simulate.js
 **/
(function(){
  
	var eventMatchers = {
		'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
		'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
	}
	var defaultOptions = {
		pointerX: 0,
		pointerY: 0,
		button: 0,
		ctrlKey: false,
		altKey: false,
		shiftKey: false,
		metaKey: false,
		bubbles: true,
		cancelable: true
	}
  
	Event.simulate = function(element, eventName) {
		var options = Object.extend(defaultOptions, arguments[2] || { });
		var oEvent, eventType = null;
    
		element = $(element);
    
		for (var name in eventMatchers) {
			if (eventMatchers[name].test(eventName)) { eventType = name; break; }
		}
		
		if (!eventType)
			throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
 
		if (document.createEvent) {
			oEvent = document.createEvent(eventType);
			if (eventType == 'HTMLEvents') {
				oEvent.initEvent(eventName, options.bubbles, options.cancelable);
			} else {
				oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
						options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
						options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
			}
			element.dispatchEvent(oEvent);
		} else {
			options.clientX = options.pointerX;
			options.clientY = options.pointerY;
			oEvent = Object.extend(document.createEventObject(), options);
			element.fireEvent('on' + eventName, oEvent);
		}
		return element;
	}
	
	Element.addMethods({ simulate: Event.simulate });
})();

/**
 * Notify with "dom:changed" custom event when DOM is modified.
 *
 * @see http://www.schuerig.de/michael/blog/index.php/2008/01/07/dom-change-notification/
 */
 (function() {
	var methods = ['remove', 'update', 'replace', 'insert', 'wrap', 'empty', 'removeSelection'];
	var changes = [];
	var timeout;
	
	function rememberChange(element, method) {
		changes.push({
			element: $(element),
			parent: element.parentNode,
			operation: method
		});
	}
	
	function scheduleEvent() {
		if (timeout) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(fireEvent, 10);
	}
	
	function fireEvent() {
		changes.each(function(change) {
			var affectedNode = change.element;
			var operation = change.operation;
			if (!change.parent || (change.parent && !affectedNode.descendantOf(change.parent))) {
				affectedNode = (change.parent || affectedNode.parentNode);
				operation += 'Child';
			}
			/*if (affectedNode.fire) {
				affectedNode.fire('dom:changed', {operation: operation});
			}*/
		});
		changes = [];
	}
	
	var s = 'Element.addMethods({';
	methods.each(function(m, i) {
		s += (i > 0 ? ',' : '') + m + ' : Element.Methods[\'' + m + '\'].wrap(function(proceed, element) {rememberChange(element,\'' + m + '\');scheduleEvent();return proceed.apply(null, $A(arguments).slice(1));})';
	});
	s += '});';
	eval(s);
})();

 
/**
 * Remove flickering of background images in IE
 */
if (Prototype.Browser.IE6) {
	document.execCommand("BackgroundImageCache", false, true);
}

/**
 * Handle not installed Firebug.
 */
if (window['console'] === undefined) {
	window.console = {
		log: Prototype.emptyFunction,
		debug: Prototype.emptyFunction,
		info: Prototype.emptyFunction,
		warn: Prototype.emptyFunction,
		error: Prototype.emptyFunction,
		assert: Prototype.emptyFunction,
		dir: Prototype.emptyFunction,
		dirxml: Prototype.emptyFunction,
		trace: Prototype.emptyFunction,
		group: Prototype.emptyFunction,
		groupEnd: Prototype.emptyFunction,
		time: Prototype.emptyFunction,
		timeEnd: Prototype.emptyFunction,
		profile: Prototype.emptyFunction,
		profileEnd: Prototype.emptyFunction,
		count: Prototype.emptyFunction
	};
}

/**
 * Remove XML comments from a string.
 */
String.prototype.removeXMLComments = function() {
	return this.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g, '');
};

function contains(strText, strPattern)
{
	for (i = 0; i < strText.length; i++)
	{
	if (strPattern.indexOf(strText.charAt(i)) > -1) return true;
	}
	return false;
}

/**
 * Provide CSS hover effects for all elements.
 * This adds the classname "hover" when hovering over a registered element.
 */
var IE6HoverFix = {
	init: function() {
		if (Prototype.Browser.IE6) {
			$$(ClientSideConstants.IE6HoverFix.elements).each(function(el) {
				if (!el.IE6HoverFix) {
					el.observe('mouseenter', this.mouseHandler);
					el.observe('mouseleave', this.mouseHandler);
					el.IE6HoverFix = true;
				}
			}.bind(this));
		}
	},
	
	mouseHandler: function(ev) {
		var el = Event.element(ev);
		if (['mouseover', 'mouseenter'].indexOf(ev.type) != -1) {
			el.addClassName('hover');
		} else {
			el.removeClassName('hover');
		}
	}
};

/**
 * Handle initial values for an input field (remove value on focus).
 */
var InitialInputValueHandler = {
	init: function() {
		$$('input.initialInputField').each(function(el) {
			if (!el.initialInputValue && !el.hasClassName('realValue')) {
				el.initialInputValue = el.value;
				el.observe('focus', this.eventHandler.bind(this));
				el.observe('blur', this.eventHandler.bind(this));
				var form = el.up('form');
				if (form) {
					form.observe('submit', this.submitHandler.bindAsEventListener(this, el));
				}
			}
		}.bind(this));
	},

	eventHandler: function(ev) {
		var el = Event.element(ev);
		if (el.initialInputValue) {
			if (ev.type == 'focus' && el.value == el.initialInputValue) {
				el.value = '';
			} else if (ev.type == 'blur' && el.value == '') {
				el.value = el.initialInputValue;
			}
		}
	},
	
	submitHandler: function(ev, el) {
		if (el.initialInputValue && el.value == el.initialInputValue) {
			el.value = '';
		}
	}
};


/**
 * Intercepts links marked by hidden fields with class "ajaxLinkSwapPipeline" and calls a specified ajax pipeline instead with the parameters of the original request.
 * - example for hidden fields:
 * - <input type="hidden" class="ajaxLinkSwapPipeline" id="classNameUsedByLinks" name="classNameUsedByLinks" value="${URLUtils.url('Some-Pipeline')}"/>
 * - <input type="hidden" id="classNameUsedByLinks_content" name="classNameUsedByLinks_content" value="idOfContentToUpdate"/>
 */
var AjaxLinkSwapper = {
	init: function() {
		var swapper = this;
		$$('.ajaxLinkSwapPipeline').each(function(el) {
			var linkClass = el.id;
			var ajaxUrl = el.value;
			var content = $(linkClass+'_content').value;
			if(content && ajaxUrl){
				$$('.'+linkClass).each(function(link) {
					link.observe('click', this.clickHandler.bindAsEventListener(this, ajaxUrl, content, swapper, link));
					}.bind(this));
			}
		}.bind(this));
	},
	
	clickHandler: function(event, url, updateContent, swapper, el) {
				
				var parameterStr = '';
				var pos = el.href.indexOf('?');
				if(el.href && (pos != -1))
					var parameterStr = el.href.substr(pos);
				
				new Ajax.Request(url, { parameters: parameterStr , 
					method:'get',
					onSuccess: function(transport) {
						$(updateContent).update(transport.responseText);
						swapper.init();
					}, onException : function(t, e) {
						//alert(e);
					}
				});
				
				Event.stop(event);
	}
};


/**
 * Provide cachable requests for a <input type="image"> element. (Prevent submission of coodinates)
 */
var CachedSubmit = Class.create({
	submitButton : null,
	
	initialize: function(form) {
		if (form && form.method == 'get') {
			this.form = form;
			var inputImages = form.getInputs('image');
			for (var i = 0; i < inputImages.length; i++) {
				var button = inputImages[i];
				button.cachedSubmitHandler = this;
				if (this.submitButton == null) {
					this.submitButton = new Element('input', {type: 'submit'});
					this.submitButton.hide();
					button.insert({after: this.submitButton});
				}
				button.onclick = this.clickHandler; // TODO not good
			}
		}
	},
	
	clickHandler: function() {
		if (this.disabled == false) {
			var bindObj = this.cachedSubmitHandler;
		    bindObj.submitButton.click();
		}
		return false;
	}
});
CachedSubmit.init = function() {
	ClientSideConstants.CachedSubmit.elements.each(function(id) {
		var el = $(id);
		if (el) {
			new CachedSubmit(el);
		}
	});
}

/**
 * Size Group Slider
 */
var SizeSliderLink = {
	init: function() {
		$$('a.sizeSliderLink').each(function(el) {
				el.observe('click', function(ev) {
					Event.stop(ev);
					Effect.toggle('sizegroupslider','Slide', {duration:1});
					$('sizemore').toggle();
					$('sizeless').toggle();
					//Effect.toggle('.sizeSliderLink.sizemore', 'Appear', {duration:0});
					//Effect.toggle('.sizeSliderLink.sizeless', 'Appear', {duration:0});
				});
		});
	}
};

/**
 * Handle drop down elements.                                                                                                                     		                                                                                                                                                                                                                                                                    
 */
var DropDownBox = Class.create({
	element: null,
	dropdown: null,
	field: null,
	elements: null,
	open: null,
	waitingForClose: null,
	closeExecuter: null,
	initialValue: null,
	valueField: null,
	behaviourConfig: null,
	inReinit: null,

	initialize: function(element) {
		if (element && !element.dropDownBox) {
			this.element = element;
			this.open = false;
			this.waitingForClose = false;
			this.inReinit = false;

			this.initBehaviour();

			this.buildDropDownElement();
			this.initValues();
			
			this.initEventHandlers();
			document.observe('click', this.externalClickHandler.bind(this));
			
			this.element.observe('dom:changed', function(ev) {
				if (!this.inReinit) {
					this.reinit();
				}
			}.bind(this));
			
			this.inReinit = false;
			element.dropDownBox = true;
		}
	},
	
	reinit: function() {
		this.inReinit = true;
		this.buildDropDownElement();
		this.initValues();
		this.initEventHandlers();
		this.inReinit = false;
	},
	
	initEventHandlers: function() {
		this.field.observe('click', this.clickHandler.bind(this));
		this.dropdown.observe('mouseenter', this.enterLeaveHandler.bind(this));
		this.dropdown.observe('mouseleave', this.enterLeaveHandler.bind(this));
	},
	
	buildDropDownElement: function() {
		var dropdownElement = !this.inReinit ? new Element('div', {'class': 'dropdown'}) : this.dropdown;
		if (this.inReinit) {
			dropdownElement.update('');
			dropdownElement.className = 'dropdown';
		}
		$w(this.element.className).without('dropdown').each(function(className) {
			dropdownElement.addClassName(className);
		});
		if (this.element.disabled) {
			dropdownElement.addClassName('disabled');
		}
		
		var ddfield = new Element('div', {'class': 'ddfield'});
		var currentValueField = new Element('a', {href: 'javascript:void(0);'});
		currentValueField.update('&nbsp;');
		ddfield.insert(currentValueField);
		
		var ddbox = new Element('div', {'class': 'ddbox', style: 'display:none'});
		var ul = new Element('ul');
		this.element.select('option').each(function(option) {
			var attrs = {};
			if (option.disabled == true) {
				attrs['class'] = 'disabled';
			}
			var li = new Element('li', attrs);
			li.update('<a href="javascript:void();">' + option.text + '</a>');
			li.dropDownOption = option;
			option.dropDownOption = li;
			ul.insert(li);
			li.observe('click', this.valueSelectHandler.bind(this));
		}.bind(this));
		ddbox.insert(ul);
		
		dropdownElement.insert(ddfield);
		dropdownElement.insert(ddbox);
		
		if (!this.element.visible()) {
			dropdownElement.hide();
		}
		
		this.element.insert({after: dropdownElement});
		
		this.dropdown = dropdownElement;
		this.field = ddfield;
		this.elements = ddbox;
		this.valueField = currentValueField;
	},
	
	initValues: function() {
		var initialValue = null;
		var selected = null;
		this.element.select('option').each(function(option) {
			if (initialValue == null && option.hasClassName('initial')) {
				initialValue = option;
			}
			if (option.selected) {
				selected = option;
			}
		});
		this.selectValue(initialValue && initialValue == selected ? initialValue : selected, true);
		if (initialValue) {
			initialValue.dropDownOption.hide();
		}
	},
	
	initBehaviour: function() {
		var elementConfig = this.element.getConfiguration('DropDownBox', true);
		// Behaviour config must be put as next sibling to support f***ing IE!!!
		if (elementConfig) {
			this.behaviourConfig = elementConfig;
			this.element.observe('change', this.changeBehaviourHandler.bind(this));
		}
	},
	
	selectValue: function(option, dontFireChange) {
		if (option) {
			var optionNotDisabled = !option.disabled;
			if (Prototype.Browser.WebKit && !optionNotDisabled) {
				var select = option.up('select');
				if (select && select.disabled) {
					optionNotDisabled = true;
				}
			}
			if (optionNotDisabled) {
				this.valueField.update(option.innerHTML);
				option.selected = true;
			}
			if (!dontFireChange && !this.element.disabled && !option.disabled) {
				this.element.simulate('change');
			}
		}
	},
	
	valueSelectHandler: function(ev) {
		var el = Event.element(ev);
		if (el.nodeName != 'LI') {
			el = el.up('li');
		}
		this.selectValue(el.dropDownOption);
		this.hide();
		Event.stop(ev);
	},
	
	externalClickHandler: function(ev) {
		if (this.open) {
			this.hide();
		}
	},
	
	clickHandler: function(ev, dropDownBox) {
		if (!this.element.disabled) {
			this[this.open ? 'hide' : 'show']();
		}
		Event.stop(ev);
	},
	
	enterLeaveHandler: function(ev) {
		if (['mouseover', 'mouseenter'].indexOf(ev.type) != -1) {
			if (this.open && this.waitingForClose && this.closeExecuter) {
				this.closeExecuter.stop();
				this.closeExecuter = null;
				this.waitingForClose = false;
			}
		} else {
			if (this.open && !this.waitingForClose) {
				this.closeExecuter = new PeriodicalExecuter(this.hide.bind(this), ClientSideConstants.DropDownBox.closeDelay);
				this.waitingForClose = true;
			}
		}
	},
	
	show: function() {
		if (!this.open && !this.element.disabled) {
			if (DropDownBox.open) {
				DropDownBox.open.hide();
			}
			this.elements.show();
			this.open = true;
			DropDownBox.open = this;
		}
	},
	
	hide: function() {
		if (this.open) {
			this.elements.hide();
			this.waitingForClose = false;
			if (this.closeExecuter) {
				this.closeExecuter.stop();
				this.closeExecuter = null;
			}
			this.open = false;
			DropDownBox.open = null;
		}
	},
	
	changeBehaviourHandler: function(ev) {
		if (this.behaviourConfig) {
			var value = $F(this.element);
			if (this.behaviourConfig.behaviour == 'urlSelection') {
				if (value && value != '') {
					window.location.href = value;
				}
			} else if (this.behaviourConfig.behaviour == 'clickElement') {
				if (this.behaviourConfig.options && this.behaviourConfig.options.elementId) {
					var elementId = this.behaviourConfig.options.elementId;
					var theElement = $(elementId);
					if (theElement && theElement.click) {
						theElement.click();
					}
				}
			}
		}
	}
});
DropDownBox.open = null;
DropDownBox.init = function() {
	$$('select.dropdown').each(function(el) {
		new DropDownBox(el);
	});
}

/**
 * Handle MiniCart.
 */
var MiniCart = null;

var MiniCartHandler = Class.create({

	form: null,
	isClosing: null,
	isOver: null,
	isDeactivated: null,
	addToCardButtons: null,
	/*addToCardActiveImages: null,
	addToCardInactiveImages: null,*/
	content: null,
	forcedClose: null,
	hiddenDropdowns: null,

	initialize: function() 
	{
		this.addToCardButtons = new Array();
		this.addToCardActiveImages = new Array();
		this.addToCardInactiveImages = new Array();

		$$('.jsAddToCartButton').each(function(el) 
			{
				this.registerAddToCartButton(el);
			}.bind(this));
		this.initializeMiniCartArea();
		$(document.body).observe('ajaxLogin:succeeded', function() {
			this.initializeMiniCartArea();
		}.bind(this));
	},
	
	registerAddToCartButton: function(element) {
		if (element) {
			element.onclick = this.clickHandler.bind(this);
			this.form = element.form;
			if(this.addToCardButtons.indexOf(element) < 0){
				/*var elementActiveImage = new Image();
				elementActiveImage.src = element.src;
				var elementInactiveImage = new Image();
				elementInactiveImage.src = element.src.replace(/.gif/,"_deactivated.gif");*/
				this.addToCardButtons.push(element);
				/*this.addToCardActiveImages.push(elementActiveImage);
				this.addToCardInactiveImages.push(elementInactiveImage);*/
			}
		}
		this.reactivatedAddToCartButtons();
	},
	
	deactivateAddToCartButtons: function() {
		this.isDeactivated = true;
		if(this.addToCardButtons){
			for(var i = 0; i < this.addToCardButtons.length; i++){
				this.addToCardButtons[i].active = false;
				//this.addToCardButtons[i].src = this.addToCardInactiveImages[i].src;
			}				
		}
	},
	
	reactivatedAddToCartButtons: function() {
		this.isDeactivated = false;
		if(this.addToCardButtons){
			for(var i = 0; i < this.addToCardButtons.length; i++){
				this.addToCardButtons[i].active = true;
				//this.addToCardButtons[i].src = this.addToCardActiveImages[i].src;
			}				
		}		
	},
	
	initializeMiniCartArea: function() {
		var minicart = $('minicart');
		this.isClosing = false;
		this.isOver = false;
		this.forcedClose = false;
		if (minicart) {
			this.content = $('minicartcontent');
			if (this.content && !this.content.hasClassName('basketEmpty') && !this.content.hasClassName('dontExpand')) {
				/* TAL: NO minicart flyout
				 
				minicart.observe('mouseover', this.mouseOverHandler.bind(this));
				minicart.observe('mouseout', this.mouseOutHandler.bind(this));
				var closeButtons = this.content.select('.minicartCloseButton');
				closeButtons.each(function(e) {
					e.onclick = this.closeButtonClick.bind(this);
				}.bind(this));
				
				*/
			}
		}
	},
	
	clickHandler: function(event) {
		if(!this.isDeactivated){
			this.addToCart();
		}
		return false;
	},
	
	mouseOverHandler: function(event) {
		if (!this.forcedClose) {
			this.isOver = true;
			this.isClosing = false;
			if (this.content && !this.content.visible()) {
				this.content.show();
				this.content.style.left = ($('header').positionedOffset().left + 554) + 'px';
				this.hiddenDropDowns = [];
				if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
					$('main').getElementsBySelector('select').each(function(el,i){
						if (el.overlaps(this.content)) {
							this.hiddenDropDowns.push(el);
							el.style.visibility = 'hidden';
						}
					}.bind(this));
				}
				this.isClosing = false;
			}
		}
	},
	
	mouseOutHandler: function(event) {
		if (this.content && this.content.visible()) {
			setTimeout('MiniCart.hideMiniCart()',1000);
			this.isOver = false;
			this.isClosing = true;
		}
	},
	
	closeButtonClick: function() {
		this.forcedClose = true;
		this.isClosing = true;
		this.isOver = false;
		this.hideMiniCart();
		return false;
	},
	
	hideMiniCart: function() {
		if (this.content && this.content.visible() && this.isClosing && !this.isOver) {
			this.content.hide();
			this.hiddenDropDowns.each(function(el) {
				el.style.visibility = 'visible';
			});
			this.hiddenDropDowns = [];
			this.isClosing = false;
			this.forcedClose = false;
		}
		return false;
	},

	addProduct: function(prodID) {
		var data = 'pid=' + prodID + '&Quantity=1';
		this.addToCart(data);
		return false;
	},

	addToCart: function(data) {
		var miniCartUrl = $F('miniCartURL');
		if (miniCartUrl) {
			var postdata = null;
			if (data) {
				postdata = data;
			} else {
				postdata = $(this.form).serialize();
			}
			if (Overlay) {
				Overlay.hideAll();
			}
			StatusWindow.openProgressWindow();
			document.body.style.cursor = 'wait';
			new Ajax.Request(miniCartUrl, {postBody: postdata, onSuccess: this.successHandler, onFailure: this.errorHandler});
		}
	},
	
	successHandler: function(req) {
		var minicart = $('minicart');
		var contentParts = req.responseText.split(Constants.ajax.contentSplitter);
		minicart.update(contentParts[0]);
		$('addtocartview').update(contentParts[1]);
		//tabHandlerInit();		
		StatusWindow.close();
		var addtocartoverlay = new Overlay('addtocartview');
		addtocartoverlay.show(200);
		//slideGalleryInit();
		document.body.style.cursor = 'auto';
		MiniCart.initializeMiniCartArea();
		//initializePopupLinkHandler();
		//document.fire("tracking:onAjaxSuccess", {elementID : 'addtocartview'});
	},
	
	errorHandler: function(req) {
		document.body.style.cursor = 'auto';
		StatusWindow.close();
		AjaxErrorHandler(req);
	}
});


/**
 * Handle WishList
 */
var WishList = {
	init: function() {
		$$('.addToWishlistButton').each(function(el) {
			if (!el.addWishlistButton) {
				el.observe('click', this.buttonClickHandler.bind(this));
				el.addWishlistButton = true;
			}
		}.bind(this));
	},
	
	buttonClickHandler: function(ev) {
		var el = Event.element(ev);
		StatusWindow.openProgressWindow();
		var elConfig = el.getConfiguration('Wishlist');
		var multiadd = false;
		if (elConfig && elConfig.multiAdd) {
			multiadd = elConfig.multiAdd;
		}
		Event.stop(ev);
		if (!multiadd) {
			new Ajax.Request(el.href, {onSuccess: this.addSuccess.bind(this), onFailure: AjaxErrorHandler});
		} else {
			var parameters = {};
			var products = [];
			$$('input.pid').each(function(el) {
				if (!el.hasClassName('remove')) {
					products.push(el.value);
				}
			});
			if (!products || products.length == 0) {
				StatusWindow.close();
				StatusWindow.message(elConfig.noSelectionTitle, elConfig.noSelectionMessage, 3000, false);
				return;
			}
			parameters.pid = products;
			new Ajax.Request(elConfig.addURL, {parameters: parameters, onSuccess: this.addSuccess.bind(this), onFailure: AjaxErrorHandler});
		}
	},
	
	addSuccess: function(transport) {
		StatusWindow.close();
		var contentParts = transport.responseText.split(Constants.ajax.contentSplitter);
		var responseProlog = contentParts[0].removeXMLComments();
		var prolog = null;
		try {
			eval('prolog=' + responseProlog);
		} catch(e) {
			prolog = {success: false};
		}
		if (prolog.success == true) {
			var wishlistCount = $('wishlistCount');
			if (wishlistCount) {
				wishlistCount.update(prolog.wishlistCount);
			}
		}
		StatusWindow.message(contentParts[1], contentParts[2], 3000, false);
	}
};

var LinkedInputField = {
	init: function() {
		$$('input.linkToButton').each(function(el) {
			if (!el.linkedInputField) {
				var configComment = el.nextSiblingComment();
				if (configComment) {
					var config = configComment.getObjectForComponent('LinkedInputField');
					var linkedEl = $(config.linkedElement);
					if (linkedEl) {
						el.observe('keypress', this.keyHandler.bind(this));
						el.linkedInputField = linkedEl;
					}
				}
			}
		}.bind(this));
	},
	
	keyHandler: function(ev) {
		if (ev.keyCode == Event.KEY_RETURN) {
			var el = Event.element(ev);
			Event.stop(ev);
			if (!Prototype.Browser.Gecko) {
				el.linkedInputField.click();
			} else {
				this.fakeClickForGecko(el.linkedInputField);
			}
		}
	},
	
	fakeClickForGecko: function(el) {
		var form = el.form;
		form.insert(new Element('input', {type:'hidden', name: el.name, value: el.value}));
		form.submit();
	}
};

var PrintButton = {
	init: function() {
		$$('.printButton').each(function(el) {
			if (!el.printButton) {
				el.observe('click', function(ev) {
					Event.stop(ev);
					window.print();
				});
				el.printButton = true;
			}
		});
	}
};

var CheckFieldOnFocus = Class.create({
	element: null,

	initialize: function(element) {
		if (!element.checkFieldOnFocus) {
			this.element = element;
			
			var config = this.element.nextSiblingComment();
			if (config) {
				var confObj = config.getObjectForComponent('CheckFieldOnFocus');
				if (confObj && confObj.linkedElements) {
					confObj.linkedElements.each(function(id) {
						var el = $(id);
						if (el) {
							el.observe('focus', this.focusHandler.bind(this));
						}
					}.bind(this));
					this.element.checkFieldOnFocus = true;
				}
			}
		}
	},
	
	focusHandler: function(ev) {
		if (!this.element.checked) {
			this.element.checked = true;
		}
	}
});
CheckFieldOnFocus.init = function() {
	$$('input.checkFieldOnFocus').each(function(el) {
		new CheckFieldOnFocus(el);
	});
}

function AjaxErrorHandler(transport) {
	var responseText = transport.responseText;
	var contentParts = responseText.split(Constants.ajax.contentSplitter);
	
	var errorInformation = {};
	try {
		var str = contentParts[0];
		str = str.removeXMLComments();
		
		errorInformation = eval(str)[0];
	} catch(e) {
	}
	
	if (errorInformation.ajaxError.statuswnd) {
		StatusWindow.message("",errorInformation.ajaxError.message,3000);
	} else {
		
		var errorContent = contentParts[1];
		
		$('ajaxErrorContent').update(errorContent);
		new Overlay('ajaxError').show();
		
		if (StatusWindow.isOpen) {
			StatusWindow.close();
		}
	}
}


var StatusWindow = {

	isOpen: null,

	init: function() {
		this.statusWindow = $('statusWnd');
		if (this.statusWindow) {
			this.statusWindow.select('a.statusClose').each(function(link) {
				link.observe('click', this.closeLinkClick.bind(this));
			}.bind(this));
			this.hideAllWindows();
			
			this.isOpen = false;
			this.yesButton = $('statusWindowYes');
			this.noButton = $('statusWindowNo');
			if (this.yesButton) {
				this.yesButton.observe('click', this.buttonHandler.bindAsEventListener(this, 'yes'));
			}
			if (this.noButton) {
				this.noButton.observe('click', this.buttonHandler.bindAsEventListener(this, 'no'));
			}
		}
	},
	
	closeLinkClick: function(ev) {
		if(Prototype.Browser.IE9) {
			Event.stop(event);
		} else {
			Event.stop(ev);
		}
		this.close();
	},
	
	hideAllWindows: function() {
		this.statusWindow.select('.statusCont').each(function(statusCont) {
			statusCont.hide();
		}.bind(this));
	},
	
	open: function(id, delay, showButtons) {
		if (this.statusWindow.visible()) {
			this.close();
		}
		if (id) {
			element = this.statusWindow.select('#' + id + '.statusCont');
			if (element.length > 0) {
				element[0].show();
				element[0].style.display = 'block';
				this.statusWindow.show();
				this.statusWindow.style.display = 'block';
				this.isOpen = true;
				
				var y = window.scrollY ? window.scrollY : document.documentElement.scrollTop+document.body.scrollTop;
				this.statusWindow.style.marginTop = y + 'px';

				if (delay && delay > 0) {
					window.setTimeout('StatusWindow.close()', delay);
				}
				if (showButtons && null!=$('layerBttns')) {
					$('layerBttns').style.display = 'block';
				}
					
				return true;
			} else {
				return false;
			}
		}
		return false;
	},

	close: function() {
		if (this.isOpen) {
			this.statusWindow.fire('statuswindow:close');
		}
		this.hideAllWindows();
		this.statusWindow.hide();
		this.isOpen = false;
	},
	
	buttonHandler: function(ev, buttonType) {
		Event.stop(ev);
		if (buttonType == 'yes') {
			this.statusWindow.fire('statuswindow:yes');
		} else if (buttonType == 'no') {
			this.statusWindow.fire('statuswindow:no');
		}
		this.close();
	},

	message: function(header, msg, delay, showButtons) {
		if (null != header) {
			$('statusWndHeader').update(header);
		}
		$('statusWndMessageContent').update(msg);
		StatusWindow.open('statusWndMessage', delay, showButtons);
	},
	
	showUrl: function(url, parameter, hideClose) {
		if (null!=url) {
			new Ajax.Updater('statusWndAjaxContent', url, {
				method: 'post', 
				parameters: parameter ,
				onSuccess: function(transport) {
					if(hideClose) {
						$('statusWndAjax_close').hide();
					}
					StatusWindow.open('statusWndAjax');		
				}
			});
		}
	},
	showSize: function(url, parameter, hideClose) {
		if (null!=url) {
			new Ajax.Updater('statusWndSizeContent', url, {
				method: 'post', 
				parameters: parameter ,
				onSuccess: function(transport) {
					if(hideClose) {
						$('statusWndSize_close').hide();
					}
					StatusWindow.open('statusWndSize');		
				}
			});
		}
	},
	openProgressWindow: function() {
		this.open('statusWndPleaseWait');
	}
};

var StatusWindowError = {
	init: function() {
		$$('.statusWindowErrors').each(function(el) {
			if (!el.statusWindowErrorShown) {
				var errorMessages = el.select('.errorMsg');
				if (errorMessages.length > 0) {
					var theMsg = '';
					errorMessages.each(function(msg) {
						theMsg += '<span class="errorMsg">' + msg.innerHTML + '</span><br/>';
					});
					StatusWindow.message('', theMsg);
				}
				el.statusWindowErrorShown = true;
			}
		});
	}
};

var InfoLinkHandler = Class.create({
	initialize: function(el) {
		if (!el.infoLinkHandler) {
			el.observe('click', this.clickHandler);
			el.infoLinkHandler = true;
		}
	},
	
	clickHandler: function(ev) {
		if(Prototype.Browser.IE9) {
			Event.stop(event);
		} else {
			ev.preventDefault();
			Event.stop(ev);
		}
		var el = Event.element(ev);
		StatusWindow.showUrl(el.href);
	}
});
InfoLinkHandler.init = function() {
	$$('a.jsInfoLink').each(function(el) {
		new InfoLinkHandler(el);
	});
};

var InfoSizeHandler = Class.create({
	initialize: function(el) {
		if (!el.infoSizeHandler) {
			el.observe('click', this.clickHandler);
			el.infoSizeHandler = true;
		}
	},
	
	clickHandler: function(ev) {
		Event.stop(ev);
		var el = Event.element(ev);
		StatusWindow.showSize(el.href);
	}
});
InfoSizeHandler.init = function() {
	$$('a.jsInfoSize').each(function(el) {
		new InfoSizeHandler(el);
	});
};

var ConfirmDialogHandler = Class.create({
	element: null,
	config: null,
	
	initialize: function(el) {
		if (el && !el.confirmDialogHandler)  {
			this.element = el;
			this.clickHandlerFunc = this.clickHandler.bind(this);
			el.observe('click', this.clickHandlerFunc);
			this.config = el.getConfiguration('ConfirmDialogHandler', true);
			if (!this.config) {
				this.config = el.getConfiguration('ConfirmDialogHandler');
			}
			el.confirmDialogHandler = this;
			if(Prototype.Browser.IE7)
			{
				if(el.hasClassName('ie7show')) el.style.display="block";
				if(el.hasClassName('ie7hide')) el.style.display="none";
			}
			else {
				if(el.hasClassName('ie7show')) el.style.display="none";
				if(el.hasClassName('ie7hide')) el.style.display="block";
			}
		}
	},
	
	clickHandler: function(ev) {
		Event.stop(ev);
		
		var statWnd = StatusWindow.statusWindow;
		this.yesListener = this.buttonHandler.bindAsEventListener(this, 'yes');
		this.noListener = this.buttonHandler.bindAsEventListener(this, 'no');
		this.closeListener = this.buttonHandler.bindAsEventListener(this, 'close');
		statWnd.observe('statuswindow:yes', this.yesListener);
		statWnd.observe('statuswindow:no', this.noListener);
		statWnd.observe('statuswindow:close', this.closeListener);
		
		if(this.config.yes_text != null) {
			$('statusWindowYes').value = this.config.yes_text;
		}
		
		if(this.config.no_text != null) {
			$('statusWindowNo').value = this.config.no_text;
		}
		
		if(this.config.hideClose == "true") {
			$('statusWndMessage_Close').hide();
		}
		
		StatusWindow.message(this.config.header, this.config.message, -1, true);
	},
	
	buttonHandler: function(ev, type) {
		var statWnd = StatusWindow.statusWindow;
		statWnd.stopObserving('statuswindow:yes', this.yesListener);
		statWnd.stopObserving('statuswindow:no', this.noListener);
		statWnd.stopObserving('statuswindow:close', this.closeListener);
		
		if (type == 'yes') {
			this.element.stopObserving('click', this.clickHandlerFunc);
			if (this.element.nodeName == 'A') {
				window.location.href = this.element.href;
			} else {
				this.element.setAttribute("type","submit");
				//this.element.attr('type', 'submit')
				this.element.click();
			}
		}
	}
});
ConfirmDialogHandler.init = function() {
	$$('.jsConfirmAction').each(function(el) {
		new ConfirmDialogHandler(el);
	});
};

var PopupLinkHandler = Class.create({
	
	popupParams : ['windowname','height','width','top','left','scrollbars'],

	element : null,
	url     : null,
	
	windowname : null,
	height     : null,
	width      : null,
	top        : null,
	left       : null,
	scrollbars : null,

	initialize : function(element) {
		if (element) {
			if (!element.popupLinkHandler) {
				element.popupLinkHandler = this;
				element.onclick = this.clickHandler;
				this.element = element;
				var params = element.href.toQueryParams();
				
				this.popupParams.each(function(key) {
					if (params[key]) {
						this[key] = params[key];
						delete(params[key]);
					}
				}.bind(this));
				this.url = element.href.substring(0, element.href.indexOf('?')) + '?' + Object.toQueryString(params);
			}
		}
	},
	
	clickHandler : function() {
		
		var popupLinkHandler = this.popupLinkHandler;
		
		var wndParams = 'dependent=no,menubar=no,toolbar=no,status=no,location=no,locationbar=no,resizeable=yes';
		wndParams += ',width='  + (popupLinkHandler.width  ? popupLinkHandler.width  : Constants.popup.defaultWidth);
		wndParams += ',height=' + (popupLinkHandler.height ? popupLinkHandler.height : Constants.popup.defaultHeight);
		wndParams += ',top='    + (popupLinkHandler.top    ? popupLinkHandler.top    : Constants.popup.defaultTop);
		wndParams += ',left='   + (popupLinkHandler.left   ? popupLinkHandler.left   : Constants.popup.defaultLeft);
		wndParams += ',scrollbars='   + (popupLinkHandler.scrollbars   ? popupLinkHandler.scrollbars   : Constants.popup.defaultScrollbars);
		
		var wndName = popupLinkHandler.windowname ? popupLinkHandler.windowname : Constants.popup.defaultWindowName;
		var wnd = window.open(popupLinkHandler.url, wndName, wndParams);
		return false;
	}
});
PopupLinkHandler.init = function() {
	var popupLinks = $$('a.trackinfo');
	//popupLinks = popupLinks.concat($$('a.somethingelse'));
	popupLinks.each(function(element) {
		new PopupLinkHandler(element);
	});
}

var Captcha = {
	init: function() {
		if (!this.initialized) {
			this.captchaImage = $('captchaImage');
			if (this.captchaImage) {
				this.config = this.captchaImage.getConfiguration('Captcha', true);
				if (this.config) {
					this.captchaImage.observe('click', this.clickHandler.bind(this));
					this.initialized = true;
				}
			}
		}
	},
	
	clickHandler: function(ev) {
		Event.stop(ev);
		new Ajax.Request(this.config.url, {onSuccess: function(transport) {
			this.captchaImage.src = transport.responseText;
		}.bind(this)});
	}
};

/* ===================== Login ====================== */
var login = {
	nCrackrate : 1000000,
	nTreshholddays : 365 * 100,
	nSteps : 10,

	checkPwd: function(strPass, firstName, lastName, loginName) {
		var nCombinationCount = 0;
		var pwdState = 0;

		strToCheck = '0123456789';
		if (contains(strPass, strToCheck)) {
			nCombinationCount += strToCheck.length;
		}
		strToCheck = 'abcdefghijklmnopqrstuvwxyz'; 
		if (contains(strPass, strToCheck)) {
			nCombinationCount += strToCheck.length;
		}
		strToCheck = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
		if (contains(strPass, strToCheck)) {
			nCombinationCount += strToCheck.length;
		}
		strToCheck = ',;:-_=+|//?^&!.@$�*()%~<>{}[]';
		if (contains(strPass, strToCheck)) {
			nCombinationCount += strToCheck.length;
		}
		
		var nDays = ((Math.pow(nCombinationCount, strPass.length) / login.nCrackrate) / 2) / 86400;
		var nStrongness = Math.round(nDays / login.nTreshholddays * 100);
		if (nStrongness < (strPass.length * 5)) {
			nStrongness += strPass.length * 5;
		}
		if (nStrongness > 100) {
			nStrongness = 100; 
		}
		nStrongness = Math.round(nStrongness / (100 / login.nSteps)); 

		if (strPass.length < 6 && strPass.length != 0) { 
			nStrongness = 0; 
			pwdState = 1;
		} else if ('' != firstName && strPass.toLowerCase().indexOf(new String(firstName).toLowerCase()) != -1) { 
			nStrongness = 0; 
			pwdState = 2;
		} else if ('' != lastName && strPass.toLowerCase().indexOf(new String(lastName).toLowerCase()) != -1) { 
			nStrongness = 0; 
			pwdState = 2;
		} else if ('' != loginName &&  strPass.toLowerCase() == new String(loginName).toLowerCase()) { 
			nStrongness = 0; 
			pwdState = 3;
		} else {
			pwdState = 0;
		}
		
		return {nStrongness: nStrongness, pwdState: pwdState};
		
	},

	checkPassword: function(strPass, strId, strClassname, strTextId, aTextsOutput, aTextsErrorOutput) {
		var aTexts = aTextsOutput;
		var aTextsErrors = aTextsErrorOutput;
		
		var res = login.checkPwd(strPass, firstName, lastName, loginName);
		
		oId = document.getElementById(strId);
		oId.className = strClassname + '-' + res.nStrongness;
		
		otId = document.getElementById(strTextId);
		
		if (aTexts) {
			if (res.pwdState == 0) {			
				nKey = Math.round((aTexts.length - 1) / login.nSteps * res.nStrongness);
				otId.innerHTML = aTexts[nKey];
			} else if (res.pwdState == 1) {
				otId.innerHTML = aTextsErrors[0];
			} else if (res.pwdState == 2) {
				otId.innerHTML = aTextsErrors[1];
			} else if (res.pwdState == 3) {
				otId.innerHTML = aTextsErrors[2];
			}
		}
	}
};

var PasswordStrengthCheck = Class.create({
	element: null,
	config: null,
	passwordField: null,
	descriptionField: null,
	firstNameField: null,
	lastNameField: null,
	loginNameField: null,
	strongnessBar: null,
	
	initialize: function(el) {
		if (el && !el.passwordStrengthCheck) {
			this.element = el;
			this.config = el.getConfiguration('PasswordStrengthCheck');
			if (this.config) {
				this.passwordField = $(this.config.passwordField);
				this.descriptionField = $(this.config.descriptionField);
				this.firstNameField = $(this.config.firstNameField);
				this.lastNameField = $(this.config.lastNameField);
				this.loginNameField = $(this.config.loginNameField);
				this.strongnessBar = el.down('.strongness');

				this.passwordField.observe('keyup', this.keyHandler.bind(this));
				this.checkPassword();
				el.passwordStrengthCheck = this;
			}
		}
	},
	
	keyHandler: function(ev) {
		this.checkPassword();
	},
	
	checkPassword: function() {
		var res = login.checkPwd(this.passwordField.value, this.firstNameField.value, this.lastNameField.value, this.loginNameField.value);
		
		var factor = res.nStrongness < 5 ? 0 : (res.nStrongness < 9 ? 1 : 2);
		
		var text = '';
		if (res.pwdState == 0) {			
			nKey = Math.round((this.config.texts.length - 1) / login.nSteps * res.nStrongness);
			text = this.config.texts[nKey];
		} else if (res.pwdState == 1) {
			text = this.config.errorTexts[0];
		} else if (res.pwdState == 2) {
			text = this.config.errorTexts[1];
		} else if (res.pwdState == 3) {
			text = this.config.errorTexts[2];
		}
		this.descriptionField.update(text);
		this.descriptionField.className = 'seclabel' + (factor + 1);
		this.strongnessBar.className = 'strongness strong-' + res.nStrongness;
	}
});
PasswordStrengthCheck.init = function() {
	$$('.passwordStrengthCheck').each(function(el) {
		new PasswordStrengthCheck(el);
	});
};

var ReturnKeySubmit = Class.create({
	element: null,
	config: null,

	initialize: function(el) {
		if (el && !el.ReturnKeySubmit) {
			this.element = el;
			this.config = el.getConfiguration('ReturnKeySubmit', true);
			el.observe('keypress', this.keyPressHandler.bind(this));
		}
	},
	
	keyPressHandler: function(ev) {
		if (ev && (ev.which == 13 || ev.keyCode == 13)) {
		  	Event.stop(ev);
			var form = this.element.form;
			form.insert(new Element('input', {type: 'hidden', name: this.config.action, value: ''}));
			form.submit();
		}
	}
});
ReturnKeySubmit.init = function() {
	$$('.returnKeySubmit').each(function(el) {
		new ReturnKeySubmit(el);
	});
}

var noHoverCursorFix = {
	init: function() {
		if (Prototype.Browser.IE) {
			$$('.imgMap.noHover map area').each(function(el) {
				var upEl = el.up('.noHover');
				if (upEl) {
					el.observe('mouseover', function(ev) {
						upEl.removeClassName('noHover');
					});
					el.observe('mouseout', function(ev) {
						upEl.addClassName('noHover');
					});
				}
			});
		}
	}
};

var sweepstakesHandler = {

	overlay: null,

	init: function() {
		$$('.sweepstakesLink').each(function(el) {
			if (!el.sweepstakesLink) {
				el.observe('click', this.clickHandler.bind(this));
				el.sweepstakesLink = true;
			}
		}.bind(this));
	},
	
	clickHandler: function(ev) {
		Event.stop(ev);
		var el = Event.element(ev);
		StatusWindow.openProgressWindow();
		new Ajax.Request(el.href, {method: 'get', onSuccess: this.overlayLoaded.bind(this)});
	},
	
	overlayLoaded: function(transport) {
		StatusWindow.close();
		this.initOverlay(transport.responseText);
	},
	
	initOverlay: function(markup) {
		var overlayCnt = $('sweepstakesOverlay');
		if (overlayCnt) {
			overlayCnt.update(markup);
			initComponents();
			this.overlay = new Overlay('sweepstakesOverlay');
			this.overlay.show();
			$('sweepstakesSend').observe('click', this.formSend.bind(this));
			$$('#sweepstakesOverlay a.privacyLink').each(function(el) {
				el.observe('click', function(ev) {
					Event.stop(ev);
					$('sweepstakesForm').hide();
					$('sweepstakesPrivacy').show();
				});
			});
			$$('#sweepstakesOverlay a.legalLink').each(function(el) {
				el.observe('click', function(ev) {
					Event.stop(ev);
					$('sweepstakesForm').hide();
					$('sweepstakesLegal').show();
				});
			});
			$$('#sweepstakesOverlay a.sweepstakesBack').each(function(el) {
				el.observe('click', function(ev) {
					Event.stop(ev);
					$('sweepstakesLegal').hide();
					$('sweepstakesPrivacy').hide();
					$('sweepstakesForm').show();
				});
			});
		}
	},
	
	formSend: function(ev) {
		Event.stop(ev);
		var el = Event.element(ev);
		var form = $(el.form);
		var data = form.serialize(true);
		data[el.name] = el.value;
		this.overlay.hide();
		StatusWindow.openProgressWindow();
		new Ajax.Request(form.action, {method: 'post', parameters: data, onSuccess: this.formSubmitted.bind(this)});
	},
	
	formSubmitted: function(transport) {
		StatusWindow.close();
		var splitted = transport.responseText.split(Constants.ajax.contentSplitter);
		var responseProlog = eval('(' + splitted[0].removeXMLComments() + ')');
		if (responseProlog.sweepstakesSuccess == true) {
			$('statusWndSweepstakesContent').update(splitted[1]);
			StatusWindow.open('statusWndSweepstakes');	
		} else {
			this.initOverlay(splitted[1]);
		}
	}
}

function initComponents() {
	MiniCart = new MiniCartHandler();
	ClientSideConstants.ComponentsToInit.each(function(component) {
		window[component].init();
	});
	if (null!=statusMsg && ''!=statusMsg)
		StatusWindow.message(null, statusMsg, 3000, false);
}

/**
 * Browser Check.
 */
var evilBrowserInformation = {
		isEvil : null,
		evilVersion : null
	}

function checkEvilBrowser() {
	var isEvil = /msie\s(\d)/.test(navigator.userAgent.toLowerCase());
	var ieVersion = null;
	if (isEvil) {
		var ieVersion = RegExp.$1;
	}
	evilBrowserInformation.isEvil = isEvil;
	if (isEvil) {
		evilBrowserInformation.evilVersion = ieVersion;
	}
}

checkEvilBrowser();



var DW = Class.create();
DW.Autocompleter = Class.create(Ajax.Autocompleter, 
{
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

	selectEntry : function() {
		this.active = false;
		if( this.index>-1 ) {
			this.updateElement(this.getCurrentEntry());
		} else {
			if( this.afterUpdateElement ) this.afterUpdateElement(this.element,null);
		}
	},
	updateChoices: function(choices) {
		if(!this.changed && this.hasFocus) {
	    	this.update.innerHTML = choices;
	    	Element.cleanWhitespace(this.update);
	    	Element.cleanWhitespace(this.update.down());
	
	    	if(this.update.firstChild && this.update.down().childNodes) {
	        	this.entryCount = this.update.down().childNodes.length;
	        
	        	for (var i = 0; i < this.entryCount; i++) {
	          		var entry = this.getEntry(i);
	          		entry.autocompleteIndex = i;
	          		this.addObservers(entry);
	        	}
	      	} else {
	        	this.entryCount = 0;
	      	}
	
	      	this.stopIndicator();
	      	this.index = -1;
	
	      	if(this.entryCount==1 && this.options.autoSelect) {
	        	this.selectEntry();
	        	this.hide();
	      	} else {
	        	this.render();
				this.active = false;
	      	}
	    }
	}
});

var SearchUtils = {

		doAutoCompletionSearch : function(text,li) {
			$('SimpleSearchForm').submit();
		},
		
		prefillSimpleSearch : function() {
			var q = MiscUtils.getQuerystring(window.location.href,"q");
			var qold = MiscUtils.getQuerystring(window.location.href,"qold");
			if (qold != ""){
				$('SimpleSearchForm').q.value=qold;
			}
			else if ( q != "" && document.forms.SimpleSearchForm && typeof( $('SimpleSearchForm').q ) != 'undefined' ){
				$('SimpleSearchForm').q.value=q;
			}
		},
		
		cleanIO : function(text) {
			if (text != null) {
				return text.replace(/(.*)javascript:(.*)/g, "").replace(/<(.*)script(.*)/g, "").replace(/(.*)eval\((.*)\)/g, "");
			}
			else {
				return null;
			}	
		}

	};


var MiscUtils = {
		getQuerystring : function(url, key, default_) {
		  if (default_==null) default_="";
		  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
		  var qs = regex.exec(url);
		  if(qs == null)
		    return default_;
		  else
		    return SearchUtils.cleanIO(decodeURIComponent(qs[1].replace(/\+/g,' ')));
		}
	};

/**
 * Initialize page components.
 */
document.observe('dom:loaded', function() {
	initComponents();
	document.fire('components:initialized');
});

