/*
GLobal variables
*/
var shoppingListsLimitReached=true;

/* JSONPath 0.8.0 - XPath for JSON
 *
 * Copyright (c) 2007 Stefan Goessner (goessner.net)
 * Licensed under the MIT (MIT-LICENSE.txt) licence.
 */
function jsonPath(obj, expr, arg) {
   var P = {
      resultType: arg && arg.resultType || "VALUE",
      result: [],
      normalize: function(expr) {
         var subx = [];
         return expr.replace(/[\['](\??\(.*?\))[\]']/g, function($0,$1){return "[#"+(subx.push($1)-1)+"]";})
                    .replace(/'?\.'?|\['?/g, ";")
                    .replace(/;;;|;;/g, ";..;")
                    .replace(/;$|'?\]|'$/g, "")
                    .replace(/#([0-9]+)/g, function($0,$1){return subx[$1];});
      },
      asPath: function(path) {
         var x = path.split(";"), p = "$";
         for (var i=1,n=x.length; i<n; i++)
            p += /^[0-9*]+$/.test(x[i]) ? ("["+x[i]+"]") : ("['"+x[i]+"']");
         return p;
      },
      store: function(p, v) {
         if (p) P.result[P.result.length] = P.resultType == "PATH" ? P.asPath(p) : v;
         return !!p;
      },
      trace: function(expr, val, path) {
         if (expr) {
            var x = expr.split(";"), loc = x.shift();
            x = x.join(";");
            if (val && val.hasOwnProperty(loc))
               P.trace(x, val[loc], path + ";" + loc);
            else if (loc === "*")
               P.walk(loc, x, val, path, function(m,l,x,v,p) { P.trace(m+";"+x,v,p); });
            else if (loc === "..") {
               P.trace(x, val, path);
               P.walk(loc, x, val, path, function(m,l,x,v,p) { typeof v[m] === "object" && P.trace("..;"+x,v[m],p+";"+m); });
            }
            else if (/,/.test(loc)) { // [name1,name2,...]
               for (var s=loc.split(/'?,'?/),i=0,n=s.length; i<n; i++)
                  P.trace(s[i]+";"+x, val, path);
            }
            else if (/^\(.*?\)$/.test(loc)) // [(expr)]
               P.trace(P.eval(loc, val, path.substr(path.lastIndexOf(";")+1))+";"+x, val, path);
            else if (/^\?\(.*?\)$/.test(loc)) // [?(expr)]
               P.walk(loc, x, val, path, function(m,l,x,v,p) { if (P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v[m],m)) P.trace(m+";"+x,v,p); });
            else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) // [start:end:step]  phyton slice syntax
               P.slice(loc, x, val, path);
         }
         else
            P.store(path, val);
      },
      walk: function(loc, expr, val, path, f) {
         if (val instanceof Array) {
            for (var i=0,n=val.length; i<n; i++)
               if (i in val)
                  f(i,loc,expr,val,path);
         }
         else if (typeof val === "object") {
            for (var m in val)
               if (val.hasOwnProperty(m))
                  f(m,loc,expr,val,path);
         }
      },
      slice: function(loc, expr, val, path) {
         if (val instanceof Array) {
            var len=val.length, start=0, end=len, step=1;
            loc.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g, function($0,$1,$2,$3){start=parseInt($1||start);end=parseInt($2||end);step=parseInt($3||step);});
            start = (start < 0) ? Math.max(0,start+len) : Math.min(len,start);
            end   = (end < 0)   ? Math.max(0,end+len)   : Math.min(len,end);
            for (var i=start; i<end; i+=step)
               P.trace(i+";"+expr, val, path);
         }
      },
      eval: function(x, _v, _vname) {
         try { return $ && _v && eval(x.replace(/@/g, "_v")); }
         catch(e) { throw new SyntaxError("jsonPath: " + e.message + ": " + x.replace(/@/g, "_v").replace(/\^/g, "_a")); }
      }
   };

   var $ = obj;
   if (expr && obj && (P.resultType == "VALUE" || P.resultType == "PATH")) {
      P.trace(P.normalize(expr).replace(/^\$;/,""), obj, "$");
      return P.result.length ? P.result : false;
   }
} 

/* jQuery AlphaNumeric filter */
(function($){
	$.fn.alphanumeric = function(p) { 
		p = $.extend({
			ichars: "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
			nchars: "",
			allow: ""
		  }, p);	
		return this.each
			(
				function() 
				{
					if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
					s = p.allow.split('');
					for ( i=0;i<s.length;i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
					p.allow = s.join('|');
					var reg = new RegExp(p.allow,'gi');
					var ch = p.ichars + p.nchars;
					ch = ch.replace(reg,'');
					$(this).keypress
						(
							function (e)
								{
									if (!e.charCode) k = String.fromCharCode(e.which);
										else k = String.fromCharCode(e.charCode);
									if (ch.indexOf(k) != -1) e.preventDefault();
									if (e.ctrlKey&&k=='v') e.preventDefault();
								}
						);
					$(this).bind('contextmenu',function () {return false});
				}
			);
	};

	$.fn.numeric = function(p) {
		var az = "abcdefghijklmnopqrstuvwxyz";
		az += az.toUpperCase();
		p = $.extend({
			nchars: az
		  }, p);	
		return this.each (function()
			{
				$(this).alphanumeric(p);
			}
		);
	};
	
	$.fn.alpha = function(p) {
		var nm = "1234567890";
		p = $.extend({
			nchars: nm
		  }, p);	
		return this.each (function()
			{
				$(this).alphanumeric(p);
			}
		);
	};	
})(jQuery);


/**
 *  jquery.spin-button
 *  (c) 2008 Semooh (http://semooh.jp/)
 *
 *  Dual licensed under the MIT (MIT-LICENSE.txt)
 *  and GPL (GPL-LICENSE.txt) licenses.
 *
 **/
(function($){
  $.fn.extend({
    spin: function(opt){
      return this.each(function(){
        opt = $.extend({
            imageBasePath: '/img/spin/',
            spinBtnImage: 'spin-button.png',
            spinUpImage: 'spin-up.png',
            spinDownImage: 'spin-down.png',
            interval: 1,
            max: null,
            min: null,
            timeInterval: 500,
            timeBlink: 200
          }, opt || {});
        
        var txt = $(this);
        
        var spinBtnImage = opt.imageBasePath+opt.spinBtnImage;
        var btnSpin = new Image();
        btnSpin.src = spinBtnImage;
        var spinUpImage = opt.imageBasePath+opt.spinUpImage;
        var btnSpinUp = new Image();
        btnSpinUp.src = spinUpImage;
        var spinDownImage = opt.imageBasePath+opt.spinDownImage;
        var btnSpinDown = new Image();
        btnSpinDown.src = spinDownImage;
        
        var btn = $(document.createElement('img'));
        btn.attr('src', spinBtnImage);
        btn.css({cursor: 'pointer', verticalAlign: 'bottom', padding: 0, margin: 0});
        txt.after(btn);
        txt.css({marginRight:0, paddingRight:0});
        
        function spin(vector){
          var val = txt.val();
          if(!isNaN(val)){
            val = parseFloat(val) + (vector*opt.interval);
            if(opt.min!=null && val<opt.min) val=opt.min;
            if(opt.min!=null && val>opt.max) val=opt.max;
            if(val != txt.val()){
              txt.val(val);
              txt.change();
              src = (vector > 0 ? spinUpImage : spinDownImage);
              btn.attr('src', src);
              if(opt.timeBlink<opt.timeInterval)
                setTimeout(function(){btn.attr('src', spinBtnImage);}, opt.timeBlink);
            }
          }
        }
        
        btn.mousedown(function(e){
          var pos = e.pageY - btn.offset().top;
          var vector = (btn.height()/2 > pos ? 1 : -1);
          (function(){
            spin(vector);
            var tk = setTimeout(arguments.callee, opt.timeInterval);
            $(document).one('mouseup', function(){
              clearTimeout(tk); btn.attr('src', spinBtnImage);
            });
          })();
          return false;
        });
      });
    }
  });
})(jQuery);


var map;
var gmarkers;

function addStoreProfile(storeId) {
jQuery.post("store_locator_landing_page.jsp", 
{form_action:"storeProfile",
 op:"add",
 storeId:storeId},
 function(result) {
	jQuery("#s_"+storeId).attr("href","Javascript:removeStoreProfile('" + storeId + "');");
	jQuery("#s_"+storeId).empty();
	jQuery("#s_"+storeId).html(lcloStoreMessages["store.remove_store.link"]);
	showGMapInfoWindow(storeId);
	}, "json");
}

function removeStoreProfile(storeId) {
jQuery.post("store_locator_landing_page.jsp", 
{form_action:"storeProfile",
 op:"remove",
 storeId:storeId},
 function(result) {
 	jQuery("#s_"+storeId).attr("href","Javascript:addStoreProfile('" + storeId + "');");
	jQuery("#s_"+storeId).empty();
	jQuery("#s_"+storeId).html(lcloStoreMessages["store.add_store.link"]);
	showGMapInfoWindow(storeId);
	}, "json");
}

function toggleAdditionalStoreFiltersDisplay(){
	if (jQuery("#additionalStoreFilters").hasClass("hidden")) {
		jQuery("#additionalStoreFilters").removeClass("hidden");
		jQuery("a#toggleStoreFilters").html("Hide more options");
	} else {
		jQuery("#additionalStoreFilters").addClass("hidden");
		jQuery("a#toggleStoreFilters").html("Show more options");
	}
}

function toggleMemberPreferencesDisplay() {
    //jQuery("label.extra").toggle();
    if (jQuery("label.extra").css("display") == "none") {
		jQuery("label.extra").css("display","block");
        jQuery("a#memberPreferencesToggleLink").html("Hide More");
    } else {
		jQuery("label.extra").css("display","none");
        jQuery("a#memberPreferencesToggleLink").html("Show More");
    }
}

function toggleProductsCategoriesDisplay() {
    jQuery("li.extra").toggle();
    if (jQuery("li.extra").css("display") == "none") {
        jQuery("a#productsCategoriesToggleLink").html("Show More");
    } else {
        jQuery("a#productsCategoriesToggleLink").html("Hide More");
    }
}

function toggleMemberPreferencesPhotoUploadDisplay() {
    jQuery("#memberPreferencesPhoto fieldset").toggle();
    if (jQuery("#memberPreferencesPhoto fieldset").css("display") == "none") {
        jQuery("#memberPreferencesPhoto a.upload").show();
    } else {
        jQuery("#memberPreferencesPhoto a.upload").hide();
    }
}

function showConfirmField(fromWhichObject){
    jQuery(fromWhichObject).parent().find("div.confirmField").show();
    jQuery(fromWhichObject).parent().find("div.confirmField input").focus();
	jQuery(fromWhichObject).parent().addClass("edit");
}

function showErrorMessage(forWhichField, message) {
    jQuery(forWhichField).parent().find("span.errorMessage:first").html(message);
}

function clearErrorMessage(forWhichField) {
    jQuery(forWhichField).parent().find("span.errorMessage:first").empty();
}

function isValidEmail(thisEmail) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(thisEmail);
}

function validateEmail(whichEmail) {
    if (isValidEmail(whichEmail.value)) {
        clearErrorMessage(whichEmail);
        return true;
    } else {
        showErrorMessage(whichEmail, profileMessages["err.profile.registration.notvalidemail"]);
        return false;
    }
}

function confirmEmail(whichEmail, originalEmail) {
    if ((isValidEmail(whichEmail.value)) && (whichEmail.value == document.getElementById(originalEmail).value)) {
        clearErrorMessage(whichEmail);
    } else {
        showErrorMessage(whichEmail, profileMessages["err.profile.registration.confirmemail"]);
    }
}

function validatePassword(whichPassword) {
    //generic validation - checks that the length is >= 6 characters
    if (whichPassword.value.length < 6) {
        showErrorMessage(whichPassword, profileMessages['err.profile.registration.passwordlength']);
        jQuery(whichPassword).focus();        
    } else {
        clearErrorMessage(whichPassword);
    }
}

function confirmPassword(whichPassword, originalPassword) {
    if (whichPassword.value != document.getElementById(originalPassword).value) {
        showErrorMessage(whichPassword, profileMessages["err.profile.registration.confirmpassword"]);
    } else {
        clearErrorMessage(whichPassword);
    }
}

function validatePostalCode(pcodePart1, pcodePart2){
    var tempPCode = jQuery("#"+pcodePart1).val() + "" + jQuery("#"+pcodePart2).val();
    var pattern = new RegExp(/^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/i);
    if (pattern.test(tempPCode)) {
        clearErrorMessage("#"+pcodePart1);
    } else {
        showErrorMessage("#"+pcodePart1, profileMessages["err.profile.notvalidpostalcode"]);
    }
}



function getLoginStatus(){
    //if the user isn't logged in, redirect them to the login page (or return false)
    //if the user is logged in, return true
    //for now, just return true
    return true;
}


function reviewClass(whichClassID){
    if (getLoginStatus()){
        tb_show("ClassReview","communityroom_createreview.html?height=400&width=400&modal=true", "");
    } else {
        //redirect the user to the login page (perhaps with a 'returnURL' parameter to be able to return to the current page
        window.location.href = "";
    }
}

function reviewBirthdayParties(whichBirthdayPartyID){
    if (getLoginStatus()){
        tb_show("BirthdayPartyReview","communityroom_birthdayparty_createreview.html?height=400&width=400&modal=true", "");
    } else {
        //redirect the user to the login page (perhaps with a 'returnURL' parameter to be able to return to the current page
        window.location.href = "";
    }
}

/*function deleteShoppingListConfirm(whichShoppingListID){
    var boolResult = confirm("Are you sure you want to delete this Shopping List?");
    if (boolResult){
        //do an AJAX request to delete the appropriate ID passed in
        // then update the display
    }
}*/

/*function deleteShoppingListItemConfirm(whichShoppingListID){
    var boolResult = confirm("Are you sure you want to delete this Shopping List item?");
    if (boolResult){
        //do an AJAX request to delete the appropriate ID passed in
        // then update the display
    }
}*/

function deleteMealPlanConfirm(whichMealPlanID){
    var boolResult = confirm(profileMessages["mealplan.delete.message"]);
    if (boolResult){
        jQuery.post("/LCLOnline/test/piplinetest.jsp",{
             form_action: "mealPlan",
             form_command: "delete",
             mealPlanId: whichMealPlanID             
           }, function(data) { 
         if(data.status=='1'){
         	reloadMealPlans(data);
         	tb_remove();         	
         }else{
         	alert(data.error);
         }
       }, "json");
    }
}

function copyMealPlanConfirm(whichMealPlanID){
    var boolResult = confirm(profileMessages["mealplan.copy.message"]);
    if (boolResult){
        jQuery.post("/LCLOnline/test/piplinetest.jsp",{
             form_action: "mealPlan",
             form_command: "copy",
             mealPlanId: whichMealPlanID             
           }, function(data) { 
         if(data.status=='1'){
         	reloadMealPlans(data);
         	tb_remove();         	
         }else{
         	alert(data.error);
         }
       }, "json");
    }
}

function deleteMealPlanItemConfirm(whichMealPlanItemID,whichMealPlan){
    var boolResult = confirm(profileMessages["mealplan.item.delete.message"]);
    if (boolResult){
        jQuery.post("/LCLOnline/test/piplinetest.jsp",{
             form_action: "mealPlan",
             form_command: "deleteItem",
             mealPlanItemId: whichMealPlanItemID,
             mealPlanId: whichMealPlan             
           }, function(data) { 
         if(data.status=='1'){
         	reloadMealPlans(data);
         	tb_remove();         	
         }else{
         	alert("There was a problem deleting this meal plan. Please try again.");
         }
       }, "json");
    }
}

function timedShoppingListsNotesAutoSave(whichListID){
    //autosave AJAX functionality for Shopping List notes
}

function clearTimedShoppingListsNotesAutoSave(whichListID){
    //clear autosave AJAX functionality when user moves away from the field;
    //save the field contents first, then clear the timer object
}

var objJSONData = [];
var objJSONMealPlanData = [];

function deleteShoppingListItemFromOverlay(shoppingListPosition, shoppingListItemPosition){ 
  var boolResult = confirm(shoppingListMessages["shoppinglist.item.delete_are_you_sure.message"]);
    if (boolResult){
        var form_action='handleShoppingListItems';
		var actionRequested ='delete';        
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:objJSONData.shoppingLists[shoppingListPosition].ID,
			itemId:objJSONData.shoppingLists[shoppingListPosition].shoppingListItems[shoppingListItemPosition].itemID},
			function (result, textStatus) {
			if (result.status =="1") {
			    objJSONData.shoppingLists[shoppingListPosition].shoppingListItems.splice(shoppingListItemPosition,1);
			    updateShoppingListsWidgetDisplay(objJSONData, objJSONData.shoppingLists[shoppingListPosition].ID);
			} else {
			alert("There was a problem removing item. Please try again letter");
			
			}
 
			},"json"
	);        
        
    }
              

}

