// Administration JavaScript Document



$(document).ready(function()
{

	$(".deleteConf").click(
		function ()
		{
		
			var delMsg = "Are you sure you wish to permanently remove this item?";
			if($(this).attr("title").length > 0) delMsg = $(this).attr("title");
			
			if(!confirm(delMsg)) return false;
		
		});

	// menu item clicked to expand/collapse
	$('.accordion h3').click(function()
	{
		$(this).next().slideToggle('slow'); // toggle it open or closed
		
		// check if cookie exists and update to relevant state (with expiry of 21 days)
		if($.cookie($(this).next().attr('class'))=='open' || !$.cookie($(this).next().attr('class')))
		{
			$.cookie($(this).next().attr('class'), 'closed', { expires: 21 });
			$(this).removeClass("open");
			$(this).addClass("closed");
		}
		else
		{
			$.cookie($(this).next().attr('class'), 'open', { expires: 21 });
			$(this).removeClass("closed");
			$(this).addClass("open");
		}
		
		return false;
		
	}).next().hide();
	
	// loop through all coockies and see if it should be open or not 
	$.each(document.cookie.split(';'), function(i, cookie) 
	{
		var c = $.trim(cookie), name = c.split('=')[0], value = c.split('=')[1];
		
		// if open, show the content
		if (value == 'open') 
		{
			$('.' + name).show();
			$('.' + name).prev('h3').addClass("open");
		}
		else
		{
			$('.' + name).prev('h3').addClass("closed");
		}
	});
	
	$(function() {
		$('.datepicker').datepicker({
			changeMonth: true,
			changeYear: true
		});
	});
	
	
	/* table ordering stuff */
	
	// IF RELEVANT TABLE EXISTS
	if($(".dragTable").length > 0)
	{
		// INITIALISE TABLE WITH A DRAGCLASS AND ONDROP FUNCTION
		$(".dragTable").tableDnD({
			onDragClass: "myDragClass",
	
			onDrop: function(table, row) 
			{
				var rows = table.tBodies[0].rows;
				var varsToPass = "";
				var lastInserted = 0;
				
				for (var i=0; i<rows.length; i++) 
				{
					// CREATE VARIABLES OF NEW ORDER
					varsToPass += "id" + rows[i].id + "=" + i + "&";
				}
				
				var ref = String(table.id).substring(11); // ID OF TABLE BEING UPDATED
				
				var tableToChange = "&tableToChange=" + $('#tableToChange').val();
				
				$("#hiddenOrder_"+ref).val(varsToPass + tableToChange);
			}
		});
		
		// UPDATE BUTTON CLICKED, UPDATE THE ORDER
		$(".updateOrder").click(function()
		{	
			var ref = String(this.id).substring(12); // ID OF TABLE BEING UPDATED
			
			// SEND DATA THROUGH AJAX TO BE UPDATED
			$.ajax({
				type: "POST",
				url: "table_order.php",
				data: $("#hiddenOrder_"+ref).val(),
				error: function(msg)
				{
					alert("There was an error saving your order");
				},
				success: function(msg)
				{
					alert("Order saved");
				}
			});
		});
	}

});