/*
 * All java script logic for the Demandware reference application.
 *
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */

// IMPORTANT!!! This removes flickering of background images in IE
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


/** 
 * This class helps to synchronize the functions of a hidden formfield, with his subsituted 
 * elements.
 * e.g. a phone number is split up into 2 fields using javascript
 * This Helper Class holds the parent element and the children derived from it.
 *  
 */
var FieldExchangeHelper = Class.create({			
 	parent: '',
	children:null,
 
 	/**
 	* Constructor
 	* @param parent : String - id of hidden form field
 	* @param children : Array of String - ids of the new created form items
 	*/
	initialize : function(parent, children) {
		this.parent = parent;
		this.children = children;
	},
 
 	/**
 	* synchronizes the children form fields to it's parent after entering data
 	* @param (optional) fillingChar : String - divider char between the values (. in 01.01.1970) 
 	*/
	fillHiddenField : function (fillingChar) {
		document.getElementById(this.parent).value = "";
		for (var i = 0; i < this.children.length; i++) {
			document.getElementById(this.parent).value += (((i != 0) && (typeof(fillingChar) != 'undefined')) ? fillingChar : '') + document.getElementById(this.children[i]).value;
		}
	}
});

function set_cookie(my_cookie, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = my_cookie + "=" + value + expires + "; path=/";
}

function read_cookie(my_cookie) {
	var my_cookie_eq = my_cookie + "=";
	var ca = document.cookie.split(';');
	for (var i=0; i < ca.length; i++) {
 		var c = ca[i];
		while (c.charAt(0)==' ') {
			c = c.substring(1,c.length);
		}
		if (c.indexOf(my_cookie_eq) == 0) {
			return c.substring(my_cookie_eq.length,c.length);
		}
	}
	return null;
}

function allowNumbers(field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if ((keyCode > 34 && keyCode < 58) || keyCode == 16 || keyCode == 8 || keyCode == 9 || (keyCode > 95 && keyCode < 106)) {
		return true;
	} else {
		return 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];
	}
});

/* Extend element */
Element.addMethods({
	
	/* Return dimensions of an element */
	dimensions : function(element) {
		var vpOffset = element.viewportOffset();
		return {
			minX: vpOffset.left,
			minY: vpOffset.top,
			maxX: vpOffset.left + element.getWidth(),
			maxY: vpOffset.top + element.getHeight()
		};
	},

	/* checks if a element overlaps another one */
	overlaps : function(element, el) {
		var elDim = el.dimensions();
		var myDim = element.dimensions();

		if (((myDim.minX >= elDim.minX && myDim.minX <= elDim.maxX) || (myDim.maxX > elDim.minX && myDim.minX < elDim.maxX)) &&
        	((myDim.minY >= elDim.minY && myDim.inY <= elDim.minY) || (myDim.maxY > elDim.minY && myDim.minY < elDim.maxY))) {
			return true;
		} else {
			return false;
		}
	},
	
	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;
	},
	
	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;
	}

});


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();
		var addToCartButton = $('addToCartButton');
		if (addToCartButton) {
			this.registerAddToCartButton(addToCartButton);
		}
		this.initializeMiniCartArea();
	},
	
	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')) {
				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();
				if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion == 7) {
					this.content.style.left = ($('header').positionedOffset().left + 550) + '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();		
		var addtocartoverlay = new Overlay('addtocartview');
		addtocartoverlay.show();
		slideGalleryInit();
		document.body.style.cursor = 'auto';
		MiniCart.initializeMiniCartArea();
		initializePopupLinkHandler();
		StatusWindow.close();
	},
	
	errorHandler: function(req) {
		document.body.style.cursor = 'auto';
		StatusWindow.close();
		AjaxErrorHandler(req);
	}
});

var StatusWindow = null;

