function getPage(url, target){
	/* This function is called by the flash HeroBanner to open new windows or change location */
	if(target =="_blank"){
		window.open(url);
	}else{
		window.location = url;
	}
}
$(window).load(function() {


	// height-equalizing script for featured products
	if($('#featuredProducts').size() > 0){
		var featureHeight = 0;
		var feature = $('#featuredProducts .features .feature .inner');
		for(var i=0; i<feature.length; i++) {
			if ( featureHeight < $(feature[i]).height() )
				featureHeight = $(feature[i]).height();
		}
		$('#featuredProducts .features .feature .inner').css('height', featureHeight+9 + 'px');
	}
	
	// height-equalizing script for seasonal projects
	if($('#seasonalProjects').size() > 0){
		var projectHeight = 0;
		var project = $('#seasonalProjects .features .feature .inner');
		for(var i=0; i<project.length; i++) {
			if ( projectHeight < $(project[i]).height() )
				projectHeight = $(project[i]).height();
		}
		$('#seasonalProjects .features .feature .inner').css('height', (projectHeight+9) + 'px');	
	}
	
	// height-equalizing script for related products
	if($('#relatedProducts').size() > 0){

		var productHeight = 0;
		var product = $('#relatedProducts .feature .inner');
		for(var i=0; i<product.length; i++) {
			if ( productHeight < $(product[i]).height() )
				productHeight = $(product[i]).height();
		}
		$('#relatedProducts .feature .inner').css('height', productHeight+9 + 'px');	
	}

	if($('#projectsBlock').size() > 0){
		featureHeight = 0;
		feature = $('#projectsBlock .features .feature > .inner');
		for(var i=0; i<feature.length; i+=2) {
			featureHeight = ( $(feature[i]).height() < $(feature[i+1]).height() ) ? $(feature[i+1]).height() : $(feature[i]).height();
			$(feature[i]).css('height', featureHeight + 'px');
			$(feature[i+1]).css('height', featureHeight + 'px');
		}
	}	
	
	// height-equalizing script for projects listings
	if($('#expertProjects').size() > 0){
		featureHeight = 0;
		feature = $('#expertProjects .features .feature > .inner');
		for(var i=0; i<feature.length; i+=2) {
			featureHeight = ( $(feature[i]).height() < $(feature[i+1]).height() ) ? $(feature[i+1]).height() : $(feature[i]).height();
			$(feature[i]).css('height', featureHeight + 'px');
			$(feature[i+1]).css('height', featureHeight + 'px');
		}
	}	

	$(".js-pages").hide(); 
	$(".js-pages:first").show();
	$(".pagination.js li.pages a:first").addClass("current");
						   
	// height equalizing script for search results (grid)
	if($('#resultsGrid').size() > 0){
		var productHeight = 0;
		var infoHeight = 0;
		var product = $('#resultsGrid div.features div.feature > div.inner');
		for(var i=0; i<product.length; i++) {
			info = $(product[i]).find(".info");
			if ( productHeight < $(product[i]).height() )
				productHeight = $(product[i]).height();
			if ( infoHeight < $(info).height() )
				infoHeight = $(info).height();
		}
		$('#resultsGrid div.features div.feature > div.inner').css('height', (productHeight+10) + 'px');	
		$('#resultsGrid div.features div.feature > div.inner div.info').css('position', 'relative').css('height', (infoHeight+2)+'px')
		
	}	
});

