// Reservation page - Javascript
$(document).ready(function() {
	Initialize();
});
/**
 * This function loads when the page loads.
 * It calls all the functions that need to be called when setting up the page.
 */
Initialize = function(){
	SetDateTime(null);
	SetupDatePicker();
	SetupTimeSlots();
	SetupUiElements();
	//load the cart onload
	LoadCart();
	//Reset button for cart
	$("#cart-reset-btn").click(function(){
		CancelAllReservationsClick();
	});
}
/******************* AJAX METHODS *********************/
/**
 * When a user clicks an available timeslot this function is called.
 * This function takes the date, time, cage id and the rate of the clicked slot
 * and processes the transatction through ajax and reloads the timetable and cart
 */
MakeAjaxReservation = function(date,time,cage,rate)
{
	/***** Process the reservation via ajax and update the cart *****/
	var d = date;
	var t = time;
	var c = cage;
	var r = rate;
	var rt = "update";
	var cc = $("#phCartRows").html();
	$("#phCartRows").load("scripts/process-cart.php", {reqType:rt,cartCode:cc,dateSelected:d,timeSelected:t,cageSelected:c,rateSelected:r,sid:Math.random()},function(){
		UpdateCart(d,t,c,r);
 	});
}

LoadTimetable = function(sDate)
{
	var d = sDate;
	//call ajax file that creates table cells and insert them into the tbody
    $("#phTimeSlotRows").load("scripts/load-time-slot-table.php", {date:d},function(){
		
		LoadReservedSlots(d);
	});
}

