// JavaScript Document
<!--//
// Used to calcualate the Inc GST and Ex GST amount based on one value being present.
function computeGST(field) 
{
	var form = field.form;
	var gst_rate = form.calc_gst.value;
	if (field.value == null || field.value.length == 0)
	{				
		// Make sure all field are blank.
		form.ex_gst.value = "";
		form.inc_gst.value = "";
		form.gst_temp.value = "";
		gst_amount.innerHTML = "$";
		return;
	}	
	// check numeric will return a numeric value minus any commas
	var test_value = checknumeric(field, form);
	// If there is a test value i.e. it is numeric then continue.
	if(test_value)
	{	
		var number = parseFloat(test_value);
		// find out which field was changed and check for a value.
		if(field.name == "ex_gst")
		{
			// must make sure that the ex_gst value on the form is without commas for formatting after IF.
			form.ex_gst.value = test_value;
			// Calculate the Inc Gst value and set the field.
			var inc = number * (gst_rate/100) + number;
			form.inc_gst.value = inc;			
			var gst = inc - number;			
		}	
		if(field.name == "inc_gst")
		{
			// must make sure that the inc_gst value on the form is without commas for formatting after IF.
			form.inc_gst.value = test_value;
			// Calculate the Ex Gst value and set the field.
			ex = number / (gst_rate/100+1);						
			form.ex_gst.value = ex;
			var gst = number - ex;			
		}
		// Set GST hidden field for formatting purposes.
		form.gst_temp.value = gst;		
		// Format GST Numbers.
		var ex_gst = form.ex_gst.value;
		var inc_gst = form.inc_gst.value;
		// Send Field Name, Value, Form, and number format required.
		formatNumber("ex_gst", ex_gst, form, ",0.00");
		formatNumber("inc_gst", inc_gst, form, ",0.00");
		formatNumber("gst_temp", gst, form, ",0.00");
		gst = form.gst_temp.value;
		gst_amount.innerHTML = "$&nbsp;&nbsp;" + gst;
	}
	else
	{
		// Make sure all field are blank.
		form.ex_gst.value = "";
		form.inc_gst.value = "";
		form.gst_temp.value = "";
		gst_amount.innerHTML = "$";
		return;
	}
}


// Used to calculate the repayments.
function computeRepayments(field, altfield) 
{	
	var form = field.form;	
	// Altfield means that weeks/days or hours has been changed. the alternate field is the actual field that we want to recalcualate.
	if(altfield)
	{
		field = form[altfield];
	}
	// check that weeks, workdays and workhours are entered.
	if(!checkRepayments(form.weeks)) { return; }
	if(!checkRepayments(form.workdays)) { return; }
	if(!checkRepayments(form.workhours)) { return; }
	
	if (field.value == null || field.value.length == 0)
	{				
		clearRepayments(form);
		return;
	}
	
	// check numeric will return a numeric value minus any commas
	var test_value = checknumeric(field, form);
	// If there is a test value i.e. it is numeric then continue.
	if(test_value)
	{
		var number = parseFloat(test_value);
		var weeks = parseFloat(form.weeks.value);
		var days = parseFloat(form.workdays.value);
		var hours = parseFloat(form.workhours.value);		
		
		// find out which field was changed and check for a value.
		if(field.name == "monthly")
		{
			// must make sure that the monthly value on the form is without commas for formating after IF.
			form.monthly.value = number;
			// Calculate the Inc Gst value and set the field.
			weekly = (number * 12) / weeks;
			daily = weekly/days;
			hourly = daily / hours;
			form.weekly.value = weekly;
			form.daily.value = daily;
			form.hourly.value = hourly;
		}	
		if(field.name == "weekly")
		{
			// must make sure that the weekly value on the form is without commas for formating after IF.
			form.weekly.value = number;
			monthly = (number * weeks) / 12;
			daily = number/days;
			hourly = daily / hours;
			form.monthly.value = monthly;
			form.daily.value = daily;
			form.hourly.value = hourly;
		}
		if(field.name == "daily")
		{
			// must make sure that the daily value on the form is without commas for formating after IF.
			form.daily.value = number;
			monthly = (number * days * weeks) / 12;
			weekly = (monthly * 12) / weeks;
			hourly = number / hours;
			form.monthly.value = monthly;
			form.weekly.value = weekly;
			form.hourly.value = hourly;
		}
		if(field.name == "hourly")
		{
			// must make sure that the hourly value on the form is without commas for formating after IF.
			form.hourly.value = number;
			daily = number * hours;
			weekly = daily * days;
			monthly = weekly * weeks / 12;
			form.monthly.value = monthly;
			form.weekly.value = weekly;
			form.daily.value = daily;		
		}	
		
		// Format Repayment Numbers.
		var monthly = form.monthly.value;
		var weekly = form.weekly.value;
		var daily = form.daily.value;
		var hourly = form.hourly.value;
	
		// Send Field Name, Value, Form, and number format required.
		formatNumber("monthly", monthly, form, ",0.00");
		formatNumber("weekly", weekly, form, ",0.00");
		formatNumber("daily", daily, form, ",0.00");
		formatNumber("hourly", hourly, form, ",0.00");
	}
	else
	{
		// Make sure all field are blank.
		clearRepayments(form);
		return;
	}	
}
// Fuction will clear all of the repayment values.
function clearRepayments(form)
{
	form.monthly.value = "";
	form.weekly.value = "";
	form.daily.value = "";
	form.hourly.value = "";
	return;
}