var StatusWindowHandler = Class.create({

	statusWindow: null,
	isOpen: null,

	initialize: function() {
		this.statusWindow = $('statusWnd');
		if (this.statusWindow) {
			this.statusWindow.select('a.statusClose').each(function(link) {
				link.onclick = this.closeLinkClick.bind(this);
			}.bind(this));
			this.hideAllWindows();
			this.isOpen = false;
		}
	},
	
	closeLinkClick: function(event) {
		this.close();
		return false;
	},
	
	hideAllWindows: function() {
		this.statusWindow.select('.statusCont').each(function(statusCont) {
			statusCont.hide();
		}.bind(this));
	},
	
	open: function(id, delay) {
		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);
				}
				return true;
			} else {
				return false;
			}
		}
		return false;
	},

	close: function() {
		this.hideAllWindows();
		this.statusWindow.hide();
		this.isOpen = false;
	},

	message: function(msg, delay) {
		$('statusWndMessageContent').update(msg);
		StatusWindow.open('statusWndMessage', delay);
	},

	openProgressWindow: function() {
		this.open('statusWndPleaseWait');
	}
});

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;
	}
});

function AjaxErrorHandler(transport) {
	var responseText = transport.responseText;
	var contentParts = responseText.split(Constants.ajax.contentSplitter);
	
	var errorInformation = {};
	try {
		var str = contentParts[0];
		str = removeXMLComments(str);
		
		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 IE6HoverFix = Class.create({
	
	element: null,
	
	initialize: function(el, onlyIfNotActive) {
		if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
			if (!el.hoverFixAttached) {
				this.element = el;
				if(!onlyIfNotActive || !el.hasClassName("active")){
					this.element.observe('mouseenter', this.mouseOverHandler);
					this.element.observe('mouseleave', this.mouseOutHandler);
					this.element.hoverFixAttached = true;
				}
			}
		}
	},
	
	mouseOverHandler: function(ev) {
		var element = Event.element(ev);
		element.addClassName('hover');
	},
	
	mouseOutHandler: function(ev) {
		var element = Event.element(ev);
		element.removeClassName('hover');
	}
	
});

function initIE6HoverFix() {
	if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
		$$('.prodMini,a.instructionEl,a.highlProp').each(function(el) {
			new IE6HoverFix(el,false);
		});
		$$('.colorSelector a').each(function(el) {
			new IE6HoverFix(el,true);
		});
	}
}

function removeXMLComments(str) {
	return str.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g, ''); // remove comments in response
}

function initializePopupLinkHandler() {
	var popupLinks = $$('a.popupLink');
	popupLinks.each(function(element) {
		new PopupLinkHandler(element);
	});
}

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();

function vipCouponMessage() {
	var vipCouponMessage = $('vipWelcomeCouponMessage');
	var cookieValue = read_cookie('vipCouponMessage');
	if (vipCouponMessage && cookieValue == null) {
		var msgCont = $('overlayMessageContent');
		msgCont.update(vipCouponMessage.innerHTML);
		var ol = new Overlay('overlayMessage');
		ol.show();
		document.cookie = 'vipCouponMessage=true; path=/';
	}
}