function updateShoppingListsWidgetDisplay(objJSONData, selectedShoppingListID){
    //put the init code in here
    jQuery("div#shoppingListsOverlayWidgetContents div.scrolling").empty();
    
    //find the Shopping List array position
    var intShoppingListPosition = 0;
    var shoppingListToDisplay=[];
    if(objJSONData.shoppingLists.length > 1) {

	    for (x=0;x < objJSONData.shoppingLists.length; x++){
	        if (selectedShoppingListID == objJSONData.shoppingLists[x].ID){
	            intShoppingListPosition = x;
	            break;
	        }
	    }
	 }
	 if(objJSONData.shoppingLists.length > 1) {
	 	shoppingListToDisplay =objJSONData.shoppingLists[intShoppingListPosition];
	 } else {
	 	shoppingListToDisplay =objJSONData.shoppingLists;
	 }   

	if(shoppingListToDisplay.shoppingListItems) {	

	    jQuery(shoppingListToDisplay.shoppingListItems).each(function(i){
	    	if (this.itemName != null) {
	    	var htmlToAppend ="<div>";
	    	var qtyDescr="";
		    	if (this.recipeId.length<1 ) {
		    		htmlToAppend+="<input type=\"text\" id=\"" + this.itemID + "\" value=\"" + this.itemQuantity + "\" />";
		    	} else {
		    	qtyDescr=this.quantityDescription+" - ";
		    	}
	    	
	    		if (this.productId.length>1 ) {
	    		htmlToAppend+=qtyDescr+"<a href=\"products.jsp?type=details&catIds="+this.productId+"&productId="+this.productId+"\">" +this.itemName + "</a>";
	    		} else{
	    		htmlToAppend+=qtyDescr+this.itemName;
	    		}
		
	    	htmlToAppend+="<a class=\"btnDeleteSmall\" href=\"JavaScript:void(0);\" onclick=\"JavaScript:deleteShoppingListItemFromOverlay('" + intShoppingListPosition + "','" + i + "');\"><span>delete</span></a></div>"
				jQuery("div#shoppingListsOverlayWidgetContents div.scrolling").append(htmlToAppend);
			}
	    });
    jQuery("div#shoppingListsOverlayWidgetContents div.scrolling input").spin({imageBasePath:"images/pc/",max:100,min:0});
    //jQuery("div#shoppingListsOverlayWidgetContents div.scrolling input").numeric();
    jQuery('div#shoppingListsOverlayWidgetContents div.scrolling input').change(function(){
        //update the JSON object
        //find the item position in the selected Shopping List
        //var strThisItemID = jQuery.trim($(this).attr("id"));
        updateShoppingListItemQtyOnOverlay(shoppingListToDisplay.ID,jQuery.trim($(this).attr("id")),jQuery(this).val());
        /*for (y=0; y <= jQuery(objJSONData.shoppingLists[intShoppingListPosition].shoppingListItems).length; y++){
        	var thisShoppingListItem = jQuery(objJSONData.shoppingLists[intShoppingListPosition].shoppingListItems[y]);
            var thisItemID = jQuery.trim(thisShoppingListItem.itemID);
            if (thisItemID == strThisItemID){
                thisShoppingListItem.itemQuantity = jQuery(this).val();
            }
        }*/
    }).change();	    
	} else {
		jQuery("div#shoppingListsOverlayWidgetContents div.scrolling").append("<div>"+shoppingListMessages["shoppinglist.no_items_in_list.message"]+"</div>");	
	}    
    

	jQuery("div#shoppingListsOverlayWidgetContents a#shoppingListLink").attr("href", "myShoppingLists.jsp?shoppingListId=" + selectedShoppingListID);
	//jQuery("div#shoppingListControl").show();
}
function loadOnDemandShoppingListOverlayMessages(){
	if (typeof(shoppingListMessages) == "undefined") {
		jQuery.post("global-scripts.jsp",function (data, textStatus) {
		jQuery('head').append(data);	
		});
	}
}

