/* This file has shopping list specific Javascript
*/
//Page scope variables
 var initialLoading=true;
//Begin Reinitializer functions

function reinitializeShoppingListHovers(){
jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").unbind('hover');
jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").hover(
	    function(){
	        jQuery(this).find("ul").show();
	        //jQuery("#memberPreferencesShoppingListsTabNavigationMenu").show();
	    },
	    function(){
	        jQuery(this).find("ul").hide();
	        //jQuery("#memberPreferencesShoppingListsTabNavigationMenu").hide();
	    }
	);
}


//Function to auto save shopping list notes
 function autoSaveShoppingListNotes(){
		jQuery("div#memberPreferencesShoppingListsNotes span.statusMessage").css("display","none");
		var selector ='#myNotes'+listToBeSaved;
		var notes=jQuery(selector).val();
		
		if(notes && notes.length>200) {
		
		alert (shoppingListMessages["shoppinglist.notes_limit_exceeded.warning"]);	
		notes = notes.substr(0,199);	
		
		}
       
        var form_action='handleShoppingList';
		var actionRequested ='autoSaveNotes';
		if(listToBeSaved!=null &&notes!=null) {        
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:listToBeSaved,
			note:notes},
			function (data, textStatus) {
			//jQuery(selector).val(notes);
			jQuery("div#memberPreferencesShoppingListsNotes span.statusMessage").css("display","block");
 
			}
	);
	}          

}
//end of function auto save 
 	

//end of function tb_reinit
 
  //put listeners for auto save
	 function putShoppingListAutoSaveListeners(){
 	  //var timedShoppingListSave
		jQuery("#memberPreferencesShoppingListsNotes, textarea[id ^= 'myNotes']").unbind('keyup');
		
		
		jQuery("#memberPreferencesShoppingListsNotes, textarea[id ^= 'myNotes']").keyup(function() {
		listToBeSaved=jQuery(this).parent().children("input:hidden").val();
		autoSaveShoppingListNotes();
		});

 }
 //end of function putAutoSaveListeners

//Delete shopping list function
 function addShoppingListReminder(whichShoppingListId,whichShoppingListReminderId){

    var form_action='handleShoppingListItems';
	var actionRequested ='addReminder';

    	jQuery.ajax({
		url: 'myShoppingLists.jsp',
		type: 'POST',
		data: 'form_action='+form_action +'&actionRequested='+ actionRequested + '&shoppingListId='+ whichShoppingListId+ '&reminderId='+ whichShoppingListReminderId,

		success: function(result) {
		//post success processing
		//console.log(result);
		}
	});
  
}


//Delete shopping list function
 function deleteShoppingListReminder(whichShoppingListId,whichShoppingListReminderId){
        		var form_action='handleShoppingListItems';
				var actionRequested ='deleteReminder';

       				jQuery.ajax({
					url: 'myShoppingLists.jsp',
					type: 'POST',
					data: 'form_action='+form_action +'&actionRequested='+ actionRequested + '&shoppingListId='+ whichShoppingListId+ '&reminderId='+ whichShoppingListReminderId,
					
					//on success call the jsp that reloads list of shopping lists and display our response
					success: function(result) {
					
					}
				});

}

//Delete shopping list function
 function deleteShoppingListConfirm(whichShoppingListID){
    var boolResult = confirm(shoppingListMessages["shoppinglist.delete_are_you_sure.message"]);
    if (boolResult){
        		var form_action='handleShoppingList';
				var actionRequested ='delete';
				var posDeleted =jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").index(jQuery("#shoppingList"+whichShoppingListID));
	
				jQuery.ajax({
					url: 'myShoppingLists.jsp',
					type: 'POST',
					data: 'form_action='+form_action +'&actionRequested='+ actionRequested + '&shoppingListId='+ whichShoppingListID,
					dataType:'json',
					success: function(result) {
					if(!result.limitReached){
       					shoppingListsLimitReached=false;
           				}
           				if(!result.limitExceeded){
           							 	if (getQuerystring("enrouteToSpringBoard") == "true") {
										tb_show("Start shopping with CONCIERGE&reg;","/LCLOnline/springboard_optin.jsp?height=320&width=730", "");
									}          					
           				}

					jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + (posDeleted) + ")").remove();
					var posToActivate=posDeleted-1;
					if (posToActivate > -1 && posToActivate!=posDeleted) {
					jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + posToActivate + ")").click();
					} else if (jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").length > 0) {
					jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + 0 + ")").click();
					
					}else {
						jQuery('#memberPreferencesShoppingListsTabScroller').remove();
						jQuery('#memberPreferencesShoppingListsTools').remove();
						jQuery('#memberPreferencesShoppingListsDetails').remove();
					}
				
					}
				});
    }
}

