var serviceURLHR =localStorage['serviceURLHR'];
var hosturl    =localStorage['basicURL'];

var id = getUrlVars()["tid"];
$(window).load(function() {
	
if(localStorage.getItem('username')===null || localStorage.getItem('userid')===null || localStorage['username'] =='' || localStorage['userid']=='' || localStorage['activation']===null){
	window.location = "login.html";	
}else{
	loadFunctions();
}
	
	
});

function loadFunctions(){
	setTimeout(getTableList, 50);
	setTimeout(loadSettings,100);
	setTimeout(loadSupplier,150);
	setTimeout(listAllCategory,200);
	setTimeout(loadHomeDel,250);
};

//setInterval( getTableList, 10000 ); // refresh every 10000 milliseconds

$.getJSON(serviceURLHR+'managetax.php',function(resp){
		taxpers = resp.tax;
		localStorage['tax']=taxpers.tax;									  
	})
	
	
$('#booktable').click(function(){
	var datastring	= $('#booktableform').serialize();
	
	$.post(serviceURLHR+'newbooking.php',datastring,function(o){
			if(o=='success'){
				alert('Table booking successfull.');
				window.location ="../index.html";
			}
	})
});

$(document).ajaxError(function(event, request, settings) {
	$('#busy').hide();
	//alert("Error accessing the server");
});

////////////////////////////////////////////////////////// Home delivery /////////////////////////////////////////////////////////////////


function loadHomeDel(){
	$.getJSON(serviceURLHR + 'loadHomeDel.php', function(data){
			var homedelivery = data.userdetails;
			//console.log(homedel);
			if(homedelivery!='true' ){
			
					$.each(homedelivery, function(index, homedelivery) {
	
							datetime=homedelivery.status_change;
							booktime =	 extractdatetime_to_time(datetime);
							$('.homedel').append('<div class="order-status-tab">'+
												'<p>'+ homedelivery.name +' <span>'+homedelivery.phone+'</span></p>'+
												'<h6>'+
												booktime+
												'<span>RS.'+ homedelivery.collection +' <input name="" type="checkbox" value="" /></span>'+
												'</h6>'+
												'</div>');
						});	
					
					
					
					
			}else{
				$('.homedelivery').append('<div class="homedelusers" id="'+homedelivery.id+'">'+ homedelivery.name +' '+homedelivery.phone+'</div>');
			}
	});
	
	
	//setInterval( homedel, 5000 );
	
}
/////////////////////////////////////////////////////////  Load Home delivery details /////////////////////////////////////////////////////


/////////////////////////////////////////////////////////  Load Settings ///////////////////////////////////////////////////////////////////
var settings;
function loadSettings(){
	$.getJSON(serviceURLHR + 'loadSettings.php', function(data) {
		$('#header').html('');
		settings = data.settings;
		$('#header').append('<div align="center"><img src='+hosturl+'images/'+settings.logo+' width=50px>'+
							'<H1>'+settings.restaurentname+'</H1></div>');
		
	});
}
//////////////////////////////////////////////////////////// Load booked dates and highlight in datepicker ///////////////////////////////

	var disabledDays='';
	var date = new Date();
	$.post(serviceURLHR + 'listTableBooked.php', function(data) {
	disabledDays =data;
	  $(".calender-holder").datepicker("refresh");
	},"json");

////////////////////////////////////////////////////////////   Datepicker Function with Highlighting Dats ////////////////////////////////
$(function() {
	 var selected = null;
    $(".calender-holder").datepicker({
	 beforeShowDay: function(date) {
						var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
						for (i = 0; i < disabledDays.length; i++) {
							if($.inArray(y + '-' + (m+1) + '-' + d,disabledDays) != -1) {
								return [true, 'css-class-to-highlight', 'Table booking'];
								
							}
						}
						return [true];
			},
		dateFormat: 'yy-m-d',
	 onSelect: function(dateText, inst) {            //// This is on select function of date picker.
	  var currentDate = $(this).val();
	  $('#tablelist').attr('style','')
//////////////////////////////////////////////////////////////////Search picked date in booked date array and load bookd table details /////////////////////// 
			if(disabledDays.indexOf(currentDate) != -1){

				var datastring = 'date='+currentDate+'&action=tables';
				$('#tablelist').html('');
				$('.mainbodyLabel').html(currentDate+' Table Booking status');
				$.post(serviceURLHR+'listTable.php',function(alltbl){
					var alltables = alltbl.alltable;
					
					$.each(alltables, function(index, alltables) {
							$('#tablelist').append('<li  class="aval"  id="'+alltables.tid+'"><a href="#">'+
													'<div class="status-icon"><img src="images/icon-table.png" alt="" border="0" /></div>'+
													'<div class="status-text">'+
													alltables.tab_nam+
													//'<h5>01</h5>'+
													'</div>'+
													'</a>'+
													'</li>');
						});	
					
					
									$.post(serviceURLHR+'listTableBooked.php',datastring,function(tbls){
											var tablelist = tbls.tablelist;
											
											$('#tablelist').find('#'+tablelist.tableid).attr('class','notaval');
											$('#tablelist').find('#'+tablelist.tableid).addClass('bookedday');
											$('#tablelist').find('#'+tablelist.tableid+' a').attr('id','status-selected');
											$('#tablelist').find('#'+tablelist.tableid).attr('date-date',currentDate);
											$.each(tablelist, function(index, tablelist) {
												$('#tablelist').find('#'+tablelist.tableid).attr('class','notaval');
												$('#tablelist').find('#'+tablelist.tableid).addClass('bookedday');
												$('#tablelist').find('#'+tablelist.tableid).attr('date-date',currentDate);
											});
								   },'json');
				},'json');
			}


        var date = $(this).val();
        $('#pickdate').val(date);
		var data = 'date='+date;

		$.post(serviceURLHR+'totalIncome.php',data,function(o){
			$("#totalcoll").val(o);
		});
		
    }
	});
});


//////////////////////////////////////////////////////////// List all menu category from database ////////////////////////////////////

var catlist;
function listAllCategory(){
$.getJSON(serviceURLHR + 'listCategory.php', function(data) {
		$('#busy').hide();
		$('#available').html('');
		catlist = data.category;
		$.each(catlist, function(index, catlist) {
				if(catlist.status == '1' ){
				$('#menucategory').append('<li  class="menucat" id="'+catlist.cat_id+'"><span>'+catlist.category+'</span>'+ 
				'<div class="categ-icon">'+
				'<img id="active" class="status" src="images/active.png" alt="" border="0" />'+
				'<img id="edit" src="images/edit.png" alt="" /></div></li>');
				
				}else{
				$('#menucategory').append('<li  class="menucat" id="'+catlist.cat_id+'"><span>'+catlist.category+'</span>'+ 
				'<div class="categ-icon">'+
				'<img id="inactive" class="status" src="images/deactive.png" alt="" border="0" />'+
				'<img id="edit" src="images/edit.png" alt="" /></div></li>');	
				}
		});
		$('#menucategory').append('<input type="button" class="menucatnew" value="Add New Category"/>');
		$('#menucategory').append('<input type="button" class="newcuisine" value="Add New Cuisine"/>');
	});
}

