/* 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) {}

/*
 * Register more initializations here
 */
window.onload = function()
{
	// Don't initialize things this way!!! It's bad, evil and not recommended.
}

/* 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();

		return (((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)));
	}
});

/**
 * 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 });
})()

/*
 * This function is used to submit forms in iBoxes and reload the content.
 */
function formSubmitToiBox(form, showLoadingPanel) {
	
	if (!$(form)) return;
	
	if (showLoadingPanel) {
		iBox.showLoading();
	}
	
	form.request({
		onComplete: function(transport) {
			iBox.show(transport.responseText);
		}
	});
}

/*
	Opens a new window with the provided url and dimension. Used
	for Scene7 and other situations.

	@param url the url to open
	@param width the window width
	@param height the window height
*/
function openPopup( url, width, height )
{
	if (url != null)
	{
		if (width != null && height != null)
		{
			window.open(url, "", "width=" + width +", height=" + height +", scrollbars=no, resizable=yes");
		}
		else
		{
			window.open(url, "", "scrollbars=no, resizable=yes");
		}
	}
}


/*
 * Support for the compare window
 */
ProductCompare = {
	openPopup: function( url ) {
		window.open(
			url,
			'product_compare',
			'width=800,height=600,scrollbars=yes,resizable=yes',
			true /* replace history in the popped up window */
		).focus();
	}
}


/*
 * Functionality around the mini cart.
 */
var MiniCart = {
	// flag, whether cart is open or not
	isDown: false,

	// timer for automatic close of cart item view
	timer: null,
	
	// the arrow in the minicart
	navlnk : null,
	
	// the image in the minicart
	cartlnk : null,	
	
	isSliding : false,
	
	init: function() {
		this.navlnk = $('navlnk');
		this.cartlnk = $('cartlnk');

		if (!(this.navlnk || this.cartlnk)) {
			return;
		}
		Event.observe(this.navlnk,'click',this.handleClick.bind(this));
	
		Event.observe(this.cartlnk,'click',this.handleClick.bind(this));
		Event.observe(this.cartlnk,'mouseover',this.handleMouseOver.bind(this));
		Event.observe(this.cartlnk,'mouseout',this.handleMouseOut.bind(this));
	},
	
	cartOpen: function()
	{
		this.isSliding=true;
		Effect.SlideDown('minicartcontent',{afterFinish:function(){
			this.timer = setTimeout( 'MiniCart.cartClose()', 2500 );		
			this.isDown=true;	
			this.cartlnk.style.backgroundPosition='0px -33px';
			this.navlnk.removeClassName('activeimg');
			this.navlnk.addClassName('inactiveimg');		
			this.isSliding=false;
		}.bind(this)});
	},	
	
	cartClose: function()
	{
		this.isSliding=true;
		if ( this.timer != null )
		{
			clearTimeout( this.timer );
			this.timer = null;
			Effect.SlideUp('minicartcontent',{afterFinish:function(){
				this.isDown=false;	
				this.cartlnk.style.backgroundPosition='0px 0px';
				this.navlnk.removeClassName('inactiveimg');
				this.navlnk.addClassName('activeimg');		
				this.isSliding=false;
			}.bind(this)});
		}
	},
	
	handleMouseOver: function() {
		this.cartlnk.style.backgroundPosition='0px -33px';
	},
	
	handleMouseOut: function() {
		this.cartlnk.style.backgroundPosition='0px 0px';
	},
	
	handleClick: function() {
		if(!MiniCart.isSliding)
		{
			if (MiniCart.isDown) {
				MiniCart.cartClose();
			}
			else {
				MiniCart.cartOpen();
			}
		}
	}
}

var TopNavSelection = {
	initialize : function() {
		var selectedContentID = $('currentlySelectedContentId');
		$$('#mainmenu li a').each(function(element) {
			var params = element.href.toQueryParams();
			// when cid was not found as a parameter
			// try to parse it from the url
			if((!("cid" in params) || params.cgid == "") && element.href.match(/([^/]*),[^,]*,pg\.html/)) {
				params.cid = RegExp.$1;
			}
			if (element.href.endsWith('#')) {
				params.cid = null;
			}
			
			if (params.cid && selectedContentID && selectedContentID.value == params.cid) {
				element.up().addClassName('active');
			}
		});
	}
};