var previewRating = {

	init: function() {
		var links = $$('.previewRatingLink');
		
		links.each(function(e){
			e.observe('click', this.showPreviewRating.bind(this));
		}.bind(this));
	},
	
	initRatingHandlers: function() {
		var stars = $$('.inactiveRatingStar');
		
		stars.each(function(e){
			e.observe('click', this.rateP.bind(this));
		}.bind(this));
		stars.each(function(e){
			e.observe('mouseover', this.showRate.bind(this));
		}.bind(this));	
		stars.each(function(e){
			e.observe('mouseout', this.hideRate.bind(this));
		}.bind(this));
		
		var submitButton = $('previewRatingSubmitButton');
		if (submitButton) {
			submitButton.observe('click', this.submitPreviewRating.bind(this));
		}
	},
	
	rateP: function(event) {
		var element = Event.element(event);
		if (!element.hasClassName('activeRatingStar')) {
			element.addClassName('activeRatingStar');
		}
		if (!element.hasClassName('selected')) {
			element.addClassName('selected');
		}
		element.removeClassName('inactiveRatingStar');
		var id = element.identify().toArray().last();
		rateName = this.getRateName(element);	 
		var i = 1;
		for (i = 1; i < id; i++) {
			var es = $(rateName+i);
			es.addClassName('activeRatingStar');
			es.removeClassName('inactiveRatingStar');
		}
		for (i = id; i < 6; i++) {
			if (i != id) {
				var es = $(rateName+i);
				es.addClassName('inactiveRatingStar');
				es.removeClassName('activeRatingStar');
				es.removeClassName('selected');
			}
		}	 
	},
	
	showRate: function(event) {
		var element = Event.element(event);
		var rateName = this.getRateName(element);
		if (!element.hasClassName('activeRatingStar')) {
			element.addClassName('activeRatingStar');
		}
		var id = element.identify().toArray().last();	 

		var i = 1;
		for (i = 1; i < id; i++) {
			var es = $(rateName + i);
			if (!es.hasClassName('activeRatingStar')) {
				es.addClassName('activeRatingStar');
			}
			es.removeClassName('inactiveRatingStar');
		}
		for (i = id; i < 6; i++) {
			if (i != id) {
				var es = $(rateName + i);
				if (!es.hasClassName('inactiveRatingStar')) {
					es.addClassName('inactiveRatingStar');
				}
				es.removeClassName('activeRatingStar');
			}
		}
		 
		var descs = $$('.ratingDescription');			
		descs.each(function(e) {
			if (e.identify().startsWith(rateName)) {
				 e.setStyle({
			 		display: 'none'		
			 	});	
			}
		});	
		 
		$(rateName + 'Des' + id).setStyle({
			display: 'block'
		});
		
	},

	hideRate: function(event) {
		var element = Event.element(event);
		var rateName = this.getRateName(element);
		var selected = this.getSelectedRatingValue(rateName);
		
		var id = selected;

		var stars = [$(rateName + '5'), $(rateName + '4'), $(rateName + '3'),
		             $(rateName + '2'), $(rateName + '1')];
		var selBef = false;
		var i = 0;
		for (i = 0; i < stars.size(); i++) {
			es = stars[i];
			if (selBef) {
				if (!es.hasClassName('activeRatingStar')) {
					es.addClassName('activeRatingStar');
				}
				es.removeClassName('inactiveRatingStar');
			} else {
				if (es.hasClassName('selected')) {
					selBef = true;
				} else {
					if (!es.hasClassName('inactiveRatingStar')) {
						es.addClassName('inactiveRatingStar');
					}
					es.removeClassName('activeRatingStar');
				}
			}
		}
		if (selected != '') {
			var m = $(rateName + selected);
			if (!m.hasClassName('activeRatingStar')) {
				m.addClassName('activeRatingStar');
			}
		}

		var descs = $$('.ratingDescription');			
		descs.each(function(e) {
			if (e.identify().startsWith(rateName)) {
				e.setStyle({
					display: 'none'		
				});	
			}
		});	
		 
		var el = $(rateName + 'Des' + selected);
		if (el != null) {
			el.setStyle({
				display: 'block'
			});
		}
	},
	
	showPreviewRating: function(e) {
		var element = Event.element(e);
		var pid = element.identify();
		
	    var url = $('productRatingCallUrl').value;
				
		var pars = 'p=' + pid;
		var ajaxRequest = new Ajax.Request(url, {
			method: 'get', 
			parameters: pars, 
			asynchronous: true,
			onComplete: function(xmlHttpRequest, responseHeader) {
				this.showResponse(xmlHttpRequest, responseHeader, element);
			}.bind(this),
			onFailure: this.showResponseFailure.bind(this)
		});
	},
	
	showResponse: function(xmlHttpRequest, responseHeader, element) {
		var a = xmlHttpRequest.responseText; // Process HTTP response and update input form

		try {
			var ovQv = new Overlay('quickview');
			ovQv.hide();
		} catch(e) {
		}
				  
		var container = $('productPreviewRating');
		var content = a;
		container.update(content);
		var ratingOverlay = new Overlay('productPreviewRating', {centerOnElement: element});
		ratingOverlay.show(); 
		
		var p = $('productID').innerHTML;
		var cookieValue = read_cookie("ProductPreviewRating");
		if ((cookieValue != null) && (cookieValue != 'null')) {
			var cVs = cookieValue.split('|');
			var i = 0;
			var found = false;
			for (i = 0; i < cVs.length; i++) {
				if (cVs[i] == p){
					found = true;
					break;
				}	 	
			}		
		} 
		if (found) {
			this.hideRatingFields($F('productRatingAlreadyRatedMsg'));		 
		}
		this.initRatingHandlers();
	},
	
	showResponseFailure: function() {
	},
	
	getRateName: function(element) {
		var rateName = "";
		element.identify().toArray().each(function(txt, index) {		
			rateName = rateName + txt;			
		});
		var id = element.identify().toArray().last();
		rateName = rateName.sub(id, '');
		return rateName;
	},
	
	getSelectedRatingValue: function(rateName) {
		var value = '';
		if ($(rateName + '1').hasClassName('selected')) {
			value = '1';
		}
		if ($(rateName + '2').hasClassName('selected')) {
			value = '2';
		}
		if ($(rateName + '3').hasClassName('selected')) {
			value = '3';
		}
		if ($(rateName + '4').hasClassName('selected')) {
			value = '4';
		}
		if ($(rateName + '5').hasClassName('selected')) {
			value = "5";
		}
		return value;	
	},
	
	submitPreviewRating: function() {
	    var url = $('productRatingSubmitURL').value;
	    
		var p = $('productID').innerHTML;
		var cookieValue = read_cookie("ProductPreviewRating");
		if ((cookieValue == null) || (cookieValue == 'null')) {
			set_cookie("ProductPreviewRating", p, 30);		
		} else {
			var cVs = cookieValue.split('|');
			var i = 0;
			var found = false;
			for (i = 0; i < cVs.length; i++) {
				if (cVs[i] == p) {
					found = true;
					break;
				}	 	
			}		
		}
	    
		if (!found) {
			set_cookie("ProductPreviewRating", cookieValue + '|' + p, 30);	
			
			var lrv = this.getSelectedRatingValue('look');
			var crv = this.getSelectedRatingValue('color');
			var prv = this.getSelectedRatingValue('price');
					
			var pars = 'p=' + p + '&lrv=' + lrv + '&crv=' + crv + '&prv=' + prv;
			var ajaxRequest = new Ajax.Request(url, {
				method:       'get', 
				parameters:   pars, 
				asynchronous: true,
				onComplete:   function(transport) {
					this.hideRatingFields(transport.responseText);
					window.setTimeout(function() {
						Overlay.hideAll();
					}.bind(this), 5000);
				}.bind(this),
				onFailure: 	  this.showResponseFailure
			}); 
		} else {
			this.hideRatingFields();
		}	
	},
	
	hideRatingFields: function(message) {
		var old = $('previewRatingField');
		old.setStyle({
			display: 'none'
		});
		var msg = $('previewStatusMessage');
		msg.innerHTML = message;
		msg.setStyle({
			width: '180px'
		});
		var btn = $('previewRatingCloseButton');
		btn.setStyle({
			display: 'block'
		});
		var btnOld = $('previewRatingSubmitButton');
		btnOld.setStyle({
			display: 'none'
		});
	}
}

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,' ')));
	}
};

if ('observe' in document) {
	document.observe('dom:loaded', function() {
		MiniCart = new MiniCartHandler();
		StatusWindow = new StatusWindowHandler();
		initializePopupLinkHandler();
		initIE6HoverFix();
		vipCouponMessage();
		previewRating.init();
	});
}


