/* 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) {}

/* Extend jQuery element */
jQuery.fn.extend({
	dimensions : function() {
		
		var element = this[0];
		element = jQuery(element);
		
		var vpOffsetLeft = element.offset().left - jQuery(window).scrollLeft();
		var vpOffsetTop = element.offset().top - jQuery(window).scrollTop()
		return {
			minX: vpOffsetLeft,
			minY: vpOffsetTop,
			maxX: vpOffsetLeft + element.width(),
			maxY: vpOffsetTop + element.height()
		};
	
	},
	
	overlaps : function(el) {
		var element = this[0];
		element = jQuery(element);
		
		var elDim = jQuery(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)));
	}
});

/*
 * This function is used to submit forms in iBoxes and reload the content.
 */
function formSubmitToiBox(form, showLoadingPanel) {
	
	var formElem = jQuery(form);
	if (formElem.length == 0) return;
	
	if (showLoadingPanel) {
		iBox.showLoading();
	}
	
    jQuery.ajax({ 
    	type: "POST", url: formElem.attr('action'), data: formElem.serialize(),	success: function(resp) {
    		iBox.show(resp);
    	}
    });
    
    return false;
}

/*
	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");
		}
	}
}

/*
 * 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,	
	
	// during page loading, the Demandware URL is stored here
	url: '',
	
	// during page loading, the Demandware Cart URL is stored here
	cartURL: '',	
	
	isSliding : false,
	
	init: function() {
		this.navlnk = jQuery('#navlnk');
		this.cartlnk = jQuery('#cartlnk');
		this.minicarthead = jQuery('#minicarttotal');

		if (!(this.navlnk || this.cartlnk)) {
			return;
		}
		
		this.navlnk.bind('click', function(ev) { 
			MiniCart.handleClick(ev);
		});
		this.cartlnk.bind('click', function(ev) { 
			MiniCart.handleClick(ev);
		});
		this.navlnk.bind('mouseover', function(ev) { 
			MiniCart.handleMouseOver(ev);
		});
		this.cartlnk.bind('mouseover', function(ev) { 
			MiniCart.handleMouseOver(ev);
		});
		
		/*this.cartlnk.bind('mouseout', function(ev) { 
			MiniCart.handleMouseOut(ev);
		});*/
		
	},
	setContent: function(response) {
        // replace the content
        var minicart = jQuery('#minicart');
        minicart.html(response);
        this.init();
    },

	
	cartOpen: function()
	{
    	if (this.isSliding!=true && !this.isDown) {
			this.isSliding=true;
			
			if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
				//avoid graphic error on ie6
				jQuery('#minicartcontent').show(1);
			}
			
			jQuery('#minicartcontent').show('slide', { direction: "up" }, 1000, function() { 
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 2500 );
				MiniCart.isDown=true;
				MiniCart.isSliding=false;
			});
			
			this.cartlnk.addClass(this.cartlnk.hasClass('fullcartbutton') ? "fullCartBtnHover" : "emptyCartBtnHover");
			this.navlnk.removeClass('activeimg');
			this.navlnk.addClass('inactiveimg');		
    	}
	},	
	cartAdd: function(form, progressImageSrc) {
        // get the data of the form as serialized string
        var postdata = jQuery(form).serialize();
        // disable form
       // Form.disable(form);           
        
        // callback handler for ajax request
        var handlerFunc = function(responseText) {
           // Form.enable(form);
            
            // the minicart response contains some tracking information, which has to be splitted
            var miniCartContent = responseText;
            var trackingInfo = "";
            if (miniCartContent.indexOf("%%%%SPLITHERE%%%%") != -1) {
            	var response = miniCartContent.split("%%%%SPLITHERE%%%%");
            	response[0] = response[0].replace(/<!-- (.)* -->/, "");
            	trackingInfo = eval('(' + response[0] + ')');
            	miniCartContent = response[1];
            }
            // insert data
            MiniCart.setContent(response[1]);
            // clear timer
            if (MiniCart.timer != null) {
                clearTimeout(MiniCart.timer);
                if (!MiniCart.isSliding) MiniCart.isDown = false;
            }

            MiniCart.cartOpen();
            
    		if (trackingInfo != "") {
    			// call omniture.js
    			clickTracking.performAddToCart(trackingInfo);
    		}
        }

        var errFunc = function(req) {
            Form.enable(form);
            location.href=MiniCart.cartURL + '?MiniCartError=payment';
        }

        // add the product
            
        jQuery.ajax({
        	type: "POST",
        	url: MiniCart.url,
        	data: postdata,
        	success: handlerFunc,
        	error: errFunc
        });
    },

	cartClose: function()
	{
		this.isSliding=true;
		if ( this.timer != null )
		{
			clearTimeout( this.timer );
			this.timer = null;
			
			jQuery('#minicartcontent').hide('slide', { direction: "up" }, 1000, function() {
				MiniCart.isDown=false;	
				MiniCart.cartlnk.removeClass(MiniCart.cartlnk.hasClass('fullcartbutton') ? "fullCartBtnHover" : "emptyCartBtnHover");
				MiniCart.navlnk.removeClass('inactiveimg');
				MiniCart.navlnk.addClass('activeimg');		
				MiniCart.isSliding=false;
			});
		}
	},
	
	handleMouseOver: function() {
		this.cartlnk.addClass(this.cartlnk.hasClass('fullcartbutton') ? "fullCartBtnHover" : "emptyCartBtnHover");
		MiniCart.cartOpen();
	},
	
	handleMouseOut: function() {
		this.cartlnk.removeClass(this.cartlnk.hasClass('fullcartbutton') ? "fullCartBtnHover" : "emptyCartBtnHover");
	},
	
	handleClick: function() {
		if(!MiniCart.isSliding)
		{
			if (MiniCart.isDown) {		
				//MiniCart.cartClose();
				//normal slide up looks strange at this point (unknown reason): so use timeout again.
				if ( this.timer != null )
				{
					clearTimeout( this.timer );
					this.timer = null;
				}	
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 1 );
			}
			else {
				MiniCart.cartOpen();
			}
		}
	}
}

