/*global window, document, jQuery, $, lh */

(function($){
	
	/**
	 * Paramify href
	 * @param {Object} key
	 * @param {Object} value
	 */
    function paramifyHref(key, value){
        var href, params, qs = [], keyAdded = false;
        
        // If there's an existing query string, modify it
        if (window.location.search.length > 0) {
            params = window.location.search.split('?')[1].split('&');
            for (var i = 0; i < params.length; i++) {
                var keyval = params[i].split('=');
                if (keyval[0] === key) {
                    keyval[1] = value;
                    keyAdded = true;
                    
                }
                qs.push(keyval.join('='));
            }
        }
        // Otherwise, append a new query string containing the key-value pair
        if (!keyAdded) {
            qs.push([key, value].join('='));
        }
        href = window.location.pathname + '?' + qs.join('&');
        // Append the #hash fragment if it exists
        if (window.location.hash.length > 0) {
            href += window.location.hash;
        }
        return href;
    }
	
	/**
	 * Currency switcher
	 * @param {Object} options
	 */
	$.fn.currencySwitcher = function(options) {
		
		return $(this).each(function() {
			
			var defaults = {
				selectedCurrencyId: 'selectedCurrency',
				format: 'compact',
				dropdown: true
			};
			
			options = $.extend({}, defaults, options);
			
			var $currencySwitcher = $(this),
				$span = $('#'+options.selectedCurrencyId),
				text = $span.text(),
				$img = $span.find('img'),
				$currencyList = $('#currencyList'),
				currencyListWidthDelta = options.format === 'compact' ? 4 : 156,
				$sitename = $('#sitename'),
				$a;
			
			/**
			 * Close the currency menu
			 * @param {Object} e
			 */
			function closeCurrencyMenu() {
				$currencyList.fadeOut('fast', function () {
					window.setTimeout(function() {
						$currencySwitcher.removeClass('open');
						// Color animation throws an invalid property error in IE
						// @see http://stackoverflow.com/questions/530866/
						if (!$.browser.msie) {
							$currencySwitcher.animate({'backgroundColor':'transparent'}, 'fast');
						}
					}, 250);
				});
				if (!$sitename.is(':visible')){
					$sitename.show();	
				}
			}
			
			
			// Fix the currency switcher URLs, even if we're not going to do 
			// the drop-down
		    $currencyList.find('a').each(function(){
		        var qs = this.href.split('?')[1].split('&'), cs;       
		        for (var i = 0; i < qs.length; i++) {
		            var kv = qs[i].split('=');
		            if (kv[0] === 'cs') {
		                cs = kv[1];
		            }
		        }
		        this.href = paramifyHref('cs', cs.toUpperCase());
		    });
			
			// Do the drop-down if format isn't set to basic
			if (options.format !== 'basic') {
				$currencySwitcher
					.addClass('currency-switcher-enabled')
					.add($currencyList)
					.hover(function(){
						$(this).addClass('hover');
					}, function(){
						$(this).removeClass('hover');
					});
				
				$a = $('<a href="#currencyList" />')
						.text(text)
						.prepend($img)
						.append('<span class="currency-switcher-handle" />')
						.insertAfter($span).attr({
							'id': options.selectedCurrencyId,
							'title': $span.attr('title'),
							'class': $span.attr('class')
						})
						.click(function (e) {
							e.preventDefault();
							if ($currencyList.is(':visible') && $currencySwitcher.hasClass('open')) {
								closeCurrencyMenu();
							}
							else if (!$currencyList.is(':visible') && !$currencySwitcher.hasClass('open')) {
								if ($.browser.msie && $.browser.version < 8) {
									$sitename.hide();
								}
								$currencyList.fadeIn('fast', function() {
									window.setTimeout(function () {
										$currencySwitcher.addClass('open');
									}, 250);
								});
							}
						});
				
				$currencyList
					.css({
						top: ($a.outerHeight() + 2) + 'px',
						width: ($a.outerWidth() + currencyListWidthDelta) + 'px'
					})
					.addClass('currency-list-' + options.format)
					.hide();
				
				if (options.format === 'full') {
					var $description = $('<li class="currency-description" />').text($span.attr('title')),
						$closer = $('<a href="#" title="Close" class="currency-list-close"><span>x</span></a>')
							.click(function (e) {
								e.preventDefault();
								closeCurrencyMenu();
							});
					$description.append($closer);
					$currencyList.prepend($description);
				}
				
				$span.remove();
				
				// Close the menu on mouseleave after 1 sec - BUGGY
				/*$currencySwitcher.mouseleave(function () {
					window.setTimeout(closeCurrencyMenu, 1000);
				});*/
				
				// Close the menu when a click is made anywhere in the document,
				// apart from the currency links in the menu, so that the logo
				// doesn't bleed through in IE7
				$(document).click(function (e) {
					if ($(e.target).parents('#currencyList').size() === 0 && $currencyList.is(':visible') && $currencySwitcher.hasClass('open')) {
						closeCurrencyMenu();
					}
				});
			}
			
		});
	};
})(jQuery);

