var isIE = /*@cc_on!@*/false;

function ChangeJobTab(newTab)
{
	var tabs = new Array('inf', 'app', 'rep', 'par', 'not', 'int');
	
	for(var i = 0; i < tabs.length; i++)
	{
		try
		{
			$$(tabs[i]+"l").className = '';
			$$(tabs[i]).style.display = 'none';
		}
		catch(e)
		{
		}
	}
		
	if(InArray(tabs, newTab))
	{
		try
		{
			$$(newTab+"l").className = 'active';
			$$(newTab).style.display = 'block';
		}
		catch(e)
		{
		}
	}
	
	return false;
}

function ChangePolicyTab(newTab)
{
	var tabs = new Array('inf', 'cla', 'rep');
	
	for(var i = 0; i < tabs.length; i++)
	{
		try
		{
			$$(tabs[i]+"l").className = '';
			$$(tabs[i]).style.display = 'none';
		}
		catch(e)
		{
		}
	}
	
	if(InArray(tabs, newTab))
	{
		try
		{
			$$(newTab+"l").className = 'active';
			$$(newTab).style.display = 'block';
		}
		catch(e)
		{
		}
	}
	
	return false;
}

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 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)
{	
	var els = $$('form-user').elmsByClass('techOnly');
	
	// so ie6 doesn't hide istechnician checkbox
	$$('IsTechnician').style.display = 'none';
	
	for(var i = 0; i < els.length; i++)
		els[i].style.display = (show == "1" ? 'block' : 'none');
	
	// so ie6 doesn't hide istechnician checkbox
	$$('IsTechnician').style.display = ($$('LoginType').value == 0 ? '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, defaultDate)
{
	var parts = value.split(',');
	
	if(parts.length == 3)
	{
		var d = new Date();
		var year = d.getFullYear();
		var timeSelectedIndex = 0;
		var techSelectedIndex = 0;
		
		if(parts[0] == -1 || parts[1] == -1 || parts[2] == -1)
		{
			var date = defaultDate.split('/');
			
			$$('cbovisitDateDD').selectedIndex = date[0] - 1;
			$$('cbovisitDateDD').onchange = '';
			$$('cbovisitDateMM').selectedIndex = date[1] - 1;
			$$('cbovisitDateMM').onchange = '';
			
			var yearSelectedIndex = year - date[2] + 1;
			
			$$('cbovisitDateYYYY').selectedIndex = yearSelectedIndex;
			$$('cbovisitDateYYYY').onchange = '';
			
			$$('cboVisitTimeID').onchange = '';
			$$('cbotechnicianAssigned').onchange = '';
		}
		else
		{
			var date = parts[0].split('/');
			
			$$('cbovisitDateDD').selectedIndex = date[0] - 1;
			$$('cbovisitDateDD').onchange = 'this.selectedIndex = '+(date[0] - 1);
			
			$$('cbovisitDateMM').selectedIndex = date[1] - 1;
			$$('cbovisitDateMM').onchange = 'this.selectedIndex = '+(date[1] - 1);
			
			var yearSelectedIndex = year - date[2] + 1;
			
			$$('cbovisitDateYYYY').selectedIndex = yearSelectedIndex;
			$$('cbovisitDateYYYY').onchange = '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 = 'this.selectedIndex = '+timeSelectedIndex;
			
			// set the technician
			for(i = 0; i < $$('cbotechnicianAssigned').length; i++)
			{
				if($$('cbotechnicianAssigned')[i].value == parts[1])
				{
					techSelectedIndex = i;
					break;
				}
			}
			$$('cbotechnicianAssigned').onchange = 'this.selectedIndex = '+techSelectedIndex;
		}
		
		$$('cboVisitTimeID').selectedIndex = timeSelectedIndex;
		$$('cbotechnicianAssigned').selectedIndex = techSelectedIndex;
	}
}

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(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)
{
	var newJobStatus = $$('cboStatusID').value;
	
	if(newJobStatus != originalJobStatus && (newJobStatus == 9 || newJobStatus == 3 || newJobStatus == 16 || newJobStatus == 19))
		return confirm('This job has an non-cancelled appointment on '+appointmentDate+' are you sure the job status should be changed?');
	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.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.id).replace('number', '');
		var value = parseInt(this.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 = users.slice();
		
		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)
{
	if(a.Name < b.Name)
		return -1;
	else if(a.Name == b.Name)
		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;
}