var TopNavSelection = {
		initialize : function() {
			var selectedContentID = jQuery('#currentlySelectedContentId');
			jQuery('#mainmenu li a').each(function(idx, element) {
				var params = TopNavSelection.unparam(element.href);
				// 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.match(/#$/)) {
					params.cid = null;
				}		
				
				if (params.cid && selectedContentID && selectedContentID.length > 0 && selectedContentID.val() == params.cid) {
					jQuery(element).parent().addClass('active');
				}
			});
		},
		
		unparam : function (value) {
		    var
		    params = {},
		    // Get query string pieces (separated by &)
		    pieces = value.replace(/\?/,'&').split('&'),
		    // Temporary variables used in loop.
		    pair, i, l;

		    // Loop through query string pieces and assign params.
		    for (i = 0, l = pieces.length; i < l; i++) {
		        pair = pieces[i].split('=', 2);
		        if (pair.length < 2) continue;
		        // Repeated parameters with the same name are overwritten. Parameters
		        // with no value get set to boolean true.
		        params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
		            decodeURIComponent(pair[1].replace(/\+/g, ' ')) : '');
		    }
		    
		    return params;
		}

	};

var AddToCartButton = {
		
	cartBtn : null,
	symbolicCartBtn : null,
	
	initialize : function() {
		this.cartBtn = jQuery('#add-to-cart-button');
		this.symbolicCartBtn = jQuery('#symbolicButtonAddToCart');
		
		this.cartBtn.bind('mouseover', function() {
			jQuery(this).addClass('cartButtonHover');
		});
		this.cartBtn.bind('mouseout', function() {
			jQuery(this).removeClass('cartButtonHover');
		});
		this.cartBtn.bind('focus', function() {
			if(jQuery(this).blur) {
				jQuery(this).blur();
			}
		});
		
		// only use add to mini cart for product details (not gift card, wishlist)
		if (jQuery('#giftcardAddToCart').length == 0 && jQuery('#wishListContainer').length == 0) {
			jQuery(this.symbolicCartBtn).add(this.cartBtn).each(function (idx, el) {
				jQuery(el).bind("click",function (ev){
					var element = jQuery(ev.target);
					var parentForms = element.parents('form');
					if (MiniCart && parentForms.length > 0) {
						ev.stopImmediatePropagation(); 
						MiniCart.cartAdd(parentForms[0]);
						return false;
					}
				});	
			});
		}
	}
}