function updateShoppingListItemQtyOnOverlay(shoppingListId,itemId,itemQty) {
	var form_action ="handleShoppingListItems";
	var actionRequested="updateQuantity";

	jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			itemId:itemId,
			shoppingListId:shoppingListId,			
			quantity:itemQty
			}, function (data, textStatus) {
 
			},"json"); 

}

function showOrHideShoppingListCopyMenu(){
	if(shoppingListsLimitReached){
		jQuery("div#memberPreferencesShoppingListsTabNavigation ul li#listCopy").hide();
		jQuery("div#memberPreferencesShoppingListsContainer p#createListInstructions").hide();
		jQuery("div#memberPreferencesShoppingListsContainer a#btnCreateNewShoppingList").hide();
		jQuery("div#memberPreferencesShoppingListsContainer p#limitReachedInstruction").show();
		
	} else {
		jQuery("div#memberPreferencesShoppingListsContainer p#limitReachedInstruction").hide();
		jQuery("div#memberPreferencesShoppingListsTabNavigation ul li#listCopy").show();
		jQuery("div#memberPreferencesShoppingListsContainer p#createListInstructions").show();
		jQuery("div#memberPreferencesShoppingListsContainer a#btnCreateNewShoppingList").css('display', 'block');
		
	}
}


function initializeShoppingListsWidget(objJSONData){
    //based on the returned data, display the display
	//tb_show("Shopping Lists","shoppinglists_overlay.html?height=300&width=730");
	var shoppingListTitleLabel = jQuery("div#myPCAccount a.thickbox").attr("title"); 
	loadOnDemandShoppingListOverlayMessages();	
	if (typeof(shoppingListMessages) == "undefined") {
		tb_show(shoppingListTitleLabel,"profile-shoppinglists-overlay.jsp?width=730&height=350");
	}else { 
		
    var intNumberOfShoppingLists;
    
    if(objJSONData.shoppingLists){
     	intNumberOfShoppingLists = jQuery(objJSONData.shoppingLists).length;
     } else {
     	intNumberOfShoppingLists = 0;
     }
    
    //jQuery("div#shoppingListControl").append("<h6>My Shopping Lists</h6>");
    if (intNumberOfShoppingLists == 0) {
        jQuery("div#shoppingListsOverlayWidgetContents").append("<p>" + lcloGlobalMessages["shoppinglist.notcreated"] + "</p><a href=\"profile-create-new-shopping-list.jsp?width=730&height=300&calledFrom=overlay\" title=\""+shoppingListTitleLabel+"\" class=\"btnCreateNewShoppingList thickbox\"><span>New List</span></a>");
    } else {
        //process the Shopping List content
        //save the list data to a string (perhaps a cookie) for retrieval
        if(!shoppingListsLimitReached) {
        	jQuery("div#shoppingListsOverlayWidgetContents").append("<a href=\"profile-create-new-shopping-list.jsp?width=730&height=300&calledFrom=overlay\"  class=\"btnCreateNewShoppingList thickbox\" title=\""+shoppingListTitleLabel+"\"><span>Create a New Shopping List</span></a>");
        } else {
        	jQuery("div#shoppingListsOverlayWidgetContents").append("<span>"+lcloGlobalMessages["shoppinglists.shoppinglists_limit_reached.text"]+"</span>");
        }
        jQuery("div#shoppingListsOverlayWidgetContents").append("<label class=\"subheader\" for=\"dd_shoppinglists\">" + lcloGlobalMessages["shoppinglist.selectlist"] + "</label>");
        jQuery("div#shoppingListsOverlayWidgetContents").append("<select id=\"dd_shoppinglists\"></select>");
        jQuery(objJSONData.shoppingLists).each(function(){
            jQuery("div#shoppingListsOverlayWidgetContents select").append("<option value=\"" + this.ID + "\">" + this.shoppingListName + " (" + this.numberOfItems + " " + lcloGlobalMessages["shoppinglist.item.name.label"] + "s)" + "</option>");
        });
        jQuery("div#shoppingListsOverlayWidgetContents select").change(function(){
            //bind an onchange handler for when the user changes the shopping list
            updateShoppingListsWidgetDisplay(objJSONData, $(this).find("option:selected").val());
        });
        jQuery("div#shoppingListsOverlayWidgetContents").append("<div class=\"scrolling\"></div>");
        jQuery("div#shoppingListsOverlayWidgetContents").append("<a href=\"\" class=\"btnGoToList\" id=\"shoppingListLink\"><span>Go to List</span></a>");
		//update the widget display by setting the selected shopping list based on the user's last view activity (retrieved from cookie or session?)
		//use test list ID for now
		var userSelectedID = "1444";
		jQuery("div#shoppingListsOverlayWidgetContents select option[value='" + userSelectedID + "']").attr({"selected":"selected"});
		jQuery("div#shoppingListsOverlayWidgetContents select").change();
    }
    tb_reinit('div#shoppingListsOverlayWidgetContents a.thickbox');
   } 	
}

function deleteMealPlanItem(whichPlanID, whichDay, whichCourse, whichItemPosition){
	//iterate through objJSONMealPlanData to find appropriate positions and delete item
    //find the Meal Plan array position
    var intMealPlanPosition = 0;
    for (x=0;x < objJSONMealPlanData.mealPlans.length; x++){
        if (whichPlanID == objJSONMealPlanData.mealPlans[x].ID){
            intMealPlanPosition = x;
            break;
        }
    }
    //find the Meal Plan day array position
    var intMealPlanDayPosition = 0;
	for (x=0; x<objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays.length; x++){
        if (whichDay == objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays[x].mealPlanDayName){
            intMealPlanDayPosition = x;
            break;
        }
	}
    //find the Meal Plan course array position
    var intMealPlanDayCoursePosition = 0;
	for (x=0; x<objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays[intMealPlanDayPosition].mealPlanDayNameCourses.length; x++){
        if (whichCourse == objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays[intMealPlanDayPosition].mealPlanDayNameCourses[x].mealPlanDayCourseName){
            intMealPlanDayCoursePosition = x;
            break;
        }
	}
    objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays[intMealPlanDayPosition].mealPlanDayNameCourses[intMealPlanDayCoursePosition].mealPlanDayCourseItems.splice(whichItemPosition,1);
	//if no items remain for the course, delete the course as well
	if (objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays[intMealPlanDayPosition].mealPlanDayNameCourses[intMealPlanDayCoursePosition].mealPlanDayCourseItems.length == 0){
		objJSONMealPlanData.mealPlans[intMealPlanPosition].mealPlanDays[intMealPlanDayPosition].mealPlanDayNameCourses.splice(intMealPlanDayCoursePosition,1);
	}
    showMealPlanDay(whichDay);
}

function showMealPlanDay(whichDay){
	//show the contents of the selected day for the currently selected Meal Plan
	jQuery("div#mealPlanControl div#mealPlanControlWeekdayLinks a").removeClass("active");
	jQuery("div#mealPlanControl div#mealPlanControlWeekdayLinks a:contains('" + whichDay.substring(0,3) + "')").addClass("active");
	jQuery("div#mealPlanControl div.scrolling").empty();
	var objMealPlanDayItems = jsonPath(objJSONMealPlanData, "$.mealPlans[?(@.ID==" + jQuery("div#mealPlanControl select option:selected").val() + ")].mealPlanDays[?(@.mealPlanDayName=='" + whichDay + "')].mealPlanDayNameCourses");
	jQuery(objMealPlanDayItems[0]).each(function(i, val){
		jQuery("div#mealPlanControl div.scrolling").append("<p class=\"itemCategoryTitle\">" + val.mealPlanDayCourseName + "</p>");
		for (x=0; x<val.mealPlanDayCourseItems.length; x++){
			var strThisItem = val.mealPlanDayCourseItems[x].mealPlanDayCourseItemName;
			if (val.mealPlanDayCourseItems[x].mealPlanDayCourseItemURL != "") {
				strThisItem = "<a href=\"" + val.mealPlanDayCourseItems[x].mealPlanDayCourseItemURL + "\">" + strThisItem + "</a>";
			}
			jQuery("div#mealPlanControl div.scrolling").append("<p>" + strThisItem + " <a href=\"JavaScript:void(0);\" onclick=\"JavaScript:deleteMealPlanItem('" + jQuery("div#mealPlanControl select option:selected").val() + "','" + whichDay + "','" + val.mealPlanDayCourseName + "'," + x + ");\">X</a></p>");
		}
	});
}

function updateMealPlansWidgetDisplay(objJSONMealPlanData, selectedMealPlanID){
    //put the init code in here
    jQuery("div#mealPlanControl div.scrolling").empty();
	
	var strMealPlanStartDay = jsonPath(objJSONMealPlanData, "$.mealPlans[?(@.ID==" + selectedMealPlanID + ")].mealPlanStartDay")[0];
	//draw the day links dependent upon the 'mealPlanStartDay' value
	var arrWeekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	var intDayStartPos = jQuery.inArray(strMealPlanStartDay, arrWeekdays);
	var strWeekdayLinks = "";
	for (x=intDayStartPos; x<arrWeekdays.length; x++){
		strWeekdayLinks = strWeekdayLinks + "<a href=\"JavaScript:void(0);\" onclick=\"JavaScript:showMealPlanDay('" + arrWeekdays[x] + "');\">" + arrWeekdays[x].substring(0,3) + "</a>";
	}
	for (x=0; x<intDayStartPos; x++){
		strWeekdayLinks = strWeekdayLinks + "<a href=\"JavaScript:void(0);\" onclick=\"JavaScript:showMealPlanDay('" + arrWeekdays[x] + "');\">" + arrWeekdays[x].substring(0,3) + "</a>";
	}
	jQuery("div#mealPlanControl div#mealPlanControlWeekdayLinks").html(strWeekdayLinks);
	jQuery("div#mealPlanControl a#mealPlanLink").attr("href", "ATGURL?mealPlanID=" + selectedMealPlanID);
	showMealPlanDay(strMealPlanStartDay);
    
	jQuery("div#mealPlanControl").show();
}