//Delete recipe items from shopping list
function deleteShoppingListItemConfirm(whichShoppingListID, whichShoppingListItemID){

	var boolResult = true;// confirm(shoppingListMessages["shoppinglist.item.delete_are_you_sure.message"]);
    if (boolResult){
        var form_action='handleShoppingListItems';
		var actionRequested ='delete';
	
		// force synchronization to avoid a problem with IE
		jQuery.ajaxSetup({async:false});
		try {
			jQuery.post("myShoppingLists.jsp", 
				{form_action:form_action,actionRequested:actionRequested,shoppingListId:whichShoppingListID,itemId:whichShoppingListItemID},
				function (result, textStatus) {
					if (result.status =="1") {
						 var sizeStr="("+result.numberOfItems+") ";
						 jQuery('#shoppingList'+whichShoppingListID+' > span').text(result.shoppingListName+sizeStr);
		  				 cleanShoppingListLabels();
		  				 jQuery('#shoppingList'+whichShoppingListID).click();
		  				 tb_remove();
					} else {
						alert("There was a problem removing item. Please try again later.");
						tb_remove();
					}
				},"json"
			);
		} finally {
			jQuery.ajaxSetup({async:true});
		}
    }
}

//Delete shopping list item function
function deleteShoppingListRecipeItemConfirm(whichShoppingListID, whichShoppingListItemID){
    var boolResult = true;// confirm(shoppingListMessages["shoppinglist.item.delete_are_you_sure.message"]);
    if (boolResult){
        var form_action='handleShoppingListItems';
		var actionRequested ='deleteRecipeItemsFromShoppingList';        
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,actionRequested:actionRequested,shoppingListId:whichShoppingListID,itemId:whichShoppingListItemID},
			function (result, textStatus) {
			if (result.status =="1") {
				 var sizeStr="("+result.numberOfItems+") ";
				 jQuery('#shoppingList'+whichShoppingListID+' > span').text(result.shoppingListName+sizeStr);
  				 cleanShoppingListLabels();  				 
  				 jQuery('#shoppingList'+whichShoppingListID).click();
  				 tb_remove();
			} else {
			alert("There was a problem removing item. Please try again later.");
			tb_remove();
			}
 
			},"json"
	);        
        
    }
}
//end of function deleteShoppingListItemConfirm 
function reinitializeShoppingListListeners(curActivePosition){
	var intShoppingListWindowSize = 4 //zero-based
 		//find the current 'active' li item and make all li items before that and 6 after hidden
		//var curActivePosition = jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").index(jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition li.active")); //zero-based
		var numberOfShoppingLists = jQuery("#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 + ")").css("display", "inline");
				jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").click();
				jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:lt(" + (curActivePosition - intShoppingListWindowSize) + ")").css("display", "none");
				//displaySelectedTabList(curActivePosition);
				/* AJAX call to retrieve & display the current item's shopping list */
			}
		});
 
 
 }

//Display selected shopping list tab 
 function displaySelectedTabList(curActivePosition){


	var shoppingListId =jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").children().filter("input").eq(0).val();
	if (shoppingListId!=null &&shoppingListId!='undefined')	{
		jQuery('#memberPreferencesShoppingListsTabNavigation ul.fixedPosition').children().removeClass('active'); 
		jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").addClass("active");
		jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li:eq(" + curActivePosition + ")").css("display", "inline");

		// force synchronization to avoid a problem with IE
		jQuery.ajaxSetup({async:false});
		try {
			jQuery.post("profile-my-shopping-lists-display-list.jsp",
				{shoppingListId:shoppingListId},
				function (data, textStatus) {
					jQuery('#memberPreferencesShoppingListsTabScroller').remove();
					jQuery('#memberPreferencesShoppingListsTools').remove();
					jQuery('#memberPreferencesShoppingListsDetails').remove();
		
		  			jQuery('#memberPreferencesShoppingLists').append(data);
	
		  			doShoppingListReady();
		  			reinitializeShoppingListListeners(curActivePosition);
					tb_reinit('a.thickbox, area.thickbox, input.thickbox');	
				}
			);
		} finally {
			jQuery.ajaxSetup({async:true});
		}
	}
 
 }
 
 //Display appropriate tabs given with respect to the active position
 
 function displayDesiredTabs(activePosition) {
 		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();
 
 
 }
 
 
 
//end of function displaySelectedTabList

 
 // Get JSON object of all the shopping lists  
 
function getJsonShoppingLists(){
				var form_action="handleShoppingList";	
				var actionRequested = "getJsonShoppingListsObject";
				
					//make an AJAX request to our servelt
				jQuery.ajax({
					url: 'myShoppingLists.jsp',
					type: 'POST',
					data: 'form_action='+form_action +'&actionRequested='+ actionRequested,
					dataType:"json",
					success: function(result) {
					return result;
						
					}
				});
}
 

 
 // function copy shopping list