//////////////////////////////////////////////// Add new cuisine //////////////////////////////////////////////

$('.newcuisine').live('click',function(){
		currentitem=	$(this);
		createNewCuisine(currentitem)
});
function createNewCuisine(currentitem){
	currentitem.remove();
	$('#menucategory').append('<li class="newcueli"><form id="newcuisine"><input type="text" name="newcue" id="newcue"/>'+
				   '<img id="addnewcue" src="images/save-ico.jpg" class="floaright" /></form></li>');
}

$('#addnewcue').live('click',function(){
	currentitem = $(this);
	saveNewCuisine(currentitem)
});
function saveNewCuisine(currentitem){
	var datastring = $('#newcuisine').serialize();
	var catname =$('#newcue').val();

	$.post(serviceURLHR + 'manage_cuisines.php',datastring,function(res){
		$('#newcategory').remove();
		currentitem.parent().parent().remove();
		$('#menucategory').append('<input type="button" class="newcuisine" value="Add New Cuisine"/>');
				
	});

}


////////////////////////////////////////////////  Change Status when click Status icon ////////////////////////////////


$('#active').live('click',function(){
	currentitem =$(this);
	active(currentitem);
});

function active(currentitem){
	var catid = currentitem.parent().parent().attr('id');
	$.get(serviceURLHR + 'managecategory.php?catid='+catid+"&status=0",function(o){
		currentitem.attr('id','inactive');
		currentitem.attr('src','images/deactive.png');
	});
}


$('#inactive').live('click',function(){
	currentitem =$(this);
	deactivateCategory(currentitem);
});

function deactivateCategory(currentitem){
	var catid = currentitem.parent().parent().attr('id');
	$.get(serviceURLHR + 'managecategory.php?catid='+catid+"&status=1",function(o){
		currentitem.attr('id','active');
		currentitem.attr('src','images/active.png');												  
	});	
}

////////////////////////////////////////////////   Make a form for create new category ////////////////////////////////////////

$('.menucatnew').live('click',function(){
		currentitem=	$(this);
		createNewCategory(currentitem)
});
function createNewCategory(currentitem){
	currentitem.before('<li class="newcatli"><form id="newcategory"><input type="text" name="newcat" id="newcat"/>'+
				   '<img id="addnewcat" src="images/save-ico.jpg" class="floaright" /></form></li>');
}
////////////////////////////////////////////// Submit new category and set added category to current window//////////////////////////////
$('#addnewcat').live('click',function(){
	currentitem = $(this);
	saveNewCategory(currentitem)
});
function saveNewCategory(currentitem){
	var datastring = $('#newcategory').serialize();
	var catname =$('#newcat').val();
	if(catname!=''){
	$.post(serviceURLHR + 'managecategory.php',datastring,function(res){
		$('#newcategory').remove();
		currentitem.parent().parent().remove();
		$('.menucatnew').before('<li  class="menucat" id="'+res+'"><span>'+catname+'</span>'+ 
				'<div class="categ-icon">'+
				'<img id="inactive" class="status" src="images/active.png" alt="" border="0" />'+
				'<img id="edit" src="images/edit.png" alt="" /></div></li>');
				
	});
	}else{
		currentitem.parent().parent().remove();
		$('#newcategory').remove();
	}	
}
////////////////////////////////////////////////////////  Set a new form for edit category ////////////////////////////////////////////////////
$('#edit').live('click',function(){
	currentitem=$(this);	
	editCategoryForm(currentitem);
});

function editCategoryForm(currentitem){
	var catid= currentitem.parent().parent().attr('id');	
	var catname = currentitem.parent().parent().find('span').text();	
		currentitem.parent().parent().html('<form id="updatecategory">'+
							  '<input type="hidden" name="catid" value="'+catid+'" id="catid"/>'+
							  '<input type="text" name="newcat" value="'+catname+'" id="newcat"/>'+
							  '<img id="updatecat"  src="images/save-ico.jpg" class="floaright" /></form>');	
}

///////////////////////////////////////////////////////// Update category and set new name to current window /////////////////////////////////

$('#updatecat').live('click',function(){
var currentitem = $(this);
updateCategory(currentitem)
});

function updateCategory(currentitem){
	var datastring 	= $('#updatecategory').serialize();
	var catid		= $('#catid').parent().val();
	var newname		= $('#newcat').val();
	$.post(serviceURLHR + 'managecategory.php',datastring,function(data){
		currentitem.parent().parent().html('<span>'+newname+'</span>'+ 
				'<div class="categ-icon">'+
				'<img id="active" class="status" src="images/active.png" alt="" border="0" />'+
				'<img id="edit" src="images/edit.png" alt="" /></div>')			   
	})
}



////////////////////////////////////////////////////////////  List all product type for add/modify Product page //////////////////////////////////

var productType;
$.getJSON(serviceURLHR + 'listCategory.php?load=type', function(data) {
		$('#busy').hide();
		$('#available').html('');
		productType = data.producttype;
	});
var cuisines;
$.getJSON(serviceURLHR + 'listCategory.php?load=cue', function(data) {
		cuisines = data.cuisines;
	});


//////////////////////////////////////////////////////////// Load users details if click table booked days /////////////////////////////////////////
$('.bookedday').live('click',function(){
	 currentitem=$(this);
	 loadTblBookedUsers(currentitem);
});

