var isIE = /*@cc_on!@*/false;

function ChangeTab(newTab, tabs)
{
	for(var i = 0; i < tabs.length; i++)
	{
		try
		{
			$$(tabs[i]+'l').className = '';		// update the link to be normal
			$$(tabs[i]).style.display = 'none';	// hide the div
		}
		catch(e)
		{
			// exception occured, do nothing and carry on
		}
	}
	
	// set the active link and div
	if(InArray(tabs, newTab))
	{
		try
		{
			$$(newTab+'l').className = 'active';
			$$(newTab).style.display = 'block';
		}
		catch(e)
		{
			// exception occured, do nothing
		}
	}
	
	return false;
}

function ChangeJobTab(newTab)
{
	var tabs = new Array('inf', 'app', 'rep', 'par', 'not', 'int');
	
	return ChangeTab(newTab, tabs);
}

function ChangePolicyTab(newTab)
{
	var tabs = new Array('inf', 'cla', 'rep');
	
	return ChangeTab(newTab, tabs);
}

function ChangeUserTab(newTab)
{
	var tabs = new Array('cli', 'clu', 'serv', 'tech', 'tpay');
	
	return ChangeTab(newTab, tabs);
}

function ChangeClientTab(newTab)
{
	var tabs = new Array('inf', 'usr', 'con', 'prc', 'sal', 'not');
	
	return ChangeTab(newTab, tabs);
}

function ChangeIndexTab(newTab)
{
	var tabs = new Array('home', 'sal');
	
	return ChangeTab(newTab, tabs);
}

function ChangeArticleAdminTab(newTab)
{
	var tabs = new Array('art', 'cat');
	
	return ChangeTab(newTab, tabs);
}

function InArray(array, val)
{
	for(var i = 0; i < array.length; i++)
	{
		if(array[i] == val)
			return true;
	}
	
	return false;
}

function SubmitForm(formId)
{
	$$(formId).submit();
}

function isNumberKey(evt, allowDecimal)
{
	if(allowDecimal == undefined)
		allowDecimal = true;
	
	var charCode = (evt.which) ? evt.which : event.keyCode;
	
	if (charCode == 32 || (charCode > 40 && (charCode < 48 || charCode > 57) && (allowDecimal == false || charCode != 46)))
		return false;
	return true;
}

function isTimeKey(evt)
{
	var charCode = (evt.which) ? evt.which : event.keyCode;
	
	if(charCode == 58) // :
		return true;
	else
		return isNumberKey(evt, false);
}

function ShowHideClientFields(show)
{
	var clientEls = $$('form-user').elmsByClass('clientOnly');
	
	for(var i = 0; i < clientEls.length; i++)
		clientEls[i].style.display = (show == 1 ? 'block' : 'none');


	var staffEls = $$('form-user').elmsByClass('staffOnly');
	
	for(var i = 0; i < staffEls.length; i++)
		staffEls[i].style.display = (show == 1 ? 'none' : 'block');
}

function ShowHideTechFields(show)
{
	$$('techDetails').style.display = (show ? 'block' : 'none');
}

/*	function to move items from one menu to another */
function moveOption(oldlist, newlist, hidden, inList)
{
	var oldListElm = document.getElementById(oldlist);
	var newListElm = document.getElementById(newlist);
	var oldListLength = oldListElm.length;
	var selectedText = new Array();
	var selectedValue = new Array();
	var selectedCount = 0;
	for(var i = oldListLength - 1; i >= 0; i--)
	{
		if(oldListElm.options[i].selected)
		{
			selectedText[selectedCount] = oldListElm.options[i].text;
			selectedValue[selectedCount++] = oldListElm.options[i].value;
			oldListElm.options[i] = null;
		}
	}
	for(i = 0; i < selectedCount; i++)
	{
		var newOpt = new Option(selectedText[i], selectedValue[i]);
		newListElm.options[newListElm.length] = newOpt;
	}
	var tmp = '';
	var catInElm = document.getElementById(inList);
	for(i = 0; i < catInElm.length; i++)
	{
		tmp += catInElm.options[i].value + ',';
	}
	
	document.getElementById(hidden).value = tmp.substring(0, tmp.length - 1);
}