function initializeMealPlansWidget(objJSONMealPlanData){
    //based on the returned data, display the display
    var intNumberOfMealPlans = objJSONMealPlanData.mealPlans.length;
    jQuery("div#mealPlanControl").append("<h6>My Meal Plans</h6>");
    if (intNumberOfMealPlans == 0) {
        jQuery("div#mealPlanControl").append("<p>You have not created a Meal Plan yet. Click New Plan to create one.</p><a href=\"#\" class=\"thickbox\">New Plan</a>");
    } else {
        //process the Meal Plan content
        //save the list data to a string (perhaps a cookie) for retrieval
        jQuery("div#mealPlanControl").append("<a href=\"#\" class=\"thickbox\">New Plan</a>");
        jQuery("div#mealPlanControl").append("<label for=\"\">Select Plan</label>");
        jQuery("div#mealPlanControl").append("<select id=\"\"></select>");
        jQuery(objJSONMealPlanData.mealPlans).each(function(i){
            jQuery("div#mealPlanControl select").append("<option label=\"" + this.mealPlanName + "\" value=\"" + this.ID + "\">" + this.mealPlanName + "</option>");
        });
        jQuery("div#mealPlanControl select").change(function(){
            //bind an onchange handler for when the user changes the shopping list
            updateMealPlansWidgetDisplay(objJSONMealPlanData, jQuery(this).find("option:selected").val());
        });
		//update the widget display by setting the selected meal plan based on the user's last view activity (retrieved from cookie or session?)
		//use test plan ID for now
		var userSelectedID = "4837";
		jQuery("div#mealPlanControl select option[value='" + userSelectedID + "']").attr({"selected":"selected"});
		jQuery("div#mealPlanControl").append("<div id=\"mealPlanControlWeekdayLinks\"></div>");
        jQuery("div#mealPlanControl").append("<div class=\"scrolling\"></div>");
        jQuery("div#mealPlanControl").append("<a href=\"\" id=\"mealPlanLink\">Go to Plan</a>");
        jQuery("div#mealPlanControl").append("<a href=\"JavaScript:void(0);\" onclick=\"JavaScript:hideHeaderWidget('mealplans');\" class=\"hideWidgetLink\">Hide Plan</a>");
		jQuery("div#mealPlanControl select").change();
    }
    //update the JSON object: on change item, on delete item
}

function showHeaderWidget(whichWidget){
    switch(whichWidget){
        case "shoppinglists":
			//jQuery("div#mealPlanControl").hide();
            //check if the widget has already been initialized; if yes, show the widget; if no,
            //use the AJAX function to retrieve shopping list widget contents for this user

            var form_action="handleShoppingList";	
			var actionRequested = "getJsonShoppingListsObject";
             jQuery.post("myShoppingLists.jsp",{
             form_action: form_action,
             actionRequested: actionRequested}
             , function(result) {
                        objJSONData = result;
                        initializeShoppingListsWidget(objJSONData);
                        
                        },"json");

            break;
        case "mealplans":
			jQuery("div#shoppingListControl").hide();
            //AJAX function to retrieve shopping list widget contents for this user
			if (objJSONMealPlanData.length < 1) {
				jQuery.getJSON("http://ux.t4g.com/project_web/LCL_PC/templates/lcl_json_mealplan.asp",
                    function(data){
                        objJSONMealPlanData = data;
                        initializeMealPlansWidget(data);
                    },
                    function (data, textStatus) {
                        // data will be a jsonObj
                        // textStatus will be one of the following values: 
                        //   "timeout","error","notmodified","success","parsererror"
                        //this; // the options for this ajax request
                        //console.log(textStatus);
                    }
                );
			} else {
				jQuery("div#mealPlanControl").show();
			}
            break;
        default:
            break;
    }
    jQuery("div#headerWidgetContainer").show();
}

function hideHeaderWidget(whichWidget){
    switch(whichWidget){
        case "shoppinglists":
            
            break;
        case "mealplans":
            
            break;
        default:
            
            break;
    }
    jQuery("div#headerWidgetContainer").hide();
}

function showMealPlanCellTools(whichCell){
    jQuery(whichCell).find("a.mealPlanCellTools").show();
}

function hideMealPlanCellTools(whichCell){
    jQuery(whichCell).find("a.mealPlanCellTools").hide();
}

function showMealPlanItemTools(whichCell){
    jQuery(whichCell).find("span.mealPlanItemTools").show();
}

function hideMealPlanItemTools(whichCell){
    jQuery(whichCell).find("span.mealPlanItemTools").hide();
}

function showNextMonth(whichLink) { //used for community room Birthday Party bookings
	jQuery(whichLink).parents("div.month").hide();
	jQuery(whichLink).parents("div.month").next().show();
}

function showPreviousMonth(whichLink) { //used for community room Birthday Party bookings
	jQuery(whichLink).parents("div.month").hide();
	jQuery(whichLink).parents("div.month").prev().show();
}

function myFlyerCarousel_initCallback(carousel) {
    jQuery('.jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

    /*jQuery('.jcarousel-scroll select').bind('change', function() {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });

    jQuery('#mycarousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#mycarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });*/
};

function toggleRecommendedFlyerDisplay(whichLink, showText, hideText){
	if (jQuery("div#myFlyerCarouselMainContainerContents").css("display") == "none"){
		jQuery("ul#myFlyerToolLinks").show();
		jQuery("div#myFlyerCarouselMainContainerContents").slideDown();
		jQuery(whichLink).text(hideText);
	} else {
		jQuery("ul#myFlyerToolLinks").hide();
		jQuery("div#myFlyerCarouselMainContainerContents").slideUp();
		jQuery(whichLink).text(showText);
	}
}

function getBannerCities(whichLanguage){
	//retrieve the available cites for this banner for this province
	//once retrieved, populate & enable the city dropdown
}

function getBannerStores(whichLanguage){
	//retrieve the available stores for this banner for this city
	//once retrieved, populate & enable the stores dropdown
}



function addToFavorites(itemId,favoriteType,context,returnUrl){
        var form_action='handleMyFavorites';
		var actionRequested ='addFavorite';  
		
		jQuery.post("myFavourites.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			itemId:itemId,
			favoriteType:favoriteType},
			function (data) {
				if(data.status=='1'){
  					jQuery("li.favourites >a").text(lcloGlobalMessages["favourites.added.label"]);
         		}else if(data.status=='2'){
         			alert(data.existsMessage);
         		} else if(data.status=='4'){

	         		if (returnUrl != "" && returnUrl != null && returnUrl != undefined) {
		         		tb_show(lcloGlobalMessages["common.not_logged_in.label"],"profile-not-logged-in.jsp?height=200&width=730&returnUrl=" + escape(returnUrl));
		         	} else {
		         		tb_show(lcloGlobalMessages["common.not_logged_in.label"],"profile-not-logged-in.jsp?height=200&width=730");
		         	}
         		
         		} else{        		
         		
         			alert(data.errorMessage);
         		}
			},"json"); 
}


function deleteFavorites(favoriteType,context){
  var form_action='handleMyFavorites';
  var actionRequested ='deleteFavorites';  
  var favoriteIds = new Array();
  jQuery('#memberFavourite'+favoriteType+' input[class=checkbox]:checkbox:checked').each(function(){
  	favoriteIds.push(jQuery(this).val());     		 
  });
   
 var boolResult=false;
  if (favoriteIds.length > 0) {
 	 boolResult = confirm(context+" "+lcloGlobalMessages["favorites.will_be_deleted.warning"]); 
  }	  
  if(boolResult) {
 	jQuery.post("myFavorites.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			favoriteType:favoriteType,
			favoriteIds:favoriteIds},
			function (data) {
				if(data.status=='1'){
				window.location.href="myFavorites.jsp";

         		} else {
         			alert(data.errorMessage);
         		}
 			},"json");  
   } 
}

//Update the display for my favourites.
function updateMyFavouritesDisplay() {
NUMBER_OF_ROWS_TO_DISPLAY =2;
//Favourite products
		jQuery("#memberFavouriteProducts a.hideSome").hide();
		if (jQuery("#memberFavouriteProducts > div.row").length > 2){
		jQuery("#memberFavouriteProducts > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+")").hide();
		} else {
		jQuery("#memberFavouriteProducts a.viewMore").hide();
		}
		if (jQuery("#memberFavouriteProducts li.emptyProducts").length > 0) {
		jQuery("#memberFavouriteProducts a.btnRemoveSelectedOff").hide();
		jQuery("#memberFavouriteProducts div.footer label").hide();
		//jQuery("#memberFavouriteProducts a.viewMore").hide();
		}

//Favourite Recipes
		jQuery("#memberFavouriteRecipes a.hideSome").hide();
		if (jQuery("#memberFavouriteRecipes > div.row").length > 2){
		jQuery("#memberFavouriteRecipes > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+")").hide();
		} else {
		jQuery("#memberFavouriteRecipes a.viewMore").hide();
		}
		if (jQuery("#memberFavouriteRecipes li.emptyRecipes").length > 0) {
		jQuery("#memberFavouriteRecipes a.btnRemoveSelectedOff").hide();
		jQuery("#memberFavouriteRecipes div.footer label").hide();
		}	

//Favourite Articles
		jQuery("#memberFavouriteArticles a.hideSome").hide();
		if (jQuery("#memberFavouriteArticles > div.row").length > 2){
		jQuery("#memberFavouriteArticles > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+")").hide();
		} else {
		jQuery("#memberFavouriteArticles a.viewMore").hide();
		}
		if (jQuery("#memberFavouriteArticles li.emptyArticles").length > 0) {
		jQuery("#memberFavouriteArticles a.btnRemoveSelectedOff").hide();
		jQuery("#memberFavouriteArticles div.footer label").hide();
		}
//Favourite Videos
		jQuery("#memberFavouriteVideos a.hideSome").hide();
		if (jQuery("#memberFavouriteVideos > div.row").length > 2){
		jQuery("#memberFavouriteVideos > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+")").hide();
		} else {
		jQuery("#memberFavouriteVideos a.viewMore").hide();
		}
		if (jQuery("#memberFavouriteVideos li.emptyVideos").length > 0) {
		jQuery("#memberFavouriteVideos a.btnRemoveSelectedOff").hide();
		jQuery("#memberFavouriteVideos div.footer label").hide();
		}			
}