$(document).ready(function() {
	
	
	// IE6 doesn't play nicely with the currency switcher drop-down;
	// adjust browsers & versions to taste.
	$('#currencySwitcher').currencySwitcher({
		format: $.browser.msie && $.browser.version < 7 ? 
			'basic' :
			'full'
	});

	$(function() {
		$('#headercontainer div>ul:not(.children) li').hover(function(){
		   	$(this).addClass('hover');
		}, function() {
		    $(this).removeClass('hover');
		});
	});
	
	$('.moreinfo').click(function (e) {
		var cbox=$(this).parent().children('label').children("input[type=checkbox]");
		e.preventDefault();
		$(this).prevAll("div").children("p").children("img.crosssell-yes").click(function (e) {
			$(cbox).attr("checked", true);
			$.modal.close();
		});
		$(this).prevAll("div").children("p").children("img.crosssell-no").click(function (e) {
			$(cbox).attr("checked", false);
			$.modal.close();
		});
		$(this).prevAll("div").modal({overlayClose:true});
	});
	
	$("form.atb").submit(function () {
		var sItem = $(this).find(':selected');
		if(sItem.length)
		{
			if(sItem.val() == 'choose' || sItem.val().substring(0,1) == 'o')
			{
				$(this).find('select').addClass('error');
				alert("Please choose an in-stock size or variety from the highlighted drop-down menu");
				return false;
			}
		}	
	});
	$('.printBtn').bind('click',function() {
	    	var thePopup = window.open( '', "Print label", "menubar=0,location=0,height=400,width=600" );
    		$('#printlabel').clone().appendTo( thePopup.document.body );
	    	thePopup.print();
	    	return false;
	});
});

/*
 * SimpleModal 1.3.4 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2010 Eric Martin (http://twitter.com/EricMMartin)
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 237 2010-03-11 05:51:01Z emartin24 $
 */