function loadTblBookedUsers(currentitem){
$('#tablelist').attr('style','background:#fff; padding:10px');
	var tableid = currentitem.attr('id');
	var pickDate = currentitem.attr('date-date');
	var datalist = 'tableid='+tableid+"&date="+pickDate+"&action=users";
	$.post(serviceURLHR+'bookedusers.php',datalist,function(userdetails){
			
			var bookeduserdetails = userdetails.userdetails;
			$('#tablelist').html('<table width="100%" class="userlist" border="0" cellspacing="0" cellpadding="0"></table>');
				if(!bookeduserdetails.length){
			$('.userlist').append('<tr>'+
					'<td><strong>Name :</strong> '+ bookeduserdetails.name +' </td>'+
				 '</tr><tr><td><strong>Address :</strong> '+bookeduserdetails.address+' </td>'+
				  '</tr><tr>'+
					'<td><strong>Phone :</strong> '+bookeduserdetails.phone+' </td>'+
				  '</tr><tr>'+
					'<td><strong>E-mail:</strong> '+bookeduserdetails.email+'</td>'+
				  '</tr><tr>'+
					'<td><strong>Book Date :</strong> '+bookeduserdetails.date+' </td>'+
				  '</tr><tr>'+
					'<td><strong>Book Time:</strong> '+bookeduserdetails.timefrom+' to '+bookeduserdetails.timeto+' </td>'+
				  '</tr><tr>'+
					'<td height="1px" bgcolor="#CCCCCC"></td>'+
				  '</tr>');
				}
				if(bookeduserdetails.length > 1){
			$.each(bookeduserdetails, function(index, bookeduserdetails) {
			
				$('.userlist').append('<tr>'+
					'<td><strong>Name :</strong> '+ bookeduserdetails.name +' </td>'+
				 '</tr><tr><td><strong>Address :</strong> '+bookeduserdetails.address+' </td>'+
				  '</tr><tr>'+
					'<td><strong>Phone :</strong>'+bookeduserdetails.phone+' </td>'+
				  '</tr><tr>'+
					'<td><strong>E-mail:</strong>'+bookeduserdetails.email+'</td>'+
				  '</tr><tr>'+
					'<td><strong>Book Date :</strong>'+bookeduserdetails.date+' </td>'+
				  '</tr><tr>'+
					'<td><strong>Book Time:</strong>'+bookeduserdetails.timefrom+' to '+bookeduserdetails.timeto+' </td>'+
				  '</tr><tr>'+
					'<td height="1px" bgcolor="#CCCCCC"></td>'+
				  '</tr>');
			});
				}
				
			$('#tablelist').append('<div class="backtoTables category-status-button2">Go Back</div>');	
				
			
	},'json');
	
	
		
}

//////////////////////////////////////////////  Set menu item to main window, if click on menu category /////////////////////////////////////////

$('.menucat').live('click',function(){
	currentitem = $(this);
	displayCategoryItems(currentitem);
});
function displayCategoryItems(currentitem){
	var catid = currentitem.attr('id');
	var catname = currentitem.find('span').text();
	$('.mainbodyLabel').html(catname+' Items');
	$.getJSON(serviceURLHR + 'loadMenu.php?catid='+catid,function(data){
		var menuitems = data.items;
		$('#tablelist').html('');
		
		$.each(menuitems, function(index, menuitems) {
				$('#tablelist').append('<div class="menuitems category-status" id="'+menuitems.item_id+'">'+
									   '<img src="'+hosturl+'upload/thumb/'+menuitems.image+'" width="120px">'+menuitems.item_name+'</div>');
		});
		$('#tablelist').append('<div class="menuitemsnew category-status-button" data-cat="'+catid+'" data-cname="'+catname+'" id="newitem">'+
							   'Add New Item to '+catname+'<div class="category-add-icon"><img src="images/icon-add.png" alt="" />'+
							   '</div></div><div class="bookedday" style="display:none"></div><div class="backtoTables color-button2">Go Back</div>');
		
	})
}


//////////////////////////////////////////////// If click menu item, setup a new form for edit menu ///////////////////////////////////////////
$('.menuitems').live('click',function(){
	currentitem =$(this); 								  
	editmenuItem(currentitem);
});

function editmenuItem(currentitem){
	var itemid = currentitem.attr('id');
	$('#tablelist').html('');

	$.getJSON(serviceURLHR + 'singleItem.php?item_id='+itemid,function(data){
		var itemdetails = data.items
		var category =itemdetails.cat_id;
		var item_type =itemdetails.item_type;
		$('#tablelist').append('<form id="updateproduct"><table width="100%" border="0"  class="table-holder" cellspacing="0" cellpadding="0">'+
							  '<tr>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
							  '</tr><tr>'+
								'<td><translate>Product Name</translate></td>'+
								'<td><input name="itemid" type="hidden" value="'+itemdetails.item_id+'" id="itemid" />'+
								'<input name="productname" type="text" value="'+itemdetails.item_name+'" id="productname" /></td>'+
								'<td><translate>Product Category</translate></td>'+
								'<td><select name="productCategory" id="productCategory">'+
								'</select>'+
								'</td>'+
							  '</tr><tr>'+
								'<td><translate>Product Type</translate></td>'+
								'<td><select name="productType" id="productType">'+
									'</select></td>'+
								'<td><translate>Description</translate></td>'+
								'<td><textarea name="description" id="description">'+itemdetails.item_desc+'</textarea></td>'+
							 '</tr><tr>'+
								'<td><translate>Cuisines</translate></td>'+
								'<td><select id="cuisines" name="cuisines"></select></td>'+
								'<td></td>'+
								'<td></td>'+
							  '</tr><tr>'+
								'<td><translate>Price</translate></td>'+
								'<td><input name="price" type="text" id="price" value="'+itemdetails.price+'"  /></td>'+
								'<td><translate>Quantity</translate></td>'+
								'<td><input name="quantity" type="text" value="'+itemdetails.qty+'"  id="quantity" /></td>'+
							  '</tr><tr>'+
								'<td><translate>Packing Charge</translate></td>'+
								'<td><input name="deliveryCharge" type="text" value="'+itemdetails.delivery_charge+'"  id="deliveryCharge" /></td>'+
								'<td><translate>Image</translate></td>'+
								'<td><img src="'+hosturl+'upload/thumb/'+itemdetails.image+'" width="80px">'+
								'<input type="file" class="table-nobord" name="image"></td>'+
							  '</tr><tr>'+
								'<td><translate>Changes Status</translate></td>'+
								'<td class="itemstatus"></td>'+
								'<td>&nbsp;</td>'+
								'<td><input type="button" id="submit" class="color-button3" value="Update"></td>'+
							  '</tr>'+
							'</table></form>');

			if(itemdetails.status == 'Active'){
				$('.itemstatus').html('<a href="#" class="toggleStatus" data-menuid="'+itemdetails.item_id+'" id="iteminactive"><img src="images/active.png"></a>');
			}else{
				$('.itemstatus').html('<a href="#" class="toggleStatus" data-menuid="'+itemdetails.item_id+'" id="itemactive"><img src="images/deactive.png"></a>');
			}	
		
		$.each(catlist, function(index, catlist) {
			 if(itemdetails.cat_id == catlist.cat_id){
				 $('#productCategory').append('<option value="'+catlist.cat_id+'" selected="selected">'+catlist.category+'</option>');
			 }else{
				$('#productCategory').append('<option value="'+catlist.cat_id+'">'+catlist.category+'</option>');
			 }
		});
		$.each(productType, function(index, productType) {
			if(itemdetails.item_type == productType.food_id){
				$('#productType').append('<option value="'+productType.food_id+'" selected="selected">'+productType.food_type+'</option>');
			}else{
				$('#productType').append('<option value="'+productType.food_id+'">'+productType.food_type+'</option>');
			}
		});
		$.each(cuisines, function(index, cuisines) {
								
			if(itemdetails.cuisines_id == cuisines.cu_id){
				$('#cuisines').append('<option value="'+cuisines.cu_id+'" selected="selected">'+cuisines.cuisines_name+'</option>');
			}else{
				$('#cuisines').append('<option value="'+cuisines.cu_id+'">'+cuisines.cuisines_name+'</option>');
			}
		});
		

	});
}