function copyShoppingList(){
 proceed = validateShoppingListCreateNewForm();
 var NUMBER_OF_SHOPPING_LISTS_TO_DISPLAY = 5;

 if (proceed==true){
	

	var newShoppingListName = jQuery('#tb_shoppinglist_title').val();
	var form_action ="handleShoppingList";
	var actionRequested="copy";
	var shoppingListId = jQuery('#tb_shoppingListId').val();
				jQuery.ajax({
					url: 'myShoppingLists.jsp',
					type: 'POST',
					data: 'form_action='+form_action +'&actionRequested='+ actionRequested +'&newShoppingListName='+ newShoppingListName + '&shoppingListId='+shoppingListId,
					dataType: 'json',
					success: function(result) {
					if(result.status=='1'){
					    if(result.limitReached){
           					shoppingListsLimitReached=true;
           				}
					var curActivePosition = jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").length;
					 jQuery('ul#fixedPosition li').removeClass('active');
						var listHTML ='<li class="active" id="shoppingList'+result.ID+'"> <input type="hidden" name="hiddenId" value ="'+result.ID+'"/> <a href="#" title="'+result.shoppingListName+'" id=';
						listHTML+='"shoppingList'+result.ID+'">';
						 
						listHTML+= '<span>'+newShoppingListName+' ('+result.numberOfItems+')</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+'" title="'+shoppingListMessages["shoppinglist.rename_list_heading.label"]+'" class="thickbox" title="'+shoppingListMessages["shoppinglist.rename_list_heading.label"]+'">'+lcloGlobalMessages["shoppinglist.rename.link"]+'</a></li>';
						listHTML+='<li id="listCopy"><a href="profile-copy-shopping-list.jsp?width=730&amp;height=300&shoppingListId='+result.ID+'" title="'+lcloGlobalMessages["shoppinglist.copy_list_heading.label"]+'" class="thickbox">'+lcloGlobalMessages["shoppinglist.copy.link"]+'</a></li>';
						listHTML+='<li><a href="JavaScript:void(0);" onclick="JavaScript:deleteShoppingListConfirm(\''+result.ID+'\');return false;">'+lcloGlobalMessages["shoppinglist.delete.link"]+'</a></li>';
						listHTML+='</ul></li>';
						jQuery('#fixedPosition').append(listHTML);
								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 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.");
         		}
}
				});
}
}

//function rename a shopping list
function renameShoppingList(){
 proceed = validateShoppingListCreateNewForm();
				
	if (proceed){
				    
				
		 var newListTitle = jQuery('#tb_shoppinglist_title').val();
		 var actionRequested="rename";
		 var shoppingListId=jQuery('#tb_shoppingListId').val();
		 var form_action="handleShoppingList";	 
 				jQuery.ajax({
				url: 'myShoppingLists.jsp',
				type: 'POST',
				dataType: 'json',
				data: 'form_action='+form_action +'&actionRequested='+ actionRequested +'&shoppingListNewName='+ newListTitle + '&shoppingListId='+shoppingListId,
				success: function(result) {
				if (result.status =='1') {

				
				var sizeStr=" ("+(result.numberOfItems)+") ";
				 jQuery('#shoppingList'+shoppingListId+' > span').text(newListTitle + sizeStr);
				 jQuery('#shoppingListName'+result.ID).val(newListTitle);
				 jQuery('a#shoppingList'+shoppingListId).attr("title",newListTitle);
				 
				 //refresh shopping list widget				
				 jQuery('#shoppingList'+shoppingListId).click();
				 
				 tb_remove();
				  }
		 
				 else if(result.status=='5'){      		
         			alert(shoppingListMessages["shoppinglist.already_exists.message"]);
         		} else {
				 alert ("Their was a problem renaming this shopping list. Please try again later");
				 tb_remove();
				 }
				 
				 }
		 });
		 
		  }
}
 
 //Add an item to a shopping list
function addShoppingListItem(){
	 proceed = validateShoppingListAddItemForm();
 	 if (proceed==true){
		var shoppingListId = jQuery('#shoppingListId').val();
		var itemName = jQuery('#tb_shoppinglist_item_name').val();
		var itemStore =jQuery('#tb_shoppinglist_item_store').val();
		var itemQuantity = jQuery('#tb_shoppinglist_item_quantity').val();
		var itemDescription = jQuery('#tb_shoppinglist_item_description').val();
		var itemDepartment = jQuery('#dd_shoppinglist_item_department').val();
		var form_action ="handleShoppingListItems";
		var actionRequested="add";

		// force synchronization to avoid problems with IE
		jQuery.ajaxSetup({async:false});
		try {
			jQuery.post("myShoppingLists.jsp", 
				{form_action:form_action,
				actionRequested:actionRequested,
				shoppingListId:shoppingListId,
				store:itemStore,
				quantity:itemQuantity,
				itemName:itemName,
				department:itemDepartment,
				description:itemDescription},
				function (data, textStatus) {
	  				 var sizeStr=" ("+(data.numberOfItems)+") ";
	  				 var newListTitle=jQuery('#shoppingList'+shoppingListId+' > span').text();
					 jQuery('#shoppingList'+shoppingListId+' > span').text(data.shoppingListName + sizeStr);
					 jQuery('#shoppingListName'+data.ID).val(data.shoppingListName);
	  				 jQuery('#shoppingList'+shoppingListId).click();
					 tb_remove(); 
	 
				},"json"
			);
		} finally {
			jQuery.ajaxSetup({async:true});
		}
	}
} 