function UpdateAppointmentDetails(value, status, canUpdateVariableName)
{
	var parts = value.split(',');
	
	if(parts.length == 3)
	{
		var d = new Date();
		var year = d.getFullYear();
		var timeSelectedIndex = 0;
		var techSelectedIndex = 0;
		
		
		var date = parts[1].split('/');
		
		$$('cbovisitDateDD').selectedIndex = date[0] - 1;
		$$('cbovisitDateDD').onchange = status == 0 || status == 5 ? '' : 'this.selectedIndex = '+(date[0] - 1);
		
		$$('cbovisitDateMM').selectedIndex = date[1] - 1;
		$$('cbovisitDateMM').onchange = status == 0 || status == 5 ? '' : 'this.selectedIndex = '+(date[1] - 1);
		
		var yearSelectedIndex = year - date[2] + 1;
		
		$$('cbovisitDateYYYY').selectedIndex = yearSelectedIndex;
		$$('cbovisitDateYYYY').onchange = status == 0 || status == 5 ? '' : 'this.selectedIndex = '+yearSelectedIndex;
		
		var i;
		// set the time slot
		for(i = 0; i < $$('cboVisitTimeID').length; i++)
		{
			if($$('cboVisitTimeID')[i].value == parts[2])
			{
				timeSelectedIndex = i;
				break;
			}
		}
		
		$$('cboVisitTimeID').onchange = status == 0 || status == 5 ? '' : 'this.selectedIndex = '+timeSelectedIndex;
		
		// set the technician
		for(i = 0; i < $$('cbotechnicianAssigned').length; i++)
		{
			if($$('cbotechnicianAssigned')[i].value == parts[0])
			{
				techSelectedIndex = i;
				break;
			}
		}
		$$('cbotechnicianAssigned').onchange = status == 0 || status == 5 ? '' : 'this.selectedIndex = '+techSelectedIndex;
		
		$$('cboVisitTimeID').selectedIndex = timeSelectedIndex;
		$$('cbotechnicianAssigned').selectedIndex = techSelectedIndex;
		
		// set the status
		for(i = 0; i < $$('cboStatus').length; i++)
		{
			if($$('cboStatus')[i].value == status)
			{
				$$('cboStatus').selectedIndex = i;
				break;
			}
		}
		
		window[canUpdateVariableName] = (status == 0 || status == 5);
	}
}

var docCount = 1;

function AddDocumentUpload()
{
	var fileInput = document.createElement('input');
	fileInput.name = "doc["+docCount+"]";
	fileInput.setAttribute("type", "file");
	
	var tbl = $$("docsList");
	
	try
	{
		var row = tbl.insertRow(docCount+1);
		var cell = row.insertCell(0);
		cell.appendChild(fileInput);
		
		docCount++;
	}
	catch(e)
	{
		alert(e);
	}
}

function CheckConfirmed(frm)
{
	var errorstring = '';
	
	if(frm.cboStatus.value == 0)
		errorstring += '\tStatus of appointment has not been selected\n';
	
	if(frm.cboVisitTimeID.value == -1)
		errorstring += '\tTime of visit has not been selected\n';
	if(frm.cbotechnicianAssigned.value == '')
		errorstring += '\tTechnician to assign has not been selected\n';
	if(frm.cboStatus.value != 4 && (frm.txtMins.value == '' || frm.txtMins.value == '0') && (frm.txtHours.value == '' || frm.txtHours.value == '0'))
		errorstring += '\tJob Time Required has not been entered\n';
	
	if(frm.cboStatus.value == 1)
	{
		/*if(frm.techNotes.value == '' && frm.ConfirmNoSpecialInstructions.checked == false)
			errorstring += '\tSpecial Instructions are required or you must confirm there are no special instructions\n';
	
		if(frm.adminNotes.value == '' && frm.ConfirmNoOffRoad.checked == false)
			errorstring += '\tOff Road is required or you must confirm there are no off road instructions\n';
	
		if(frm.radParkingPermitYes.checked == false && frm.radParkingPermitNo.checked == false)
			errorstring += '\tParking permit is required\n';*/
		
		if(frm.checklistInstructionSet.checked == false)
			errorstring += '\tYou must confirm you have checked the new instruction is set\n';
		
		if(frm.checklistComplaint.value == '')
			errorstring += '\tYou must enter details of the complaint\n';
		
		if(frm.checklistCustomerName.checked == false)
			errorstring += '\tYou must confirm you have check the customer\'s name is correct\n';
		
		if(frm.LastName.value.trim() == '')
			errorstring += '\tYou must enter the customer\'s last name\n';
		
		if(frm.checklistAddressPostcode.checked == false)
			errorstring += '\tYou must confirm you have checked the address and postcode are correct\n';
		
		if(frm.Address1.value.trim() == '')
			errorstring += '\tYou must enter the first line of the customer\'s address\n';
			
		if(frm.Postcode.value.trim() == '')
			errorstring += '\tYou must enter the customer\'s postcode\n';
		
		if(frm.checklistContactNumbers.checked == false)
			errorstring += '\tYou must confirm you have checked all contact numbers for the customer\n';
		
		if(frm.DaytimeTelephone.value.trim() == '')
			errorstring += '\tYou must enter the customer\'s daytime telephone number\n';
		
		if(frm.checklistBookedWith.value == '')
			errorstring += '\tYou must select who the appointment was booked with\n';
		else if(frm.checklistBookedWith.value == 'Other' && frm.checklistBookedWithOther.value == '')
			errorstring += '\tYou must specify who the appointment was booked with\n';
		
		if(frm.checklistCallPriorToVisit.value == '')
			errorstring += '\tYou must select if the customer requires a call prior to the visit\n';
		else if(!frm.checklistCallPriorToVisit.value == 1)
		{
			var callPriorTime = frm.checklistCallPriorToVisitTime.value + ':' + frm.checklistCallPriorToVisitTime_Minute.value;
		
			if(!callPriorTime.value.match(/^[0-2]\d:[0-5]$\d/))
				errorstring += '\tYou must specify a valid time to call the customer prior to the visit\n';
		}
		
		if(frm.checklistTimeRestrictions.value == '')
			errorstring += '\tYou must select if the customer has any time restrictions\n';
		else if(frm.checklistTimeRestrictions.value == 1)
		{
			if(frm.checklistTimeRestrictionsCondition.value == '')
				errorstring += '\tYou must select whether to arrive before or after the time specified\n';
			
			var timeRestrictionTime = frm.checklistTimeRestrictionsTime.value + ':' + frm.checklistTimeRestrictionsTime_Minute.value;
			
			if(!timeRestrictionTime.match(/^[0-2]\d:[0-5]\d$/))
				errorstring += '\tYou must specify a valid time for the arrival time restriction\n';
		}
		
		if(frm.checklistParkingRestrictions.value == '')
			errorstring += '\tYou must select if there are any parking restrictions\n';
		else if(frm.checklistParkingRestrictions.value.substr(0, 3) == 'Yes' && frm.checklistDistance.value == '')
			errorstring += '\tYou must specify the distance parking is from the property\n';
		
		if(frm.checklistParts.checked == false)
			errorstring += '\tYou must confirm you have checked parts are correct and will be available\n';
	}
	
	if(errorstring != '')
	{
		alert('The following errors must be corrected before this appointment can be added:\n'+errorstring);
		return false;
	}
	
	if(frm.cboStatus.value == 1)
		return true
	else
		return confirm('This appoinment has not been marked as confirmed.\n\nAre you sure you want to add an unconfirmed appointment?');
}