///////////////////////////////////////////////////// Toggle Item status ////////////////////////////////////////////////////

$('.toggleStatus').live('click',function(){
	var itemid = $(this).attr('data-menuid');
	var currentstatus = $(this).attr('id');
	switch(currentstatus){
		case "iteminactive"	: var status ="Inactive";break;
		case "itemactive" : var status ="Active";break;
	}
	$.get(serviceURLHR + 'singleItem.php?itemid='+itemid+"&status="+status,function(){
		if( status== 'Active'){
			$('.itemstatus').html('<a href="#" class="toggleStatus" data-menuid="'+itemid+'" id="iteminactive"><img src="images/active.png"></a>');
		}else{
			$('.itemstatus').html('<a href="#" class="toggleStatus" data-menuid="'+itemid+'" id="itemactive"><img src="images/deactive.png"></a>');
		}																			  
	});
	
});


/////////////////////////////////////////////////////  Submit edited menu item ////////////////////////////////////////////////////
$('#submit').live('click',function(msg){
	updateMenuItems();
});
function updateMenuItems(){
	var dataString = $('#updateproduct').serialize();

	var formData = new FormData($('form')[0]);
    $.ajax({
        url: serviceURLHR + 'singleItem.php',  //Server script to process data
        type: 'POST',
        data: formData,
		processData: false,  // tell jQuery not to process the data
  		contentType: false ,  // tell jQuery not to set contentType
		success: function(data){
				if(data=='success'){
				alert("Item successfully updated.");
				window.location="../index.html";
			}
		}
	});	
}
/////////////////////////////////////////////////////// Setup a new form for create new menu item/////////////////////////////////////////////// 
$('.menuitemsnew').live('click',function(){
	currentitem = $(this);
	createNewMenuItem(currentitem);
});

function createNewMenuItem(currentitem){
$('#tablelist').html('');
	var catid = currentitem.attr('data-cat');
	var catname = currentitem.attr('data-cname');
	$('#tablelist').append('<form id="newproduct" enctype="multipart/form-data">'+
						   '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="table-holder">'+
							  '<tr>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
							  '</tr><tr>'+
								'<td><translate>Product Name</translate></td>'+
								'<td><input name="productname" type="text" value="" id="productname" /></td>'+
								'<td><translate>Product Category</translate></td>'+
								'<td><input type="hidden" name="productCategory" id="productCategory" value="'+catid+'"/>: '+catname+
								'</td>'+
							  '</tr><tr>'+
								'<td><translate>Product Type</translate></td>'+
								'<td><select name="productType" id="productType">'+
									'</select></td>'+
								'<td><translate>Description</translate></td>'+
								'<td><textarea name="description" id="description"></textarea></td>'+
							 '</tr><tr>'+
								'<td><translate>Cuisines</translate></td>'+
								'<td><select id="cuisines" name="cuisines"></select></td>'+
								'<td></td>'+
								'<td></td>'+
							  '</tr><tr>'+
								'<td><translate>Price</translate></td>'+
								'<td><input name="price" type="text" id="price" value=""  /></td>'+
								'<td><translate>Quantity</translate></td>'+
								'<td><input name="quantity" type="text" value=""  id="quantity" /></td>'+
							  '</tr><tr>'+
								'<td><translate>Packing Charge</translate></td>'+
								'<td><input name="deliveryCharge" type="text" value=""  id="deliveryCharge" /></td>'+
								'<td><translate>Image</translate></td>'+
								'<td><input type="file" name="image" class="table-nobord"></td>'+
							  '</tr><tr>'+
								'<td><translate>Status</translate></td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td><input type="button" id="create" class="color-button3" value="Save"></td>'+
							  '</tr>'+
							'</table></form>');	
	$.each(catlist, function(index, catlist) {
				$('#productCategory').append('<option value="'+catlist.cat_id+'">'+catlist.category+'</option>');
		});
		$.each(productType, function(index, productType) {
				$('#productType').append('<option value="'+productType.food_id+'">'+productType.food_type+'</option>');
		});	
		
		$.each(cuisines, function(index, cuisines) {
				$('#cuisines').append('<option value="'+cuisines.cu_id+'">'+cuisines.cuisines_name+'</option>');
		});
}


/////////////////////////////////////////////////////////  Submit new menu item to db ////////////////////////////////////////////////////////

$('#create').live('click',function(){
	currentitem = $(this);							   
	saveNewMenuItem(currentitem);
});

function saveNewMenuItem(currentitem){
//var dataString = $('#newproduct').serialize();

	var productName	= $('#productname').val();
	var price =$('#price').val();
	var description = $('#description').val();
	var productCategory = $('#productCategory').val();
	//alert(productCategory);
	$('#busy').show();
	if(productName.length > 2  && price.length !='' && description.length > 2 ){
	
		var formData = new FormData($('form')[0]);
		$.ajax({
			url: serviceURLHR + 'singleItem.php',  //Server script to process data
			type: 'POST',
			data: formData,
			processData: false,  // tell jQuery not to process the data
			contentType: false ,  // tell jQuery not to set contentType
			success: function(data){
				$('#busy').hide();
					alert(data);
					displayCategoryItems($('#'+productCategory));	
					//window.location= "../index.html";
			}
		});
		
	}else{
		alert('Please fill all fields');	
	}	
}

//////////////////////////////////////////////////////////////////// create new form for create table//////////////////////////////////////////////

$('.newTAble').live('click',function(){
	$(this).before('<li  class="createTable" style="display:none;"><a href="#">'+
				   '<input type="text" id="newtable" name="newtable" style="width:80px;">'+
				   '<input type="button" class="color-button2" value="Save" id="savetable">'+
				   '<input type="button" class="color-button2" value="Cancel" id="cancel"></a>'+
					'</li>');
	$('.createTable').fadeIn();	
	
});

//////////////////////////////////////////////////////////////// Save new menu item to db ///////////////////////////////////////////////////////
$('#savetable').live('click',function(){
	var tablename = $('#newtable').val();
	var datastring='tablename='+tablename;
	var currentitem =$(this);
	if(tablename!=''){
	$.post(serviceURLHR + 'manageTable.php',datastring,function(resp){
			currentitem.parent().remove();
			$('.newTAble').before('<li  class="aval tablehistory"  id="'+resp+'"><a href="#">'+
										'<div class="status-icon"><img src="images/icon-table.png" alt="" border="0" /></div>'+
										'<div class="status-text">'+
										tablename+
										''+//<h5>01</h5>
										'</div>'+
										'</a>'+
										'</li>');
			
			
			
			
	});
	}
});