//Edit a shopping list item
function editShoppingListItem(){
  proceed = validateShoppingListAddItemForm();
	   if (proceed==true){
			var shoppingListId = jQuery('#shoppingListId').val();
			var itemId=jQuery('#hiddenItemId').val();
			var itemName = jQuery('#tb_shoppinglist_item_name').val();
			var itemStore =jQuery('#tb_shoppinglist_item_store').val();
			var itemQuantity = jQuery('#tb_shoppinglist_item_quantity').val();
			var itemDescription = jQuery('#tb_shoppinglist_item_description').val();
			var itemDepartment = jQuery('#dd_shoppinglist_item_department').val();
			var form_action ="handleShoppingListItems";
			var actionRequested="editItem";
	
				jQuery.ajax({
					url: 'myShoppingLists.jsp',
					type: 'POST',
					data: 'form_action='+form_action +'&actionRequested='+ actionRequested +'&shoppingListId='+shoppingListId +'&itemName='+itemName+'&itemId='+itemId+'&quantity='+itemQuantity+'&store='+itemStore+'&department='+itemDepartment+'&description='+itemDescription,

					success: function(result) {
					 jQuery('#shoppingList'+shoppingListId).click();
				 	tb_remove(); 
					
					}
				});			

	 }
} 
 
 
//Add favourites to shopping list
function addFavouritesToShoppingList() {

	 var addFavouriteWhat=jQuery("#addFavouriteWhat").val();
	 
	 if (jQuery.trim(addFavouriteWhat)=="product"){
	 	proceed = true;//validateShoppingListAddProductItemForm();
	 	if (proceed==true){
			addFavoriteProductsToShoppingList();				 
		 }
	 	
	 } else if	(jQuery.trim(addFavouriteWhat)=="recipe"){
	 	proceed = true;//validateShoppingListAddProductItemForm();
	 	if (proceed==true){
			addFavoriteRecipesToShoppingList();				 
		 }				 	
	 }
} 
//Add  favorite product to shopping list 
function addFavoriteProductToShoppingList(){
	 proceed = validateShoppingListAddProductItemForm();
 	 if (proceed==true){

		   var shoppingListId = jQuery('#shoppingListId').val();
     		 var productId = jQuery('.scrollingListBox label input[name=shoppinglist_additem]:radio:checked').val();
    		var itemStore =jQuery('#tb_shoppinglist_item_store2').val();
			var itemQuantity = jQuery('#tb_shoppinglist_item_quantity2').val();
			var form_action ="handleShoppingListItems";
			var actionRequested="addProduct";
			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:shoppingListId,
			store:itemStore,
			quantity:itemQuantity,
			productId:productId},
			function (data, textStatus) {
  				 doShoppingListReady();
  				 jQuery('#shoppingList'+shoppingListId).click();
				 tb_remove(); 
 
			}
		);
	 }	
} 

//Add  favorite products to shopping list 
function addFavoriteProductsToShoppingList(){
			var form_action ="handleShoppingListItems";
			var actionRequested="addProducts";
		    var shoppingListId = jQuery('#shoppingListId').val();

     		 var productIds = new Array();
     		 jQuery('.scrollingListBox :checked').each(function(){
     		 productIds.push(jQuery(this).val()+"|"+jQuery('#prodQty'+jQuery(this).val()).val());     		 
     		 });
			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:shoppingListId,
			productIds:productIds},
			function (data, textStatus) {
  				 var sizeStr=" ("+(data.numberOfItems)+") ";
  				 var newListTitle=jQuery('#shoppingList'+shoppingListId+' > span').text();
  				 jQuery('#shoppingList'+shoppingListId+' > span').text(data.shoppingListName + sizeStr);
				 jQuery('#shoppingListName'+data.ID).val(data.shoppingListName);
  				 jQuery('#shoppingList'+shoppingListId).click();
				 tb_remove(); 
 
 			},"json"
	);
	
	}