function MarkTechnicianUnavailable(checkbox, inputName)
{
	var input = $$(inputName);
	
	if(checkbox.checked)
	{
		input.value = '';
		input.readOnly = true;
	}
	else
	{
		input.readOnly = false;
	}
}

function SingleOutcomeCheck(radiobuttonname)
{
	// get the selected status of fully settled, authorisation required, report only and return to repair 'Yes' radio button
	var fullySettled = $$('radfullySettledYes');
	var authorisationRequired = $$('radauthorisationRequiredYes');
	var reportOnly = $$('radpartlySettledYes');
	var returnToRepair = $$('radreturnToRepairYes');
	var replacement = $$('radreplacementYes');
	var partToBeSuppliedByServico = $$('radpartByServicoYes');
	var partToBeSuppliedByClient = $$('radpartByClientYes');
	var uplifted = $$('radupliftedYes');
	
	// count the number of selected yes boxes
	var selected = 0;
	selected += (fullySettled.checked ? 1 : 0);
	selected += (authorisationRequired.checked ? 1 : 0);
	selected += (reportOnly.checked ? 1 : 0);
	selected += (returnToRepair.checked ? 1 : 0);
	selected += (replacement.checked ? 1 : 0);
	selected += (partToBeSuppliedByServico.checked ? 1 : 0);
	selected += (partToBeSuppliedByClient.checked ? 1 : 0);
	selected += (uplifted.checked ? 1 : 0);
	
	// check if more than 1 selected
	if(selected > 1)
	{
		// uncheck the yes, check the no
		$$('rad'+radiobuttonname+'Yes').checked = false;
		$$('rad'+radiobuttonname+'No').checked = true;
		
		// show popup explaining only 1 outcome allowed
		alert('Only one of \'Fully Settled\', \'Authorisation Required\', \'Report Only\', \'Return To Repair\', \'Replacement\', \'Uplifted\', \'Part to be Supplied by Servico\', \'Part to be Supplied by Client\' can be set to \'Yes\'.\n\nTo set this option to \'Yes\' set all other options to \'No\'.');
	}
}