////////////////////////////////////////////////////////////// Reset created form for create table ///////////////////////////////////////////////////
$('#cancel').live('click',function(){
	$(this).parent().fadeOut(300, function() { $(this).remove(); });

	//$(this).parent().remove();								   
});

//////////////////////////////////////////////////////////// Get table list (call on load) /////////////////////////////////////////////////////
function getTableList(){

	
	$.getJSON(serviceURLHR + 'searchavltable.php', function(data) {
		$('#busy').hide();
		$('#available').html('');
		var tablelist = data.table;
		
		$('#tablelist').html('');
		$.each(tablelist, function(index, tablelist) {
			if(tablelist.availability == 1 ){
				$('#tablelist').append('<li  class="aval tablehistory"  id="'+tablelist.tid+'"><a href="#">'+
										'<div class="status-icon"><img src="images/icon-table.png" alt="" border="0" /></div>'+
										'<div class="status-text">'+
										tablelist.tab_nam+
										''+//<h5>01</h5>
										'</div>'+
										'</a>'+
										'</li>');
			}else if(tablelist.availability == 2){
				$('#tablelist').append('<li  class="notaval notavaltable"  id="'+tablelist.tid+'"><a href="#" id="status-selected">'+
										'<div class="status-icon"><img src="images/icon-table.png" alt="" border="0" /></div>'+
										'<div class="status-text">'+
										tablelist.tab_nam+
										''+//<h5>01</h5>
										'</div>'+
										'</a>'+
										'</li>');

			}else{
				$('#tablelist').append('<li  class="notaval notavaltable"  id="'+tablelist.tid+'"><a href="#" id="status-selected">'+
										'<div class="status-icon"><img src="images/icon-table.png" alt="" border="0" /></div>'+
										'<div class="status-text">'+
										tablelist.tab_nam+
										''+//<h5>01</h5>
										'</div>'+
										'</a>'+
										'</li>');

			}
		});
		
		$('#tablelist').append('<li  class="newTAble"><div class="status-add"><a href="#" >'+
										'<div class="add-icon"><img src="images/icon-add.png" alt="" /></div>'+
										'<span>Add </span>'+
										'New Table'+
										'</a></div>'+
										'</div>'+
										'</a>'+
										'</li>');

		setInterval( resetCurrentTableStatus, 5000 );
	});
}

///////////////////////////////////////////////////////////////   GET ALL TABLES //////////////////////////////////////////////////

function getAllTableList() {
	
	$('#busy').show();
	$.getJSON(serviceURLHR + 'searchavltable.php', function(data) {
		$('#busy').hide();
	//	$('#available').html('');
		var tablelist = data.table;
		$.each(tablelist, function(index, tablelist) {
			$('#tablelist').append('<div class="aval" id="'+tablelist.tid+'">'+tablelist.tab_nam+'</div>');
		});
		$('#tablelist').append('<div class="bookedday" id="" style="display:none"></div>');

	});
}



////////////////////////////////////////////////////////////// bill_requested //////////////////////////////////////////////////

function resetCurrentTableStatus(){
	$.getJSON(serviceURLHR + 'searchavltable.php', function(data) {
		var tablelist = data.table;
		//alert($('#tablelist').find('.bookedday').length);
		$('#tablelist').find('.bill_requested').remove();	
		if($('#tablelist').find('.bookedday').length==0){
			$.each(tablelist, function(index, tablelist) {
				
				if(tablelist.availability == 1 ){
					$('#tablelist').find('#'+tablelist.tid).attr('class','aval tablehistory');
					$('#tablelist').find('#'+tablelist.tid).find('a').attr('id','');
				}else if(tablelist.availability == 2){

						
						$('#tablelist').find('#'+tablelist.tid).append('<a id="'+tablelist.tid+'" class="bill_requested"><br/> Bill Requested</a>');
						
			}else{
					$('#tablelist').find('#'+tablelist.tid).attr('class','notaval notavaltable');
					$('#tablelist').find('#'+tablelist.tid).find('a').attr('id','status-selected');
						if(tablelist.is_notify == 0){
									callNotification('1',tablelist.tab_nam+' occupied','New Person in '+tablelist.tab_nam);
								$.get(serviceURLHR + 'notification_tableoccupystatus.php?st=1&tid='+tablelist.tid,function(){
														   
								});
						}
				}
			});
		}
	});
	loadLastTableOrder();
}


function loadLastTableOrder(){
	$.getJSON(serviceURLHR + 'lastTableOrder.php',function(data){
		var lastOrder = data.tableOrder;
		
		$('.orderList').remove();
			$.each(lastOrder, function(index, lastOrder) {
									   var time = new Date(lastOrder.time).format("hh:MM");
								//	   alert(lastOrder.tableid);
					$('.lastTableOrders').append(' <tr class="orderList"><td>'+lastOrder.tab_nam+'</td>'+
											'<td>'+time+'</td>'+
											'<td>Rs. '+lastOrder.totalAmt+'</td></tr>');				   
			});
	});
};


/*else if(tablelist.availability == 2){
				$('#tablelist').append('<div class="notaval notavaltable" id="'+tablelist.tid+'">'+tablelist.tab_nam+'<br/> <a id="'+tablelist.tid+'" class="bill_requested">Bill Requested</a></div>');
			}*/

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var taxpers=0 ;
$('.notavaltable').live('click',function(){
	
		
	
	var tblid = $(this).attr('id');		
	var sum=0;
		$.get(serviceURLHR + 'viewbill.php?action=gettax', function(tax){
					var msg=tax.split("@@");
					taxpers	= msg[0];
					var seviceCharge =msg[1];
					$("#taxp").val(msg[0]);
					
				});
		
		
		
		$('#tablelist').attr('style','background:#fff; padding:10px');
	$.getJSON(serviceURLHR + 'viewbill.php?tblid='+tblid, function(data) {
		var billdata = data.billdetails;
		$('#tablelist').html('<table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr height="25px">'+
                   ' <td><strong><translate>Item</translate></strong></td>'+
                   ' <td><strong><translate>Qty</translate></strong></td><td><strong>Price</strong></td><td><strong>Total</strong></td></tr><tr  class="total">'+
                    '<td><strong><translate>Sub Total</translate></strong></td>'+
                    '<td>&nbsp;</td>'+
                    '<td>&nbsp;</td>'+
                    '<td><strong class="subtotalamt"></strong></td>'+
                  '</tr><tr height="25px">'+
                    '<td><strong><translate>Tax</translate> (<span id="taxpres"></span>) </strong><input type="hidden" value="" id="taxp"></td>'+
                    '<td>&nbsp;</td>'+
                    '<td>&nbsp;</td>'+
                    '<td class="taxamt"></td>'+
                 ' </tr><tr style="display:none" class="delchargetr" height="25px">'+
                   ' <td><strong><translate>Packing Charge</translate></strong></td>'+
                   ' <td>&nbsp;</td>'+
                    '<td>&nbsp;</td>'+
                   ' <td class="delcharge"></td>'+
				  '</tr><tr height="25px">'+
						'<td><strong><translate>Total</translate></strong></td>'+
						'<td>&nbsp;</td>'+
						'<td>&nbsp;</td>'+
						'<td><strong class="grandtotal"></strong></td></tr></table>');
			
			$("#taxpres").html(taxpers+ " %");
				
				
			$.each(billdata, function(index, billdata) {
			$('.total').before('<tr height="25px"><td>'+billdata.order_item_name+'</td><td>'+billdata.count+'</td><td>'+billdata.order_item_price+'</td><td class="totalamt">'+billdata.total_price+'</td> </tr>');
			sum += parseInt(billdata.total_price);
			});

			$('.subtotalamt').text(sum);	//Math.round(price*2)/2
		var tax		= sum*(taxpers/100);
	//alert(taxamt);
		$('.taxamt').text((Math.round(tax*100)/100));
	

		//$('.delcharge').text(delcharge);

		$('.grandtotal').text(sum+(Math.round(tax*100)/100));//+parseInt(delcharge)
			//alert(sum);
			
		$('#tablelist').append('<input type="button" id="'+tblid+'" value="Close Table" class="closetable color-button"><div class="bookedday" style="display:none"></div>');
		
		$('#tablelist').append('<div id="todayspayment"></div><div id="orderdetails"></div>');
		loadTablehistory(tblid);
	});

	//var tableid = $(this).attr('id');	
});
/////////////////////////////////////////////////////////// Close Table ////////////////////////////////////////////////////