var SearchButton = {
	
	searchbtn : null,
	searchinput : null,
	hasFocus : false,
	
	initialize : function() {
		this.searchbtn = jQuery('#SearchButton');
		this.searchinput = jQuery('#SearchInput');

		if (this.searchbtn && this.searchinput) {
			this.searchbtn.bind('mouseover', function() {
				SearchButton.btnOver(true);
			});
			this.searchbtn.bind('mouseout', function() {
				SearchButton.btnOver(false);
			})
			this.searchinput.find(':input').bind('focus', function() {
				SearchButton.inputFocus(true);
			});
			this.searchinput.find(':input').bind('blur', function() {
				SearchButton.inputFocus(false);
			});
		}
	},
	
	btnOver : function(over) {
		if (over) {
			this.searchbtn.addClass("arrowBtnHover");
   			this.searchinput.addClass("searchInputHover");
		}
		else {
			if (!this.hasFocus) {
				this.searchbtn.removeClass("arrowBtnHover");
				this.searchinput.removeClass("searchInputHover");
	   		}		
		}
	},
	
	inputFocus : function(focus) {
		this.hasFocus = focus;
		this.btnOver(focus);
	}	
};

var NewsletterButton = {
	
	newsletterbtn : null,
	newsletterinput : null,
	newsletterform : null,
	hasFocus : false,
	autosubmit : false,
	
	initialize : function() {
		this.newsletterbtn = jQuery('#NewsletterButton');
		this.newsletterinput = jQuery('#NewsletterInput')
		this.newsletterform = jQuery('#SimpleNewsletterForm');;

		if (this.newsletterbtn.length > 0 && this.newsletterinput.length > 0 && this.newsletterform.length > 0) {
			this.newsletterbtn.bind('mouseover', function() {
				NewsletterButton.btnOver(true);
			});
			this.newsletterbtn.bind('mouseout', function() {
				NewsletterButton.btnOver(false);
			});
			this.newsletterinput.find(':input').bind('focus', function() {
				NewsletterButton.inputFocus(true);
			});
			this.newsletterinput.find(':input').bind('blur', function() {
				NewsletterButton.inputFocus(false);
			});
			
			this.newsletterform.bind('submit', function(ev) {
				ev.stopImmediatePropagation(); 
				formSubmitToiBox('#SimpleNewsletterForm', true);
				return false;
			})
			this.newsletterbtn.bind('click', function(ev) {
				ev.stopImmediatePropagation(); 
				formSubmitToiBox('#SimpleNewsletterForm', true);
				return false;
			})
		}
		
		if (this.autosubmit) {
			formSubmitToiBox('#SimpleNewsletterForm', false);
		}
	},
	
	btnOver : function(over) {
		if (over) {
			this.newsletterbtn.addClass("arrowBtnHover");   			
			this.newsletterinput.addClass("newsInputHover");
		}
		else {
			if (!this.hasFocus) {
				this.newsletterbtn.removeClass("arrowBtnHover"); 
				this.newsletterinput.removeClass("newsInputHover");
   			}		
		}
	},
	
	inputFocus : function(focus) {
		this.hasFocus = focus;
		this.btnOver(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;
	}
}

/* IE6 Hover Fix */
var IE6HoverFix = {
 
	element: null,
 
	init: function(el) {
		if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
			if (!el.hoverFixAttached) {
				this.element = el;
				this.element.bind('mouseenter',  function(ev) {
					jQuery(this).addClass('hover');
				});
				this.element.bind('mouseleave',  function(ev) {
					jQuery(this).removeClass('hover');
				});
				this.element.hoverFixAttached = true;
			}
		}
	}
};