LoadReservedSlots = function(sDate)
{
	var d = sDate;
	var url = "scripts/load-reserved-time-slots.php?sDate=" + sDate;
	
	$.getJSON(url,
        function(data){
		if(data != null)
		{
			$.each(data, function(i,item){
				var cell = ("#" + item.date + "-" + item.time + "0" + item.cage);
				if(item.isowner)
				{
					UpdateCart(item.date,item.time,item.cage,"");
				}
				else
				{
					$(cell).addClass("booked");
					$(cell).removeClass("live");
					$(cell).removeAttr("onclick");
				}
			 });
		}         
     });
}
LoadCart = function()
{
	var dateNow = new Date();
	var d = dateNow.getFullYear() + "-" + (dateNow.getMonth() + 1) + "-" + dateNow.getDate();	
	var t = "";
	var c = 1;
	var r = "";
	var rt = "load";
	var cc = $("#phCartRows").html();
	$("#phCartRows").load("scripts/process-cart.php", {reqType:rt,cartCode:cc,dateSelected:d,timeSelected:t,cageSelected:c,rateSelected:r},function(){
		CalculateTotal();
	});
}
UpdateCart = function(cartDate,cartTime,cartCage,cartRate)
{
	/***** Perform various user interface functions, changes the cell to be selected and adds a cancel event *****/
	var cell = $("#" + cartDate + "-" + cartTime + "0" + cartCage);
	//console.log("#" + cartDate + "-" + cartTime + "0" + cartCage);
	//highlight cell and set it to selected
	$(cell).addClass("selected");
	$(cell).effect("highlight", {color: 'orange',mode: 'show'}, 250);
	//remove onclick attribute and add new one
	$(cell).removeAttr("onclick");
	//add new click event params
	$(cell).click(function(){
		var cd = cartDate;
		var ct = cartTime;
		var cc = cartCage;
		var cr = cartRate;
		var rid = $("#cartRow-" + cartTime + cartCage).attr("rel");
		CancelClick(cd,ct,cc,cr,rid);
		$(this).removeClass("selected");
  	});
	
	/***** UPDATE THE TOTAL *****/
	CalculateTotal();
	var cc = $("#phCartRows").html();
	var ct = $("#cart-total").html();
	
}
CancelAllReservationsClick = function()
{
		$.ajax({
		type: "POST",
		url: "scripts/process-cancel-all-reservations.php",
		data: "",
		dataType: "html",
		success: function(data){
			// do something with the response
		}
	});
	//reload the shopping cart
	LoadCart();
	
	//get the date today and reload the shopping cart
	var dateNow = new Date();
	var d = dateNow.getFullYear() + "-" + (dateNow.getMonth() + 1) + "-" + dateNow.getDate();	
	LoadTimetable(d);
}
CancelClick = function(cartDate,cartTime,cartCage,cartRate,reservationID)
{
	var cell = $("#" + cartDate + "-" + cartTime + "0" + cartCage);
	//console.log("find this cell: " + cartDate + "-" + cartTime + "0" + cartCage);
	var sCartCage = cartCage;
	if(sCartCage == "1")
		sCartCage = sCartCage + " Mega";
	if(sCartCage == "5" || sCartCage == "6")
		sCartCage = sCartCage + " (Basketball)";
		
	var titleString = "Cage " + sCartCage + "<br />" + cartTime + ":00 to " + (parseInt(cartTime) + 1).toString() +  ":00<br />$" + cartRate;
	var s = "<a title='" + titleString + "' id='" + cartDate + "-" + cartTime + "0" + cartCage + "' class='live' onclick=\"MakeAjaxReservation('" + cartDate + "','" + cartTime + "','" + cartCage + "','" + cartRate + "')\" href='#'  />";
	//console.log(s);
	$(cell).replaceWith(s);
	$("#cartRow-" + cartTime + cartCage).remove();
	$(".qtip").qtip("hide");
	/***** UPDATE THE TOTAL ****/
	CalculateTotal();
	var cc = $("#phCartRows").html();
	var ct = $("#cart-total").html();
	
	/***** Cancel Reservation ******/
	$.ajax({
		type: "POST",
		url: "scripts/process-cancel-reservation.php",
		data: "resID=" + reservationID,
		dataType: "html",
		success: function(data){
			// do something with the response
		}
	});
	
	
	
}
SetupUiElements = function()
{
	//message box that shows when user clicks on unavailable slot
	$("#dialog").dialog({ autoOpen: false });	
	$("#logged-out").dialog({ autoOpen: false });	
	
	//setup rollovers in the dynamically generated cart
	SetupCartRollovers();
	
	
}
CalculateTotal = function()
{
		var totalLabel = document.getElementById("cart-total");
		var total = 0;

		$(".cart-cage-rate").each(function(i) {
			total += parseFloat(this.innerHTML);
		});
		////console.log("Rate: " + total.toString());
		total = formatAsMoney(total);
		totalLabel.innerHTML = total.toString();
}
/**** This function rounds any number down to 2 decimal places and makes it nice and pretty to look like money, it is used in CalculateTotal *****/
formatAsMoney = function(ObjVal)
{
	 //Obj.value = formatAsMny(Obj.value)
	 mnt = ObjVal;
	 mnt -= 0;
	 mnt = (Math.round(mnt*100))/100;
	 ObjVal = (mnt == Math.floor(mnt)) ? mnt + '.00' : ( (mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);
	 if (isNaN(ObjVal)) {ObjVal ="0.00";}
	 return ObjVal;
}
/******************* PAGE SETUP METHODS *********************/
SetupDatePicker = function()
{	
	//DATEPICKER
	$("#calendar-widget").datepicker({ onSelect: function(dateText, inst) { SetDateTime(dateText); }, dateFormat: 'yy-mm-dd' });
}
SetupTimeSlots = function()
{
	//disable default hyperlink action on all cells
	$(".booked,.live,.cartLink").live('click',function(e){
	 	 e.preventDefault();
	 });	
	$(".booked").live('click',function(){ $("#dialog").dialog('open'); });
	$(".logged-out").live('click',function(){ $("#logged-out").dialog('open'); });
	//tooltips that appear when you roll over a timeslot
	$(".live").live('mouseover',function(){
		if (!$(this).data('init'))
        {
            $(this).data('init', true);
            $(this).qtip({ style: { 
      width: 200,
      padding: 5,
      color: 'black',
      textAlign: 'center',
      border: {
         width: 7,
         radius: 5
      },
      tip: 'bottomLeft',
      name: 'light' // Inherit the rest of the attributes from the preset dark style
   },position: {
      corner: {
         target: 'topRight',
         tooltip: 'bottomLeft'
      }
   } });
            $(this).trigger('mouseover');
        }
	 });
	
}
SetupCartRollovers = function()
{
	$(".cartRow").live("mouseover",function(){$(this).toggleClass("highlight");});
	$(".cartRow").live("mouseout",function(){$(this).toggleClass("highlight");});
}
/**** SET DATE TIME:
	This function is called when the page initially loads. When the page loads for the first time it is passed a null value.
	There are 2 different ways this logic will go.
	
	1. If the selected date is null we set selectedDate to todays date and load the timetable cells for today through the LoadTimetable() function.
	
	2. If the selectedDate has a value, which means the user has clicked a day on the calendar control, we will load the timetable for that day.
	
	This function also takes the selected day and converts it into a nice string to display at the top of the page, this is done for both scenarios.
*/
SetDateTime = function(selectedDate)
{
	// Array of day names
	var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
	// Array of month Names
	var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	//get todays date
	
	var niceDate;
	//if no date is selected, make todays date the selected date
	if(selectedDate == null)
	{
		//get todays date
		var dateNow = new Date();
		//if its a single digit day, add a zero before it
		var sDay = dateNow.getDate().toString();
		var sMonth = (dateNow.getMonth() + 1).toString();
		//console.log("sDay Length:" + sDay.length.toString());
		//console.log("sMonthLength:" + sDay.length.toString());
		if(sDay.length == 1)
		{
			sDay = "0" + sDay;
		}
		if(sMonth.length == 1)
		{
			sMonth = "0" + sMonth;	
		}
		selectedDate = dateNow.getFullYear() + "-" + (sMonth) + "-" + sDay;
		//format the date so its all purrrty
		niceDate = dayNames[dateNow.getDay()] + ", " + monthNames[dateNow.getMonth()] + " " + dateNow.getDate() + ", " + dateNow.getFullYear();
		
		//load timetable
		LoadTimetable(selectedDate);
	}
	else
	{
		var ds = selectedDate.split("-");
		//load timetable
		LoadTimetable(selectedDate);
		
		var dateObj = new Date(ds[0],(ds[1] - 1),ds[2]);
		//console.log(dateObj);
		niceDate = dayNames[dateObj.getDay()] + ", " + monthNames[dateObj.getMonth()] + " " + dateObj.getDate() + ", " + dateObj.getFullYear();
		
	}
	////console.log(selectedDate);
	//set the header and hidden field with selected date
	$("#headerDate").text(niceDate);
	$("#hfSelectedDate").val(selectedDate);
}

