var errors, hddnBookingId, selClientId, edtBookingDate, txtBookingTime, selBuildingId, selServiceId, txtBookingNote;
var edtDayNumber, selRepeatCycle, selMonthType, selMonthWeekCycle, lstDOW, lstDOM, footerDesc, readonly;
var module = baseRootURL + "booking/";
var serviceItem = new addSelectionList('serviceItem', 'service', 'ServiceElement');
	
function registerBooking(action)
{
	errors = false;
	validate_hddnBookingId();
	validate_selClientId();
	validate_edtBookingDate();
	validate_txtBookingNote();
	/**
	validate_selBuildingId();
	validate_selServiceId();
	**/
	CheckServices(); //at least 1 service must be defined for a booking.
	if (!errors) validate_recurring_options();
	
	if (!errors)
	{
		var data = {};
		data.dummy = ""; //we seem to get errors from the first value, so always add a dummy value first.
		data.action = action;
		if (document.getElementById("hddnBookingId") != null) data.hddnBookingId = hddnBookingId;
		data.selClientId = selClientId;
		data.edtBookingDate = edtBookingDate;
		data.txtBookingNote = txtBookingNote;
		data.serviceList = serviceItem.getItemsAsString();
		data.cbRecurring = document.getElementById('cbRecurring').checked;
		if (data.cbRecurring)
		{
			data.cbActive			= document.getElementById('cbActive').checked;
			data.edtDayNumber 		= edtDayNumber;
			data.selRepeatCycle 	= selRepeatCycle.value;
			data.selMonthType		= selMonthType.value;
			data.selMonthWeekCycle 	= selMonthWeekCycle.value;
			data.lstDOW = (lstDOW !== undefined) ? JSON.stringify(lstDOW) : lstDOW = 0;
			data.lstDOM = (lstDOM !== undefined) ? JSON.stringify(lstDOM) : lstDOM = 0;
			data.footerDesc = footerDesc;
		}
		callModule("booking/booking_val.php", data);
	}
}
function insertBooking()
{
	var id = getActiveSableTabId();
	if ((id === null) || (id === 'sable-tab-4')) registerBooking(0);
}
function modifyBooking(){registerBooking(1)}

function validate_hddnBookingId()
{
	if (document.getElementById("hddnBookingId") != null) hddnBookingId=document.getElementById("hddnBookingId").value;
}
function validate_selClientId(){selClientId=validateRequiredSelection("selClientId", "Please make a valid selection.");}
function validate_edtBookingDate()
{
	//if (!document.getElementById('cbRecurring').checked)
		edtBookingDate=validateRequiredText("edtBookingDate", "This field is required.");
}
function validate_selBuildingId(){selBuildingId=validateRequiredSelection("selBuildingId", "Please make a valid selection.");};
function validate_selServiceId(){selClientId=validateRequiredSelection("selClientId", "Please make a valid selection.");};
function validate_txtBookingNote(){txtBookingNote=validateText("txtBookingNote", "");};

function CheckServices(){serviceItem.validateItems('1', 'selServiceId', 'service');}

function viewBooking(id)
{
	var data = {}
	data.dummy = "";
	data.hddnBookingId = id;
	data.action = 2;
	callModule("booking/booking_val.php", data);
}

function editBooking(id)
{
	var data = {}
	data.dummy = "";
	data.hddnBookingId = id;
	data.action = 3;
	callModule("booking/booking_val.php", data);
}

function deleteBooking(id, desc, scheduleId)
{
	if (confirm("Delete booking and scheduling for "+desc+"?"))
	{
		var data = {}
		data.dummy = "";
		data.hddnBookingId = id;
		data.action = 4;
		data.scheduleOnly = scheduleId === undefined ? 0 : 1;
		data.hddnBsId = scheduleId;
		callModule("booking/booking_val.php", data);
	}
}

function doClientRefinement(obj)
{
	var data = {}
	data.dummy = "";
	data.field_id = 'selClientId';
	data.input_id = obj.value;
	callModule("lib/getClientsByNameNumber.php", data);
}

function setClientName()
{
	"use strict"; 
	var sel = document.getElementById('selClientId');
	var edt = document.getElementById('edtClientName');
	if (sel.options.length)
	{
		if (sel.options[sel.selectedIndex] != undefined)
		{
			edt.value = sel.options[sel.selectedIndex].text;
			sel.disabled = true;
			sel.readOnly = true;
			edt.disabled = true;
			edt.readOnly = true;
			edt.classList.add('readonly');
			sel.classList.add('readonly');
		}
	}
}

function setClientAddress()
{
	var data = JSON.parse(document.getElementById("hddnAddress").value);
	document.getElementById('clientAddress').innerHTML = data.address;
	showAddress(data.address_lng, data.address_lat, data.address);
}

