$(function() {
	$('.shoppingListItems input:checkbox').click(function() {
		listitemclick($(this).attr('id'));
	});
	
	$('#link-planner-prev').click(function() {
		getShoppingList($('#planner-date').val(),'prev');
	});
	$('#link-planner-next').click(function() {
		getShoppingList($('#planner-date').val(),'next');
	});
	
	$('ul#freshItemList').sortable({
		axis: "y",
		cursor: "move",
		handle: $('li div'),
		items: 'li',
		update: function() {updateOrder($('ul#freshItemList').sortable("serialize"), 'fresh') }
	});
	$('ul#pantryItemList').sortable({
		axis: "y",
		cursor: "move",
		handle: $('li div'),
		update: function() {updateOrder($('ul#pantryItemList').sortable("serialize"), 'pantry') }
	});
	$('ul#otherItemList').sortable({
		axis: "y",
		cursor: "move",
		handle: $('li div'),
		update: function() {updateOrder($('ul#otherItemList').sortable("serialize"), 'other') }
	});
	$('ul#haveItemList').sortable({
		axis: "y",
		cursor: "move",
		handle: $('li div'),
		update: function() {updateOrder($('ul#haveItemList').sortable("serialize"), 'have') }
	});
	
	var current_request;
	
	function getShoppingList(weekDate,dir)
	{
		// Added by Gavin (2010-02-09) - Load date from JS and loader to imp. response to usr
		$('#plr-loader').show();
		
		date = $('#planner-date').val();
		
		crtPlrDateArr = explode(date, '-');
		
		currentDate = new Date(crtPlrDateArr[0], crtPlrDateArr[1] - 1, crtPlrDateArr[2]);
	
		var newPlrDateS = new Date();
		var newPlrDateE = new Date();
		
		if (dir == 'prev') {
			newPlrDateS.setTime(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
			newPlrDateE.setTime(newPlrDateS.getTime() + 6 * 24 * 60 * 60 * 1000);
		}
		else {
			newPlrDateS.setTime((7*86400000) + currentDate.getTime());
			newPlrDateE.setTime(currentDate.getTime() + 13 * 24 * 60 * 60 * 1000);
		}
		
		$('#planner-date-string').html(newPlrDateS.format('j M y') +' to '+ newPlrDateE.format('j M y'));
		$('#planner-date').val(newPlrDateS.format('Y-m-d'));
		
		if (current_request) current_request.abort();
		current_request = $.getJSON(url +"ajax/shopping-list.ajax.php", 
				{ 
					action: "getShoppingList",
					weekDate: weekDate,
					dir: dir
				}, 
				
				function (result)
				{				
					if (result.status == '1')
					{
						//$('#planner-date').val(result.newdate);
						//$('#planner-date-string').html(result.newdatestring);

						$('#freshItemList').html('');
						$('#pantryItemList').html('');
						$('#haveItemList').html('');
						
						for ( var i in result.shoppingList )
						{		
							
							
							if (result.shoppingList[i]['status_sli'] == 'have')
							{
								colname = '#haveItemList';
							}
							else if (result.shoppingList[i]['type_sli'] == 'fresh')
							{
								colname = '#freshItemList';
							}
							else
							{
								colname = '#pantryItemList';
							}
							id = result.shoppingList[i]['id_sli'];
							name = result.shoppingList[i]['name_sli'];
							
							$(colname).append('<li id="li_'+id+'"><div for="chk_'+id+'">'+name+'</div><input type="checkbox" id="chk_'+id+'" name = "chk_'+id+'"><br class="clearfloat" /></li>');
							

							$('#chk_'+id).click(function() {
								listitemclick($(this).attr('id'));
							});
						}
						// refresh sortables
						$('ul#freshItemList').sortable('destroy');
						$('ul#pantryItemList').sortable('destroy');
						
						
						$('ul#freshItemList').sortable({
							axis: "y",
							cursor: "move",
							handle: $('li div'),
							items: 'li',
							update: function() {updateOrder($('ul#freshItemList').sortable("serialize"), 'fresh') }
						});
						$('ul#pantryItemList').sortable({
							axis: "y",
							cursor: "move",
							handle: $('li div'),
							update: function() {updateOrder($('ul#pantryItemList').sortable("serialize"), 'pantry') }
						});
						
				
						/*$('#chk_'.id).parent().remove();*/
					}
					else
					{
						alert('fail');
					}
					$('#plr-loader').hide();
					/*$("#dialog").html('Have list Cleared');//('Have list cleared.');
					$("#dialog").dialog({
						bgiframe: true,
						modal: true,
						buttons: {
							Ok: function() {
								$(this).dialog('close');
							}
						}
					}).dialog('open');*/
					
				});
		return false;
	}
	
	
	function listitemclick(id) {
		element = $('#'+id);
		if (element.parent().parent().attr('id')=='haveItemList') return;
		
		id =  id.substr(4);
		var name = element.siblings('div').html();
		//pass the array to the php file....
		$.getJSON(url +"ajax/shopping-list.ajax.php", 
		{ 
			action: "have",
			id: id
		}, 
		
		function (result)
		{
			
			if (result.status == '1')
			{
				$('#li_'+id).remove();
				$('#haveItemList').append('<li id="li_'+id+'"><div for="chk_'+id+'">'+name+'</div><input type="checkbox" id="chk_'+id+'" name = "chk_'+id+'"><br class="clearfloat" /></li>');
				$('#chk_'+id).click(function() {
					haveitemclick($(this).attr('id'));
				});
				$('#btn-clear-have').show();
				/*$('#chk_'.id).parent().remove();*/
			}
			else
			{
				alert('fail');
			}
			/*$("#dialog").html('Have list Cleared');//('Have list cleared.');
			$("#dialog").dialog({
				bgiframe: true,
				modal: true,
				buttons: {
					Ok: function() {
						$(this).dialog('close');
					}
				}
			}).dialog('open');*/
			
		});
		
	}
	$('#haveItemList input:checkbox').click(function() {
		haveitemclick($(this).attr('id'));
	});
	function haveitemclick(id)
	{
		element = $('#'+id);
	
		id =  id.substr(4);
		var name = element.siblings('div').html();
		//pass the array to the php file....
		$.getJSON(url +"ajax/shopping-list.ajax.php", 
		{ 
			action: "donthave",
			id: id
		}, 
		
		function (result)
		{
			
			if (result.status == '1')
			{
				$('#li_'+id).remove();
				$('#'+result.type+'ItemList').append('<li id="li_'+id+'"><div for="chk_'+id+'">'+name+'</div><input type="checkbox" id="chk_'+id+'" name = "chk_'+id+'"><br class="clearfloat" /></li>');				
				$('#chk_'+id).click(function() {
					listitemclick($(this).attr('id'));
				});
				$('#btn-clear-have').show();
				/*$('#chk_'.id).parent().remove();*/
			}
			else
			{
				alert('fail');
			}
			
		});
		
	}
	$('#btn-clear-have').click(function() {
		
		//pass the array to the php file....
		$.getJSON(url +"ajax/shopping-list.ajax.php", 
		{ 
			action: "clearHaveList"
		}, 
		
		function (result)
		{
			
			if (result.status == '1')
			{
				$('#haveItemList li').remove();
				$('#btn-clear-have').hide();
				$("#dialog").attr('title','Shopping List').html('Have list Cleared');//('Have list cleared.');
			}
			else
			{
				$("#dialog").attr('title','Shopping List').html('There was an error');//('Have list cleared.');
			}
			$("#dialog").dialog({
				bgiframe: true,
				modal: true,
				buttons: {
					Ok: function() {
						$(this).dialog('close');
					}
				}
			}).dialog('open');
			
		});
		return false;
		
	});
	
	$('#fresh_item').focus(function() {
		blurAddText(this, 'focus');
	});
	
	$('#fresh_item').blur(function() {
		blurAddText(this, 'blur');
	});
	
	$('#pantry_item').focus(function() {
		blurAddText(this, 'focus');
	});
	
	$('#pantry_item').blur(function() {
		blurAddText(this, 'blur');
	});
	
	$('#other_item').focus(function() {
		blurAddText(this, 'focus');
	});
	
	$('#other_item').blur(function() {
		blurAddText(this, 'blur');
	});
	
	
	$('#add_to_fresh').click(function() {
		
		var name = $('#fresh_item').val();
		
		$('#fresh-msg').hide();
		$('#fresh-msg').html('');
		$('#fresh_item').removeClass('error');
		
		if (name != 'another item' && name.length > 0)
		{
			addto('fresh',name);
			$('#fresh_item').val('');
		}
		else
		{
			showMsg('#fresh_item', '#fresh-msg', 'error', '');
		}
		
		return false;
		
	});
	
	$('#add_to_pantry').click(function() {
		var name = $('#pantry_item').val();
		
		if (name != 'another item' && name.length > 0)
		{
			addto('pantry',name);
			$('#pantry_item').val('');
		}
		else
		{
			showMsg('#pantry_item', '#pantry-msg', 'error', '');
		}
			
		return false;
		
	});
	
	$('#add_to_other').click(function() {
		var name = $('#other_item').val();
		
		if (name != 'another item' && name.length > 0)
		{
			addto('other',name);
			$('#other_item').val('');
		}
		else
		{
			showMsg('#other_item', '#other-msg', 'error', '');
		}
		
		return false;
	});
	
	function blurAddText(element, type) {
		
		if (type == 'focus' && $(element).val() == 'another item') 
		{
			$(element).removeClass('blurred-text');
			$(element).val('');
		}
		else if (type == 'blur' && $(element).val()=='')
		{
			$(element).val('another item');
			$(element).addClass('blurred-text');
		}
	}
	
	function showMsg(elementName, elementErrName, type, msg)
	{
		if (msg.length < 1) msg = 'Need to enter an item';
			
		$(elementName).addClass(type);
		$(elementErrName).show();
		
		$(elementErrName).addClass(type);
		$(elementErrName).html(msg);
	}
	
	
	function addto(type,name)
	{
		//pass the array to the php file....
	
		$('#'+ type +'-loader').show();
		
		$.getJSON(url +"ajax/shopping-list.ajax.php", 
		{ 
			action: "add",
			type: type,
			name: name
		}, 
		
		function (result)
		{
			var id = result.id;
			
			if (result.status == '1')
			{
				$('#'+type+'ItemList').append('<li id="li_'+id+'"><div for="chk_'+id+'">'+name+'</div><input type="checkbox" id="chk_'+id+'" name = "chk_'+id+'"><br class="clearfloat" /></li>');
				$('ul#'+type+'ItemList').sortable('destroy');
				$('ul#'+type+'ItemList').sortable({
					axis: "y",
					cursor: "move",
					handle: $('li div'),
					items: 'li',
					update: function() {updateOrder($('ul#'+type+'ItemList').sortable("serialize"), type) }
				});
				
				//alert('refreshed');
				$('#chk_'+id).click(function() {
					listitemclick($(this).attr('id'));
				});
			}
			else
			{
				alert('fail');
			}
			$('#'+type +'-loader').hide();
		});
	}
	
	//print button
	$(".shoppingListActions .print").click(function(){
		slPrintWindow=window.open(url+'shoppinglist/print','slPrintWindow','height=800,width=800, menubar=yes, scrollbars=yes');

		if (slPrintWindow) {slPrintWindow.focus()}
		return false;

	});
	
	
	//sms button
	$(".shoppingListActions .sms").click(function(){
		
		
		//pass the array to the php file....
		$.getJSON(url +"ajax/shopping-list.ajax.php", 
		{ 
			action: "sms"
		}, 
		
		function (status)
		{
			
			
			$("#btmResults").html(status);//('Shopping list SMSd.');
		});
		
		return false;
	});
	
	
	
	//email button
	$(".shoppingListActions .email").click(function(){
		
		
		//pass the array to the php file....
		$.getJSON(url +"ajax/shopping-list.ajax.php", 
		{ 
			action: "email"
		}, 
		
		function (status)
		{
			$("#btmResults").html(status);//('Shopping list emailed.');
			
		});
		
		return false;
	});
});
				
				
				/*
				$(document).ready(function(){
								applyActions()
			    });
								
				function applyActions(){				
					//clear button
					$("#formShoppingList .clear").click(function(){
						
						//remove the list items from the webpage
						 $('#haveItemList').children().remove();
						 $('.clear').hide();
						
						//pass the array to the php file....
						$.getJSON(url +"ajax/shopping-list.ajax.php", 
						{ 
							action: "clearHaveList"
						}, 
						
						function (status)
						{
							$("#dialog").html('Have list Cleared');//('Have list cleared.');
							$("#dialog").dialog({
								bgiframe: true,
								modal: true,
								buttons: {
									Ok: function() {
										$(this).dialog('close');
									}
								}
							}).dialog('open');
							
						});
						
						return false;
					});
					
					//print button
					$(".shoppingListActions .print").click(function(){
						window.print();
						return false;
					});
					
					
					//sms button
					$(".shoppingListActions .sms").click(function(){
						
						var itemValuesStr='';
						var parentUL='';
						var tmpstr='';
						
						
						//read in the shopping list items...			
						var $inputs = $('#formShoppingList input');
											
						$inputs.each(function(i, el) {						
							//do not put the "other" textbox values into the array to be emailed
							if(el.name!='anotherItemFresh' && el.name!='anotherItemPantry' && el.name!='anotherItemOther'){							
								parentUL=$(el).parent().parent().attr('id')														
								if(parentUL!='haveItemList'){
									itemValuesStr+='+'+parentUL+'_'+$(el).siblings('label').html();
								
								}
							}												
						});
						
						//pass the array to the php file....
						$.getJSON(url +"ajax/shopping-list.ajax.php", 
						{ 
							action: "sms", items: itemValuesStr
						}, 
						
						function (status)
						{
							$("#dialog").append('Your shopping list has been sent to you via SMS');//('Shopping list SMSd.');
						});
						
						return false;
					});
					
					
					
					//email button
					$(".shoppingListActions .email").click(function(){
						
						var itemValuesStr='';
						var parentUL='';
						var tmpstr='';
												
						//read in the shopping list items...			
						var $inputs = $('#formShoppingList input');
											
						$inputs.each(function(i, el) {						
							//do not put the "other" textbox values into the array to be emailed
							if(el.name!='anotherItemFresh' && el.name!='anotherItemPantry' && el.name!='anotherItemOther'){							
								parentUL=$(el).parent().parent().attr('id')														
								if(parentUL!='haveItemList'){
									itemValuesStr+='+'+parentUL+'_'+$(el).siblings('label').html();
								
								}
							}						
						});
						
						//pass the array to the php file....
						$.getJSON(url +"ajax/shopping-list.ajax.php", 
						{ 
							action: "email", items: itemValuesStr
						}, 
						
						function (status)
						{
							$("#dialog").append('Shopping list emailed.');//('Shopping list emailed.');
							
						});
						
						return false;
					});
									
					//set up ajax to move items when checked
					$(".shoppingListItems input").change(function() {						
						
						var checkedState=$(this).val();
						var itemID=$(this).parent().attr('id');				
						var currentList=$(this).parent().parent().attr('id');								
																
						if(currentList!='haveItemList'){
							//('current list not have');						
							moveListItem(itemID,'have');
							$('.clear').show();
						}else{
							//('current list IS have');											
							var itemBits=itemID.split('_');								
							var itemCategoryList=itemBits[1]; //the list the item belongs to																						
							moveListItem(itemID,itemCategoryList);						
						}						
						saveShoppingList();													
					
					});	
										
				}								
				
				function moveListItem(itemToMoveID,newList){
											
						var newItemInnerHTML=$('#'+itemToMoveID).html();	//get the html of the current list item		
									
						if(newList!='have'){						
							var tempStr=itemToMoveID.replace('have_','');
							var newItemHTML='<li id="'+tempStr+'">'+newItemInnerHTML+'</li>'; //construct the html of the new list item						
						}else{
							var newItemHTML='<li id="'+newList+'_'+itemToMoveID+'">'+newItemInnerHTML+'</li>'; //construct the html of the new list item				
						}
						
						$('#'+itemToMoveID).remove();//remove from the current list											
								
						$(newItemHTML).appendTo('#'+newList+'ItemList'); //add to the new list										
						
							//need to redo this for items that have mofed.
							$(".shoppingListItems input").change(function() {
	
								var checkedState=$(this).val();
								var itemID=$(this).parent().attr('id');
								
								var currentList=$(this).parent().parent().attr('id');														
								if(currentList!='haveItemList'){ //move to have item list						
									moveListItem(itemID,'have');
								}else{//move back to category										
									var itemBits=itemID.split('_');																									
									var itemCategoryList=itemBits[1]; //the list the item belongs to												
									moveListItem(itemID,itemCategoryList);						
								}	
								
								saveShoppingList();				
												
							});
						
					}
					
					
				function saveShoppingList(){									
					
					//get all the items from the form..
					var $inputs = $('#formShoppingList input');
					var itemValues = {};
					var parentLiID='';
					var itemValuesStr='';
					
					$inputs.each(function(i, el) {
						
						parentLiID='';						
						
						//do not put the "other" textbox values into the array to be saved.	
						if(el.name!='anotherItemFresh' && el.name!='anotherItemPantry' && el.name!='anotherItemOther'){
							parentLiID=$(el).parent().attr('id');							
							var rawText=parentLiID.replace(' ','&nbsp;');
							itemValuesStr+='+'+rawText;
						}	
						
					})
					
					//(itemValuesStr);
						
					//pass the array to the php file....
					$.getJSON(url +"ajax/shopping-list.ajax.php", 
					{ 
						action: "save", items: itemValuesStr
					}, 
					
					function (status)
					{
						$("#dialog").append('Shopping list Saved.');	//alert('Shopping list saved.');
					});					
					
				}
				*/
								
function updateOrder(idArray, type)
{
	//alert('#'+type+'-ajax-loader span');
	$('#'+type+'-ajax-loader span').html('Saving order, please wait...');
	$('#'+type+'-ajax-loader').show();
	
	//pass the array to the php file....
	
	
	$.getJSON(url +"ajax/shopping-list.ajax.php", 
	{ 
		action: "order",
		idArray: idArray
	}, 
	
	function (result)
	{	
		$('#'+type+'-ajax-result').removeClass('success').removeClass('error');
		$('#'+type+'-ajax-result').addClass(result.resType);	
		$('#'+type+'-ajax-result').html(result.msg);
		setTimeout(function() { 
			$('#'+type+'-ajax-result').hide();
		},4000);
		
		$('#'+type+'-ajax-result').show();
		$('#'+type+'-ajax-loader').hide();
	});
}
