// JavaScript Document
jQuery(document).ready(function(){
	/*
		RECIPE LIST ACTIONS
	*/
	// add a recipe to your list, from the recipe details page
	jQuery('form.addToList').submit(
		function()
		{
			var recipeId = jQuery('.recipeId', this).attr('value');
			var addContainer = jQuery('.recipeListPanel', this);
			var removeContainer = jQuery('.removeFromList .recipeId[value='+recipeId+']').parents('.recipeListPanel');
			jQuery.ajax({
				data: { ajax: 'addRecipe', recipe_id: recipeId },
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				dataType: 'json',
				success: function(json)
				{
					if(json.error != null && json.error != '')
					{
						alert(json.error);
					}
					else
					{
						addContainer.animate({opacity:'hide'}, 'fast');
						removeContainer.animate({opacity:'show'}, 'fast');
						refreshSimpleList(json.list);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				}
			});
			return false;
		}
	);
	// remove a recipe from your list, from the recipe details page
	jQuery('form.removeFromList').submit(
		function()
		{
			if(!confirm("Are you sure you want to remove this recipe from your list?"))
			{
				return false;
			}
			var recipeId = jQuery('.recipeId', this).attr('value');
			var removeContainer = jQuery('.recipeListPanel', this);
			var addContainer = jQuery('.addToList .recipeId[value='+recipeId+']').parents('.recipeListPanel');
			jQuery.ajax({
				data: { ajax: 'removeRecipe', recipe_id: recipeId },
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				dataType: 'json',
				success: function(json)
				{
					if(json.error != null && json.error != '')
					{
						alert(json.error);
					}
					else
					{
						removeContainer.animate({opacity:'hide'}, 'fast');
						addContainer.animate({opacity:'show'}, 'fast');
						refreshSimpleList(json.list);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				}
			});
			return false;
		}
	);

	jQuery('.simpleShoppingList .itemRow').hover( function(){ jQuery(this).addClass('hoverItem'); }, function(){ jQuery(this).removeClass('hoverItem'); } );

	//for the delete links on the recipe list to work, need to attach the delete command
	jQuery('.recipeRow a.deleteLink').click(addRecipeDeleteSimpleList);
	
	
	/*
		FAVORITES FUNCTIONS
	*/
	// add a recipe to your favorites, from the recipe details page
	jQuery('form.addToFavorites').submit(
		function()
		{
			var recipeId = jQuery('.recipeId', this).attr('value');
			var addContainer = jQuery('.recipeListPanel', this);
			var removeContainer = jQuery('.removeFromFavorites .recipeId[value='+recipeId+']').parents('.recipeListPanel');
			jQuery.ajax({
				data: { ajax: 'addFavorite', recipe_id: recipeId },
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				dataType: 'json',
				success: function(json)
				{
					if(json.error != null && json.error != '')
					{
						alert(json.error);
					}
					else
					{
						addContainer.animate({opacity:'hide'}, 'fast');
						removeContainer.animate({opacity:'show'}, 'fast');
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				}
			});
			return false;
		}
	);

	// remove a recipe from your list, from the recipe details page
	jQuery('form.removeFromFavorites').submit(
		function()
		{
			if(!confirm("Are you sure you want to remove this recipe from your product box?"))
			{
				return false;
			}
			var recipeId = jQuery('.recipeId', this).attr('value');
			var removeContainer = jQuery('.recipeListPanel', this);
			var addContainer = jQuery('.addToFavorites .recipeId[value='+recipeId+']').parents('.recipeListPanel');
			jQuery.ajax({
				data: { ajax: 'removeFavorite', recipe_id: recipeId },
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				dataType: 'json',
				success: function(json)
				{
					if(json.error != null && json.error != '')
					{
						alert(json.error);
					}
					else
					{
						removeContainer.animate({opacity:'hide'}, 'fast');
						addContainer.animate({opacity:'show'}, 'fast');
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				}
			});
			return false;
		}
	);
	
	/*
		SAMPLE LIST
	*/
	jQuery('.viewMoreDetails').click(
		function()
		{
				jQuery('.hiddenBit:hidden', jQuery(this).parent('div.recipeBody')).slideDown('fast');
				jQuery(this).animate({opacity:'hide'}, 'fast');
				return false;
		}
	);
	jQuery('.editItemLink').click(startEditShoppingItem);
	jQuery('.deleteItemLink').click(deleteShoppingItem);
	jQuery('.addItemLink').click(startAddShoppingItem);
	jQuery('.cancelItemAddLink').click(cancelAddShoppingItem);
	jQuery('.saveItemAddLink').click(saveAddShoppingItem);
	jQuery('.clearList').click(
		function()
		{
			if(!confirm("Are you sure you want to clear your personal menu?"))
			{
				return false;
			}
			jQuery.ajax({
				data: { ajax: 'clearList' },
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				dataType: 'json',
				success: function(json)
				{
					if(json.error != null && json.error != '')
					{
						alert(json.error);
					}
					else
					{
						refreshSimpleList(new Array());
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				}
			});
			return false;
			
		}
	);
});

function refreshSimpleList(list)
{
	var recipeId = jQuery('.addToList .recipeId').attr('value');
	if(!list.length || list.length == 0)
	{
		jQuery('.simpleRecipeList:visible').animate({opacity:'hide'}, 'fast').html('');
		jQuery('.clearList:visible').animate({opacity:'hide'}, 'fast');
		jQuery('.simpleRecipeListEmpty:hidden').animate({opacity:'show'}, 'fast');
		jQuery('#headerRecipeCount').text('0');
		jQuery('.cantAddMoreNote:visible').animate({opacity:'hide'}, 'fast');
		jQuery('form.addToList div.recipeListPanel:hidden').animate({opacity:'show'}, 'fast');
		jQuery('form.removeFromList div.recipeListPanel:visible').animate({opacity:'hide'}, 'fast');
	}
	else
	{
		var theHtml = '';
		var maxLoop = list.length;
		var currentUrl = window.location;
		jQuery('#headerRecipeCount').text(maxLoop);
		for(var i = 0; i < maxLoop; i++)
		{
			theHtml += '<div class="recipeRow">\
				<a href="'+list[i].url+'" class="recipeLink'+((list[i].id == recipeId)?' currentRecipe':'')+'" id="simpleRecipe'+list[i].id+'">'+list[i].name+'</a>\
				<a href="'+currentUrl+'?remove_from_list_id='+list[i].name+'" rel="'+list[i].id+'" class="deleteLink"><span>delete</span></a>\
				<div class="clear"></div>\
			</div>';
			//theHtml += '<a href="'+list[i].url+'"'+((list[i].id == recipeId)?' class="currentRecipe"':'')+' id="simpleRecipe'+list[i].id+'">'+list[i].name+'</a>';
		}
		jQuery('.clearList:hidden').animate({opacity:'show'}, 'fast');
		jQuery('.simpleRecipeList').html(theHtml);
		jQuery('.simpleRecipeList:hidden').animate({opacity:'show'}, 'fast');
		jQuery('.simpleRecipeListEmpty:visible').animate({opacity:'hide'}, 'fast');
		jQuery('.recipeRow a.deleteLink').click(addRecipeDeleteSimpleList);
		if(list.length >= 10)
		{
			//see if the remove button is visible before doing anything funny
			if(jQuery('form.removeFromList div.recipeListPanel:visible').length == 0)
			{
				jQuery('.cantAddMoreNote:hidden').animate({opacity:'show'}, 'fast');
				jQuery('form.addToList div.recipeListPanel:visible').animate({opacity:'hide'}, 'fast');
			}
			else
			{
				jQuery('.cantAddMoreNote:visible').animate({opacity:'hide'}, 'fast');
				jQuery('form.addToList div.recipeListPanel:hidden').animate({opacity:'show'}, 'fast');
			}
		}
		else
		{
			jQuery('.cantAddMoreNote:visible').animate({opacity:'hide'}, 'fast');
			jQuery('form.addToList div.recipeListPanel:hidden').animate({opacity:'show'}, 'fast');
		}
	}
	return;
}

function addRecipeDeleteSimpleList()
{
	if(!confirm("Are you sure you want to remove this recipe from your list?"))
	{
		return false;
	}
	var recipeId = jQuery(this).attr('rel');
	var addContainer = jQuery('.addToList .recipeId[value='+recipeId+']').parents('.recipeListPanel');
	var removeContainer = jQuery('.removeFromList .recipeId[value='+recipeId+']').parents('.recipeListPanel');
	if(isNaN(recipeId))
	{
		return false;
	}
	jQuery.ajax({
		data: { ajax: 'removeRecipe', recipe_id: recipeId },
		url: 'http://www.faithfuldinners.com/recipe_ajax.php',
		dataType: 'json',
		success: function(json)
		{
			if(json.error != null && json.error != '')
			{
				alert(json.error);
			}
			else
			{
				refreshSimpleList(json.list);
				addContainer.animate({opacity:'show'}, 'fast');
				removeContainer.animate({opacity:'hide'}, 'fast');
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
		  // typically only one of textStatus or errorThrown 
		  // will have info
			alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
		}
	});
	return false;
}

function startAddShoppingItem()
{
	jQuery('#addItemForm:hidden').slideDown('fast');
	return false;
}

function cancelAddShoppingItem()
{
	jQuery('#addItemForm:visible').slideUp('fast');
	jQuery('#addItemForm input').attr('value', '');
	return false;
}

function saveAddShoppingItem()
{
	var newItemAmount = jQuery('#newItemAmount').attr('value');
	var newItemUnit = jQuery('#newItemUnit').attr('value');
	var newItemName = jQuery('#newItemName').attr('value');
	var dataString = 'ajax=addShoppingListItem';
	if(!newItemName)
	{
		alert('Please make sure the item\'s name is filled in');
		return false;
	}
	else
	{
		dataString += "&name="+escape(newItemName);
	}
	if(newItemAmount)
	{
		dataString += "&amount="+escape(newItemAmount);
	}
	if(newItemUnit)
	{
		dataString += "&unit="+escape(newItemUnit);
	}
	jQuery('.saveItemAddLink').html('Please Wait');
	jQuery('.cancelItemAddLink:visible').hide();
	jQuery.ajax({
				data: dataString,
				dataType: 'json',
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				},
				success: function(json)
				{
					if(json.success)
					{
						var currentSide = jQuery('.shoplist-left');
						var leftSide = false;
						var rightSide = false;
						var lastDepartment = '';
						var theHtml = '';
						var break_next = false;
						for(var i = 0; i < json.item_list.length; i++)
						{
							if(lastDepartment != json.item_list[i].department)
							{
								if(break_next)
								{
									if(theHtml != '')
									{
										theHtml += '</div>';
									}
									currentSide.html(theHtml);
									currentSide = jQuery('.shoplist-right');
									theHtml = '';
								}
								lastDepartment = json.item_list[i].department;
								theHtml += (theHtml == ''?'':'</div>')+'<div class="deptRow">'+json.item_list[i].department+'</div>\
											<div class="deptItemContainer" rel="'+json.item_list[i].department+'">';
							}
							theHtml += '<div class="itemRow">\
											<input type="hidden" class="itemId" value="' + json.item_list[i].id + '" />\
											<span class="itemAmount">' + ((json.item_list[i].item_amount) ? json.item_list[i].item_amount : '') + '</span>\
											<span class="itemUnit">' + ((json.item_list[i].item_unit) ? json.item_list[i].item_unit : '') + '</span>\
											<span class="itemName">' + json.item_list[i].item_name + ((json.item_list[i].in_pantry == true) ? ' <strong class="pantry-star">*</strong>' : '') + '</span>\
											<a href="#" style="visibility:visible;" class="deleteItemLink"><span>[</span>delete<span>]</span></a><a href="#" style="visibility:visible;" class="editItemLink"><span>[</span>edit<span>]</span></a>\
											<div class="clear"></div>\
										</div>';
							break_next = json.item_list[i].break_after;

						}
						if(theHtml != '')
						{
							theHtml += '</div>';
						}
						currentSide.html(theHtml);
						var itemContainer = jQuery('.simpleShoppingList');
						jQuery('.editItemLink', itemContainer).click(startEditShoppingItem);
						jQuery('.deleteItemLink', itemContainer).click(deleteShoppingItem);
						jQuery('.simpleShoppingList .itemRow', itemContainer).hover( function(){ jQuery(this).addClass('hoverItem'); }, function(){ jQuery(this).removeClass('hoverItem'); } );

						jQuery('.saveItemAddLink').html('<span>[</span>save new item<span>]</span>');
						jQuery('.cancelItemAddLink:hidden').show();
						jQuery('#addItemForm:visible').slideUp('fast');
						jQuery('#addItemForm input').attr('value', '');
						jQuery('.simpleShoppingList:hidden').show();

					}
					else
					{
						jQuery('.saveItemAddLink').html('<span>[</span>save new item<span>]</span>');
						jQuery('.cancelItemAddLink:hidden').show();
						alert(json.error);
					}
				}
			});

	return false;
}

function startEditShoppingItem()
{
	var parentContainer = jQuery(this).parents('.itemRow');
	var itemId = jQuery('.itemId', parentContainer).attr('value');
	if(isNaN(itemId))
	{
		return false;
	}
	var itemAmount = jQuery('.itemAmount', parentContainer).text();
	var itemUnit = jQuery('.itemUnit', parentContainer).text();
	var itemName = jQuery('.itemName', parentContainer).text();
	var inPantry = (jQuery('.itemName .pantry-star', parentContainer).length > 0);
	var theHtml = '';
	if(inPantry && itemName.indexOf('*') != -1)
	{
		var nameLength = itemName.length;
		itemName = itemName.substring(0,nameLength-2);
	}
	
	theHtml = '<input type="hidden" class="itemId" value="'+itemId+'" />';
	theHtml += '<input type="hidden" class="originalItemAmount" value="'+itemAmount+'" />';
	theHtml += '<input type="hidden" class="originalItemUnit" value="'+itemUnit+'" />';
	theHtml += '<input type="hidden" class="originalItemName" value="'+itemName+'" />';
	theHtml += '<label class="itemAmount">Amount</label>';
	theHtml += '<label class="itemUnit">Units</label>';
	theHtml += '<label class="itemName">Name <span style="display:inline; float:none; padding:0; " class="required">*</span></label>';
	theHtml += '<div class="clear"></div>';
	theHtml += '<input type="text" class="itemAmount form" id="itemAmount'+itemId+'" value="'+itemAmount+'" />';
	theHtml += '<input type="text" class="itemUnit form" id="itemUnit'+itemId+'" value="'+itemUnit+'" />';
	theHtml += '<input type="text" class="itemName form" id="itemName'+itemId+'" value="'+itemName+'" />';
	if(inPantry)
	{
		theHtml += '<input type="hidden" class="pantry-star" value="true" />';
	}
	theHtml += '<a href="#" style="visibility:visible;" class="cancelItemEditLink"><span>[</span>cancel<span>]</span></a>';
	theHtml += '<a href="#" style="visibility:visible;" class="saveItemEditLink"><span>[</span>save<span>]</span></a>';
	theHtml += '<div class="clear"></div>';
	parentContainer.html(theHtml);

	jQuery('.saveItemEditLink', parentContainer).click(saveEditShoppingItem);
	jQuery('.cancelItemEditLink', parentContainer).click(cancelEditShoppingItem);
	
	return false;
}

function saveEditShoppingItem()
{
	var parentContainer = jQuery(this).parents('.itemRow');
	var itemId = jQuery('.itemId', parentContainer).attr('value');
	if(isNaN(itemId))
	{
		return false;
	}
	var itemAmount = jQuery('#itemAmount'+itemId, parentContainer).attr('value');
	var itemUnit = jQuery('#itemUnit'+itemId, parentContainer).attr('value');
	var itemName = jQuery('#itemName'+itemId, parentContainer).attr('value');
	var inPantry = (jQuery('.itemName .pantry-star', parentContainer).length > 0);
	var dataString = 'ajax=editShoppingListItem&list_id='+itemId;
	if(/*!itemAmount || !itemUnit || */!itemName)
	{
		alert('Please make sure the name field is filled in');
		return false;
	}
	else
	{
		dataString += "&name="+escape(itemName);
	}
	if(itemAmount)
	{
		dataString += "&amount="+escape(itemAmount);
	}
	if(itemUnit)
	{
		dataString += "&unit="+escape(itemUnit);
	}
	jQuery('.deleteItemLink', parentContainer).hide();
	jQuery(this).html('Please wait');

	jQuery.ajax({
				data: dataString,
				dataType: 'json',
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				},
				success: function(json)
				{
					if(json.success)
					{
						var theHtml = '<input type="hidden" class="itemId" value="'+itemId+'" />';
						theHtml += '<span class="itemAmount">'+((itemAmount)?itemAmount:'')+'</span>';
						theHtml += '<span class="itemUnit">'+((itemUnit)?itemUnit:'')+'</span>';
						theHtml += '<span class="itemName">'+itemName+(inPantry ? ' <strong class="pantry-star">*</strong>' : '')+'</span>';
						theHtml += '<a href="#" style="visibility:visible;" class="deleteItemLink"><span>[</span>delete<span>]</span></a><a href="#" style="visibility:visible;" class="editItemLink"><span>[</span>edit<span>]</span></a>';
						theHtml += '<div class="clear"></div>';
						parentContainer.html(theHtml);
						jQuery('.editItemLink', parentContainer).click(startEditShoppingItem);
						jQuery('.deleteItemLink', parentContainer).click(deleteShoppingItem);
					}
					else
					{
						alert(json.error);
					}
				}
			});
	
	return false;
}

function deleteShoppingItem()
{
	var parentContainer = jQuery(this).parents('.itemRow');
	var itemId = jQuery('.itemId', parentContainer).attr('value');
	if(isNaN(itemId))
	{
		return false;
	}
	
	if(!confirm('are you sure you want to delete this item from your shopping list?'))
	{
		return false;
	}
	jQuery('.editItemLink', parentContainer).hide();
	jQuery(this).html('Please wait');
	jQuery.ajax({
				data: "list_id="+itemId+"&ajax=removeShoppingListItem",
				dataType: 'json',
				url: 'http://www.faithfuldinners.com/recipe_ajax.php',
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
					alert('an error has occurred:\n'+textStatus+'\n'+errorThrown);
				},
				success: function(json)
				{
					parentContainer.remove();
				}
			});
	return false;
}

function cancelEditShoppingItem()
{
	if(!confirm('are you sure you want to cancel editing this item?'))
	{
		return false;
	}
	var parentContainer = jQuery(this).parents('.itemRow');
	var itemId = jQuery('.itemId', parentContainer).attr('value');
	if(isNaN(itemId))
	{
		return false;
	}
	var itemAmount = jQuery('.originalItemAmount', parentContainer).attr('value');
	var itemUnit = jQuery('.originalItemUnit', parentContainer).attr('value');
	var itemName = jQuery('.originalItemName', parentContainer).attr('value');
	var inPantry = (jQuery('.pantry-star', parentContainer).length > 0);
	
	var theHtml = '<input type="hidden" class="itemId" value="'+itemId+'" />';
	theHtml += '<span class="itemAmount">'+itemAmount+'</span>';
	theHtml += '<span class="itemUnit">'+itemUnit+'</span>';
	theHtml += '<span class="itemName">'+itemName+(inPantry ? ' <strong class="pantry-star">*</strong>' : '')+'</span>';
	theHtml += '<a href="#" style="visibility:visible;" class="deleteItemLink"><span>[</span>delete<span>]</span></a><a href="#" style="visibility:visible;" class="editItemLink"><span>[</span>edit<span>]</span></a>';
	theHtml += '<div class="clear"></div>';
	
	parentContainer.html(theHtml);
	jQuery('.editItemLink', parentContainer).click(startEditShoppingItem);
	jQuery('.deleteItemLink', parentContainer).click(deleteShoppingItem);
	return false;
}