function SetTextareaHeight(textarea)
{	
	var text = textarea.value.split('\n');
	
	var rowCount = 0;
	
	// for the smaller textboxes browsers aren't showing all the columns, adjust for this
	var textareaColumns = (textarea.cols < 80 ? textarea.cols - 6 : textarea.cols);
	
	for(var i = 0; i < text.length; i++)
	{
		if(text[i].length > textareaColumns)
			rowCount += Math.floor(text[i].length / textareaColumns);
		rowCount++;
	}
	
	rowCount += 1;
	
	textarea.rows = rowCount;
}

function SetAllTextareaHeights()
{
	var textareas = $(document.body).elmsByTag('textarea');
	
	for(var i = 0; i < textareas.length; i++)
		SetTextareaHeight(textareas[i]);
}

function ShowHidePolicyFields()
{
	var relatesTo = $$('RelatesTo').value;
	
	var manufacturerPriceImageName = 'placeholder.gif';
	var modelImageName= 'placeholder.gif';
	var manufacturerPriceAltText = '';
	var modelAltText = '';

	$$('Manufacturer').readOnly = false;
	$$('Model').readOnly = false;
	
	if(relatesTo == 'MANUFACTURER')
	{
		manufacturerPriceImageName = 'manufacturer.gif'
		manufacturerPriceAltText = 'Manufacturer';
		modelImageName = 'model.gif';
		modelAltText = 'Model';
		
		$$('Manufacturer').readOnly = true;
		$$('Manufacturer').value = $$('PolicyManufacturer').value = '';
		$$('Model').readOnly = true;
		$$('Model').value = $$('PolicyModel').value = '';
	}
	else if(relatesTo == 'PRICE')
	{
		manufacturerPriceImageName = 'cost_limit.gif';
		manufacturerPriceAltText = 'Price Point Start';
		modelImageName = 'cost_limit.gif';
		modelAltText = 'Price Point End';
		
		$$('PolicyPricePointStart').value = '';
		$$('PolicyPricePointEnd').value = '';
	}
	
	$$('ManufacturerPriceImage').src = 'images/icons/'+manufacturerPriceImageName;
	$$('ManufacturerPriceImage').alt = manufacturerPriceAltText;
	$$('ManufacturerPriceImage').title = manufacturerPriceAltText;
	$$('PolicyModelImage').src = 'images/icons/'+modelImageName;
	$$('PolicyModelImage').alt = modelAltText;
	$$('PolicyModelImage').title = modelAltText;
	$$('PolicyManufacturer').style.display = (relatesTo == 'MANUFACTURER' ? 'block' : 'none');
	$$('PolicyPricePointStart').style.display = (relatesTo == 'PRICE' ? 'block' : 'none');
	$$('PolicyPricePointEnd').style.display = (relatesTo == 'PRICE' ? 'block' : 'none');
	$$('PolicyModel').style.display = (relatesTo == 'MANUFACTURER' ? 'block' : 'none');
	$$('ManufacturerPriceRequired').style.display = (relatesTo == 'MANUFACTURER' || relatesTo == 'PRICE' ? 'block' : 'none');
	$$('PolicyModelRequired').style.display = (relatesTo == 'MANUFACTURER' || RelatesTo == 'PRICE' ? 'block' : 'none');
	$$('PolicyPricePointStartCurrency').style.display = (relatesTo == 'PRICE' ? 'block' : 'none');
	$$('PolicyPricePointEndCurrency').style.display = (relatesTo == 'PRICE' ? 'block' : 'none');
}

function SetManufacturer(manufacturer)
{
	$$('Manufacturer').value = manufacturer;
}

function SetModel(model)
{
	$$('Model').value = model;
}

function SearchPolicies()
{
	window.open('policysearch.php', 'policysearch', 'scrollbars=1,width=766,height=550');
	policysearch.focus();
}

function GetValueFromChild(policyid)
{
	if(IsNumeric(policyid))
		window.location = 'viewjob.php?id=-1&edit=1&claim=1&policyid='+policyid;
}

function SendValueToParent(policyid)
{
	window.opener.GetValueFromChild(policyid);
	window.close();
	return false;
}

function IsNumeric(value)
{
	
	if(value === '')
		return false;
	
	var regex = /^\d+$/;
	return regex.test(value);
}

function ConfirmJobInstructions()
{
	return confirm('Is the Job Instruction correct?');
}

function UpdateTo(value)
{
	// get the number of options in the to select
	var length = $$('lstTo').options.length;
	
	// change the value/text of the last option
	$$('lstTo').options[length-1] = new Option((value == 'SERVICO' ? 'Servico Smart Warranties' : 'INSURERS'), (value == 'SERVICO' ? 'WARRANTIES' : 'INSURERS'), false, false);
}

function SetDelivery(fieldName, obj)
{	
	var text = obj.options[obj.selectedIndex].text;
	$$(fieldName).options[0] = new Option(text, obj.value, true, true);
}