$('.closetable').live('click',function(){
	var tableid = $(this).attr('id');
	$.get(serviceURLHR + 'closetable.php?tblid='+tableid, function(data){
		window.location="../index.html";													 
	})
});


//////////////////////////// ########################### Load Supplier details on load ###################################### 

function loadSupplier(){
$.getJSON(serviceURLHR + 'managesupplier.php', function(data) {
		$('#busy').hide();
		$('#available').html('');
		var supplier = data.supplier;
		
		
		$.each(supplier, function(index, supplier) {
				$('#supplierlist').append('<li class="loggedSupplier supplierlist" id="'+supplier.sid+'" ><a href="#">'+
											'<div class="status-icon"><img src="images/icon-supplier.png" alt="" width="45" height="45" border="0" /></div>'+
											'<div class="status-text">'+
											supplier.name+
											''+//<h5>01</h5>
											'</div>'+
											'</a>'+
											'</li>');
		});
		
		$('#supplierlist').append('<li class="addnewSupplier"><div class="status-add">'+
									'<a href="#">'+
									'<div class="add-icon"><img src="images/icon-add.png" alt="" /></div>'+
									'<span>Add </span>'+
									'New Supplier'+
									'</a></div>'+
									'</li>');
		setTimeout(function(){
			scroll.refresh();
		});
	});
}

///////////////////////////////////////////////////////// Show supplier name and number when click on supplier list ///////////////////////////

$('.supplierlist').live('click',function(){
	var sid = $(this).attr('id');	
	var currentitem = $(this);
	$.getJSON(	serviceURLHR + 'managesupplier.php?sid='+sid,function(data){
		var supplierdetails = data.supplier;
		$('.suppliercontact').remove();
		
		var supplierStatus = supplierdetails.status;
		if(supplierStatus == 0){
			var image = '<img src="images/active.png" data-status="1" id="activeSupplier">';
		}else{
			var image = '<img src="images/deactive.png" data-status="0" id="activeSupplier">';
		}
	
	$('#supplierlist').html('<form id="newSupplier"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="table-holder">'+
							  '<tr><td><translate>Name</translate></td>'+
								'<td><input type="hidden" name="sid" value="'+supplierdetails.sid+'">'+
								'<input name="suppliername" type="text" value="'+supplierdetails.name+'" id="name" /></td>'+
								'<td><translate>Phone</translate></td>'+
								'<td><input name="phone" type="text" id="phone" value="'+supplierdetails.contact+'" /></td>'+
							  '</tr><tr>'+
								'<td><translate>Address</translate></td>'+
								'<td><textarea name="address" id="address">'+supplierdetails.address+'</textarea></td>'+
								'<td><translate>City</translate></td>'+
								'<td><input name="city" type="text" id="city" value="'+supplierdetails.city+'" /></td>'+
							  '</tr><tr><td><translate>Username</translate></td>'+
								'<td><input name="username" type="text" id="username" value="'+supplierdetails.username+'" /></td>'+
								'<td><translate>Password</translate></td>'+
								'<td><input name="password" type="text" id="password" value="'+supplierdetails.passwd+'" /></td>'+
							  '</tr><tr>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>'+
								/*image+*/
								'<input type="button" id="updateSupplier" name="Submit" class="color-button3" value="Update" />'+
								'<input type="button" id="cancelSupplier" name="Submit" class="color-button3" value="Cancel" />'+
								/*'<input type="button" id="deleteSupplier" name="button" class="color-button3" value="Delete User" />'+*/
								'<td></td>'+
							  '</tr>'+
							'</table></form>');
});

});
$('#updateSupplier').live('click',function(){
	var datastring = $('#newSupplier').serialize();
	$.post(serviceURLHR + 'managesupplier.php',datastring,function(data){
		$('#supplierlist').html('');
		loadSupplier();							   
	})									   
});


$('#activeSupplier').live('click',function(){
	var status = $(this).attr('data-status');
	$.get(serviceURLHR+"")
});



//////////////////////////// ########################### Add New Supplier ###################################### /////////////////////////////
$('.addnewSupplier').live('click',function(){
		
	$('#supplierlist').html('<form id="newSupplier"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="table-holder">'+
							  '<tr><td><translate>Name</translate></td>'+
								'<td><input name="suppliername" type="text" id="name" /></td>'+
								'<td><translate>Phone</translate></td>'+
								'<td><input name="phone" type="text" id="phone" /></td>'+
							  '</tr><tr>'+
								'<td><translate>Address</translate></td>'+
								'<td><textarea name="address" id="address"></textarea></td>'+
								'<td><translate>City</translate></td>'+
								'<td><input name="city" type="text" id="city" /></td>'+
							  '</tr><tr>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
								'<td><input type="button" id="saveSupplier" name="Submit" class="color-button3" value="Submit" />'+
								'<input type="button" id="cancelSupplier" name="Submit" class="color-button3" value="Cancel" /><td></td>'+
							  '</tr>'+
							'</table></form>');
});

////////////////////////////////////////////////////// Cancel created supplier form and set supplier list ///////////////////////

$('#cancelSupplier').live('click',function(){
	$('#supplierlist').html('');
	loadSupplier();
	
});