// Check if weeks, days or hours has changed and are present.	
function checkRepayments(field)
{
	var form = field.form;
	if(field.name == "weeks")
	{
		var fieldname = "Weeks Per Year";
		var error = "more than 52";
	}
	if(field.name == "workdays")
	{
		var fieldname = "Days Per Week";
		var error = "more than 7";
	}
	if(field.name == "workhours")
	{
		var fieldname = "Hours Per Day";
		var error = "more than 24";
	}	
	// Check the field.
	if(checknull(field, fieldname, form, error))
	{
		var field_name = field.name;
		// Field has changed and is numeric so now check that it is a valid entry.
		var iserror = false;
		switch(field_name) 
		{
			case("weeks"): 
				if(field.value > 52)
				{
					iserror = true;
				}
			break;
			case("workdays"): 
				if(field.value > 7)  // Days per week
				{
					iserror = true;
				}
				else
				{
					// Check if there are more Days than weeks entered.
					if(form.weeks.value < 1) 
					{
						alert("Number of weeks should be at least 1.");
					}			
				}
			break;
			case("workhours"): 
				if(field.value > 24)
				{
					iserror = true;
				}
			break;
			default:
			break;
		}
		if(iserror)
		{
			alert(fieldname + " should not be " + error + ".");
			return true; // Still returns true as the value IS numeric, user may wish to use value anyway.
		}
		else
		{
			// Field has changed and the value is valid so therefore re-calculate based on the new value.
			return true;
		}		
	}
	else
	{
		return false;
	}
}

// Used to check for a null character in the weeks, days or hours fields and that it is numeric.
function checknull(field, fieldname, form, error)
{	
	if (field.value == null || field.value.length == 0)
	{				
		// These values should not be empty.
		alert(fieldname + " cannot be empty.");	
		// Make sure all repayment fields are blank.
		clearRepayments(form);
		return false;
	}
	else
	{		
		var numeric = checknumeric(field, form, fieldname);
		if(numeric)
		{
		   return true;		   
		}
		else
		{
			// Make sure all repayment fields are blank.
			clearRepayments(form);
			return false;
		}
	}
}

function checknumeric(field, form, msg)
{
	// Message will be sent from the checkNull function for weeks, days and hours.
	if(!msg)
	{
		msg = field.name;
	}
	pattern = /^[0-9]*\.?[0-9]*$/;
	var test_value = field.value;
	// following line will remove any commas in the number.
	test_value = test_value.replace(/,/g, "");
	if(pattern.test(test_value)==false)
	{
		alert(msg + " field must be numeric.");
		field.value = "";
		return false;
	}
	else
	{
		// will return the numeric value minus any commas for calculation.
		return test_value;
	}
}