function ShowHideCancellationReason(appointmentStatus, fieldName)
{
	if(appointmentStatus == 4)
		$$(fieldName).style.display = '';
	else
		$$(fieldName).style.display = 'none';
}

function ConfirmJobStatusChange(originalJobStatus, appointmentDate, hasParts)
{
	var newJobStatus = $$('cboStatusID').value;
	
	var msg = '';
	
	if(appointmentDate != '' && hasParts)
		msg = 'This job has a non-cancelled appointment on '+appointmentDate+', there are also open parts for this job.\n\nAre you sure the job status should be changed?\n\nIf so please either close the parts or inform Servico.';
	else if(appointmentDate != '')
		msg = 'This job has a non-cancelled appointment on '+appointmentDate+', are you sure the job status should be changed?';
	else
		msg = 'This job has open parts, are you sure the job status should be changed?\n\nIf so please either close the parts or inform Servico.';
	
	if(newJobStatus != originalJobStatus && (newJobStatus == 9 || newJobStatus == 3 || newJobStatus == 16 || newJobStatus == 19))
		return confirm(msg);
	else
		return true;
}

function UpdatePercentage(tablename)
{
	var table = $$(tablename);
	
	// work out the total number of outcomes
	var totaloutcomes = 0;
	
	var missedAppointmentCount = 0;
	
	table.elmsByClass('number').elmsByTag('input').each( function() {
		var value = parseInt(this[0].value);
		
		if(!isNaN(value))
			totaloutcomes += value;
			
		// missed appointment is the last outcome, update the value in each loop, will be left with the correct value
		missedAppointmentCount = (isNaN(value) ? 0 : value);
	});
	
	var isFirst = true;
	
	// update all the percentages
	table.elmsByClass('number').elmsByTag('input').each( function() {
		var id = (this[0].id).replace('number', '');
		var value = parseInt(this[0].value);
		
		if(isNaN(value))
			value = 0;
		
		var percentcell = $$(tablename+'_percent'+id);
		
		// check the parentcell isn't empty - it's empty if it is for missed appointments
		if(percentcell.innerHTML != '&nbsp;' && (percentcell.innerHTML).trim() != '')
		{
			var count = (value + (isFirst ? missedAppointmentCount : 0)) * 100;
			
			var percent = (totaloutcomes > 0 ? Math.round((count / totaloutcomes) * 10) / 10 : 0);
			
			percentcell.innerHTML = '('+percent+'%)';
		}
		
		isFirst = false;
	});
}

function setReadonlyOptions(users)
{
	// get a reference to the dropdown
	var readonlyDropdown = $$('ReadonlyCompany');
	
	if(readonlyDropdown != null)
	{
		var oldValue = readonlyDropdown.value;		
		var index = 0;
		
		// remove all options from the select box
		readonlyDropdown.length = 0;
		
		// add the select option
		var opt = document.createElement('option');
		opt.text = '-- Select --';
		opt.value = 0;
		
		try {
			readonlyDropdown.add(opt, null);
		}
		catch(ex) {
			readonlyDropdown.add(opt);
		}
		
		readonlyDropdown.selectedIndex = 0;
		
		// add an option for each of the users
		var u;
		var user;
		
		var duplicateUsers = new Array();
		var count = 0;
		
		for(u in users)
		{
			if(!isNaN(parseInt(u)))
				duplicateUsers[count++] = users[u];
		}
		
		duplicateUsers.sort(sortFunction);
		
		for(u in duplicateUsers)
		{
			if(!isNaN(parseInt(u)))
			{
				index++;
				
				user = duplicateUsers[u];
				opt = document.createElement('option');
				opt.text = user.Name;
				opt.value = user.ID;
				
				try {
					readonlyDropdown.add(opt, null);
				}
				catch(ex) {
					readonlyDropdown.add(opt);
				}
				
				if(user.ID == oldValue)
					readonlyDropdown.selectedIndex = index;
			}
		}
	}
}

function sortFunction(a, b)
{
	var aName = a.Name.toLowerCase();
	var bName = b.Name.toLowerCase();
	
	if(aName < bName)
		return -1;
	else if(aName == bName)
		return 0;
	else
		return 1;
}

function updateRetailerDetails(companyId)
{
	var retailerTextbox = $$('retailerNotes');
	
	if(retailerTextbox != null)
	{
		// get the selected client company
		var clientCompany = $$('cboclientCompanyID');
		
		var clientCompanyID = (clientCompany == null ? 0 : clientCompany.value);
		
		var company = null;
		
		if(readonlyCompanies.isKey(clientCompanyID) && readonlyCompanies[clientCompanyID].isKey(companyId))
			company = readonlyCompanies[clientCompanyID][companyId];
	
		if(company == null)
		{
			retailerTextbox.value = '';
		}
		else
		{
			retailerTextbox.value = company.Name+"\n"+company.Address+"\n"+company.Phone+"\n"+company.Email;
		}
	}
}