/* jQuery Carousel 0.9.5 Copyright 2008-2009 Thomas Lanciaux and Pierre Bertet. This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>*/
(function(c){c.fn.carousel=function(j){var j=c.extend({direction:"horizontal",loop:false,dispItems:1,pagination:false,paginationPosition:"inside",nextBtn:'<a role="button">Next</a>',prevBtn:'<a role="button">Previous</a>',btnsPosition:"inside",nextBtnInsert:"appendTo",prevBtnInsert:"prependTo",nextBtnInsertFn:false,prevBtnInsertFn:false,autoSlide:false,autoSlideInterval:3000,delayAutoSlide:false,combinedClasses:false,effect:"slide",slideEasing:"swing",animSpeed:"normal",equalWidths:"true",verticalMargin:0,callback:function(){},useAddress:false,adressIdentifier:"carousel",tabLabel:function(k){return k},showEmptyItems:true},j);if(j.btnsPosition=="outside"){j.prevBtnInsert="insertBefore";j.nextBtnInsert="insertAfter"}j.delayAutoSlide=j.delayAutoSlide||j.autoSlideInterval;return this.each(function(){var k={$elts:{},params:j,launchOnLoad:[]};k.$elts.carousel=c(this).addClass("js");k.$elts.content=c(this).children().css({position:"absolute",top:0});k.$elts.wrap=k.$elts.content.wrap('<div class="carousel-wrap"></div>').parent().css({overflow:"hidden",position:"relative"});k.steps={first:0,count:k.$elts.content.children().length};k.steps.last=k.steps.count-1;if(c.isFunction(k.params.prevBtnInsertFn)){k.$elts.prevBtn=k.params.prevBtnInsertFn(k.$elts)}else{k.$elts.prevBtn=c(j.prevBtn)[j.prevBtnInsert](k.$elts.carousel)}if(c.isFunction(k.params.nextBtnInsertFn)){k.$elts.nextBtn=k.params.nextBtnInsertFn(k.$elts)}else{k.$elts.nextBtn=c(j.nextBtn)[j.nextBtnInsert](k.$elts.carousel)}k.$elts.nextBtn.addClass("carousel-control next carousel-next");k.$elts.prevBtn.addClass("carousel-control previous carousel-previous");a(k);if(k.params.pagination){i(k)}h(k);c(function(){var n=k.$elts.content.children();var m=0;n.each(function(){$item=c(this);$itemHeight=$item.outerHeight();if($itemHeight>m){m=$itemHeight}});if(k.params.verticalMargin>0){m=m+k.params.verticalMargin}n.height(m);var l=k.$elts.content.children(":first");k.itemWidth=l.outerWidth();if(j.direction=="vertical"){k.contentWidth=k.itemWidth}else{if(j.equalWidths){k.contentWidth=k.itemWidth*k.steps.count}else{k.contentWidth=(function(){var o=0;k.$elts.content.children().each(function(){o+=c(this).outerWidth()});return o})()}}k.$elts.content.width(k.contentWidth);k.itemHeight=m;if(j.direction=="vertical"){k.$elts.content.css({height:k.itemHeight*k.steps.count+"px"});k.$elts.content.parent().css({height:k.itemHeight*k.params.dispItems+"px"})}else{k.$elts.content.parent().css({height:k.itemHeight+"px"})}d(k);c.each(k.launchOnLoad,function(o,p){p()});if(k.params.autoSlide){window.setTimeout(function(){k.autoSlideInterval=window.setInterval(function(){b(k,e(k,"next"))},k.params.autoSlideInterval)},k.params.delayAutoSlide)}})})};function a(j){j.$elts.nextBtn.add(j.$elts.prevBtn).bind("enable",function(){var k=c(this).unbind("click").bind("click",function(){b(j,e(j,(k.is(".next")?"next":"prev")));g(j)}).removeClass("disabled");if(j.params.combinedClasses){k.removeClass("next-disabled previous-disabled")}}).bind("disable",function(){var k=c(this).unbind("click").addClass("disabled");if(j.params.combinedClasses){if(k.is(".next")){k.addClass("next-disabled")}else{if(k.is(".previous")){k.addClass("previous-disabled")}}}}).hover(function(){c(this).toggleClass("hover")})}function i(j){j.$elts.pagination=c('<div class="center-wrap"><div class="carousel-pagination"><p></p></div></div>')[((j.params.paginationPosition=="outside")?"insertAfter":"appendTo")](j.$elts.carousel).find("p");j.$elts.paginationBtns=c([]);j.$elts.content.find("li").each(function(k){if(k%j.params.dispItems==0){j.$elts.paginationBtns=j.$elts.paginationBtns.add(c('<a role="button"><span>'+j.params.tabLabel(j.$elts.paginationBtns.length+1)+"</span></a>").data("firstStep",k))}});j.$elts.paginationBtns.each(function(){c(this).appendTo(j.$elts.pagination)});j.$elts.paginationBtns.slice(0,1).addClass("active");j.launchOnLoad.push(function(){j.$elts.paginationBtns.click(function(k){b(j,c(this).data("firstStep"));g(j)})})}function h(j){if(j.params.useAddress&&c.isFunction(c.fn.address)){c.address.init(function(l){var k=c.address.pathNames();if(k[0]===j.params.adressIdentifier&&!!k[1]){b(j,k[1]-1)}else{c.address.value("/"+j.params.adressIdentifier+"/1")}}).change(function(l){var k=c.address.pathNames();if(k[0]===j.params.adressIdentifier&&!!k[1]){b(j,k[1]-1)}})}else{j.params.useAddress=false}}function b(j,k){j.params.callback(k);f(j,k);j.steps.first=k;d(j);if(j.params.useAddress){c.address.value("/"+j.params.adressIdentifier+"/"+(k+1))}}function e(k,j){if(j=="prev"){if(!k.params.showEmptyItems){if(k.steps.first==0){return((k.params.loop)?(k.steps.count-k.params.dispItems):false)}else{return Math.max(0,k.steps.first-k.params.dispItems)}}else{if((k.steps.first-k.params.dispItems)>=0){return k.steps.first-k.params.dispItems}else{return((k.params.loop)?(k.steps.count-k.params.dispItems):false)}}}else{if(j=="next"){if((k.steps.first+k.params.dispItems)<k.steps.count){if(!k.params.showEmptyItems){return Math.min(k.steps.first+k.params.dispItems,k.steps.count-k.params.dispItems)}else{return k.steps.first+k.params.dispItems}}else{return((k.params.loop)?0:false)}}}}function f(j,k){switch(j.params.effect){case"no":if(j.params.direction=="vertical"){j.$elts.content.css("top",-(j.itemHeight*k)+"px")}else{j.$elts.content.css("left",-(j.itemWidth*k)+"px")}break;case"fade":if(j.params.direction=="vertical"){j.$elts.content.hide().css("top",-(j.itemHeight*k)+"px").fadeIn(j.params.animSpeed)}else{j.$elts.content.hide().css("left",-(j.itemWidth*k)+"px").fadeIn(j.params.animSpeed)}break;default:if(j.params.direction=="vertical"){j.$elts.content.stop().animate({top:-(j.itemHeight*k)+"px"},j.params.animSpeed,j.params.slideEasing)}else{j.$elts.content.stop().animate({left:-(j.itemWidth*k)+"px"},j.params.animSpeed,j.params.slideEasing)}break}}function d(j){if(e(j,"prev")!==false){j.$elts.prevBtn.trigger("enable")}else{j.$elts.prevBtn.trigger("disable")}if(e(j,"next")!==false){j.$elts.nextBtn.trigger("enable")}else{j.$elts.nextBtn.trigger("disable")}if(j.params.pagination){j.$elts.paginationBtns.removeClass("active").filter(function(){return(c(this).data("firstStep")==j.steps.first)}).addClass("active")}}function g(j){if(!!j.autoSlideInterval){window.clearInterval(j.autoSlideInterval)}}})(jQuery);