////////////////////////////////////////////////// Submit new supplier //////////////////////////////////////////////////////

$('#saveSupplier').live('click',function(){
	var datastring = $('#newSupplier').serialize();
	$.post(serviceURLHR + 'managesupplier.php',datastring,function(data){
		$('#supplierlist').html('');
		loadSupplier();							   
	})
	
});
////////////////////////////////////////////////// If click options, display book a table, other options //////////////////////////////////
$('.options').live('click',function(){
	$('#menu_options').fadeIn();
})

///////////////////////////////////////////////// Table Booking - Cashier ////////////////////////////////////////////////////////////////
$('.bookatable').live('click',function(){
	
		$('#tablelist').html('<form class="checkAvl">'+
		'<table width="100%" border="0" cellspacing="0" cellpadding="0">'+
			  '<tr><td width="22%"><translate>Date</translate></td>'+
				'<td width="23%"><translate>Time From</translate></td>'+
				'<td width="21%"><translate>To</translate></td>'+
				'<td width="32%">&nbsp;</td>'+
				'<td width="2%">&nbsp;</td>'+
			  '</tr><tr>'+
				'<td><input name="date" type="text" id="datepicker"></td>'+
				'<td><input name="timefrom" type="text" id="timefrom" class="timepicker"></td>'+
				'<td><input name="timeto" type="text" id="timeto" class="timepicker"></td>'+
				'<td><input name="submit" type="button" id="searchavl" value="Search"></td>'+
				'<td>&nbsp;</td>'+
			  '</tr</table>'+
		'</form>');
		getAllTableList();
			
});
/////////////////////////////////////////////////////// Search Book ////////////////////////////////////////////////////////
$('#searchavl').live('click',function(){
	var datastring = $('.checkAvl').serialize();

	$.post(serviceURLHR + 'searchavltable.php',datastring,function(msg){
			$('#tablelist').find('.aval').attr('class','aval avaltable');
			$('#tablelist').find('.notaval').attr('class','aval avaltable');
		 var notavailable = msg.notavl;	

		 	$('#tablelist').find('#'+notavailable.tableid).attr('class','notaval');	
		$.each(notavailable, function(index, notavailable) {
			$('#tablelist').find('#'+notavailable.tableid).attr('class','notaval');			  
		});
		}, "json");
		
});
//////////////////////////////////////////////////////// Book Table /////////////////////////////////////////////////////////

$('.avaltable').live('click',function(){
	var id		 = $(this).attr('id');
	var bookdate = $('#datepicker').val();
	var timefrom = $('#timefrom').val();
	var timeto	 = $('#timeto').val();	
	
	$('#tablelist').html('<form id="booktableform">'+
							'<table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr>'+
							'<td width="28%">&nbsp;</td>'+
							'<td width="15%">&nbsp;</td>'+
							'<td width="28%">&nbsp;</td>'+
							'<td width="29%">&nbsp;</td>'+
						  '</tr> <tr>'+
							'<td>&nbsp;</td>'+
							'<td><translate>Name</translate></td>'+
							'<td><input name="name" type="text" id="name"></td>'+
							'<td>&nbsp;</td>'+
						  '</tr><tr>'+
							'<td>&nbsp;</td>'+
							'<td><translate>Address</translate></td>'+
							'<td><textarea name="address" id="address"></textarea></td>'+
							'<td>&nbsp;</td>'+
						  '</tr><tr>'+
							'<td>&nbsp;</td>'+
							'<td><translate>Phone</translate></td>'+
							'<td><input name="phone" type="text" id="phone"></td>'+
							'<td>&nbsp;</td>'+
						  '</tr><tr>'+
							'<td>&nbsp;</td>'+
							'<td><translate>E-mail</translate></td>'+
							'<td><input name="email" type="text" id="email"></td>'+
							'<td>&nbsp;</td>'+
						  '</tr><tr>'+
							'<td>&nbsp;</td>'+
							'<td>&nbsp;</td>'+
							'<td><input name="booktable" type="button" id="booktable" value="Book Table"></td>'+
							'<td>&nbsp;</td>'+
						  '</tr><tr>'+
							'<td>&nbsp;</td>'+
							'<td>&nbsp;</td>'+
							'<td>&nbsp;</td>'+
							'<td>&nbsp;</td>'+
						  '</tr></table></form>');
	
	$('#booktable').append("<input type='hidden' name='tblid' id='tblid' value='"+id+"' />");
	$('#booktable').append("<input type='hidden' name='bookdate' id='bookdate' value='"+bookdate+"' />");
	$('#booktable').append("<input type='hidden' name='timefrom' id='timefrom' value='"+timefrom+"' />");
	$('#booktable').append("<input type='hidden' name='timeto' id='timeto' value='"+timeto+"' />");
	
});
///////////////////////////////////////////////////////// Book table and save user details //////////////////////////////////


$('#booktable').live('click',function(){
	var datastring	= $('#booktableform').serialize();
	
	$.post(serviceURLHR+'newbooking.php',datastring,function(o){
			if(o=='success'){
				alert('Table booking successfull.');
				window.location ="../index.html";
			}
	})
	
});

//////////////////////////////////////////////////////// Manage Restaurent /////////////////////////////////////////////////

$('.managerestaurant').live('click',function(){
	$('#tablelist').html('<form class="managerestaurent">'+
	'<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'+
    '<td><translate>Restaurant Name</translate></td>'+
    '<td><input type="text" name="resname"  value="'+settings.restaurentname+'" /></td>'+
    '<td><translate>Address</translate></td>'+
    '<td><textarea name="resaddress" cols="" rows="">'+settings.address+'</textarea></td>'+
  	'</tr><tr>'+
    '<td><translate>Logo</translate></td>'+
    '<td><input type="file" name="logofile" /></td>'+
    '<td><translate>Home Image</translate></td>'+
    '<td><input type="file" name="homefile" /></td>'+
  	'</tr><tr>'+
    '<td>&nbsp;</td>'+
    '<td>&nbsp;</td>'+
    '<td>&nbsp;</td>'+
    '<td><input type="submit" id="saveRestaurantSettings" name="Submit" value="Submit" /></td>'+
  	'</tr></table></form>');											 
});
///////////////////////////////////////////////////////  Update Restaurent settings //////////////////////////////////////////

$('#saveRestaurantSettings').live('click',function(){
		window.location="../index.html";												   
});

//////////////////////////////////////////////////////////////// Table history today ///////////////////////////////////////////////

$('.tablehistory').live('click',function(){
	var tableid = $(this).attr('id');	
	$('#tablelist').html('<div id="todayspayment"></div><div id="orderdetails"></div>'+
						 '<div class="backtoTables category-status-button2">Go Back</div>'+
						 '<div class="deleteTable category-status-button2" data-id="'+tableid+'">Delete Table</div>');
	
	loadTablehistory(tableid);
})
$('.backtoTables').live('click',function(){
$('#tablelist').attr('style','');
getTableList();										 
});