//Add  favorite recipes to shopping list 
function addFavoriteRecipesToShoppingList(){
			var form_action ="handleShoppingListItems";
			var actionRequested="addRecipeIngredientsToExistingShoppingList";
		    var shoppingListId = jQuery('#shoppingListId').val();
     		 var recipeIds = new Array();
     		 jQuery('.scrollingListBox :checked').each(function(){
     		 recipeIds.push(jQuery(this).val());     		 
     		 });
			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:shoppingListId,
			recipeId:recipeIds},
			function (data, textStatus) {
  				 var sizeStr=" ("+(data.numberOfItems)+") ";
  				 var newListTitle=jQuery('#shoppingList'+shoppingListId+' > span').text();
				 jQuery('#shoppingList'+shoppingListId+' > span').text(data.shoppingListName + sizeStr);
				 jQuery('#shoppingListName'+data.ID).val(data.shoppingListName);
  				 jQuery('#shoppingList'+shoppingListId).click();
				 tb_remove(); 
 
 			},"json"
	);
	
	}	
	
//Edit product item on shopping list 
function editProductOnShoppingList(){
   proceed = validateShoppingListAddProductItemForm();
   if (proceed==true){
		    var shoppingListId = jQuery('#shoppingListId').val();
     		var productId = jQuery('.scrollingListBox label input[name=shoppinglist_additem]:radio:checked').val();
    		var itemStore =jQuery('#tb_shoppinglist_item_store2').val();
			var itemQuantity = jQuery('#tb_shoppinglist_item_quantity2').val();
			var form_action ="handleShoppingListItems";
			var actionRequested="editProduct";
			var itemId=jQuery('#hiddenItemId').val();
			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			itemId:itemId,
			shoppingListId:shoppingListId,
			store:itemStore,
			quantity:itemQuantity,
			productId:productId
			}, function (data, textStatus) {
				 doShoppingListReady();
  				 jQuery('#shoppingList'+shoppingListId).click();
				 tb_remove(); 
 
			},"json");
   }
	
}


//Update shopping list product item quantity via ajax

function updateShoppingListProductItemQty(theOne) {
	var form_action ="handleShoppingListItems";
	var actionRequested="updateQuantity";

	jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			itemId:jQuery(theOne).attr("id"),
			shoppingListId:jQuery('#shoppingListId').val(),			
			quantity:jQuery(theOne).val()
			}, function (data, textStatus) {
 
			},"json"); 

}

//function email shopping list 
 function emailShoppingList(){
 
 	// by doing each of these separately you get both validation functions to run and their errors to display. 
 	// combining them in a single if statement will not display the second error if there is an error in the
 	// first one
 	var validEmail = validateEmailfield(jQuery("#tb_email_address"),shoppingListMessages['common.email.link']);
 	var validName = validateTextfield(jQuery("#tb_email_name"),shoppingListMessages['common.name_optional.label']);
  	var proceed = validEmail && validName;

 	if (proceed == true){
 
     	var emailToAddress = jQuery("#tb_email_address").val();
     	var emailFromAddress = jQuery("#tb_email_name").val();
     	var messageBody = jQuery("#txt_email_comments").val();
     	var shoppingListId = jQuery("#shoppingListId").val();
     	var shoppingListName =jQuery('#shoppingListName'+shoppingListId).val();
     	var emailFormat =jQuery("#smartphoneCheckbox:checked").val();
      	
     	var actionRequested ="emailShoppingList";
     	jQuery.post("myShoppingLists.jsp",{
             form_action: "handleShoppingList",
             actionRequested: actionRequested,
             emailToAddress: emailToAddress,
             emailFromAddress: emailFromAddress,
             messageBody: messageBody,
             shoppingListName:shoppingListName,
             emailFormat:emailFormat,
             shoppingListId: shoppingListId      
           }, function(data) { 
           		if(data.status=='1'){
  
         			tb_remove();
         		}else{
         			alert("There was a problem sending shopping list. Please try again.");
         		}
       		}, "json");       	
 	}
 }
 
 //Add recipe ingredients to existing shopping list 
function addRecipeIngredientsToExistingShoppingList(){
     	var recipeId = jQuery("#recipeId").val();
     	var shoppingListId = jQuery("#dd_shoppinglist_list").val();
     	var actionRequested ="addRecipeIngredientsToExistingShoppingList";
     	form_action="handleShoppingListItems";
 			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:shoppingListId,
			recipeId:recipeId},
			function (data, textStatus) {

  				 doShoppingListReady();
  				 jQuery('#'+shoppingListId).click();

				 tb_remove(); 
				 jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
			     jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList");
 
			},"json"
	);
}

 //Add recipe ingredients to new shopping list 