function viewMoreFavourites (favouriteType) {
NUMBER_OF_ROWS_TO_DISPLAY =2;
jQuery("#memberFavourite"+favouriteType+" > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+")").show();
jQuery("#memberFavourite"+favouriteType+" a.hideSome").show();
jQuery("#memberFavourite"+favouriteType+" a.viewMore").hide();
}

function hideSomeFavourites (favouriteType) {
NUMBER_OF_ROWS_TO_DISPLAY =2;
jQuery("#memberFavourite"+favouriteType+" > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+")").hide();
jQuery("#memberFavourite"+favouriteType+" a.viewMore").show();
jQuery("#memberFavourite"+favouriteType+" a.hideSome").hide();
//uncheck hidden

jQuery("#memberFavourite"+favouriteType+" > div.row:gt("+(NUMBER_OF_ROWS_TO_DISPLAY -1)+") input[type='checkbox']").removeAttr("checked");
jQuery("#memberFavourite"+favouriteType+" div.footer input").removeAttr("checked");

}

function reviewRecipe(whichRecipeID){
    if (getLoginStatus()){
        tb_show("RecipeReview","recipes_createreview.html?height=400&width=400&modal=true", "");
    } else {
        //redirect the user to the login page (perhaps with a 'returnURL' parameter to be able to return to the current page
        window.location.href = "";
    }
}

function reviewProduct(whichProductID){
    if (getLoginStatus()){
        tb_show("Rate &amp; Review","products_createreview.html?height=605&width=730", "");
    } else {
        //redirect the user to the login page (perhaps with a 'returnURL' parameter to be able to return to the current page
        window.location.href = "";
    }
}

function toggleStoreListPCSignup(fromWhichFormObject) {
	jQuery('#storeList').toggle();
	jQuery(fromWhichFormObject).parent("label").parent("p").toggleClass("selected");
}


function homePCHeroCampaignBackgroundTransition(toWhichColor) {
	//chained animation: first fade to white, then fade into color passed as parameter
	var strValidHexPattern = /^#([0-9a-f]{1,2}){3}$/i;
	if (!strValidHexPattern.test(toWhichColor)) {
		toWhichColor = "#ffffff";
	}

	jQuery("#homeCampaignHeroContainerWrapper").animate({
		backgroundColor: "#ffffff"
	}, 800)
	.animate({
		backgroundColor: toWhichColor
	}, 800);
}

function performSearch() {

  if (jQuery.trim(jQuery("#tb_citypostalcode").val()) == "") {
  	jQuery("#locatorMessage").empty();
  	jQuery("#locatorMessage").append(lcloStoreMessages["store.enter.address.prompt"]);
  	return;
  }
  
  var citypostalcode = jQuery("#tb_citypostalcode").val();
  
  if (citypostalcode != null) {
	  if (citypostalcode.toLowerCase().indexOf('canada') == -1) {
	  	citypostalcode += ' canada';
	  }
  }
  
  if (GBrowserIsCompatible()) {
    var geocoder = new GClientGeocoder();
	geocoder.getLatLng(
      citypostalcode, 
      function(point) {
        if (!point) {
          	jQuery("#locatorMessage").empty();
			jQuery("#locatorMessage").append(lcloStoreMessages["store.loc_not_found.message"]); 
			jQuery("#storeFinderContainerSearchTabResults").empty();
			jQuery("#gmapContainer").html("<img src=\""+lcloStoreMessages["store.static.map.image"]+"\" alt=\"Canada\" />");
    		jQuery("#storeFinderContainerTabNavigationContainer").triggerTab(1);
    		jQuery("#storeFinderContainerTabNavigationContainer").tabs({disabled:[2]});
        } else {
        	jQuery("#locatorMessage").empty();
			
			jQuery("input[name='search_latitude']").val(point.lat()); //set latitude as post data before submit
			jQuery("input[name='search_longitude']").val(point.lng()); //set longitude as post data before submit
			
			document.storeFinder.submit();
        }});
  }
  //else maybe put a message of some kind.
}

function formatStoreListing(i, item, fromLat, fromLon, markerFileType) {
	var letter = String.fromCharCode("A".charCodeAt(0) + i);
	
	var storeHTML = "";
	
	if (item.bannerTitle != "") {
		storeHTML += "<p><br /><b>";
		if (item.bannerTitle == "Other") {
			storeHTML += lcloStoreMessages["store.other.stores"];
		} else {
			storeHTML += item.bannerTitle;
			storeHTML += lcloStoreMessages["store.banner.stores"];
		}
		storeHTML += "</b></p>";
	}
	
	storeHTML += "<ul><li><img src=\"http://www.google.com/mapfiles/marker";
	storeHTML += letter;
	storeHTML += markerFileType;
	storeHTML += "\" alt=\"";
	storeHTML += letter;
	storeHTML += "\" class=\"mapLegendIcon\" />";                
	storeHTML += "<div class=\"searchResultsItemContent\">";
	storeHTML += "&nbsp;<a href=\"JavaScript:void(0);\" onclick=\"JavaScript:showGMapInfoWindow(";
	storeHTML += item.storeId;
	storeHTML += ");\" class=\"storeTitle\">";
	storeHTML += item.label;
	storeHTML += "</a>"
	storeHTML += "<p class=\"address\">";
	storeHTML += item.street;
	storeHTML += ", ";
	storeHTML += item.city;
	storeHTML += ", ";
	storeHTML += item.province;
	storeHTML += " ";
	storeHTML += item.postalCode;
	storeHTML += "</p><p class=\"phoneNumber\">";
	storeHTML += item.phoneNumber;
	storeHTML += "</p><a class=\"arrow\" href=\"store_details_landing_page.jsp?storeId=";
	storeHTML += item.storeId;
	storeHTML += "&amp;lat=";
	storeHTML += fromLat;
	storeHTML += "&amp;lng=";
	storeHTML += fromLon;
	storeHTML += "\">"
	storeHTML += lcloStoreMessages["store.view.link"];
	storeHTML += "</a></div><div class=\"clear\"></div></li></ul>";
	
	return storeHTML;
}

function formatStoreInfo(item, fromLat, fromLon, jsessionid) {
	var infoHTML = "<div id=\"si_";
	infoHTML += item.storeId;
	infoHTML += "\">";
	infoHTML += "<div class=\"searchResultsItemContent\">";
	infoHTML += "<img src=\"";
	infoHTML += item.logo;
	infoHTML += "\" alt=\"";
	infoHTML += item.bannerName;
	infoHTML += "\" />";

	if (item.blockBanner == "true") {
		infoHTML += "<p><a href=\"home.jsp\" class=\"storeTitle\">";
	} else {
		infoHTML += "<p><a href=\"home.jsp?storeId=";
		infoHTML += item.storeId;
		if (jsessionid != "") {
			infoHTML += "&amp;";
			infoHTML += jsessionid;
		}
		infoHTML += "\" class=\"storeTitle\">";
	}
	infoHTML += item.label;
	infoHTML += "</a></p><p class=\"address\">";

	infoHTML += item.street;
	infoHTML += "</p><p class=\"address\">";
	infoHTML += item.city;
	infoHTML += ", ";
	infoHTML += item.province;
	infoHTML += " ";
	infoHTML += item.postalCode;
	infoHTML += "</p><p class=\"phoneNumber\">";
	infoHTML += item.phoneNumber;
	infoHTML += "</p><p><a href=\"store_details_landing_page.jsp?storeId=";
	infoHTML += item.storeId;
	infoHTML += "&amp;lat=";
	infoHTML += fromLat;
	infoHTML += "&amp;lng=";
	infoHTML += fromLon;
	infoHTML += "\">"
	infoHTML += lcloStoreMessages["store.view_instore.link"];
	infoHTML += "</a></p><p>";
	
	if (item.inStore == false) {
		infoHTML += "<a id=\"s_";
		infoHTML += item.storeId;
		infoHTML += "\" href=\"Javascript:addStoreProfile('";
		infoHTML += item.storeId;
		infoHTML += "');\">";
		infoHTML += lcloStoreMessages["store.add_store.link"];
	} else {
		infoHTML += "<a id=\"s_";
		infoHTML += item.storeId;
		infoHTML += "\" href=\"Javascript:removeStoreProfile('";
		infoHTML += item.storeId;
		infoHTML += "');\">";
		infoHTML += lcloStoreMessages["store.remove_store.link"];
	}
	
	infoHTML += "</a>&nbsp;&nbsp;<a href=\"flyers_landing_page.jsp?storeId=";
	infoHTML += item.storeId;
	infoHTML += "\">";
	infoHTML += lcloStoreMessages["store.view_flyer.link"];
	infoHTML += "</a></p><p><a target=\"_blank\" href=\"http://maps.google.com/maps?hl="
	infoHTML += lcloStoreMessages["store.map.language"];
	infoHTML += "&saddr=";
	infoHTML += fromLat;
	infoHTML += ",";
	infoHTML += fromLon;
	infoHTML += "&daddr=";
	infoHTML += item.lat;
	infoHTML += ",";
	infoHTML += item.lng;
	infoHTML += "\">";
	infoHTML += lcloStoreMessages["store.driving_directions.link"];
	infoHTML += "</a></p></div><div id=\"storeHours\">";
	infoHTML += "<table><caption>";
	infoHTML += lcloStoreMessages["store.reg_hours.label"];
	infoHTML += "</caption><thead><tr><th colspan=\"2\">*";
	infoHTML += lcloStoreMessages["store.holiday_hours.label"];
	infoHTML += "</th></tr></thead><tbody>";
	for (x=0;x < item.hoursList.length; x++){
        if (item.hoursList[x].special == true){
            infoHTML += "<tr class=\"holiday\">";
        } else {
        	infoHTML += "<tr>";
        }
        infoHTML += "<th scope=\"row\">";
        infoHTML += item.hoursList[x].dayLabel;
        infoHTML += "</th><td>";
        infoHTML += item.hoursList[x].hoursLabel;
        infoHTML += "</td></tr>";
    }
	infoHTML += "</tbody></table></div></div>"; 
	
	return infoHTML;
}