function getClientAddress()
{
	var data = {};
	data.dummy = "";
	data.clientId = document.getElementById('selClientId').value;
	callModule("lib/getClientAddress.php", data, setClientAddress);
}

function getClientBuildingList()
{
	var data = {};
	data.dummy = "";
	data.id = document.getElementById('selClientId').value;
	data.field = 'selBuildingId';
	callModule("lib/getClientBuildingList.php", data, getClientAddress);
}

function setBuildingServiceList()
{
	var data = {};
	data.dummy = "";
	data.id = document.getElementById('selBuildingId').value;
	data.field = 'selServiceId';
	callModule("lib/getBuildingServiceList.php", data);
}

function setServiceItem()
{	
	//Building Info
	var psel = document.getElementById('selBuildingId');
	var ptxt = psel.options[psel.selectedIndex].text;
	
	//Service Info
	var ssel = document.getElementById('selServiceId');
	var stxt = ssel.options[ssel.selectedIndex].text;
	if (parseInt(ssel.value) > 0) buildServiceList(psel.value, ssel.value, ptxt, stxt, 1);
}

function buildServiceList(buildingId, serviceId, buildingName, serviceName, serviceActive)
{
	var uniqueId = buildingId+'.'+serviceId;
	var active		= serviceActive ? '' : ' [INACTIVE] ';
	var par			= {};
	par.buildingId		= buildingId;
	par.serviceId	= serviceId;
	
	serviceItem.setItmIdx(uniqueId);
	serviceItem.setTag(par); //keeps the building id.
	serviceItem.setDisplayText(buildingName+' <i style=\'color:green;\'>&rarr;</i> '+serviceName+active);
	if (readonly) serviceItem.setReadOnly(true);
	serviceItem.addBasicItem(uniqueId, uniqueId); //sets the service (value).
}

function formatNumberText(val)
{
	val = parseInt(val);
	var res = '';
	switch(val)
	{
		case 0: {res = '';   break;}
		case 1: {res = 'st'; break;}
		case 21: {res = 'st'; break;}
		case 31:{res = 'st'; break;}
		case 2: {res = 'nd'; break;}
		case 22: {res = 'nd'; break;}
		case 3: {res = 'rd'; break;}
		case 23: {res = 'rd'; break;}
		
		default:{res = 'th'; break;}
	}
	return res;
}

function setSchedulingFields()
{
	//selIntervalType
	//divDayOfWeek
	//divDayOfMonth
	//divDayOfMonth
	updateRepeatFooterLabel();
}

function getCheckedWeekDays()
{
	var ret = '';
	var d = '';
	var wd = document.getElementsByName('dayOfWeek');
	var c = 0;
	for (var i = 0; i < wd.length; i++)
	{
		if (wd[i].checked) 
		{
			c++;
			d = (c > 1) ? ', ' : '';
			ret += d + wd[i].value;
		}
	}
	return ret;
}

function getCheckedWeekNos(title, val)
{
	var ret = '';
	var d = '';
	var wd = document.getElementsByName('chkbxDay');
	var c = 0;
	for(var i = 0; i < wd.length; i++)
	{
		if (wd[i].checked) 
		{
			c++;
			d = (c > 1) ? ', ' : '';
			ret += d + wd[i].value+'<sup>'+formatNumberText(wd[i].value)+'</sup>';
		}
	}
	var cap = val > 1 ? title+'s' : title;
	return cap + ' on the ' + ret;
}

function showRecurringOptions()
{
	var edtDate = document.getElementById('edtBookingDate');
	var cbOpt 	= document.getElementById('recurring-options');
	if (document.getElementById('cbRecurring').checked)
	{
		cbOpt.style.display = 'block';
		//edtDate.disabled 	= 'disabled';
		//edtDate.className 	= 'readonly';
	}
	else
	{
		cbOpt.style.display = 'none';
		//edtDate.removeAttribute('disabled');
		//if (edtDate.classList.contains('readonly'))	edtDate.classList.remove('readonly');
	}
}