function addRecipeIngredientsToNewShoppingList(){
//We first create the shopping list and then add the ingredients to it.
			var newListTitle = jQuery('#tb_shoppinglist_item_newlistname').val();
			var form_action ="handleShoppingList";
			var actionRequested="add";
			var recipeId =jQuery('#recipeId').val();
			
     	jQuery.post("myShoppingLists.jsp",{
             form_action: form_action,
             actionRequested: actionRequested,
             shoppingListName: newListTitle,
             shoppingListNote: lcloGlobalMessages["shoppinglist.notes"]
           }, function(result) { 
           		if(result.status=='1'){
           		jQuery.post("myShoppingLists.jsp", 
							{form_action:"handleShoppingListItems",
							actionRequested:"addRecipeIngredientsToExistingShoppingList",
							shoppingListId:result.ID,
							recipeId:recipeId},
							function (data, textStatus) {

								tb_remove();
								jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
			  					jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList"); 
				 
							},"json"
					);
           		
           		}
           		
           		},"json"
           		);
    }

//Add flyer Item to new shopping list 
function addFlyerItemToNewShoppingList(newListTitle,flyerItemId,quantity,flyerStoreId){
//We first create the shopping list and then add the product to it.
		var form_action ="handleShoppingList";
		var actionRequested="add";
			
     	jQuery.post("myShoppingLists.jsp?take=1",{
             form_action: form_action,
             actionRequested: actionRequested,
             shoppingListName: newListTitle,
             shoppingListNote: lcloGlobalMessages["shoppinglist.notes"]
           }, function(result) { 
           		if(result.status=='1'){
           		jQuery.post("myShoppingLists.jsp?take=2", 
							{form_action:"handleShoppingListItems",
							actionRequested:"addFlyerItem",
							shoppingListId:result.ID,
							flyerItemId:flyerItemId,
							quantity:quantity,
							flyerStoreId:flyerStoreId
							},
							function (data, textStatus) {

								tb_remove(); 
								jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
								jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList");					
								//alert(data.successMessage);
		 
							},"json"
					);
           		
           		} else if(result.status=='4') {
           				tb_remove();
           				tb_show("Your are not logged in","profile-not-logged-in.jsp?height=120&width=400");
           				} 
           		else {
           				alert("There was a problem creating a new shopping list. Please try again");
           				}
           		
           		},"json"
           		);
    }    
    
    
//Add products to shopping list 
function addProductToExistingShoppingList(shoppingListId,productId,quantity){
			var form_action ="handleShoppingListItems";
			var actionRequested="addProduct";
			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:shoppingListId,
			quantity:quantity,
			productId:productId},
			function (data, textStatus) {
			//reinitialize shopping list widget
				 tb_remove(); 
				 jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
			     jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList");
			    // alert(data.successMessage);
 
			},"json"
	);
}

//Add fkyer items to existing shopping list 
function addFlyerItemToExistingShoppingList(shoppingListId,flyerItemId,quantity,flyerStoreId){
			var form_action ="handleShoppingListItems";
			var actionRequested="addFlyerItem";
			
		jQuery.post("myShoppingLists.jsp", 
			{form_action:form_action,
			actionRequested:actionRequested,
			shoppingListId:shoppingListId,
			quantity:quantity,
			flyerItemId:flyerItemId,
			flyerStoreId:flyerStoreId},
			function (data, textStatus) {
			//reinitialize shopping list widget
				 tb_remove(); 
				 jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
			     jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList");
 
			},"json"
	);
}

//Add recipe ingredients to new shopping list 
function addProductToNewShoppingList(newListTitle,productId,quantity){
//We first create the shopping list and then add the product to it.
		var form_action ="handleShoppingList";
		var actionRequested="add";
			
     	jQuery.post("myShoppingLists.jsp?take=1",{
             form_action: form_action,
             actionRequested: actionRequested,
             shoppingListName: newListTitle,
             shoppingListNote: lcloGlobalMessages["shoppinglist.notes"]
           }, function(result) { 
           		if(result.status=='1'){
           		jQuery.post("myShoppingLists.jsp?take=2", 
							{form_action:"handleShoppingListItems",
							actionRequested:"addProduct",
							shoppingListId:result.ID,
							productId:productId,
							quantity:quantity
							},
							function (data, textStatus) {

								tb_remove(); 
								jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
								jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList");					
								//alert(data.successMessage);
		 
							},"json"
					);
           		
           		} else if(result.status=='4') {
           				tb_remove();
           				tb_show("Your are not logged in","profile-not-logged-in.jsp?height=120&width=400");
           				} 
           		else {
           				alert("There was a problem creating a new shopping list. Please try again");
           				}
           		
           		},"json"
           		);
    } 

    
function validateAddingProductItemToExistingShoppingList() {

	var quantityEntered = validateIntegerField(jQuery("#tb_shoppinglist_item_quantity"), "item quantity");
	var listSelected = validateSelectOptionChosen(jQuery("#dd_shoppinglist_list"), "shopping list");
	
	if (listSelected && quantityEntered) {
		return true;
	} else {
		return false;
	}
}