// Used to determine what appears in the Residual drop down list when a Term has been selected.
residual = new Array(
	new Array(
		new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20),
		new Array("30%", 30),
		new Array("40%", 40),
		new Array("50%", 50)
	),
	new Array(
		new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20),
		new Array("30%", 30),
		new Array("40%", 40),
		new Array("50%", 50)
	),
	new Array(
	  	new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20),
		new Array("30%", 30),
		new Array("40%", 40),
		new Array("50%", 50)
	),
	new Array(
		new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20),
		new Array("30%", 30),
		new Array("40%", 40),
		new Array("50%", 50)
	),

	new Array(
		new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20),
		new Array("30%", 30),
		new Array("40%", 40)		
	),
	new Array(
		new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20),
		new Array("30%", 30)
	),
	new Array(
		new Array("[Select]", "-1"),
		new Array("Nil", "Nil"),
		new Array("10%", 10),
		new Array("20%", 20)		
	)
);

function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) 
{
	// get current value of Residual drop down, if its Nil make sure that it doesn't change.
	var form = selectCtrl.form;
 	var residual = form.Residual.value;
	var i, j;
	var prompt;
	// empty existing items
	for (i = selectCtrl.options.length; i >= 0; i--) 
	{
		selectCtrl.options[i] = null; 
	}
	
	prompt = (itemArray != null) ? goodPrompt : badPrompt;
	if (prompt == null) 
	{
		j = 0;
	}
	else 
	{
		selectCtrl.options[0] = new Option(prompt);
		j = 1;
	}
	
	if (itemArray != null) 
	{
		// add new items
		for (i = 0; i < itemArray.length; i++) 
		{
			selectCtrl.options[j] = new Option(itemArray[i][0]);
			if (itemArray[i][1] != null) 
			{
				selectCtrl.options[j].value = itemArray[i][1]; 
			}
			j++;
		}
		// select first item (prompt) for sub list unless residual is set to Nil in which case do not change it.
		if(residual == "Nil")
		{
			selectCtrl.options[1].selected = true;
		}
		else
		{
			selectCtrl.options[0].selected = true;
		}
   }
}
//  End Dropdown list -->


// Following code will format all numbers to 2 decimal places and add commas where required.
// Original JavaScript code by Duncan Crombie: dcrombie@chirp.com.au
   // Please acknowledge use of this code by including this header.

   // CONSTANTS
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function formatNumber(field, number, form, format, print) {  // use: formatNumber(number, "format")    
	if (print) document.write("formatNumber(" + number + ", \"" + format + "\")<br>");

    if (number - 0 != number) return null;  // if number is NaN return null
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
	form[field].value = output;
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  } 
// ****  END FORMAT NUMBERS