function initIE6HoverFix() {
	if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
		jQuery('.prodMini').add('a.instructionEl').add('a.highlProp').add('a.previous').each(function(ídx, el) {
			new IE6HoverFix.init(jQuery(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);
	}
}

/*
 * Changes the product image on the search result page.
 * Updates the url of the image and the product link and the name of the product variant.
 * Uses in template 'product-mini'.
 */
var loadBadgeUrl = '';
function changeVariationImgUrl(element, parentElement, productTitleElement, imageUrl, productUrl, productName, badgeUrl) {
	var imgProd = jQuery(element).parents(parentElement).find('img.productImg');
	var prodLink = jQuery(element).parents(parentElement).find('a.productLogo');
	
	if (prodLink.href != productUrl) {
		imgProd.attr('src',imageUrl);
		prodLink.attr('href',productUrl);
		jQuery(element).parents(parentElement).find(productTitleElement).replaceWith(productName);
		
		jQuery(element).parents(parentElement).find('img.overlay').each(function(e) {
			if (jQuery(this).hasClass('selectColorBorder') && jQuery(this)!=jQuery(element).find('img.overlay') ) {
	 			jQuery(this).toggleClass('selectColorBorder');	 			
	 		}
	 	});
	
	 	if (!jQuery(element).find('img.overlay').hasClass('selectColorBorder')) {
	 		jQuery(element).find('img.overlay').toggleClass('selectColorBorder');
	 	}	
	 	
	 	if (null != badgeUrl && loadBadgeUrl != badgeUrl) {
	 		loadBadgeUrl = badgeUrl;
	 		updatesBadges(element, badgeUrl);
	 	}	 	
	}
}
 
function updatesBadges(source, url) {
	var container = typeof jQuery(source).parents("div.productmini") != "undefined" ? jQuery(source).parents("div.productmini").find("div.badgeImages") : jQuery(source).parents("div.teaser").find("div.badgeImages");
	container.load(url);
}



/*
 * 
 * NaviMenu
 * 
 */

var NaviMenu = {
	menuElement: null,
	menuLayer: null,
	menuWrapper: null,
	topNavEntries: null,
	viewedElement: null,
	hiddenDropDowns: null,

	initialize: function() {
		this.menuElement = jQuery('#mainmenu');
		this.menuLayer = jQuery('#menu_layer');
		this.menuWrapper = jQuery('#menuWrapper');
		
		if (!this.menuElement || !this.menuLayer) {
			return false;
		}
		
		this.topNavEntries = jQuery('ul.menuItemList > li > a:first-child', this.menuElement);
		jQuery.each(this.topNavEntries,function(){
			var el = jQuery(this);
			var parentEl = jQuery(el).parent();			
			var hiddenMenu = jQuery('.hiddenMenu', parentEl);
			if (hiddenMenu && hiddenMenu.length > 0) {
				el.hiddenMenu = hiddenMenu[0];
			}

			el.bind('mouseover', function(ev) { 
				NaviMenu.menuOver(el);
			});
			
			el.bind('mouseout', function(ev) { 
				NaviMenu.menuOut(el);
			});
		});
		this.menuLayer.bind('mouseover', function(ev) { 
			NaviMenu.layerOver(ev);
		});
		this.menuLayer.bind('mouseout', function(ev) { 
			NaviMenu.layerOut(ev);
		});
	},
	
	calculatePosition: function(el) {
		// TODO: <iframe src="" id="overwrite" style="position:absolute;z-index:-1"></iframe>
		var itemLeft = el.offset().left - jQuery(window).scrollLeft();
		var spaceLeft = (document.body.clientWidth - 988) / 2;
	
		var wrap = spaceLeft + 988 - (itemLeft + this.menuLayer.width()); //988: content width
		if (wrap < 0) {
			itemLeft = itemLeft + wrap;
		}
		itemLeft = itemLeft - 10; // 10: left shift relative to menuitem
		
		if (itemLeft < (spaceLeft + 9)) this.menuLayer.css('left', spaceLeft + 9 + 'px'); // 9: offset position relative to content left
		else this.menuLayer.css('left',itemLeft + 'px');
		
		var rows = jQuery('.submenu_box', this.menuWrapper).add('.submenu_box_1', this.menuWrapper);
		var maxHeight = 0;
		jQuery.each(rows, function(idx, submenuBoxes){
			jQuery.each(jQuery(submenuBoxes), function(idx, el) {
		    	var height = jQuery(el).height();
		    	if (parseFloat(height) > parseFloat(maxHeight)) {
		    		maxHeight = height;
		    	}
		    });
		});

		jQuery.each(rows, function(idx, submenuBoxes){
		   jQuery.each(jQuery(submenuBoxes), function(idx, el) {
		    	jQuery(el).css('height',maxHeight + 'px');
		    });
		
		});

		this.hideDropDowns();
	},
	
	show: function(el) {
		el.parent().addClass('hover');
		this.viewedElement = el;
		this.menuLayer.show();
	},
	
	hide: function(el) {
		el.parent().removeClass('hover');
		this.menuLayer.hide();
		if (this.hiddenDropDowns) {
			jQuery(this.hiddenDropDowns).each(function(idx, el) {
				el.style.visibility = 'visible';
			});
		}
		this.hiddenDropDowns = [];
	},
	
	hideDropDowns: function() {
		this.hiddenDropDowns = [];
		if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion < 7) {
			jQuery.each(jQuery('select', jQuery('#main')), function(i, el){
				if (jQuery(el).overlaps(NaviMenu.menuLayer)) {
					NaviMenu.hiddenDropDowns.push(el);
					el.style.visibility = 'hidden';
				}
			});
		}
	},
	
	menuOver: function(ev) {
		var el = ev;
		var hiddenMenu = el.hiddenMenu;
		if (hiddenMenu) {
			NaviMenu.menuLayer.css('left','10px');
			NaviMenu.menuWrapper.html(hiddenMenu.innerHTML);
			NaviMenu.show(el);
			NaviMenu.calculatePosition(el);
			if (evilBrowserInformation.isEvil && evilBrowserInformation.evilVersion == 7) this.ie7ZoomFix();
		}
	},
	
	menuOut: function(ev) {
		this.hide(ev);
	},
	
	layerOver: function(ev) {
		this.show(this.viewedElement);
		this.hideDropDowns();
	},
	
	layerOut: function(ev) {
		this.hide(this.viewedElement);
	},
	// fix for menu link salad in ie7 when zoom != 1 (Bug #246)
	ie7ZoomFix: function() {
		var els = jQuery('.listing > li > a', this.menuWrapper);
		var cont;
		for (var i=0; i<els.length; i++) {
			cont = els[i].innerHTML
			els[i].innerHTML = '';
			els[i].innerHTML = cont;
		}
	}
};

/* 
 * Refinement Button on Search Listings
 */
function RefinementViewAllButton(el) {
	var element = el;
	var viewMore = null;

	this.initialize = function() {
		if (element) {
			var id = element.attr("id").replace('viewAllRef_', '');
			viewMore = jQuery('#viewMoreRef_' + id);
			var that = this;
			element.bind('click', function(ev) {
				that.clickHandler();
			});
		}
	},
	
	this.clickHandler = function() {
		if (viewMore) {
			element.hide();
			viewMore.addClass('showMore');
		}
	}
}

RefinementViewAllButton.init = function() {
	jQuery.each(jQuery('#filter .refViewAllBtn'), function() {
		var viewAllBtn = new RefinementViewAllButton(jQuery(this));
		viewAllBtn.initialize();
	});
}

/*
 * 
 * Buttons
 * 
 */

var blackBtnHover="blackBtnHover";
var redBtnHover="redBtnHover";
var smallBtnHover="smallRoundBtnHover";
var smallBlackBtnHover="smallBlackBtnHover";


function overBtn(btn, hoverClass){
	if (jQuery(btn).hasClass('redRoundButton'))
		jQuery(btn).addClass(redBtnHover);
	else if (jQuery(btn).hasClass('blackButton'))
		jQuery(btn).addClass(blackBtnHover);
	else
		jQuery(btn).addClass(hoverClass);
}
function outBtn(btn, hoverClass){
	if (jQuery(btn).hasClass('redRoundButton'))
		jQuery(btn).removeClass(redBtnHover);
	else if (jQuery(btn).hasClass('blackButton'))
		jQuery(btn).removeClass(blackBtnHover);
	else
		jQuery(btn).removeClass(hoverClass);
}

function BtnOver(btn){
    overBtn(btn, smallBtnHover);
}
function BtnOut(btn){
    outBtn(btn, smallBtnHover);
}

function normBtnOver(btn){
    overBtn(btn, blackBtnHover);
}
function normBtnOut(btn){
    outBtn(btn, blackBtnHover);
}

function smallBlackBtnOver(btn){
    overBtn(btn, smallBlackBtnHover);
}
function smallBlackBtnOut(btn){
    outBtn(btn, smallBlackBtnHover);
}

function smallBtnOver(btn){
    overBtn(btn, smallBtnHover);
}
function smallBtnOut(btn){
    outBtn(btn, smallBtnHover);
}

function formSubmit(domElement, name)
{
	var actEle = findParentForm(domElement);

	if(actEle.nodeName.toUpperCase() == 'FORM') {
		actEle.appendChild(getActionAsHiddenInput(name));			
		actEle.submit();
	}
}

function iBoxFormSubmit(domElement, name, callback)
{
	var form = findParentForm(domElement);
	form.appendChild(getActionAsHiddenInput(name));
	
	form = jQuery(form);
	
	var postBody = form.serialize();
	var ajaxUrl = form.attr('action');
	
    jQuery.ajax({
    	type: "POST",
    	url: ajaxUrl,
    	data: postBody,
    	success: function(responseText) {
			iBox.show(responseText);
			if(callback){
				callback();
			}
		}
    });
}

function statusFormSubmit(formname,name)
{
	var f = jQuery('#' + formname);
	if (f) {
		f.prepend(getActionAsHiddenInput(name));
		f.submit();
	}
}
function formReset(domElement)
{
	findParentForm(domElement).reset();
}

function getActionAsHiddenInput(name)
{
	var a = document.createElement('input');
	a.setAttribute('type', 'hidden');
	a.setAttribute('name', name);
	a.setAttribute('value', '1');
	return a;
}

function getElement(name, value) {
	var el = document.createElement('input');
	el.setAttribute('type', 'hidden');
	el.setAttribute('name', name);
	el.setAttribute('value', value);
	return el;
}

function findParentForm(ele)
{
	var actEle = ele;
	while(actEle.nodeName.toUpperCase() != 'FORM' && actEle.nodeName.toUpperCase() != 'BODY') {
		actEle = actEle.parentNode;
	}
	return actEle;
}

//application initialization on dom ready
jQuery(document).ready(function(){
	checkEvilBrowser();
	MiniCart.init();
	initIE6HoverFix();
	TopNavSelection.initialize();
	AddToCartButton.initialize();
	SearchButton.initialize();
	NewsletterButton.initialize();
	NaviMenu.initialize();
	RefinementViewAllButton.init();
});