function validateAddingProductItemToNewShoppingList() {

	var quantityEntered = validateIntegerField(jQuery("#tb_shoppinglist_item_quantity2"), "item quantity2");
	var nameEntered = validateTextfield(jQuery("#tb_shoppinglist_item_newlistname"), "new list name");
	
	if (nameEntered && quantityEntered) {
		return true;
	} else {
		return false;
	}
}
    
function addAnyItemToExistingShoppingList() {

	var addWhat=jQuery("#addWhat").val(); // the type of item being added
	var proceed = false;
	
	jQuery("a.btnAddingToShoppingList").addClass("btnAddedToShoppingList");
	jQuery("a.btnAddedToShoppingList").removeClass("btnAddingToShoppingList");

	
		if (jQuery.trim(addWhat)=="recipe"){
			proceed = validateSelectOptionChosen(jQuery("#dd_shoppinglist_list"), "shopping list");
			if (proceed) {
				addRecipeIngredientsToExistingShoppingList();
			}
	 	
		} else if (jQuery.trim(addWhat)=="mealPlan"){
		 	addmealPlanItemsToExistingShoppingList();
		} else if (jQuery.trim(addWhat)=="product"){
					proceed = validateAddingProductItemToExistingShoppingList();
					if (proceed) {
					  	var productId = jQuery("#productId ").val();
						var shoppingListId = jQuery("#dd_shoppinglist_list").val();
						var quantity = jQuery("#tb_shoppinglist_item_quantity").val();
					 	addProductToExistingShoppingList(shoppingListId,productId,quantity);
					} 	
		  	 
		} else if (jQuery.trim(addWhat)=="flyerItem"){
					proceed = validateAddingProductItemToExistingShoppingList();
					if(proceed) {
						var flyerItemId = jQuery("#flyerItemId").val();
						var shoppingListId = jQuery("#dd_shoppinglist_list").val();
						var quantity = jQuery("#tb_shoppinglist_item_quantity").val();
						var flyerStoreId = jQuery("#flyerStoreId").val();
			 			addFlyerItemToExistingShoppingList(shoppingListId,flyerItemId,quantity,flyerStoreId);
			 		}	
		 	
		} else {
			alert ("Sorry I can't figure out what you are trying to add. Try again");
		}
} 
      
function addAnyItemToNewShoppingList(){
	var addWhat=jQuery("#addWhat").val();
	var proceed = false;

		if (jQuery.trim(addWhat)=="recipe"){
			proceed=validateTextfield(jQuery("#tb_shoppinglist_item_newlistname"), "new list name");
			if(proceed) {
				addRecipeIngredientsToNewShoppingList();			
			}

	 	} else if (jQuery.trim(addWhat)=="mealPlan"){
			addmealPlanItemsToNewShoppingList();
	 	} else if (jQuery.trim(addWhat)=="product"){
	 		proceed = validateAddingProductItemToNewShoppingList();
	 		if (proceed) {
		    	var productId = jQuery("#productId ").val();
				var newListTitle = jQuery('#tb_shoppinglist_item_newlistname').val();
		 	 	var quantity = jQuery("#tb_shoppinglist_item_quantity2").val();
			 	addProductToNewShoppingList(newListTitle,productId,quantity);
	 		}
	
		 }  else if (jQuery.trim(addWhat)=="flyerItem"){
					proceed = true;//validateAddingProductItemToNewShoppingList()();
					if(proceed) {
				    	//var productId = jQuery("#productId ").val();
						var newListTitle = jQuery('#tb_shoppinglist_item_newlistname').val();
				 	 	var quantity = jQuery("#tb_shoppinglist_item_quantity2").val();					
						var flyerItemId = jQuery("#flyerItemId").val();
						var flyerStoreId = jQuery("#flyerStoreId").val();
						addFlyerItemToNewShoppingList(newListTitle,flyerItemId,quantity,flyerStoreId);

			 		}	
		 	
		} else {
		 	alert ("Sorry I can't figure out what you are trying to add. Try again");
		 }
}

function initializeSpinnersOnOverlay() {
  	if (jQuery("#overlayWidgetTabNavigationContainer input.spinner").length > 0) {
		jQuery("#overlayWidgetTabNavigationContainer input.spinner").spin({imageBasePath:"images/pc/",max:100,min:0});
		jQuery("#overlayWidgetTabNavigationContainer input.spinner").numeric();
	}
}

function removeAddToShoppingListAnimation(){
	 jQuery("a.btnAddToShoppingList").removeClass("btnAddingToShoppingList");

}

function updateCopyShoppingListInput(shoppingListId) {
var initialText = jQuery("#tb_shoppinglist_title").val();
jQuery("#tb_shoppinglist_title").val(initialText+" "+jQuery("#shoppingListName"+shoppingListId).val());
}
function updateRenameShoppingListInput(shoppingListId) {
jQuery("#tb_shoppinglist_title").val(jQuery("#shoppingListName"+shoppingListId).val());
}