var SearchButton = {
	
	searchbtn : null,
	searchinput : null,
	hasFocus : false,
	
	hovertop : 20,
	outtop : 3,
	
	initialize : function() {
		this.searchbtn = $('SearchButton');
		this.searchinput = $('SearchInput');

		if (this.searchbtn && this.searchinput) {
			this.searchbtn.observe('mouseover', this.btnOver.bindAsEventListener(this, true));
			this.searchbtn.observe('mouseout', this.btnOver.bindAsEventListener(this, false));
			this.searchinput.select('input')[0].observe('focus', this.inputFocus.bindAsEventListener(this, true));
			this.searchinput.select('input')[0].observe('blur', this.inputFocus.bindAsEventListener(this, false));
		}
	},
	
	btnOver : function(ev, over) {
		if (over) {
			this.searchbtn.select('span').each(function(el) {
   				el.setStyle({
   					backgroundPosition: '0px -' + SearchButton.hovertop + 'px',
   					color: '#FFFFFF'
   				});
   			}); 
   			this.searchinput.setStyle({backgroundPosition: '0px -' + SearchButton.hovertop + 'px'});
		}
		else {
			if (!this.hasFocus) {
				this.searchbtn.select('span').each(function(el) {
	   				el.setStyle({
	   					backgroundPosition: '0px ' + SearchButton.outtop + 'px',
	   					color: '#444444'});
	   			}); 
	   			this.searchinput.setStyle({backgroundPosition: '0px ' + SearchButton.outtop + 'px'});
	   		}		
		}
	},
	
	inputFocus : function(ev, focus) {
		this.hasFocus = focus;
		this.btnOver(ev, focus);
	}	
};

var NewsletterButton = {
	
	newsletterbtn : null,
	newsletterinput : null,
	hasFocus : false,
	
	hovertop : 20,
	outtop : 3,
	
	initialize : function() {
		this.newsletterbtn = $('NewsletterButton');
		this.newsletterinput = $('NewsletterInput');

		if (this.newsletterbtn && this.newsletterinput) {
			this.newsletterbtn.observe('mouseover', this.btnOver.bindAsEventListener(this, true));
			this.newsletterbtn.observe('mouseout', this.btnOver.bindAsEventListener(this, false));
			this.newsletterinput.select('input')[0].observe('focus', this.inputFocus.bindAsEventListener(this, true));
			this.newsletterinput.select('input')[0].observe('blur', this.inputFocus.bindAsEventListener(this, false));
		}
	},
	
	btnOver : function(ev, over) {
		if (over) {
			this.newsletterbtn.select('span').each(function(el) {
   				el.setStyle({
   					backgroundPosition: '0px -' + NewsletterButton.hovertop + 'px',
   					color: '#FFFFFF'
   				});
   			}); 
   			
		    this.newsletterinput.setStyle({backgroundPosition: '0px -' + NewsletterButton.hovertop + 'px'});
		}
		else {
			if (!this.hasFocus) {
				this.newsletterbtn.select('span').each(function(el) {
	   				el.setStyle({
	   					backgroundPosition: '0px ' + NewsletterButton.outtop + 'px',
	   					color: '#444444'});
	   			}); 
   				this.newsletterinput.setStyle({backgroundPosition: '0px ' + NewsletterButton.outtop + 'px'});
   			}		
		}
	},
	
	inputFocus : function(ev, focus) {
		this.hasFocus = focus;
		this.btnOver(ev, focus);
	}	
};

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();

/* IE6 Hover Fix */
var IE6HoverFix = Class.create({
 
	element: null,
 
	initialize: function(el) {
		if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
			if (!el.hoverFixAttached) {
				this.element = el;
				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,a.previous').each(function(el) {
			new IE6HoverFix(el);
		});
	}
}

/** 
 * Calls a function in ie6 only to fix a hover problem for elements which are inserted dynamically per XHR.
 * The function called is included per conditional comment.
 * @params obj 
 */
function imgLoaded(obj) {
	if (typeof IE6Hover !== 'undefined') {
		IE6Hover.fixXHRElement(obj);
	}
}

document.observe('dom:loaded', function() {
	MiniCart.init();
	initIE6HoverFix();
	TopNavSelection.initialize();
	SearchButton.initialize();
	NewsletterButton.initialize();
});