function buildMap(jsonData) {
	var centerPoint = new GLatLng(jsonData.lat, jsonData.lng);
 	map = new GMap2(document.getElementById("gmapContainer"));
	map.setCenter(centerPoint, 11); 
	map.setUIToDefault();
	map.clearOverlays();
}

function addMapInfo(jsonData) {
	if (jsonData.storeList.length <= 0) {
		jQuery("#locatorMessage").empty();
		jQuery("#locatorMessage").append(lcloStoreMessages["store.not_found.message"]); 
		jQuery("#storeFinderContainerTabNavigationContainer").enableTab(1);
		jQuery("#storeFinderContainerTabNavigationContainer").triggerTab(1);
		return;
	}
	
	if (jQuery.browser.msie == true && jQuery.browser.version < 7) {
		markerFileType = "ie.gif";
	} else {
		markerFileType = ".png";
	}
	
	gmarkers = new Object();
	
	var bounds = new GLatLngBounds();
	bounds.extend(new GLatLng(jsonData.lat, jsonData.lng));
	
	var baseIcon = new GIcon(G_DEFAULT_ICON);
   	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
   	baseIcon.iconSize = new GSize(20, 34);
   	baseIcon.shadowSize = new GSize(37, 34);
		
	var storeHTML = "<div id=\"searchTabResultsContent\"><p>";
	storeHTML += lcloStoreMessages["store.found.message"];
	storeHTML += "&nbsp;";
	storeHTML += jsonData.storeList.length;
	storeHTML += "&nbsp;";
	storeHTML += lcloStoreMessages["store.near.message"];
	storeHTML += "&nbsp;";
	storeHTML += jQuery("#tb_citypostalcode").val();
	
	storeHTML += "</p><div id=\"searchTabResultsList\">";
	
	jQuery("#storeFinderContainerSearchInfoResults").empty();
	
	jQuery.each(jsonData.storeList, function(i,item) {
		storeHTML += formatStoreListing(i, item, jsonData.lat, jsonData.lng, markerFileType);
		
		var infoHTML = formatStoreInfo(item, jsonData.lat, jsonData.lng, jsonData.jses);
		jQuery("#storeFinderContainerSearchInfoResults").append(infoHTML);
		
		var point = new GLatLng(item.lat, item.lng);
		
		var letter = String.fromCharCode("A".charCodeAt(0) + i);
      	var letteredIcon = new GIcon(baseIcon);
      	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
      	markerOptions = { icon:letteredIcon };
      	var marker = new GMarker(point, markerOptions);
		
		gmarkers[item.storeId] = marker;
		
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(jQuery("div#si_"+item.storeId).html());
		});
		
		map.addOverlay(marker);
		
		bounds.extend(new GLatLng(item.lat, item.lng));
    });

	storeHTML += "</div></div>"
	
	map.setCenter(bounds.getCenter()); 
    map.setZoom(map.getBoundsZoomLevel(bounds)-1);
	
	//Display store listing.
	jQuery("#storeFinderContainerSearchTabResults").empty();
	jQuery("#storeFinderContainerSearchTabResults").append(storeHTML);
	
	jQuery().unload(function(){GUnload();}); 
	
	//add tab link click functionality
	jQuery("#storeFinderContainerTabNavigationContainer").enableTab(2);
	jQuery("#storeFinderContainerTabNavigationContainer").triggerTab(2);
}

function getSearchAddress() {
	if (jQuery("#tb_citypostalcode").val() == "") {
		jQuery.post("store_locator_landing_page.jsp", 
		{form_action:"searchAddress"},
		 function(result) {
			jQuery("#tb_citypostalcode").val(result.addr);
		 }, "json");
	}
}

function showGMapInfoWindow(i) {
	if (gmarkers != null && gmarkers[i] != null) {
		GEvent.trigger(gmarkers[i], "click"); //triggers the 'click' event of the marker as if the marker was clicked
	}
}

function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

/* background position helper function */
(function($) {
  jQuery.fn.backgroundPosition = function() {
    var p = $(this).css('background-position');
    if(typeof(p) === 'undefined') return $(this).css('background-position-x') + ' ' + $(this).css('background-position-y');
    else return p;
  };
})(jQuery);


//Shopping list functions START

//Reinitialize thickbox listeners for selected DOM items
function tb_reinit(domChunk) {
	jQuery(domChunk).unbind("click");
	tb_init(domChunk);
}
function cleanShoppingListLabels() {
	jQuery("#memberPreferencesShoppingListsTabNavigation li a span").each(function(){
		var tempStrListLabel = jQuery(this).text();
		if (tempStrListLabel.length > 22){ //include the likely 4 characters at the end for '(xx)'
			tempStrListLabel = tempStrListLabel.substr(0,19) + "..." + tempStrListLabel.substr(tempStrListLabel.indexOf("("));
			jQuery(this).text(tempStrListLabel);
		}
	});
}


 //Make Ajax call to add new list and update the display
 function addNewShoppingList(){
 	proceed = validateShoppingListCreateNewForm();
 	var NUMBER_OF_SHOPPING_LISTS_TO_DISPLAY = 5;
				 
	if (proceed){			
			var newListTitle = jQuery('#tb_shoppinglist_title').val();
			var calledFrom = jQuery('#calledFrom').val();
			var form_action ="handleShoppingList";
			var actionRequested="add";
			
     	jQuery.post("myShoppingLists.jsp",{
             form_action: form_action,
             actionRequested: actionRequested,
             shoppingListName: newListTitle,
             shoppingListNote: "",
             status:proceed}
             , function(result) { 
           		if(result.status=='1'){
           			if(result.limitReached){
           				shoppingListsLimitReached=true;
           			}
           			
           		 if (calledFrom!="overlay") {
           		 
					var curActivePosition = jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").length;//index(jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition li:last")); //zero-based			
					var listHTML ='<li class="active"> <input type="hidden" name="hiddenId" value ="'+result.ID+'"/> <a href="#" title="'+result.shoppingListName+'" id=';
					listHTML+='"shoppingList'+result.ID+'">';
					listHTML+= '<span>'+newListTitle+' (0)</span>';
					listHTML+='<input type="hidden" id="shoppingListName'+result.ID+'" value ="'+result.shoppingListName+'"/>';
					listHTML+='</a> <a href="#" class="menu"><span>V</span></a>';
					listHTML+='<ul>';
					listHTML+='<li><a href="profile-rename-shopping-list.jsp?width=730&amp;height=300&shoppingListId='+result.ID+'&shoppingListName='+result.shoppingListName+'" class="thickbox" title="'+shoppingListMessages["shoppinglist.rename_list_heading.label"]+'">' + lcloGlobalMessages["shoppinglist.rename"] + '</a></li>';
					listHTML+='<li id="listCopy"><a href="profile-copy-shopping-list.jsp?width=730&amp;height=300&shoppingListId='+result.ID+'&shoppingListName='+result.shoppingListName+'" class="thickbox">' + lcloGlobalMessages["shoppinglist.copy"] + '</a></li>';
					listHTML+='<li><a href="JavaScript:void(0);" onclick="JavaScript:deleteShoppingListConfirm('+result.ID+');">' + lcloGlobalMessages["shoppinglist.delete"] + '</a></li>';
					listHTML+='</ul></li>';
					jQuery('#noShoppingListFoundMessage').remove();
					jQuery('#fixedPosition').append(listHTML);
					//Put necessary listeners
					reinitializeShoppingListHovers();			
					doShoppingListReady();
					             
					jQuery('ul#fixedPosition li').removeClass('active');	
					jQuery('#shoppingList'+result.ID).addClass('active');
		
					var posOfLastShoppingList = jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").length-1;
					var numberOfShoppingLists = jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").length;
				
							if (numberOfShoppingLists > NUMBER_OF_SHOPPING_LISTS_TO_DISPLAY) {
								jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:lt(" + (numberOfShoppingLists - NUMBER_OF_SHOPPING_LISTS_TO_DISPLAY) + ")").css("display","none");
								jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:gt(" + (numberOfShoppingLists - NUMBER_OF_SHOPPING_LISTS_TO_DISPLAY-1) + ")").css("display", "inline");		
			
							} else {
			
								jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:lt(" + (NUMBER_OF_SHOPPING_LISTS_TO_DISPLAY-1) + ")").css("display","inline");
							}
			
				
								jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + posOfLastShoppingList + ")").click();
								tb_remove();
				} else {

				tb_show(shoppingListMessages["shoppinglist.label"],"profile-shoppinglists-overlay.jsp?width=730&height=350");
				
				}				
         		} else if(result.status=='4'){
		         		tb_remove();
		         		tb_show("Your are not logged in","profile-not-logged-in.jsp?height=120&width=400");
         		} else if(result.status=='5'){      		
		         		alert(shoppingListMessages["shoppinglist.already_exists.message"]);
         		} else if(result.status=='6'){      		
         			alert(lcloGlobalMessages["shoppinglists.shoppinglists_limit_reached.text"]);
         		} else{
	         			alert("There was a problem adding this Shopping List. Please try again.");
         		}
       		}, "json"); 
       		
       		}
	
  }


jQuery(document).ready(function(){
      doReady();
      
});