//Overlay specific listeners
function doShoppingListOverlayReady(returnUrl){
initializeSpinnersOnOverlay();
	if (jQuery("div#shoppingListsWidget input.spinner").length > 0) {
		//jQuery("div#shoppingListsWidget input.spinner").spin({imageBasePath:"images/pc/",max:100,min:0});
	//	jQuery("div#shoppingListsWidget input.spinner").numeric();
		jQuery("div#shoppingListsWidget input.spinner").change(function(){
			if (jQuery(this).val() > 0){
				jQuery(this).parent().find("input[type='checkbox']").attr("checked", "checked");
			} else {
				jQuery(this).parent().find("input[type='checkbox']").removeAttr("checked");
			}
		});
		
		jQuery("div#shoppingListsWidget div#tab2 fieldset:eq(1) input[type='checkbox']").attr("disabled", "disabled");
	}
	jQuery("div#shoppingListsWidget input[name='shoppinglist_additemtype']").click(function(){
		if (jQuery(this).val() == "recipe"){
			jQuery("div#shoppingListsWidget div#tab2 fieldset:eq(1) input[type='checkbox']").removeAttr("disabled");
			jQuery("div#shoppingListsWidget div#tab2 fieldset:eq(0) input[type='checkbox']").attr("disabled", "disabled");
			jQuery("#addFavouriteWhat").val('recipe');
		} else {
			jQuery("div#shoppingListsWidget div#tab2 fieldset:eq(1) input[type='checkbox']").attr("disabled", "disabled");
			jQuery("div#shoppingListsWidget div#tab2 fieldset:eq(0) input[type='checkbox']").removeAttr("disabled");
			jQuery("#addFavouriteWhat").val('product');
		}
	});			   

	if (jQuery("#overlayWidgetTabNavigationContainer").length > 0){
	    jQuery("#overlayWidgetTabNavigationContainer").tabs();
	}
	
	if(notLoggedIn) {
	tb_remove();

  		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");
      	}

		//tb_show("You are not logged in","profile-not-logged-in.jsp?height=200&width=730");

	}
	showOrHideShoppingListCopyMenu();
}


 //Calls listeners to shopping list specific items in the DOM
 function doShoppingListReady(){
 
 if (!initialLoading) {
jQuery('#memberPreferencesShoppingListsContainer *').unbind('click');
}
cleanShoppingListLabels();
 putShoppingListAutoSaveListeners();
 //tb_reinit('a.thickbox, area.thickbox, input.thickbox');
 
 //Test fix
  	if (jQuery("#memberPreferencesShoppingListsDetails table").length > 1) {
	    jQuery("#memberPreferencesShoppingListsDetails table").tablesorter({sortList:[[2,0],[3,0],[4,0]]});
	}
//End of test fix	
   //When a tab is clicked activate it and display the list details
 		  jQuery('ul#fixedPosition > li').click(function() { 
 		   var curActivePosition = jQuery("#memberPreferencesShoppingListsTabNavigation ul.fixedPosition > li").index(this);
			 displaySelectedTabList(curActivePosition);	   

		   });
  
 		   jQuery('#memberPreferencesShoppingListsReminders input').click(function() { 
 		   var shoppingListId = jQuery("#memberPreferencesShoppingListsReminders input#shoppingListId").val();
 		   var reminderId =jQuery(this).val();
 		   if (jQuery(this).attr("checked") == true){
 		   //alert("s id = " + shoppingListId + " and r id = " +reminderId);
			 addShoppingListReminder(shoppingListId,reminderId);
		   } else {
		   deleteShoppingListReminder(shoppingListId,reminderId);
		   }	   
	   
		   });		   
		  	if (jQuery("input.spinner").length > 0) {
			jQuery("input.spinner").spin({
				imageBasePath:"images/pc/",
				max:100,
				min:0 /*,
				changed: function(o,n){
					updateShoppingListProductItemQty(jQuery(this));
			
					return false;
				}*/
			});
			jQuery("input.spinner").numeric();
		}

	jQuery("input.spinner").change(function(){
              updateShoppingListProductItemQty(jQuery(this));
                return false;
		});
      if (jQuery("#memberPreferencesShoppingListsDetails table tr").length > 1) {
          jQuery("#memberPreferencesShoppingListsDetails table").tablesorter({sortList:[[2,0],[3,0],[4,0]]});
      }		   		   
showOrHideShoppingListCopyMenu();
 }
//end doShoppingListReady();

   //The main driver function
 jQuery(document).ready(function() {

 var JsonShoppingList ="";

  //put listeners to shipping list related DOM items
	doShoppingListReady();
	initialLoading=false;
 });
 
 