$(document).ready(function(){	
	// Remove French search box default text
	if (lang == 'fr') {
		$("input#searchTerm").val("");
	}
	
	// Add autocomplete="off" to search type-ahead
	$('#searchTerm').attr("autocomplete","off");
	
	// Remove register today link
	$("#account_form .registertoday").remove();
	
	var initialValue = $('#searchTerm').val(); // save it's value on page load 
	
	// Print buttons
	$("a.print").click(function(e){
		e.preventDefault();
		window.print();
	});
	
	//Brands rotator	
	$("#brandsRotator").carousel({ 
		autoSlide: true, 
		autoSlideInterval: 8000,
		dispItems: 4,
		pagination: true,
		effect: "fade"
	});

	// Login box
	if($("#account_form").length > 0){
			$("#account_form").dialog({
				autoOpen: 	false,
				resizable: 	false,
				width: 		378,
				modal: 		true,
				dialogClass:'clearfix account_form',
				close: function() {
					// Reset Forgot password form
					$("#account_form #signin_message").hide();
					$("div.forgotpwd div.email").show();
					$("div.forgotpwd a#sendpwd").show();
					$("div.forgotpwd a.closelink").html(labelCancelAndClose);
					$("div.forgotpwd input#forgot_username").val("");
					$("div.forgotpwd form div:eq(1)").html(messageEnterAddress);
				}
			});
			$( "#account_form" ).bind( "dialogopen", function(event, ui) {
				$("#account_form").dialog( "option", "title", labelSignIn );
				$("#account_form .forgotpwd").hide();
				$("#account_form .keepsignedin").hide(); 
				$("#account_form #signin_message").hide();
				$("#account_form .signin").show();
			});
			$("#account_form .forgotpwd").hide();
			$("#account_form .keepsignedin").hide();
			
			$("#account_form .forgot a").click(function(){
				$("#account_form .signin").hide();
				$("#account_form #signin_message").hide();
				$("#account_form").dialog( "option", "title", $("#account_form .forgotpwd").attr("title") );
				$("#account_form .forgotpwd").show();
			});
			
			$("#account_form .infobubble").click(function(){
				$("#account_form .signin").hide();
				$("#account_form #signin_message").hide();
				$("#account_form").dialog( "option", "title", $("#account_form .keepsignedin").attr("title") );
				$("#account_form .keepsignedin").show();
			});
			
			$("#account_form #backtosignin").click(function(){
				$("#account_form .keepsignedin").hide();
				$("#account_form #signin_message").hide();
				$("#account_form").dialog( "option", "title", $("#account_form .signin").attr("title") );
				
				$("#account_form .signin").show();
				
			});	
			
			$("#account_form .closelink").click(function(e){
				$("#account_form").dialog("close");
				e.preventDefault();
			});
			$("#account_form #signin").click(function(e){
				signIn();
			});
			$('#account_form #username').keypress(function(event) {
				if (event.keyCode == '13') {
					signIn();
				}
			});	
			$('#account_form #password').keypress(function(event) {
				if (event.keyCode == '13') {
					signIn();
				}
			});	
			$('#account_form #remember_me').keypress(function(event) {
				if (event.keyCode == '13') {
					signIn();
				}
			});	
			
			// Loading bar
			$('<div id="loading-bar" style="display:none;"></div>').insertBefore("#account_form #signin_message");
			
			function signIn() {
				// Hide any messages
				$("#account_form #signin_message").hide();				
				// Show loading bar
				$("#account_form #loading-bar").show();
				
				var email = $("#username").val();
				var pwd = $("#password",".password").val();
				var emailValidate = /^\w+([\.\+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/;
				
				// Validate email
				if (emailValidate.test(email)) {
					var reqUrl = "/processLogin";	
				
					var data = new Object();
					data.j_username = email;
					data.j_password = pwd;
		
					if( $("#remember_me").is(':checked') ) {
						data._spring_security_remember_me = "on";
					}						 
					
					$.ajax({ url: reqUrl, type: 'POST', contentType: "application/x-www-form-urlencoded; charset=utf-8", scriptCharset: "utf-8", dataType: 'json', data: data, success: handleLogin, error:handleLoginError });	
				} else {
					var msg = $("#account_form #signin_message");
					msg.addClass("error");
					msg.html(messageError);
					$("#account_form #loading-bar").hide();
					msg.show();
				}

			}			
			
			function handleLoginError( data ){
				var msg = $("#account_form #signin_message");
				msg.addClass("error");
				msg.html(messageError);
				$("#account_form #loading-bar").hide();
				msg.show();
			}
			function handleLogin( data ){
				if(data.success == true ){
					location.reload();
				}else{
					var msg = $("#account_form #signin_message");
					msg.addClass("error");
					msg.html(bad_login);
					$("#account_form #loading-bar").hide();
					msg.show();
				}
			}
		}
		
	// Pricing box
	$(pricingPopupText).insertAfter("#wrap");
	$("#pricingPopup").dialog({
		autoOpen: 	false,
		resizable: 	false,
		width: 		378,
		modal: 		true,
		dialogClass:'clearfix pricingPopupPrint'
	});
	
	$("#results a.pricing, #footerNav a.pricing").click(function(){$("#pricingPopup").dialog("open")});
	
	
	// eFlyer boxes
	$('<div id="eFlyerPopup" style="display:none;"></div>').insertAfter("#wrap");
	if($("#eFlyerNoStore").length > 0){
		$("#eFlyerNoStore").click(function(){
			$("#eFlyerPopup").html(eFlyerPopupText);
			$("#eFlyerPopup").dialog("open");
			$("#eFlyerPopup .closelink").click(function(){$("#eFlyerPopup").dialog("close");});
			$("#eFlyerPopup #findstoreeflyer").click(function(){
				
				$("#eFlyerPopup #postalCodeForm").submit();
			});
		});
	}
	
	if($("#eFlyerNoFlyer").length > 0){
		$("#eFlyerNoFlyer").click(function(){
			$("#eFlyerPopup").html(noeFlyerPopupText);
			$("#eFlyerPopup").dialog("open");
		});
	}
		
	$("#eFlyerPopup").dialog({
		autoOpen: 	false,
		resizable: 	false,
		width: 		378,
		modal: 		true,
		title:		"View eFlyer",
		dialogClass:'clearfix '
	});	

	/* Helper to check current sort/display/items per page */

	//Constants
	DO_LIST = '1' 
	DO_GRID = '0'
	urlParams = {};

	//Parse query string and gets parameters out.
	(function () {
	    var e,
	        a = /\+/g,  // Regex for replacing addition symbol with a space
	        r = /([^&=]+)=?([^&]*)/g,
	        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
	        q = window.location.search.substring(1);

	    while (e = r.exec(q))
	       urlParams[d(e[1])] = d(e[2]);
	})();
	
	//Update query string creating parameter if required
	//REQUIRED: urlParams
	function updateParameter( param, value){
		var paramValue = param + "=" + value; //setup query parameter
		var regex = new RegExp(param + '=' + '[^&]*') 
		var location = document.location.href.replace('#', ''); //remove anchor 
		if("list" in urlParams){ //already a parameter?
			document.location = location.replace(regex,paramValue)
		}else if ((location).match(/\?/)){ //is there already a query
			document.location = location + "&" + paramValue
		}else{
			document.location = location + "?"+ paramValue
		}

	}
	
	// Should we be rendering Grid
	isGrid = function(){
		return urlParams["list"] != DO_LIST;	
	}
	
	if(!isGrid()){
		doList();
	}
	
						   
	// Grid / List toggle for Results
		

	$('#results .displayOpts li.list').click(
			function(event){
				updateParameter("list", DO_LIST) // do list 
				event.preventDefault();
			});

	$('#results .displayOpts li.grid').click(
			function(event){
				updateParameter("list", DO_GRID); // do grid
				event.preventDefault();
			}
			
	);

	// Change result list to 'list' updated UI to reflect choice	
	function doList () {

	  $('#resultsGrid').addClass("list");

	  $('#results .displayOpts li a').removeClass("current");
	  $('#results .displayOpts li.list a').addClass("current");
	  
	  $('#resultsGrid img').each(function(){
			src = $(this).attr("src");
			src = src.replace("/195/", "/90/");
			$(this).attr("src", src);
											  
		});
	}

	// Change result list to 'grid' updated UI to reflect choice
	function doGrid() {

		$('#resultsGrid').removeClass("list");

		$('#results .displayOpts li a').removeClass("current");
		$('#results .displayOpts li.grid a').addClass("current");
		
		
	  $('#resultsGrid img').each(function(){
			src = $(this).attr("src");
			src = src.replace("/90/", "/195/");
			$(this).attr("src", src);
											  
	  });
	}
		
	// remove hint text on focus
	$('#searchTerm').focusin(function() {
		$(this).removeClass('pre');
		$(this).attr('value', ''); 
	});
		
	// home page brand rotation area
	/*
	var currentGroup = '#brandsOne';
	$('#brands .nav a').click(function(event) {
		event.preventDefault();
		if( !($(this).hasClass('current')) ) {
			$('#brands .nav a').removeClass('current');
			$(this).addClass('current');
			$(currentGroup).fadeOut('fast');
			currentGroup = $(this).attr('href');
			$(currentGroup).fadeIn('slow');
		}
	})
	*/
	
	// Tabs
	if($("div.tabbedContent").length > 0){
		$(".tabbedContent .tab").hide(); 
		$(".tabbedContent ul.nav li:first a").addClass("current");
		$(".tabbedContent .tab:first").show();
		$(".tabbedContent .tab h2").hide();
	
		//Click Event
		$(".tabbedContent ul.nav li").click(function(e) {
			$(".tabbedContent ul.nav li a").removeClass("current");
			$(this).find("a").addClass("current");
			$(".tabbedContent .tab").hide();
			var activeTab = $(this).find("a").attr("href");
			$(activeTab).show();
			e.preventDefault();
			return false;
		});
	}
		
	/********* Featured Products  Nav ****************/
	if($("div.featureBlock ul.nav").length > 0){
		$("div.featureBlock ul.nav").parent().parent().addClass("featureBlockJS");
		$("div.featureBlockJS div.features").hide(); 
		firstLink = $("div.featureBlockJS ul.nav li:first a");
		firstLink.addClass("current");
		var currentFeatures = firstLink.attr('href');
		
		$(currentFeatures).show();
		
		
		$("div.featureBlockJS div.feature").each(function(index){
			$(this).data('pos',index+1);
		  });

		$('div.featureBlockJS ul.nav a').click(function(event) {
			event.preventDefault();
			if( !($(this).hasClass('current')) ) {
				$('div.featureBlockJS ul.nav a').removeClass('current');
				$(this).addClass('current');
				
				nextFeatures = $(this).attr('href');
				$(currentFeatures).fadeOut('fast', function(){
					currentFeatures = nextFeatures;
					$(currentFeatures).fadeIn('slow');											
				});
				firstFeature = $(nextFeatures).find(".feature:first").data('pos');
				lastFeature = $(nextFeatures).find(".feature:last").data('pos');
				$('div.featureBlockJS p.displaying').html(commonStrings.displaying + " " + firstFeature+"-"+lastFeature);
			}
		});
	}
		
	// Paged content
	var nextPage = $(".pagination.js li.pages a:first").parent().next().find("a").attr("href");
	if(nextPage != null){
		$(".pagination.js ul li a.next").attr("href", nextPage);
	}
	var prevPage;

	
	$(".pagination.js ul li a").click(function(e){
		$(".js-pages").hide(); 
		var activePage = $(this).attr("href");
		$(".pagination.js ul li.pages a ").removeClass("current");
		$(".pagination.js ul li.pages a[href="+activePage+"]").addClass("current");
		

		
		$(activePage).show();
		
		nextPage = $(".pagination.js ul li.pages a[href="+activePage+"]").parent().next(".pages").find("a").attr("href");
		if(nextPage != null){
			$(".pagination.js ul li a.next").attr("href", nextPage);
			$(".pagination.js ul li > a.next").show();
		}
		
		$(".pagination.js ul li a.next").attr("href", nextPage);
		
		prevPage = $(".pagination.js ul li.pages a[href="+activePage+"]").parent().prev(".pages").find("a").attr("href");
		if(prevPage != null){
			$(".pagination.js ul li a.prev").attr("href", prevPage);
			$(".pagination.js ul li > a.prev").show();
		}

		
		e.preventDefault();
		return false;
	});	
	
	
	/***************************************
		Functions for the Shopping list
	****************************************/
	
	// shopping list open/close
	$('#shoppingList .header h3').click(function() { loadShoppingList(); });
	$('#shoppingList .header .itemCnt').click(function() { loadShoppingList(); });
	$('#shoppingList .hotspot').hover(function() { loadShoppingList(); });	
	$('#shoppingList .header .close').click(function() { $('#shoppingList').removeClass('expanded'); });
	$('#shoppingList').append('<a href="#" id="shopListClose" style="display:block;height:17px;"></a>');
	$('#shoppingList #shopListClose').click(function(e) { 
		e.preventDefault();
		$('#shoppingList').removeClass('expanded');
	 });
		
	var loadingShopList = false;
	function loadShoppingList(){
		var listService = "";

                if( lang == "fr" ) {
                        listService = "/fr/shop/view";
                } else {
                        listService = "/en/shop/view";
                }

                if(!loadingShopList){
                        loadingShopList = true;
                        $.ajax({
                                url: listService,
                                dataType: "json",
                                success: populateShoppingList,
                                error: noList,
                                complete: function(){loadingShopList = false}
                        });
                }
	}

	function noList(){
		$('#shoppingList').addClass('expanded');	
	}
	function populateShoppingList(data){

		if(data.items != null){
			$('#shoppingList .content').empty();
			$('#shoppingList .content').append('<ul class="items"></ul>');
			var shoplist = $('#shoppingList .content ul');
			
			var itemCount = data.items.length;
			
			for (i = 0; i < itemCount; i++) {
				
				var prod = data.items[i];
				var content = '\
				<li>\
					<h4><a href="'+ prod.detailLink +'">'+ prod.name +'</a></h4>\
					<div class="item clearfix">\
						<div class="thumb"><img src="/products/60/'+ prod.image +'.jpg" alt="'+ prod.name +'" /></div>\
						<div class="deets">\
							<h5>'+ prod.name +'</h5>\
							<p><span class="price"> '+ prod.itemNum +'</span><br />\
							'+commonStrings.quantity+': '+ prod.quantity +'</p>\
						</div>\
					</div>\
				</li>';
				shoplist.append(content);
			}
		}
		$('#shoppingList').addClass('expanded');
	}
	
	
	// Keep me signed in dialog
	$("a#keep_signed_in_how").click(function(){
		// Set the dialog text
		$("#keep_signed_in_how_msg").html(keepSignedInPopup); 
		
		// Add class for proper formatting
		$("#keep_signed_in_how_msg").addClass("bodyContent"); 
		
		// Open the dialog
		$("#keep_signed_in_how_msg").dialog("open"); 
		
		// Prevent the page from scrolling to the top on click
		return false; 
	});	
	
	// Dialog settings	
	$("#keep_signed_in_how_msg").dialog({
		autoOpen: 	false,
		resizable: 	false,
		width: 		378,
		modal: 		true,
		title:		keepSignedInTitle, // Title of dialog
		dialogClass:'clearfix '
	});
	
	/**
	  * Search type-ahead
	**/		
	// Add the listing div
	$('<div id="searchTypeAhead" class="searchTypeAhead clearfix" style="display:none;"><ul id="searchTerms"></ul></div>').insertAfter("#searchTerm");
	
	// Query the type-ahead service on keyup
	$("#searchTerm").keyup(function(event) {
		if ($("#searchTerm").val().length >= 3) {
			if ((event.keyCode != '38') && (event.keyCode != '40') && (event.keyCode != '13')) {
				$.getJSON('/' + lang + '/dim/search?q=' + $("#searchTerm").val(), function(data) {
					var resultName = "";
					var resultNameArray = new Array();	
					var splitOp = "";
					var counter = 0;
					
					selectedSearchTerm = -1;
					
					if(data.results != "") {
						// Clear the listing on each new query
						$("#searchTypeAhead ul#searchTerms").empty();
					
						for (var i = 0; i < data.results.length; i++) {					
							
								resultName = "";
							
								if (data.results[i].name.indexOf("-") != -1) {
									splitOp = "-";
								} else if (data.results[i].name.indexOf("/") != -1) {
									splitOp = "/";
								} else {
									splitOp = " ";
								}
								resultNameArray = data.results[i].name.split(splitOp);
								
								// camelCase city names
								for (var j = 0; j < resultNameArray.length; j++) {
									resultName += resultNameArray[j].substr(0,1).toUpperCase() + resultNameArray[j].substr(1).toLowerCase() + splitOp;
								}	
								
								$("#searchTypeAhead ul#searchTerms").append('<li class="typeAheadSearchTerm" id="term_' + counter + '" onclick="searchFormSubmit(' + counter + ');">' + resultName.substr(0,resultName.length-1) + '</li>');						
								
								counter++;						
						}				
						
						// Show city listing
						$("#searchTypeAhead").show();			
					} else {
						// Hide city listing
						if ($("#searchTypeAhead").css("display") == "block") {							
							$("#searchTypeAhead").hide();
							selectedSearchTerm = -1;
						}
					}
				});			
			} else if (event.keyCode == '40') {
				// Arrow down key press
				if ($("#searchTypeAhead").css("display") == "none") {
					selectedSearchTerm = -1;
				} else {
					// Don't allow user to go past last store in list
					if (selectedSearchTerm != $("#searchTypeAhead ul#searchTerms li").size()-1) {
						// Increment selected store num
						selectedSearchTerm++;
					}
					//Set list item background color
					$(".typeAheadSearchTerm").removeClass("active");
					$("#term_" + selectedSearchTerm).addClass("active");
					// Set city input box value
					$("#searchTerm").val($("#term_" + selectedSearchTerm).text());
				}			
			} else if (event.keyCode == '38') {
				// Arrow up key press
				if ($("#searchTypeAhead").css("display") == "none") {
					selectedSearchTerm = -1;
				} else {
					// Don't allow user to go past first store in list
					if (selectedSearchTerm >= 1) {
						// Decrement selected store num
						selectedSearchTerm--;
					}
					//Set list item background color
					$(".typeAheadSearchTerm").removeClass("active");
					$("#term_" + selectedSearchTerm).addClass("active");
					// Set city input box value
					$("#searchTerm").val($("#term_" + selectedSearchTerm).text());
				}
			} else if (event.keyCode == '13') {
				// 'Enter' key press
				$("form#search").submit();
			}
		} else {
			// Hide if < 3 characters
			$("#searchTypeAhead").hide();
		}
    });		
	
	// Hide type-ahead listing on window click (when the user clicks somewhere else in the browser)
	$("html,body").click(function() {
		$("#searchTypeAhead").hide();	
    });
	
	// Hide type-ahead listing on window blur (when the browser loses focus)
	$(window).blur(function() {
		$("#searchTypeAhead").hide();	
    });
	
	/* Forgot Password */
	$("div.forgotpwd a#sendpwd").click(function() {
		// Hide error message, if any
		$("#account_form #signin_message").hide();
		sendPassword($("div.forgotpwd input#forgot_username").val());
    });	
	$('div.forgotpwd form div.email input#forgot_username').keypress(function(event) {
		if (event.keyCode == '13') {
			// Hide error message, if any
			$("#account_form #signin_message").hide();
			sendPassword($("div.forgotpwd input#forgot_username").val());
		}
	});
	
	// Clear default text on click
	$("form#search a").click(function() {		
		if( $('#searchTerm').val() == initialValue){ 
			$('#searchTerm').val(""); //Don't search on example text initialValue
		}
		if ($('#searchTerm').val() != "") {			
			$("#search").submit();		
		}
	});
	
	$('#registration input').keypress(function(event) {
		// 'Enter' keypress event on registration form
		if (event.keyCode == '13') {
			// Do not submit if postal code input (this should show store locator pop-up instead)
			if ($(this).attr("Id") != "reg_postalcode")
				$("#registration").submit();
		}
	});	
	
	$('#settings input').keypress(function(event) {
		// 'Enter' keypress event on registration form
		if (event.keyCode == '13') {
			// Do not submit if postal code input (this should show store locator pop-up instead)
			if ($(this).attr("Id") != "reg_postalcode")
				$("#settings").submit();
		}
	});
	
	$('#contestEntry input').keypress(function(event) {
		// 'Enter' keypress event on contest entry form
		if (event.keyCode == '13') {
			$("#contestEntry").submit();
		}
	});
	
	$('#contestFriend input').keypress(function(event) {
		// 'Enter' keypress event on contest entry form
		if (event.keyCode == '13') {
			$("#contestFriend").submit();
		}
	});
	
	$('#updateMailingAddress input').keypress(function(event) {
		// 'Enter' keypress event on update address form
		if (event.keyCode == '13') {
			$("#updateMailingAddress").submit();
		}
	});
	
	$('#login input').keypress(function(event) {
		// 'Enter' keypress event on static login form
		if (event.keyCode == '13') {
			$("#login").submit();
		}
	});
	
});

function searchFormSubmit(termId) {
	// Set city input box value
	$("#searchTerm").val($("#searchTypeAhead ul#searchTerms li#term_" + termId).html());
	
	// Submit the form
	$("form#search").submit();
}

function sendPassword(email) {	
	// Hide any messages
	$("#account_form #signin_message").hide();				
	// Show loading bar
	$("#account_form #loading-bar").show();
	
	var emailValidate = /^\w+([\.\+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/;
				
	// Validate email
	if (emailValidate.test(email)) {		  
		var data = new Object();
		data.email = email;

		$.ajax({ url: '/' + lang + '/forms/forgotPassword', type: 'POST', contentType: "application/x-www-form-urlencoded; charset=utf-8", scriptCharset: "utf-8", dataType: 'json', data: data, success: handleForgot, error:handleForgotError });	
	} else {
		$("#account_form #signin_message").addClass("error");
		$("#account_form #signin_message").html(messageError);
		$("#account_form #loading-bar").hide();
		$("#account_form #signin_message").show();
	}
}
function handleForgotError( data ){	
	$("#account_form #signin_message").addClass("error");
	$("#account_form #signin_message").html(messageError);
	$("#account_form #loading-bar").hide();
	$("#account_form #signin_message").show();
}
function handleForgot( data ){
	if (data.error) {
		// Error
		$("#account_form #signin_message").addClass("error");
		$("#account_form #signin_message").html(messageError);
		$("#account_form #loading-bar").hide();
		$("#account_form #signin_message").show();
	} else {
		// Send email
		$("#account_form #signin_message").hide();
		$("#account_form #loading-bar").hide();
		$("div.forgotpwd div.email").hide();
		$("div.forgotpwd a#sendpwd").hide();
		$("div.forgotpwd form div:eq(1)").html(messagePasswordSent);
		$("div.forgotpwd a.closelink").html(labelClose);
	}
}
function get_cookie(cookie_name) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
	if (results) {
		return (unescape(results[2]));	
	} else {
    	return null;
	}
}

function clear_errors() {
	$("#message.error").hide();
}