function doReady(){
      jQuery("#storeDepartments table tr:odd").addClass("even");
      // enable instructional text display for forms
      jQuery("fieldset div.row input").focus(function(){
            jQuery(this).parent().find("div.instructional").show();
      });
      jQuery("fieldset div.row input").blur(function(){
            jQuery(this).parent().find("div.instructional").hide();
      });
	  	/* This is being called from shopping.list.functions.js so don't uncomment
	  	
	  	if (jQuery("input.spinner").length > 0) {
			jQuery("input.spinner").spin({
				imageBasePath:"images/pc/",
				max:100,
				min:0,
				changed: function(o,n){
					//console.log('changed');
					return false;
				}
			});
			//jQuery("input.spinner").numeric();
		} */
      
      if (jQuery("#inlineRating").length > 0) {
          jQuery("#inlineRating").children().not(":input, .title").hide();
          jQuery("#inlineRating").stars({
              cancelShow: false,
              callback: function(ui, type, value)
              {
                  //use the returned value to update the img src in the '#inlineRecipeRatingContent img' target and the 'based on x customer ratings' text
                  //the value should be either a numeric value or a filename for the avg. rating image
              }
          });
      }
      
      if (jQuery(".inlineRating").length > 0) {
          jQuery(".inlineRating").children().not(":input, .title").hide();
          jQuery(".inlineRating").stars({
              cancelShow: false,
              callback: function(ui, type, value)
              {
                  //use the returned value to update the img src in the 'ratingContent img' target and the 'based on x customer ratings' text
                  //the value should be either a numeric value or a filename for the avg. rating image
              }
          });
      }
      /*console.log("length is " +$("#memberPreferencesShoppingListsDetails table").length);
      if ($("#memberPreferencesShoppingListsDetails table").length > 0) {
          $("#memberPreferencesShoppingListsDetails table").tablesorter({sortList:[[2,0],[3,0],[4,0]]});
      }*/

      if (jQuery("#memberPreferencesShoppingListsTabNavigation").length > 0) {
            var intShoppingListWindowSize = 4 //zero-based
            //find the current 'active' li item and make all li items before that and 5 after hidden
            var curActivePosition = $("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").index($("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition li.active")); //zero-based
            var numberOfShoppingLists = $("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").length;
            jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:lt(" + curActivePosition + ")").css("display","none");
            jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:gt(" + (curActivePosition + intShoppingListWindowSize) + ")").css("display","none");
            jQuery("#memberPreferencesShoppingListsTabScroller a.left").click(function(){

                  if (curActivePosition > 0) {
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").removeClass("active");
                        curActivePosition--;
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").addClass("active");
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").css("display", "inline");                        
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").click();

                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:gt(" + (curActivePosition + intShoppingListWindowSize) + ")").css("display","none");
                        /* AJAX call to retrieve & display the current item's shopping list */
                        //displaySelectedTabList(curActivePosition);
                  }
            });
            jQuery("#memberPreferencesShoppingListsTabScroller a.right").click(function(){
            
                  if (curActivePosition < (numberOfShoppingLists - 1)) {
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").removeClass("active");
                        curActivePosition++;
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").addClass("active");
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").click();
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").css("display", "inline");
                        jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:lt(" + (curActivePosition - intShoppingListWindowSize) + ")").css("display", "none");
                        //displaySelectedTabList(curActivePosition);
                        /* AJAX call to retrieve & display the current item's shopping list */
                  }
            });
      }
      
      jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").hover(
          function(){
              jQuery(this).find("ul").show();
              //$("#memberPreferencesShoppingListsTabNavigationMenu").show();
          },
          function(){
              jQuery(this).find("ul").hide();
              //$("#memberPreferencesShoppingListsTabNavigationMenu").hide();
          }
      );
      
      jQuery("#memberPreferencesMealPlansTabNavigation ul.fixedPosition > li").hover(
          function(){
              jQuery(this).find("ul").show();
              //$("#memberPreferencesShoppingListsTabNavigationMenu").show();
          },
          function(){
              jQuery(this).find("ul").hide();
              //$("#memberPreferencesShoppingListsTabNavigationMenu").hide();
          }
      );
      
      jQuery("#memberPreferencesMealPlansDetails table tbody td").hover(
          function(){
              showMealPlanCellTools($(this));
          },
          function(){
              hideMealPlanCellTools($(this));
          }
      );
      
      jQuery("#memberPreferencesMealPlansDetails table tbody td div").hover(
          function(){
              jQuery(this).css({"background-color":"#efefef", "outline":"1px solid #cccccc", "cursor":"pointer"});
              showMealPlanItemTools($(this));
          },
          function(){
              jQuery(this).css({"background-color":"#ffffff", "outline":"none", "cursor":"default"});
              hideMealPlanItemTools($(this));
          }
      );
      
      jQuery("#communityRoomLocation a").click(
            function(){
                  jQuery(this).parent().find("div#communityRoomLocationForm").toggle();
            }
      );
      
      jQuery("#communityRoomSearchResults ul li div.nextClass a").hover(
          function(){
              jQuery(this).parent().find("div").show();
          },
          function(){
              jQuery(this).parent().find("div").hide();
          }
      );
      
      if (jQuery("#videosBrowseControlContainer").length > 0){
          jQuery("#videosBrowseControlContainer").tabs();
      }
      
      if (jQuery("#csrTransactionsContainer").length > 0){
          jQuery("#csrTransactionsContainer").tabs();
      }
      
      if (jQuery("#myFlyerCarousel").length > 0){
            jQuery("#myFlyerCarousel").jcarousel({
                  //config
                  initCallback: myFlyerCarousel_initCallback
            });
      }
	  
	/* additions for PC.ca */
	  
	//global navigation: add functionality to support IE6 (since IE6 doesn't support the 'hover' pseudo-class on 'div' elements
	//save the current background image position for the global navigation to allow the 'hover' state to set the background position
	// to zero
	//var strCurrentGlobalNavBackgroundPosition = jQuery("#globalNavigation .active").css("background-position");
	var strCurrentGlobalNavBackgroundPosition = jQuery("#globalNavigation div[class*='active']").backgroundPosition();
	//alert(strCurrentGlobalNavBackgroundPosition);
	if (strCurrentGlobalNavBackgroundPosition != undefined) {
		arrCurrentGlobalNavBackgroundPosition = strCurrentGlobalNavBackgroundPosition.split(" ");
		currentXPos = arrCurrentGlobalNavBackgroundPosition[0];
		currentYPos = arrCurrentGlobalNavBackgroundPosition[1];
	}
	jQuery("div.globalNavigationItem").hover(
		function(){
			jQuery(this).addClass("over");
			jQuery(this).find("div.globalNavigationFlyout").css("display", "block");
			var strThisItemsClass = jQuery(this).attr("class");
			if (strCurrentGlobalNavBackgroundPosition != undefined) {
				//if (!jQuery(this).hasClass("active")) {
				if (strThisItemsClass.indexOf("active") < 0) {
					//jQuery("#globalNavigation .active").css("background-position", currentXPos + " 0px");
					if (jQuery.support.opacity) {
						jQuery("#globalNavigation div[class*='active']").css("background-position", currentXPos + " 0px");
					} else {
						jQuery("#globalNavigation div[class*='active']").css("background-position-x", currentXPos);
						jQuery("#globalNavigation div[class*='active']").css("background-position-y", "0px");
					}
				}
			}
		},
		function(){
			jQuery(this).removeClass("over");
			jQuery(this).find("div.globalNavigationFlyout").css("display", "none");
			if (strCurrentGlobalNavBackgroundPosition != undefined) {
				var strThisItemsClass = jQuery(this).attr("class");
				//if (!jQuery(this).hasClass("active")) {
				if (strThisItemsClass.indexOf("active") < 0) {
					//jQuery("#globalNavigation .active").css("background-position", strCurrentGlobalNavBackgroundPosition);
					if (jQuery.support.opacity) {
						jQuery("#globalNavigation div[class*='active']").css("background-position", strCurrentGlobalNavBackgroundPosition);
					} else {
						jQuery("#globalNavigation div[class*='active']").css("background-position-x", currentXPos);
						jQuery("#globalNavigation div[class*='active']").css("background-position-y", currentYPos);
					}
				}
			}
		}
	);
	
	if (jQuery("#homeCampaignHeroContainerNonFlashContent").length > 0){
		//NOTE: this code should run only if the Flash movie has not been instantiated
		var boolAutoAnimateHeroCampaign = true;
		var intNumberOfHeroCampaignSlides = jQuery("#homeCampaignHeroContainerNonFlashNavigation li").length;
		//set up auto-animation & carousel
		//default to 1st (zero-based) item
		var currentPCHeroCampaignSlide = 0;
		jQuery("#homeCampaignHeroContainerWrapper").animate({
			backgroundColor: jQuery("#homeCampaignHeroContainerNonFlashNavigation li:eq(" + currentPCHeroCampaignSlide + ") a").attr("rel")
		}, 500);
		jQuery("#homeCampaignHeroContainerNonFlashNavigationContainer div.wrapper div").jCarouselLite({
			btnNext: "#homeCampaignHeroContainerNonFlashNavigationContainer .next",
			btnPrev: "#homeCampaignHeroContainerNonFlashNavigationContainer .previous",
			circular: false,
			visible: 4,
			scroll: 1
		});
		jQuery("#homeCampaignHeroContainerPlayPause").click(function(){
			//change the image
			if (boolAutoAnimateHeroCampaign) {
				boolAutoAnimateHeroCampaign = false;
			} else {
				boolAutoAnimateHeroCampaign = true;
			}
		});
		var objHomeHeroInterval = function(){
			if (boolAutoAnimateHeroCampaign) {
				jQuery("#homeCampaignHeroContainerWrapper").animate({
					backgroundColor: "#fff"
				}, 400);
				if (currentPCHeroCampaignSlide < (intNumberOfHeroCampaignSlides - 1)) {
					tempNextPCHeroCampaignSlide = currentPCHeroCampaignSlide + 1;
				} else {
					tempNextPCHeroCampaignSlide = 0;
				}
				//if the next slide is part of the next window, scroll to that item
				var autoBGColor = jQuery("#homeCampaignHeroContainerNonFlashNavigation li:eq(" + tempNextPCHeroCampaignSlide + ") a").attr("rel");
				jQuery("#homeCampaignHeroContainerNonFlashContent div:eq(" + currentPCHeroCampaignSlide + ")").fadeOut(500, function(){
					jQuery("#homeCampaignHeroContainerWrapper").animate({
						backgroundColor: autoBGColor
					}, 400);
					jQuery("#homeCampaignHeroContainerNonFlashContent div:eq(" + tempNextPCHeroCampaignSlide + ")").fadeIn(500);
					currentPCHeroCampaignSlide = tempNextPCHeroCampaignSlide;
					actualCarouselPosition = parseInt(jQuery("ul#homeCampaignHeroContainerNonFlashNavigation").css("left"));
					actualCarouselPosition = actualCarouselPosition/46;
					//requiredCarouselPosition = (currentPCHeroCampaignSlide + 1 - 4) * -46;
					//console.log("currentPCHeroCampaignSlide: " + currentPCHeroCampaignSlide + " actualCarouselPosition: " + actualCarouselPosition);
					/*if (currentPCHeroCampaignSlide > 3) {
						requiredCarouselPosition = (currentPCHeroCampaignSlide + 1 - 4) * -46;
						actualCarouselPosition = jQuery("ul#homeCampaignHeroContainerNonFlashNavigation").css("left");
						if (actualCarouselPosition ) {
						
						}
					}*/
				});
			}
		};
		setInterval(objHomeHeroInterval, 8000);
		//set the first child of #homeCampaignHeroContainerNonFlashContent to display
		jQuery("#homeCampaignHeroContainerNonFlashContent div:eq(" + currentPCHeroCampaignSlide + ")").css("display","block");
		jQuery("#homeCampaignHeroContainerNonFlashNavigation li a").click(function(){
			boolAutoAnimateHeroCampaign = false;
			var thisBGColor = jQuery(this).attr("rel");
			//hide the current slide
			nextPCHeroCampaignSlide = jQuery("#homeCampaignHeroContainerNonFlashNavigation li").index(jQuery(this).parent());
			jQuery("#homeCampaignHeroContainerWrapper").animate({
				backgroundColor: "#fff"
			}, 400);
			jQuery("#homeCampaignHeroContainerNonFlashContent div:eq(" + currentPCHeroCampaignSlide + ")").fadeOut(500, function(){
				jQuery("#homeCampaignHeroContainerWrapper").animate({
					backgroundColor: thisBGColor
				}, 400);
				jQuery("#homeCampaignHeroContainerNonFlashContent div:eq(" + nextPCHeroCampaignSlide + ")").fadeIn(500);
				currentPCHeroCampaignSlide = nextPCHeroCampaignSlide;
			});
			return false;
		});
	}
	
	if (jQuery("#homeFeaturedProductContentNavigation").length > 0) {
		var totalNumberOfFeaturedProducts = jQuery("#homeFeaturedProductContentNavigation li").length;
		jQuery("#homeFeaturedProductContentCarouselWrapper").jCarouselLite({
			btnNext: "#homeFeaturedProductContentCarousel .next",
			btnPrev: "#homeFeaturedProductContentCarousel .previous",
			circular: true,
			visible: 3,
			afterEnd: function(a) {
				curLeft = parseInt(jQuery("#homeFeaturedProductContentNavigation").css("left"));
				jQuery("#homeFeaturedProductContentNavigation").css("left",curLeft - 27 + "px")
			}
		});
		curLeft = parseInt(jQuery("#homeFeaturedProductContentNavigation").css("left"));
		jQuery("#homeFeaturedProductContentNavigation").css("left",curLeft - 27 + "px");
		//the default 'center' product is item #1 (zero-based)
		var currentPCFeaturedProduct = 1;
		//set the second child of #homeFeaturedProductContent to display - **there must be at least two featured products
		jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").css("display","block");
		//selecting a brand will update the text of the #homeFeaturedProductAllLink anchor link
		strBrandURLContent = jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").find("a.title").attr("rel");
		strBrandURLArray = strBrandURLContent.split("|");
		strBrandName = strBrandURLArray[0];
		strBrandURL = strBrandURLArray[1];
		jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").text("View all " + strBrandName + " Products");
		jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").attr("href",strBrandURL);
		jQuery("#homeFeaturedProductContentCarousel a.next").click(function(){
			if (currentPCFeaturedProduct < (totalNumberOfFeaturedProducts - 1)) {
				jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeOut("fast", function(){
					currentPCFeaturedProduct++;
					jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeIn("fast");
					strBrandURLContent = jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").find("a.title").attr("rel");
					strBrandURLArray = strBrandURLContent.split("|");
					strBrandName = strBrandURLArray[0];
					strBrandURL = strBrandURLArray[1];
					jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").text("View all " + strBrandName + " Products");
					jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").attr("href",strBrandURL);
				});
			} else {
				jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeOut("fast", function(){
					currentPCFeaturedProduct = 0;
					jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeIn("fast");
					strBrandURLContent = jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").find("a.title").attr("rel");
					strBrandURLArray = strBrandURLContent.split("|");
					strBrandName = strBrandURLArray[0];
					strBrandURL = strBrandURLArray[1];
					jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").text("View all " + strBrandName + " Products");
					jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").attr("href",strBrandURL);
				});
			}
		});
		jQuery("#homeFeaturedProductContentCarousel a.previous").click(function(){
			if (currentPCFeaturedProduct > 0) {
				jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeOut("fast", function(){
					currentPCFeaturedProduct--;
					jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeIn("fast");
					jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").text("View all " + jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").find("a.title").attr("rel") + " Products");
				});
			} else {
				jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeOut("fast", function(){
					currentPCFeaturedProduct = totalNumberOfFeaturedProducts - 1;
					jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").fadeIn("fast");
					jQuery("#PC_Home_FeaturedProducts a#homeFeaturedProductAllLink").text("View all " + jQuery("#homeFeaturedProductContent div:eq(" + currentPCFeaturedProduct + ")").find("a.title").attr("rel") + " Products");
				});
			}
		});
	}

	jQuery("#searchControl input.text").focus(function(){
	    jQuery(this).val("");
	});
	jQuery("#searchControl input.text").blur(function(){
	    if (jQuery(this).val() == ""){
	        jQuery(this).val(lcloGlobalMessages["searchbox.searchterms"]);
	    }
	});
	
	jQuery("table.zebra tr:even").addClass("odd");
	
	jQuery("#subBrandIdentifier").hover(
		function(){
			jQuery(this).addClass("over");
		},
		function(){
			jQuery(this).removeClass("over");
		}
	);
	
	if (jQuery("#storeFinderContainerTabNavigationContainer").length > 0){
	    jQuery("#storeFinderContainerTabNavigationContainer").tabs({disabled:[2]});
	}
	
	jQuery("#memberPreferencesDetails label").click(function(){
		jQuery(this).toggleClass("selected");
		var checkbox = jQuery(this).find('input');
		if(checkbox.attr("checked")){
			checkbox.removeAttr('checked');
		} else {
			checkbox.attr("checked", "checked");			 
		}
		return false;
	});

	if (getQuerystring("bvProductForm") == "true") {
		var strQS = location.search;
		strQS = strQS.substring(1);
		//alert("to show product form");
		tb_show("Rate &amp; Review","product-review-form.jsp?height=605&width=730&" + strQS, "");
	}
	
	if (getQuerystring("bvArticleForm") == "true") {
		var strQS = location.search;
		strQS = strQS.substring(1);
		//alert("to show article form");
		tb_show("Rate &amp; Review","article-review-form.jsp?height=605&width=730&" + strQS, "");
	}
	
	if (getQuerystring("bvFoodGuideForm") == "true") {
		var strQS = location.search;
		strQS = strQS.substring(1);
		//alert("to show article form");
		tb_show("Rate &amp; Review","article-review-form.jsp?height=605&width=730&" + strQS, "");
	}
	
	if (getQuerystring("bvRecipeForm") == "true") {
		var strQS = location.search;
		strQS = strQS.substring(1);
		//alert("to show recipe form");
		tb_show("Rate &amp; Review","recipe-review-form.jsp?height=605&width=730&" + strQS, "");
	}
	
	if (getQuerystring("bvVideoForm") == "true") {
		var strQS = location.search;
		strQS = strQS.substring(1);
		//alert("to show video form");
		tb_show("Rate &amp; Review","video-review-form.jsp?height=605&width=730&" + strQS, "");
	}

	if (jQuery("#storeLocatorPageMainContent").length > 0) {
		GDownloadUrl("store/storeSearchResults.jsp", function(data) {
			var jsonData = eval('(' + data + ')');
			if (jsonData.lat != "" && jsonData.lng != "") {
				buildMap(jsonData);
				addMapInfo(jsonData);	
			} else {
				jQuery("#gmapContainer").html("<img src=\""+lcloStoreMessages["store.static.map.image"]+"\" alt=\"Canada\" />");
				getSearchAddress();
				jQuery("#storeFinderContainerTabNavigationContainer").tabs({disabled:[2]});
			}
		});
	}
	
	jQuery("div.favouritesCategory div.row input[type='checkbox']").click(function(){
		if (jQuery("div.favouritesCategory div.row input[type='checkbox']:checked").length > 0){
			jQuery(this).parents(".favouritesCategory").find("a.btnRemoveSelectedOff").addClass("btnRemoveSelectedOn");
		} else {
			jQuery(this).parents(".favouritesCategory").find("a.btnRemoveSelectedOff").removeClass("btnRemoveSelectedOn");
		}
	});
	
	jQuery("div.favouritesCategory div.footer input[type='checkbox']").click(function(){
		if (jQuery(this).is(":checked")){
			jQuery(this).parents(".favouritesCategory").find("div.row input[type='checkbox']").attr("checked","false");
			jQuery(this).parents(".footer").find("a.btnRemoveSelectedOff").addClass("btnRemoveSelectedOn");
		} else {
			jQuery(this).parents(".favouritesCategory").find("div.row input[type='checkbox']").click();
			jQuery(this).parents(".footer").find("a.btnRemoveSelectedOff").removeClass("btnRemoveSelectedOn");
		}
	});
	
	jQuery("span.recoFlyerItemInfo").hover(
		function(){
			var thisItem = jQuery(this).attr("rel");
			var thisOffset = jQuery(this).offset();
			var carouselOffset = 0;
			if (jQuery("ul#myFlyerCarousel").css("left") <= -441){
				var carouselOffset = 30;
			}
			jQuery("span.recoFlyerItemInfoContents[rel='" + jQuery(this).attr("rel") + "']").css({
				"display":"block",
				"top":(0) + "px",
				"left": (parseInt(jQuery("ul#myFlyerCarousel").css("left")) + (jQuery("ul#myFlyerCarousel li").index(jQuery(this).parent()) * 157) - carouselOffset) + "px"
			});
			var thisPosition = jQuery(this).parent().position();
		},
		function(){
			jQuery("span.recoFlyerItemInfoContents[rel='" + jQuery(this).attr("rel") + "']").css("display","none");
		}
	);
	
	jQuery("span.recoFlyerItemInfoContents").hover(
		function(){
			jQuery(this).css("display","block");
		},
		function(){
			jQuery(this).css("display","none");
		}
	);
	
	jQuery("input#tb_citypostalcode").live('keypress', function(e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
	  		jQuery("input#ss_btn").click();
	  		return false;
	  	}
	 });
	 
	jQuery("div#productSearchResults a.btnAddToShoppingList").css("display","block");

	 
	jQuery("a.btnAddToShoppingList").click(function(){
		jQuery(this).addClass("btnAddingToShoppingList");
	});
	

	updateMyFavouritesDisplay();
	
}