$('.deleteTable').live('click',function(){
 var tableid =$(this).attr('data-id');
	var r=confirm("Are you Sure?");
		if (r==true)
		  {
			$.get( serviceURLHR+'listTable.php?tblid='+tableid,function(){
				alert("Table deleted.");												   
			});
		  }


});


$('.tblhistory').live('click',function(){
	$('.tblhistory').removeClass('tblhistorysel');
	$(this).addClass('tblhistorysel');
	var usercount = $(this).attr('data-user'); 
	loadBill(usercount);
});

var tableTotal =0;

function loadTablehistory(tableid){
	

	
	
	$.getJSON(serviceURLHR+'report_tablehistory.php?tblid='+tableid, function(data){
		var orderlist = data.orderlist;		
		$.each(orderlist, function(index, orderlist) {
				var taxamt =parseFloat(orderlist.totalamt)*(parseFloat(localStorage['tax'])/100)	//			   tax
				var total =parseFloat(taxamt)+parseFloat(orderlist.totalamt);
			$('#todayspayment').append('<div class="tblhistory category-status-button2" data-user="'+orderlist.bill_number+'" > Rs: '+total+"</div>");
			tableTotal +=parseFloat(orderlist.totalamt);
		});
		$('#todayspayment').append('<div class="category-status-button2" style="width:150px;background:#1080c7">Total Rs:'+tableTotal+'<div>');
	});
};


function loadBill(usercount){
	$('#orderdetails').html('<table width="100%" border="0" cellspacing="0" cellpadding="0" class="table-holder table-holder2"> <tr><td>&nbsp;</td>'+
                   ' <td><strong><translate>Item</translate></strong></td>'+
                   ' <td><strong><translate>Qty</translate></strong></td><td><strong>Price</strong></td><td><strong>Total</strong></td></tr><tr  class="totalamount">'+
                    '<td>&nbsp;</td>'+
                    '<td><strong><translate>Sub Total</translate></strong></td>'+
                    '<td>&nbsp;</td>'+
                    '<td>&nbsp;</td>'+
                    '<td><strong class="subtotal"></strong></td>'+
                  '</tr><tr><td>&nbsp;</td>'+
                    '<td><strong><translate>Tax</translate> (<span id="taxpresentage"></span>) </strong><input type="hidden" value="" id="taxp"></td>'+
                    '<td>&nbsp;</td>'+
                    '<td>&nbsp;</td>'+
                    '<td><strong class="taxamount"></strong></td>'+
                 ' </tr><tr style="display:none" class="delchargetr">'+
                    '<td>&nbsp;</td>'+
                   ' <td><translate>Delivery Charge</translate></td>'+
                   ' <td>&nbsp;</td>'+
                    '<td>&nbsp;</td>'+
                   ' <td class="delcharge"></td>'+
				  '</tr><tr><td>&nbsp;</td>'+
						'<td><strong><translate>Total</translate></strong></td>'+
						'<td>&nbsp;</td>'+
						'<td>&nbsp;</td>'+
						'<td><strong class="grandtotalamt"></strong></td></tr></table>');
	var sum=0;
		$.get(serviceURLHR + 'viewbill.php?action=gettax', function(tax){
					var msg=tax.split("@@");
					taxpers	= msg[0];
					var seviceCharge =msg[1];
					$("#taxp").val(msg[0]);
					
				});

	$.getJSON(serviceURLHR + 'viewbill.php?bill='+usercount, function(data) {
		var billdata = data.billdetails;

			$("#taxpres").html(taxpers+ " %");

			
			$.each(billdata, function(index, billdata) {
			$('.totalamount').before('<tr><td></td><td>'+billdata.order_item_name+'</td><td>'+billdata.count+'</td><td>'+billdata.order_item_price+'</td><td class="totalamt">'+billdata.total_price+'</td> </tr>');
			sum += parseInt(billdata.total_price);
			});

			$('.subtotal').text(sum);	//Math.round(price*2)/2
		var tax		= sum*(taxpers/100);
	//alert(taxamt);
		$('.taxamount').text((Math.round(tax*100)/100));
		

		//$('.delcharge').text(delcharge);

		$('.grandtotalamt').text(sum+(Math.round(tax*100)/100));//+parseInt(delcharge)
			//alert(sum);
			
		$('#tablelist').append('<input type="button" id="'+tblid+'" value="Close Table" class="closetable"><div class="bookedday" style="display:none"></div>');
	});
	
}
///////////////////////////////////////////////   Notification ///////////////////////////////////

setInterval( loadNotification, 2000 );
function loadNotification(){
	$.getJSON(serviceURLHR+'notification.php?action=load', function(data){
		var notifications = data.notifications;		
		$.each(notifications, function(index, notifications) {
								//	   alert(notifications.title);
			type = '1';
			title =notifications.title;
			msg =notifications.content;
			callNotification(type,title,msg);
			
			$.getJSON(serviceURLHR+'notification.php?action=update&nid='+notifications.id, function(data){ });
			
		});
	});
};


function createnotification( template, vars, opts ){
	return $container.notify("create", template, vars, opts);
}

$("#default").live('click',function(){
		callNotification('1','Table 5 occupied','New Person in table 5');
	});
function callNotification(type,title,msg){
		$container = $("#container").notify();
		switch (type){
			case '1':createnotification("default", { title:title, text:msg});break;
		};
}
/////////////////////////////////////////////////////// This function extract values from address ///////////////////////////
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function extractdatetime_to_time(datetime){
	var hours = datetime[11] + datetime[12];
        var min = datetime[14] + datetime[15];
        if (hours < 12) {
            return hours + ':' + min + ' AM';
        } else {
            hours=hours - 12;

            hours=(hours < 10) ? '0'+ hours : hours;
            return hours+ ':' + min + ' PM';
        }
	
}


$('.takeaway').click(function(){
	localStorage['homedelivery']='2';
	if(localStorage['userdetails']){
		window.location = "home.html";	
	}else{
		window.location = "http://"+localStorage['serviceIp']+"/kotz/user/userdetailshomedel.html";
	}
});

$('.homedelivery').click(function(){
	localStorage['homedelivery']='1';
	if(localStorage['userdetails']){
		window.location = "http://"+localStorage['serviceIp']+"/kotz/user/home.html";	
	}else{
		window.location = "http://"+localStorage['serviceIp']+"/kotz/user/userdetailshomedel.html";
	}
});
$('.booktable').click(function(){
	window.location = "http://"+localStorage['serviceIp']+"/kotz/user/booktable.html";
});
$('.dinein').click(function(){
	localStorage['homedelivery']='0';
	window.location = "http://"+localStorage['serviceIp']+"/kotz/user/home.html";							  
});