;(function($){var ie6=$.browser.msie&&parseInt($.browser.version)==6&&typeof window['XMLHttpRequest']!="object",ieQuirks=null,w=[];$.modal=function(data,options){return $.modal.impl.init(data,options);};$.modal.close=function(){$.modal.impl.close();};$.fn.modal=function(options){return $.modal.impl.init(this,options);};$.modal.defaults={appendTo:'body',focus:true,opacity:50,overlayId:'simplemodal-overlay',overlayCss:{},containerId:'simplemodal-container',containerCss:{},dataId:'simplemodal-data',dataCss:{},minHeight:null,minWidth:null,maxHeight:null,maxWidth:null,autoResize:false,autoPosition:true,zIndex:1000,close:true,closeHTML:'<a class="modalCloseImg" title="Close"></a>',closeClass:'simplemodal-close',escClose:true,overlayClose:false,position:null,persist:false,transient:false,onOpen:null,onShow:null,onClose:null};$.modal.impl={o:null,d:{},init:function(data,options){var s=this;if(s.d.data){return false;}ieQuirks=$.browser.msie&&!$.support.boxModel;s.o=$.extend({},$.modal.defaults,options);s.zIndex=s.o.zIndex;s.occb=false;if(typeof data=='object'){data=data instanceof jQuery?data:$(data);s.d.placeholder=false;if(data.parent().parent().size()>0){data.before($('<span></span>').attr('id','simplemodal-placeholder').css({display:'none'}));s.d.placeholder=true;s.display=data.css('display');if(!s.o.persist){s.d.orig=data.clone(true);}}}else if(typeof data=='string'||typeof data=='number'){data=$('<div></div>').html(data);}else{alert('SimpleModal Error: Unsupported data type: '+typeof data);return s;}s.create(data);data=null;s.open();if($.isFunction(s.o.onShow)){s.o.onShow.apply(s,[s.d]);}return s;},create:function(data){var s=this;w=s.getDimensions();if(!s.o.transient&&ie6){s.d.iframe=$('<iframe src="javascript:false;"></iframe>').css($.extend(s.o.iframeCss,{display:'none',opacity:0,position:'fixed',height:w[0],width:w[1],zIndex:s.o.zIndex,top:0,left:0})).appendTo(s.o.appendTo);}s.d.overlay=$('<div></div>').attr('id',s.o.overlayId).addClass('simplemodal-overlay').css($.extend(s.o.overlayCss,{display:'none',opacity:s.o.opacity/100,height:s.o.transient?0:w[0],width:s.o.transient?0:w[1],position:'fixed',left:0,top:0,zIndex:s.o.zIndex+1})).appendTo(s.o.appendTo);s.d.container=$('<div></div>').attr('id',s.o.containerId).addClass('simplemodal-container').css($.extend(s.o.containerCss,{display:'none',position:'fixed',zIndex:s.o.zIndex+2})).append(s.o.close&&s.o.closeHTML?$(s.o.closeHTML).addClass(s.o.closeClass):'').appendTo(s.o.appendTo);s.d.wrap=$('<div></div>').attr('tabIndex',-1).addClass('simplemodal-wrap').css({height:'100%',outline:0,width:'100%'}).appendTo(s.d.container);s.d.data=data.attr('id',data.attr('id')||s.o.dataId).addClass('simplemodal-data').css($.extend(s.o.dataCss,{display:'none'})).appendTo('body');data=null;s.setContainerDimensions();s.d.data.appendTo(s.d.wrap);if(ie6||ieQuirks){s.fixIE();}},bindEvents:function(){var s=this;$('.'+s.o.closeClass).bind('click.simplemodal',function(e){e.preventDefault();s.close();});if(!s.o.transient&&s.o.close&&s.o.overlayClose){s.d.overlay.bind('click.simplemodal',function(e){e.preventDefault();s.close();});}$(document).bind('keydown.simplemodal',function(e){if(!s.o.transient&&s.o.focus&&e.keyCode==9){s.watchTab(e);}else if((s.o.close&&s.o.escClose)&&e.keyCode==27){e.preventDefault();s.close();}});$(window).bind('resize.simplemodal',function(){w=s.getDimensions();s.setContainerDimensions(true);if(ie6||ieQuirks){s.fixIE();}else if(!s.o.transient){s.d.iframe&&s.d.iframe.css({height:w[0],width:w[1]});s.d.overlay.css({height:w[0],width:w[1]});}});},unbindEvents:function(){$('.'+this.o.closeClass).unbind('click.simplemodal');$(document).unbind('keydown.simplemodal');$(window).unbind('resize.simplemodal');this.d.overlay.unbind('click.simplemodal');},fixIE:function(){var s=this,p=s.o.position;$.each([s.d.iframe||null,s.o.transient?null:s.d.overlay,s.d.container],function(i,el){if(el){var bch='document.body.clientHeight',bcw='document.body.clientWidth',bsh='document.body.scrollHeight',bsl='document.body.scrollLeft',bst='document.body.scrollTop',bsw='document.body.scrollWidth',ch='document.documentElement.clientHeight',cw='document.documentElement.clientWidth',sl='document.documentElement.scrollLeft',st='document.documentElement.scrollTop',s=el[0].style;s.position='absolute';if(i<2){s.removeExpression('height');s.removeExpression('width');s.setExpression('height',''+bsh+' > '+bch+' ? '+bsh+' : '+bch+' + "px"');s.setExpression('width',''+bsw+' > '+bcw+' ? '+bsw+' : '+bcw+' + "px"');}else{var te,le;if(p&&p.constructor==Array){var top=p[0]?typeof p[0]=='number'?p[0].toString():p[0].replace(/px/,''):el.css('top').replace(/px/,'');te=top.indexOf('%')==-1?top+' + (t = '+st+' ? '+st+' : '+bst+') + "px"':parseInt(top.replace(/%/,''))+' * (('+ch+' || '+bch+') / 100) + (t = '+st+' ? '+st+' : '+bst+') + "px"';if(p[1]){var left=typeof p[1]=='number'?p[1].toString():p[1].replace(/px/,'');le=left.indexOf('%')==-1?left+' + (t = '+sl+' ? '+sl+' : '+bsl+') + "px"':parseInt(left.replace(/%/,''))+' * (('+cw+' || '+bcw+') / 100) + (t = '+sl+' ? '+sl+' : '+bsl+') + "px"';}}else{te='('+ch+' || '+bch+') / 2 - (this.offsetHeight / 2) + (t = '+st+' ? '+st+' : '+bst+') + "px"';le='('+cw+' || '+bcw+') / 2 - (this.offsetWidth / 2) + (t = '+sl+' ? '+sl+' : '+bsl+') + "px"';}s.removeExpression('top');s.removeExpression('left');s.setExpression('top',te);s.setExpression('left',le);}}});},focus:function(pos){var s=this,p=pos||'first';var input=$(':input:enabled:visible:'+p,s.d.wrap);input.length>0?input.focus():s.d.wrap.focus();},getDimensions:function(){var el=$(window);var h=$.browser.opera&&$.browser.version>'9.5'&&$.fn.jquery<='1.2.6'?document.documentElement['clientHeight']:$.browser.opera&&$.browser.version<'9.5'&&$.fn.jquery>'1.2.6'?window.innerHeight:el.height();return[h,el.width()];},getVal:function(v){return v=='auto'?0:v.indexOf('%')>0?v:parseInt(v.replace(/px/,''));},setContainerDimensions:function(resize){var s=this;if(!resize||(resize&&s.o.autoResize)){var ch=$.browser.opera?s.d.container.height():s.getVal(s.d.container.css('height')),cw=$.browser.opera?s.d.container.width():s.getVal(s.d.container.css('width')),dh=s.d.data.outerHeight(true),dw=s.d.data.outerWidth(true);var mh=s.o.maxHeight&&s.o.maxHeight<w[0]?s.o.maxHeight:w[0],mw=s.o.maxWidth&&s.o.maxWidth<w[1]?s.o.maxWidth:w[1];if(!ch){if(!dh){ch=s.o.minHeight;}else{if(dh>mh){ch=mh;}else if(dh<s.o.minHeight){ch=s.o.minHeight;}else{ch=dh;}}}else{ch=ch>mh?mh:ch;}if(!cw){if(!dw){cw=s.o.minWidth;}else{if(dw>mw){cw=mw;}else if(dw<s.o.minWidth){cw=s.o.minWidth;}else{cw=dw;}}}else{cw=cw>mw?mw:cw;}s.d.container.css({height:ch,width:cw});if(dh>ch||dw>cw){s.d.wrap.css({overflow:'auto'});}}if(s.o.autoPosition){s.setPosition();}},setPosition:function(){var s=this,top,left,hc=(w[0]/2)-(s.d.container.outerHeight(true)/2),vc=(w[1]/2)-(s.d.container.outerWidth(true)/2);if(s.o.position&&Object.prototype.toString.call(s.o.position)==="[object Array]"){top=s.o.position[0]||hc;left=s.o.position[1]||vc;}else{top=hc;left=vc;}s.d.container.css({left:left,top:top});},watchTab:function(e){var s=this;if($(e.target).parents('.simplemodal-container').length>0){s.inputs=$(':input:enabled:visible:first, :input:enabled:visible:last',s.d.data[0]);if((!e.shiftKey&&e.target==s.inputs[s.inputs.length-1])||(e.shiftKey&&e.target==s.inputs[0])||s.inputs.length==0){e.preventDefault();var pos=e.shiftKey?'last':'first';setTimeout(function(){s.focus(pos);},10);}}else{e.preventDefault();setTimeout(function(){s.focus();},10);}},open:function(){var s=this;s.d.iframe&&s.d.iframe.show();if($.isFunction(s.o.onOpen)){s.o.onOpen.apply(s,[s.d]);}else{s.d.overlay.show();s.d.container.show();s.d.data.show();}s.focus();s.bindEvents();},close:function(){var s=this;if(!s.d.data){return false;}s.unbindEvents();if($.isFunction(s.o.onClose)&&!s.occb){s.occb=true;s.o.onClose.apply(s,[s.d]);}else{if(s.d.placeholder){var ph=$('#simplemodal-placeholder');if(s.o.persist){ph.replaceWith(s.d.data.removeClass('simplemodal-data').css('display',s.display));}else{s.d.data.hide().remove();ph.replaceWith(s.d.orig);}}else{s.d.data.hide().remove();}s.d.container.hide().remove();s.d.overlay.hide().remove();s.d.iframe&&s.d.iframe.hide().remove();s.d={};}}};})(jQuery);

function check_email(e) {
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
	for(i=0; i < e.length ;i++){
		if(ok.indexOf(e.charAt(i))<0){ 
			return (false);
		}
	} 
	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return (-1);		
		} 
	}
}
function check_form(theform) {
	if(theform.suggestion.value=='') {
		alert('Please enter your question or suggestion in the box');
		theform.suggestion.focus();
		return false;
	} else if(theform.email.value != '' && !check_email(theform.email.value)) {
		alert('Please enter your e-mail address');
		theform.email.style.backgroundColor='yellow';
		theform.email.focus();
		return false;
	} else if(theform.captchatext.value=='') {
		alert('Please check your answer to the question');
		theform.captchatext.style.backgroundColor='yellow';
		theform.captchatext.focus();
		return false;
	} else {
		theform.doit.value='Please Wait...';
		return true;
	}
}
