//globals
var dateSelected = '';
var child;
function getSchedule(year, month, day)
{	
	var args = arguments;
	dateSelected = year+'-'+month+'-'+day;
	var xmlhttp =  new XMLHttpRequest();
	xmlhttp.open('POST', 'ajax_getSchedule.php', true);
	xmlhttp.onreadystatechange = function()
	{	
		if (xmlhttp.readyState == 4)
		{
			if (xmlhttp.status == 200)
			{
				processResponse(xmlhttp.responseXML);
			}
			else
			{
				var s = 'Error with AJAX in getSchedule(';
				for(var i=0; i<args.length; i++)
  				{
					s += args[i];
					if(i < args.length-1)
						s += ',';
				}
				s += ')';
				//alert(s);
			}
		}
	}
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send('year='+year+'&month='+month+'&day='+day+'&serviceSelectedId='+serviceSelectedId);
}
function processResponse(responseXML)
{
	if(responseXML.getElementsByTagName('day_of_week')[0].firstChild && responseXML.getElementsByTagName('date_formatted')[0].firstChild)
	{
		var date_formatted = responseXML.getElementsByTagName('date_formatted')[0].firstChild.data;
		showDateSelected(date_formatted);
		switch(responseXML.getElementsByTagName('day_of_week')[0].firstChild.data)
		{	
			case 'Sunday': showClosedInfo(); break;
			case 'Monday':
				if(date_formatted.indexOf('December') == -1)
					showClosedInfo();
				else
					showWeekdaySchedule(responseXML);				
				break;
			case 'Saturday': showSaturdaySchedule(responseXML); break;
			default: showWeekdaySchedule(responseXML);
		}
	}
}
function showSchedule(responseXML, startTime, numTimeSlots)
{
	var scheduleDiv = document.getElementById('scheduleDiv');
	if(responseXML.getElementsByTagName('num_booked_time_slots')[0].firstChild)
	{
		var num_booked_time_slots = responseXML.getElementsByTagName('num_booked_time_slots')[0].firstChild.data;
		var prospective_service_num_time_slots = responseXML.getElementsByTagName('prospective_service_num_time_slots')[0].firstChild.data;
		var minutes = '', nextHour = 0, count = 0, booked = false, html = '', customer_id = '';
		var booked_time_slot_id = '', booking_id = '', editBookingLink = '';
		html += '<table cellspacing="1" class="data">';
		html += '<tr><th>Time</th><th>Availability</th></tr>';
		//build string of booked time slots for each member of staff
		var staffBookedTimeSlots = [];
		var staffBookedHere = [];
		var prospective_service_staff_member_time_slots = [];
		var selectedDate = new Date();
		var timeslotIsInFuture;
		selectedDate.setFullYear(responseXML.getElementsByTagName('year')[0].firstChild.data);
		selectedDate.setDate(responseXML.getElementsByTagName('day')[0].firstChild.data);
		//javascript counts months from zero, note also the day is set first so that JS doesn't "repair" the month if the day is illegal for the month (e.g. 30th Feb)
		selectedDate.setMonth(parseInt(responseXML.getElementsByTagName('month')[0].firstChild.data, 10)-1); 
		var today = new Date();
		today.setSeconds(0);
		selectedDate.setSeconds(0);
		today.setMilliseconds(0);
		selectedDate.setMilliseconds(0);
		var dateIsInPast = selectedDate < today;
		var dateIsToday = selectedDate.getFullYear() == today.getFullYear()
								&& selectedDate.getMonth() == today.getMonth()
								&& selectedDate.getDate() == today.getDate();
		for(var i=0; i<staffIds.length; i++) //for each staff member
		{
			staffBookedTimeSlots[i] = []; //create an array
			prospective_service_staff_member_time_slots[i] = responseXML.getElementsByTagName('prospective_service_staff_member_time_slots')[i].firstChild.data.split(",");
			//alert(prospective_service_staff_member_time_slots[i].join(','));
			staffBookedHere[i] = false; //init staffBookedHere array to all false
		}
		//start hack
		var colleteInvolved = false;
		for(var i=0; i<prospective_service_staff_member_time_slots[0].length; i++) //check colette's time slots
		{
			if(prospective_service_staff_member_time_slots[0][i] == '1')
				colleteInvolved = true;
		}
		//end hack
		for(var t=startTime; count<numTimeSlots; count++)  //for every possible time slot
		{
			for(var i=0; i<staffBookedTimeSlots.length; i++) //for each staff member
			{
				for(var j=0; j<num_booked_time_slots; j++) //for every booked slot
				{
					//if the time of the booked slot matches this time and this staff_id, set the character to 1
					if(responseXML.getElementsByTagName('time')[j].firstChild.data == t && responseXML.getElementsByTagName('staff_id')[j].firstChild.data == staffIds[i])
					{
						staffBookedTimeSlots[i][count] = '1';
						staffBookedHere[i] = true;
					}
				}
				//otherwise set it to zero
				if(!staffBookedHere[i])
					staffBookedTimeSlots[i][count] = '0';
				else
					staffBookedHere[i] = false;
			}
			//increment time
			t = addFifteenMinutes(t);
		}
		count = 0;
		for(var t=startTime; count<numTimeSlots; count++)  //for every possible time slot
		{
			//init variables
			booked = false;
			staff_id = '';
			booked_time_slot_id = '';
			editBookingLink = '';
			//show time
			html += '<tr><td>'+t+'</td>';			
			for(var i=0; i<num_booked_time_slots; i++) //for every booked slot
			{
				if(responseXML.getElementsByTagName('time')[i].firstChild.data == t) //check the time against this one
				{
					if(booked) //if already found
					{	
						if(booking_id != responseXML.getElementsByTagName('booking_id')[i].firstChild.data)  //different booking for the same time
						{
							//append info to existing info
							staff_id += '|' + (responseXML.getElementsByTagName('staff_id')[i].firstChild.data);
							booked_time_slot_id = responseXML.getElementsByTagName('booked_time_slot_id')[i].firstChild.data;
						}
						else //additional staff member for the same time and booking
						{
							staff_id += '|' + (responseXML.getElementsByTagName('staff_id')[i].firstChild.data);
						}
					}
					else
					{
						booked = true;
						staff_id = responseXML.getElementsByTagName('staff_id')[i].firstChild.data;
						booked_time_slot_id = responseXML.getElementsByTagName('booked_time_slot_id')[i].firstChild.data;
						booking_id = responseXML.getElementsByTagName('booking_id')[i].firstChild.data;
					}
				}
			}
			//see if there are sufficient consecutive time slots to 
			//allow the service selected to be booked bearing in mind
			//the assignations of service time slots to members of staff
			var enoughSlotsFreeAhead = true;
			if(count > (numTimeSlots - prospective_service_num_time_slots))
			{
				enoughSlotsFreeAhead = false;
			}
			else
			{
				for(var i=0; i<staffIds.length; i++) //for each staff member
				{
					for(var j=0; j<prospective_service_num_time_slots; j++)
					{
						if(prospective_service_staff_member_time_slots[i][j] == '1' && staffBookedTimeSlots[i][count+j] == '1')
							enoughSlotsFreeAhead = false;
					}
				}
			}
			//see if prospective timeslot is in the future by at least 15 mins
			selectedDate.setHours(parseInt(t.substring(0,3), 10));
			selectedDate.setMinutes(parseInt(t.substring(3, 5), 10));
			timeslotIsInFuture = 
			(
				selectedDate.getHours() > (phpHour+1)
				||
				(selectedDate.getHours() == (phpHour+1) && selectedDate.getMinutes() == 00 && phpMinute <= 45)
				||
				(selectedDate.getHours() == (phpHour+1) && selectedDate.getMinutes() >= 15)
				||
				(selectedDate.getHours() == phpHour && selectedDate.getMinutes()-phpMinute >= 15)
			);
			//hack - see if this is October or November 2010
			var yearIs2010 = false; //hack
			var monthIsOctoberOrNovember = false; //hack
			if(responseXML.getElementsByTagName('year')[0].firstChild.data == "2010") //hack
				yearIs2010 = true; //hack
			if(responseXML.getElementsByTagName('month')[0].firstChild.data == "10" || responseXML.getElementsByTagName('month')[0].firstChild.data == "11") //hack
				monthIsOctoberOrNovember = true; //hack
			if
				(
				 	enoughSlotsFreeAhead
					&& !dateIsInPast 
					&& (!dateIsToday || (dateIsToday && timeslotIsInFuture))
					&& !(colleteInvolved && yearIs2010 && monthIsOctoberOrNovember) //hack
				)
			{			
				selectedDate.setHours(parseInt(t.substring(0,3), 10));
				selectedDate.setMinutes(parseInt(t.substring(3, 5), 10));
				var bookingCode = Math.floor(selectedDate.getTime()/1000) + serviceSelectedId;
				html += '<td><a href="book_an_appointment.php?action=promptForConfirmation&bookingCode='+ bookingCode +'&bookingAlreadyRecorded=N">available</a></td>';
			}
			else
				html += '<td>not available</td>';
			html += '</tr>';
			//increment time
			t = addFifteenMinutes(t);
		}
		html += '</table><br>';
		scheduleDiv.innerHTML += html;
	}
}
function addFifteenMinutes(t)
{
	var minutes = t.substring(3, 5);
	switch(minutes)
	{
		case '00': t = (t.substring(0,3)+"15"); break;
		case '15': t = (t.substring(0,3)+"30"); break;
		case '30': t = (t.substring(0,3)+"45"); break;
		case '45': 
			var nextHour = String(parseInt(t.substring(0,3), 10)+1);
			if(nextHour.length == 1) nextHour = '0' + nextHour;
			t = nextHour + ':00';
			break;
	}
	return t;
}
function showSaturdaySchedule(responseXML)
{
	showSchedule(responseXML, "07:00", 42);
}
function showWeekdaySchedule(responseXML)
{
	showSchedule(responseXML, "18:00", 12);
}
function showDateSelected(date_formatted)
{
	var scheduleDiv = document.getElementById('scheduleDiv');
	scheduleDiv.innerHTML = '<p id="scheduleDate">Currently showing: ' + date_formatted + '</p>';
}
function showClosedInfo()
{
	var scheduleDiv = document.getElementById('scheduleDiv');
	scheduleDiv.innerHTML += '<h3>Closed</h3><p>Bookings are only available on Saturday daytime<br>and in the evenings from Tuesday to Friday.</p><p>In December, bookings are also available on Monday evenings.';
}
function serviceSelectChanged(value)
{
	var text = document.getElementById('serviceSelect').options[document.getElementById('serviceSelect').selectedIndex].text;
	serviceSelectedId = value;
	triggerScheduleRefresh();
}
function availableClicked(time, serviceSelectedId)
{
	popUp(time, serviceSelectedId, '');
}
function triggerScheduleRefresh()
{
	dateChanged(cal);
}
function showEditBookingPopUp(booked_time_slot_id, time)
{
	popUp(time, '', booked_time_slot_id);
}
function popUp(time, serviceSelectedId, booked_time_slot_id)
{
	var x = (window.screen.width/2) - 500/2;
	var y = (window.screen.height/2) - 475/2;
	var width = 500;
	var height = 475;
	var mode = '';
	if(booked_time_slot_id == '')
		mode = 'new';
	else
		mode = 'edit';
	child = open("editBookingPopUp.php?time="+time+"&serviceSelectedId="+serviceSelectedId+"&mode="+mode+"&booked_time_slot_id="+booked_time_slot_id,"child","height="+height+",width="+width+",screenX="+x+",screenY="+y+",left="+x+",top="+y+",alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=0,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=1,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0");
	child.focus();
}
function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		if(func) window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldonload(); 
			func(); 
		}
	}
}
addLoadEvent(triggerScheduleRefresh());