// Used to validate the form and display messages as required.
function validateForm(form)
{
	// Collect which section has been chosen to 'solve'.
	for (i=0;i<document[form].solve.length;i++)
	{
		if (document[form].solve[i].checked)
		{
			solve = document[form].solve[i].value;
		}
	}

	// gather 1 variable from each section then test to ensure we have at least 3.
	var ex_gst = document[form].ex_gst.value;
	var Term = document[form].Term.value;
	var Residual = document[form].Residual.value;
	var monthly = document[form].monthly.value;
	var one = false;
	var two = false;
	var three = false;
	var four = false;
	// Validate needs to be true so that selected section does not show error message on calculate if correct..
	var validate = true;  
	
	if(ex_gst != "") { one = true; }
	if(Term != "-1") { two = true; }
	if(Residual != "-1") { three = true; }
	if(monthly != "") { four = true; }	
	
	// variable used to toggle messages on/off
		object1 = document.getElementById("r_cog");
		object2 = document.getElementById("r_term");
		object3 = document.getElementById("r_residual");
		object4 = document.getElementById("r_repayment");
		
	// test depending on the selected solve value.
	switch(solve) 
	{
		case("cog"): 
			if(two && three && four)
			{
				// hide the error messages
				object1.style.display = "none";		
				object2.style.display = "none";		
				object3.style.display = "none";		
				object4.style.display = "none";	
				document[form].validated.value = "yes";
				document[form].solve_for.value = "cog";
			}
			else
			{
				validate = false;
			}
		break;

		case("term"): 
			if(one && three && four)
			{
				// hide the error messages
				object1.style.display = "none";		
				object2.style.display = "none";		
				object3.style.display = "none";		
				object4.style.display = "none";	
				document[form].validated.value = "yes";
				document[form].solve_for.value = "term";
			}
			else
			{
				validate = false;
			}  
		break;
		
		case("residual"): 
	  		if(one && two && four)
			{
				// hide the error messages
				object1.style.display = "none";		
				object2.style.display = "none";		
				object3.style.display = "none";		
				object4.style.display = "none";	
				document[form].validated.value = "yes";
				document[form].solve_for.value = "residual";
			}
			else
			{
				validate = false;
			}  
		break;
		
		case("repayments"): 
  			if(one && two && three)
			{
				// hide the error messages
				object1.style.display = "none";		
				object2.style.display = "none";		
				object3.style.display = "none";		
				object4.style.display = "none";	
				document[form].validated.value = "yes";
				document[form].solve_for.value = "repayments";
			}
			else
			{
				validate = false;
			}  
		break;
		
		default:
		break;
	}
	
	// if the form did not validate then work out which values are required and make the messages visible.
	if(!validate)	
	{
		// If not 3 of the 4 sections filled out then determine which and display message accordingly.
		if(!one)
		{		
			object1.style.display = "block";
		}
		else
		{
			object1.style.display = "none";
		}
	
		if(!two)
		{
			object2.style.display = "block";
		}
		else
		{
			object2.style.display = "none";
		}
	
		if(!three)
		{
			object3.style.display = "block";
		}
		else
		{
			object3.style.display = "none";
		}
	
		if(!four)
		{
			object4.style.display = "block";
		}
		else
		{
			object4.style.display = "none";
		}
	}
	else
	{
		document[form].can_print.value = "yes";
		// Gather address details from print_form and place them in the calcualted form.
		var comp = document['print_form'].comp_name.value;
		var cont = document['print_form'].contact.value;
		var tel = document['print_form'].phone.value;
		var email = document['print_form'].email.value;
		var desc = document['print_form'].desc.value;
		document[form].client_company.value = comp;
		document[form].client_contact.value = cont;
		document[form].client_telephone.value = tel;
		document[form].client_email.value = email;
		document[form].client_desc.value = desc;
		submitform(form);
	}
}

// Any changes to the left hand side of the screen should cancel any result in the right hand side of the screen.
function clearCalcs(field)
{
	form = field.form;
	// Make sure that the right hand side is displaying the blank div.
	object1 = document.getElementById("actual_calcs");
	object2 = document.getElementById("blank_calcs");
	object1.style.display = "none";
	object2.style.display = "block";	

	form.validated.value = "";
	form.solve_for.value = "";
	form.can_print.value = "no";
}

// Generic hide and show.
function showHideMessage(line, task)
{
	var object = document.getElementById(line);	
	object.style.display = task;
}

// Will open the window for printing.
function openwindowprint(frm, button)
{	
	if(button)
	{
		frm = document.getElementById(frm);
	}
	if(document["calc"].can_print.value == "yes")
	{
		var newwindow = window.open('',"my_new_window","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=780 height=580, left=50, top=50");
		frm.target = "my_new_window";
		frm.submit();	
		if (window.focus) {newwindow.focus();}else{alert("POO");}
	}
	else
	{
		alert("Calculations not complete.");
	}
}

// Used to submit any form via javascript.
function submitform(x)
{
 	document.getElementById(x).submit(); 
}


// The following function is now obsolete and not in use.
// Hide residual drop down and set to Nil if sovle for COG is selected otherwise show it 
function setResidual(field)
{
	var form = field.form;
	// Collect which section has been chosen to 'solve'.
	for (i=0;i<form.solve.length;i++)
	{
		if (form.solve[i].checked)
		{
			solve = form.solve[i].value;
		}
	}
	if(solve == "cog")
	{
		form.Residual.value = "Nil";
		object = document.getElementById("residual_div");
		object.style.display = "none";
		object1 = document.getElementById("residual_div_alt");
		object1.style.display = "block";
	}
	else
	{
		object = document.getElementById("residual_div");
		object.style.display = "block";
		object1 = document.getElementById("residual_div_alt");
		object1.style.display = "none";
	}
}