function updateRepeatFooterLabel()
{
	footerDesc		= 'Repeats every day.';
	var weekDays		= '';
	var pnlFooter 		= document.getElementById('pnlFooter');
	
	selMonthType 		= document.getElementById('selMonthType');
	edtDayNumber 		= document.getElementById('edtDayNumber').value;
	selMonthWeekCycle 	= document.getElementById('selMonthWeekCycle');
	selRepeatCycle 		= document.getElementById('selRepeatCycle');
	
	var selCycleTxt		= selMonthWeekCycle.options[selMonthWeekCycle.selectedIndex].text;
	var divDayOfWeek	= document.getElementById('divDayOfWeek');
	var divDayOfMonth	= document.getElementById('divDayOfMonth');
	var divIntervalType = document.getElementById('divIntervalType');
	
	var divMonthDayInterval = document.getElementById('divMonthDayInterval'); 
	var suff 				= '';
	
	//initialise
	divDayOfMonth.style.display			= 'none';
	divDayOfWeek.style.display			= 'none';
	divIntervalType.style.display		= 'none';
	divMonthDayInterval.style.display	= 'none';
	
	switch(selRepeatCycle.selectedIndex)
	{
		case(0): //Day
		{
			if (edtDayNumber == 1)
			{
				footerDesc = 'Repeats every day.';
				selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Day';
			}
			else
			{
				footerDesc = 'Repeats every '+edtDayNumber+' days.';
				selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Days';
			}
			break;
		}
		case(1): //Week
		{
			divDayOfWeek.style.display = 'block';
			weekDays = getCheckedWeekDays();			
			if (edtDayNumber == 1)
			{
				footerDesc = 'Repeats every week on '+weekDays+'.';
				selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Week';
			}
			else
			{			
				footerDesc = 'Repeats every '+edtDayNumber+'<sup>'+formatNumberText(edtDayNumber)+'</sup> week on '+weekDays+'.';
				selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Weeks';
			}			
			break;
		}
		case(2): //Month
		{
			divIntervalType.style.display = 'block';
			if (selMonthType.selectedIndex == 0)//by day numbers
			{
				divDayOfMonth.style.display = 'block';
				weekDays = getCheckedWeekNos('month', edtDayNumber);
				suff = weekDays+'.';
				
				if (edtDayNumber == 1)
				{
					footerDesc = 'Repeats every '+suff;
					selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Month';
				}
				else
				{
					footerDesc = 'Repeats every '+edtDayNumber+' '+suff;
					selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Months';
				}				
				
			}
			else //by week days
			{
				divMonthDayInterval.style.display = 'block';
				divDayOfWeek.style.display = 'block';
				weekDays = getCheckedWeekDays();
				
				if (edtDayNumber == 1)
				{
					footerDesc = 'Repeats every month on the '+selCycleTxt+' '+weekDays;
					selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Month';
				}
				else
				{
					footerDesc = 'Repeats every '+edtDayNumber+' months, every '+selCycleTxt+' '+weekDays;
					selRepeatCycle.options[selRepeatCycle.selectedIndex].text = 'Months';
				}				
			}
			
			break;
		}
	}
	
	pnlFooter.innerHTML = footerDesc;
}
	
function validate_recurring_options()
{
	errors = false;
	clearError('recurring');
	showRecurringOptions(); //update values
	selRepeatCycle		= document.getElementById('selRepeatCycle');
	edtDayNumber 		= document.getElementById('edtDayNumber').value;
	selMonthType 		= document.getElementById('selMonthType');
	selMonthWeekCycle 	= document.getElementById('selMonthWeekCycle');
	
	switch(selRepeatCycle.selectedIndex)
	{
		case(0): //Day
		{
			break;
		}
		case(1): //Week
		{			
			//must select at least one day of the week.
			var wd = document.getElementsByName('dayOfWeek');
			lstDOW = {};
			var c = 0;
			for(var i = 0; i < wd.length; i++) 
			{
				if (wd[i].checked) 
				{
					lstDOW[c] = {};
					lstDOW[c].day = i;
					c++;
				}
			}
			
			if (c === 0) 
			{
				errors = true;
				handleError('recurring', "At least 1 day of the week should be selected.");
			};
			break;
		}
		case(2): //Month
		{
			if (selMonthType.selectedIndex == 0)//by day numbers
			{
				//must select at least one day of the week.
				var md = document.getElementsByName('chkbxDay');
				lstDOM = {};
				var c = 0;
				for(var i = 0; i < md.length; i++) 
				{
					if (md[i].checked) 
					{
						lstDOM[c] = {};
						lstDOM[c].day = i;
						c++;
					}
				}
				
				if (c === 0) 
				{
					errors = true;
					handleError('recurring', "At least 1 day of the month should be selected.");
				};
			}
			else //by week days
			{
				//must select at least one day of the week.
				var wd = document.getElementsByName('dayOfWeek');
				lstDOW = {};
				var c = 0;
				for(var i = 0; i < wd.length; i++) 
				{
					if (wd[i].checked) 
					{
						lstDOW[c] = {};
						lstDOW[c].day = i;
						c++;
					}
				}

				if (c === 0) 
				{
					errors = true;
					handleError('recurring', "At least 1 day of the week should be selected.");
				};				
			}
			break;
		}
	}	
}