function ManufacturerStatusNotes(originalStatus, companyName)
{
	var manufacturerStatus = $$('cboManufacturerStatusID');
	
	if(manufacturerStatus != null)
	{
		var comments = $$('ManufacturerStatusChangeComment');
		
		if(originalStatus != manufacturerStatus.value  && (manufacturerStatus.value == 28 || manufacturerStatus.value == 29 || manufacturerStatus.value == 30) && comments.value.trim() == '')
		{
			alert('A note is required for this '+companyName+' status.\n\nThe status of this job has NOT been updated.');
			return false;
		}
	}
	
	return true;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

Array.prototype.isKey = function() {
	for(i in this)
	{
		if(i === arguments[0])
			return true;
	}
	
	return false;
}

function showHideAppointmentDateTimeChangedRow(confirmed, originalDate, originalTimeSlot)
{
	if(!confirmed)
		return;
	
	// get the currently selected date and timeslot
	var y = $$('cbovisitDateYYYY').value;
	var m = $$('cbovisitDateMM').value;
	var d = $$('cbovisitDateDD').value;
	var timeSlot = $$('cboVisitTimeID').value;
	
	var newDate = y+'-'+m+'-'+d;
	
	var display = newDate == originalDate && timeSlot == originalTimeSlot ? 'none' : 'block';
	
	$$('customerNotified').style.display = display;
}

function showHideAppointmentDateTimeHistory(id)
{
	var row = $$('rowAppointmentChanges' + id);
	
	// get the current display value for the row	
	var display = row.style.display;
	
	display = display.toLowerCase();
	
	row.style.display = (display == 'none' ? '' : 'none');
	
	$$('appointmentDateTimeHistory' + id).innerHTML = (display == 'none' ? 'hide history' : 'show history');
}

function enableDisableInvoiceEmailAddress(isChecked)
{
	var input = $$('InvoiceEmailAddress');
	
	if(isChecked)
		input.disabled = false;
	else
		input.disabled = true;
}

function changeCloseDaySubmitText(isChecked, editing)
{
	if(editing == undefined)
		editing = false;
	
	var input = $$('closeDaySubmit');
	
	input.value = (isChecked ? ' Save Job Order & Complete Day ' : ' Save Job Order & ' + (editing ? 'Edit' : 'Close') + ' Day ');
}

function UpdateArrivalAppointmentTimes()
{
	// get the start time
	var arrivalTime = $$('ArrivalTimeAtFirstJob').value;
	
	var time = arrivalTime.split(':');
	
	if(time.length != 2 || time[0] == '' || time[1].length != 2)
	{
		// clear all the arrival times of appointments
		$$('ArrivalTimeStart').innerHTML = '';
		
		for(var i = 0; i < timeAtAppointmentInMinutes.length - 1; i++)
			$$('ArrivalTime' + i).innerHTML = '';
	}
	else
	{
		var hour = time[0];
		var minute = time[1];
		
		if(hour != '0' && hour != '00')
			hour = hour.replace(/^0+(?=\d)/, '');
		if(minute == '00')
			minute = '0';
		else
			minute = minute.replace(/^0+(?=\d)/, '');
		
		hour = parseInt(hour);
		minute = parseInt(minute);
		
		if(isNaN(hour) || isNaN(minute) || ((minute + '').length != 2) && (minute + '') != 0)
			return;
		
		var setArrivalTime = true;
		
		$$('ArrivalTimeStart').innerHTML = Pad(hour, 2) + ':' + Pad(minute, 2);
		
		// is there an additional time restriction
		var timeRestriction = timeConditions[0];
		
		if(timeRestriction != undefined)
		{
			var restrictedTime = timeRestriction.Time.split(':');
			var restrictedHour = restrictedTime[0];
			var restrictedMinute = restrictedTime[1];
			
			if(restrictedHour != '0' && restrictedHour != '00')
				restrictedHour = restrictedHour.replace(/^0+(?=\d)/, '');
			if(restrictedMinute == '00')
				restrictedMinute = '0';
			else
				restrictedMinute = restrictedMinute.replace(/^0+(?=\d)/, '');
			
			restrictedHour = parseInt(restrictedHour);
			restrictedMinute = parseInt(restrictedMinute);
			
			if(timeRestriction.Before)
			{
				if(hour > restrictedHour || (hour == restrictedHour && minute > restrictedMinute))
					$$('ArrivalTimeStart').innerHTML = $$('ArrivalTimeStart').innerHTML + '<br /><span style="color:#f00">Arrival time after time restriction of appoinment</span>';
			}
			else
			{
				if(hour < restrictedHour || (hour == restrictedHour && minute < restrictedMinute))
					$$('ArrivalTimeStart').innerHTML = $$('ArrivalTimeStart').innerHTML + '<br /><span style="color:#f00">Arrival time before time restriction of appointment</span>';
			}
		}
		
		for(var i = 0; i < timeAtAppointmentInMinutes.length - 1; i++)
		{
			// get the travel time (hours and minutes)
			var travelHours = $$('Hours' + i).value;
			var travelMinutes = $$('Minutes' + i).value;
			
			travelHours = travelHours.replace(/^0+(?=\d)/, '');
			travelMinutes = travelMinutes.replace(/^0+(?=\d)/, '');
			
			travelHours = parseInt(travelHours);
			travelMinutes = parseInt(travelMinutes);
			
			if(isNaN(travelHours) && isNaN(travelMinutes) || (!isNaN(travelHours) && travelHours > 23) || (!isNaN(travelMinutes) && travelMinutes > 59))
				setArrivalTime = false;
			
			if(setArrivalTime)
			{
				// add the travel time
				if(!isNaN(travelHours))
					hour += travelHours;
				if(!isNaN(travelMinutes))
					minute += travelMinutes;
				
				if(minute >= 60)
				{
					hour += Math.floor(minute / 60);
					minute = minute % 60;
				}				
				
				// add the time at the appointment
				hour += Math.floor(timeAtAppointmentInMinutes[i] / 60);
				minute += (timeAtAppointmentInMinutes[i] % 60);
				
				if(minute >= 60)
				{
					hour += Math.floor(minute / 60);
					minute = minute % 60;
				}
				
				$$('ArrivalTime' + i).innerHTML = Pad(hour, 2) + ':' + Pad(minute, 2);
				
				// is there an additional time restriction
				var timeRestriction = timeConditions[i+1];
				
				if(timeRestriction != undefined)
				{
					var restrictedTime = timeRestriction.Time.split(':');
					var restrictedHour = restrictedTime[0];
					var restrictedMinute = restrictedTime[1];
					
					if(restrictedHour != '0' && restrictedHour != '00')
						restrictedHour = restrictedHour.replace(/^0+(?=\d)/, '');
					if(restrictedMinute == '00')
						restrictedMinute = '0';
					else
						restrictedMinute = restrictedMinute.replace(/^0+(?=\d)/, '');
					
					restrictedHour = parseInt(restrictedHour);
					restrictedMinute = parseInt(restrictedMinute);
					
					if(timeRestriction.Before)
					{
						if(hour > restrictedHour || (hour == restrictedHour && minute > restrictedMinute))
							$$('ArrivalTime' + i).innerHTML = $$('ArrivalTime' + i).innerHTML + '<br /><span style="color:#f00">Arrival time after time restriction of appoinment</span>';
					}
					else
					{
						if(hour < restrictedHour || (hour == restrictedHour && minute < restrictedMinute))
							$$('ArrivalTime' + i).innerHTML = $$('ArrivalTime' + i).innerHTML + '<br /><span style="color:#f00">Arrival time before time restriction of appointment</span>';
					}
				}
			}
			else
				$$('ArrivalTime' + i).innerHTML = '';
		}
	}
}

function Pad(str, length, padString)
{
	if(padString == undefined)
		padString = '0';
	
	str = str + '';
	
	while(str.length < length)
		str = padString + str;
	
	return str;
}

function UpdateCompanyAddress()
{
	if($$('AddressSelect').value == 1)
		UpdateSalesAppointmentAddress(1);
}

function UpdateSalesAppointmentAddress(selectedValue)
{
	if(selectedValue == 1)	// customer address
	{
		var clientCompanyID = $$('cboClientCompanyID').value;
		
		if(clientCompanyID < 0 || companyAddresses[clientCompanyID] == undefined)
		{
			// update the address
			$$('Address').value = '';
			
			// clear the zone
			$$('SalesZoneID').selectedIndex = 0;
		}
		else
		{
			// update the address
			$$('Address').value = companyAddresses[clientCompanyID].Address;
			
			// set the sales zone
			if(companyAddresses[clientCompanyID].SalesZone == null)
				$$('SalesZoneID').selectedIndex = 0;
			else
			{
				var index = 0;
				var salesZoneSelect = $$('SalesZoneID');
				
				for(var i = 0; i < $$('SalesZoneID').options.length; i++)
				{
					if(salesZoneSelect.options[i].value == companyAddresses[clientCompanyID].SalesZone)
					{
						index = i;
						break;
					}
				}
				
				$$('SalesZoneID').selectedIndex = index;
			}
		}
	}
	else if(selectedValue == 2)
	{
		// update the address
		$$('Address').value = 'Unit J\nSK14 Business Park\nBroadway\nHyde\nCheshire\nSK14 4QF';
		
		// clear the zone
		$$('SalesZoneID').selectedIndex = 0;
	}
}

function GenerateWebServiceKey()
{
	var chars = '23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
	var length = 10;
	var string = '';
	var strpos;
	for(var i = 0; i < length; i++)
	{
		strpos = Math.floor(Math.random() * chars.length);
		string += chars.substr(strpos, 1);
	}
	
	$$('WebServiceKey').value = string;
}

function enableDisable(fieldNameToEnableDisable, enabled, radioButton)
{
	if(radioButton.checked)
	{
		$(document.body).elmsByAttribute('name', fieldNameToEnableDisable, 'input').each( function(elm) {
				elm.disabled = !enabled;
			});
		
		$$('rad' + fieldNameToEnableDisable + 'YesLabel').className = (enabled ? '' : 'grey');
		$$('rad' + fieldNameToEnableDisable + 'NoLabel').className = (enabled ? '' : 'grey');
	}
}

function appendAdditionalAccess(id)
{
	var link = $$('Link' + id);
	var input = $$('Input' + id);
	
	link.href += '&n=' + input.value;
}

function enableDisableAppointmentOptions(number, enableNext, total)
{
	if(number > total)
		return;
	
	var checkedOption = null;
	var hasCheckboxes = false;
	
	$('#timeslot'+(number+1)+' input[type=radio]').each( function(elm, idx, set) {
		elm.disabled = !enableNext;
		if(elm.checked)
			checkedOption = elm.value.substring(elm.value.length - 3);
		hasCheckboxes = true;
	});
	
	enableNext = enableNext && (!hasCheckboxes || checkedOption == 'ref');
	
	enableDisableAppointmentOptions(number+1, enableNext, total);
}

function displayDiaryTimeslot(userID, timestamp, timeslotID, linkId)
{
	$('#'+linkId+' div.timeslot').load('ajax.php?u='+userID+'&d='+timestamp+'&t='+timeslotID, false);
}

function ShowHideChecklist(selectedStatus)
{
	var display = selectedStatus == 1 ? (isIE ? 'block' : 'table-row') : 'none';
	
	$$('checklist').style.display = display;
}

function ShowHideList(show, elementId)
{
	var display = show ? 'block' : 'none';
	
	$$(elementId).style.display = display;
}

function ShowHideCourtesyCall(selectedStatus)
{
	var display = selectedStatus == 5 ? 'none' : (isIE ? 'block' : 'table-row');
	
	$$('trCourtesyCall').style.display = display;
}

function UpdatePercentageOffered(tablename)
{
	var table = $$(tablename);
	
	// work out the total number of complaints
	var totalcomplaints = 0;
	
	table.elmsByClass('number').elmsByTag('input').each( function() {
		var value = parseInt(this[0].value);
		
		if(!isNaN(value))
			totalcomplaints += value;
	});
	
	// update all the percentages
	table.elmsByClass('number').elmsByTag('input').each( function() {
		var id = (this[0].id).replace('speakOffered', '');
		var value = parseInt(this[0].value);
		
		if(isNaN(value))
			value = 0;
		
		var percentcell = $$(tablename+'_'+id);
		
		var percent = (totalcomplaints > 0 ? '('+(Math.round(((value * 100) / totalcomplaints) * 10) / 10)+'%)' : '&nbsp;');
		
		percentcell.innerHTML = percent;
	});
}

function UpdatePercentageContact(tablename)
{
	var table = $$(tablename);
	
	// work out the total number of complaints
	var totalcomplaints = 0;
	
	table.elmsByClass('number').elmsByTag('input').each( function() {
		var value = parseInt(this[0].value);
		
		if(!isNaN(value))
			totalcomplaints += value;
	});
	
	// update all the percentages
	table.elmsByClass('number').elmsByTag('input').each( function() {
		var id = (this[0].id).replace('contact', '');
		var value = parseInt(this[0].value);
		
		if(isNaN(value))
			value = 0;
		
		var percentcell = $$(tablename+'_'+id);
		
		var percent = (totalcomplaints > 0 ? '('+(Math.round(((value * 100) / totalcomplaints) * 10) / 10)+'%)' : '&nbsp;');
		
		percentcell.innerHTML = percent;
	});
}

function displayOpenParts(jobID)
{
	$('#partsLink div#partsDetails').load('ajax.php?j='+jobID, false);
}

function openPartsPopup(jobID)
{
	window.open('editparts.php?id='+jobID, '_blank', 'scrollbars=1,width=700,height=400');
}