function saveBooking(params)
{
	errors = false;
	//var info = JSON.parse(params);
	var id = params.booking_id;
	var data				= {};
	data.dummy				= "";
	data.action				= '5';
	//data.hddnBookingId		= id;
	data.params				= JSON.stringify(params);
	data.edtBookingDate 	= document.getElementById('edtBookingDate'+id).value;
	data.selTeamId 			= document.getElementById('selTeamId'+id).value;
	data.txtBookingTime		= document.getElementById('edtBookingTime'+id).value;
	data.cbScheduleActive	= document.getElementById('cbScheduleActive'+id).checked;
	
	var elems = document.getElementsByName('edtServicePrice'+id);
	var svcItms = {};
	var svc;
	for(var i = 0; i < elems.length; i++)
	{
		svc = {};
		svc.service_id	= elems[i].getAttribute('service-id');
		svc.building_id		= elems[i].getAttribute('building-id');
		svc.price		= elems[i].value;
		svcItms[i]		= svc;
	}
	data.serviceItems	= JSON.stringify(svcItms);
	
	if (data.selTeamId)
	{
		data.txtBookingTime = validateRequiredText('edtBookingTime'+id, 'Time is required.')
	}
	
	var selectField = document.getElementById('selTeamId'+id);
	var index = parseInt(selectField.options.selectedIndex);
	if (index <= 0)
	{
		errors = true;
		handleError('edtBookingTime'+id, "Please select a team.");		
	}	
	
	if (!errors)
	{
		callModule("booking/booking_val.php", data);
	}
}

function addPayment(params)
{
	errors = false;
	//var info = JSON.parse(params);
	var data				= {};
	data.dummy				= "";
	data.action				= '12';
	data.params				= JSON.stringify(params);
	callModule("booking/booking_val.php", data);
}

function filterTeams(eventDate)
{
	//alert('functionality not yet implemented.');
	var data = {};
	data.selTeamId = document.getElementById('selTeamFilter').value;
	data.action = 6;
	data.edtBookingDate = eventDate;
	callModule("booking/booking_val.php", data);
}

function showNextOccurrence(id)
{
	var data = {}
	data.dummy = "";
	data.hddnBookingId = id;
	data.action = 11;
	callModule("booking/booking_val.php", data);
}

function savePlan(eventDate)
{
	var cont, i, changed = false, list = [], elems = document.getElementsByName('dragblock');
	var c, d, p;

	for (i = 0; i < elems.length; i++)
	{
		d = {};
		d.before = elems[i].parentElement.id;
		d.after  = elems[i].id;

		c = d.before.split("_");
		p = d.after.split("_");

		if (!changed)
		{
			changed = !((c[1] == p[1]) && (c[2] == p[2]) && (c[3] == p[3]) && (c[4] == p[4]) && (c[5] == p[5]));
		}

		cont					= {};
		cont.before				= {}; //"div_1_08_00"
		cont.before.team_id		= p[1];
		cont.before.hour		= p[2];
		cont.before.minute		= p[3];
		cont.before.client_id	= p[4];
		cont.before.booking_id	= p[5];

		cont.after				= {}//"td_1_08_00"
		cont.after.team_id		= c[1];
		cont.after.hour			= c[2];
		cont.after.minute		= c[3];
		cont.after.client_id	= p[4];
		cont.after.booking_id	= p[5];

		list[i] = cont.after;
	}

	/**
	if (!changed)
	{
		alert('Nothing has changed.');	
	}
	else
	{
		console.log(list);
	}
	**/
	cont.action		= "13";
	cont.eventDate	= eventDate;
	cont.params		= JSON.stringify(list);
	callModule("booking/booking_val.php", cont);
}

function showDetail(elem)
{
	var info		= elem.id.split("_");
	var teamid		= info[1];
	var clientid 	= info[4];
	var targetid	= 'tr_'+clientid+'_'+teamid;
	var target		= document.getElementById(targetid);
	openSableTab('sable-tab-3');
	target.scrollIntoView(true);
}

function showPlanItem(targetid)
{
	//div_1_08_00_322_284 :: div_[teamid]_[hour]_[minute]_[clientid]_[booking_id]
	var target		= document.getElementById(targetid);
	openSableTab('sable-tab-2');
	target.scrollIntoView(true);
}

function SMSNotify(eventDate)
{
	if (confirm("Are you sure you want to send out SMS's to clients?"))
	{
		var cont = {};
		cont.action		= "14";
		cont.eventDate	= eventDate;
		callModule("booking/booking_val.php", cont);
	}
}

function sendSingleSMS(bsid)
{
	errors = false;
	var data				= {};
	data.dummy				= "";
	data.action				= '15';
	data.hddnBsId			= bsid;
	callModule("booking/booking_val.php", data);
}
