///////////////////////////////////////////////////////////////////////////////
// General functions
///////////////////////////////////////////////////////////////////////////////
function trim(string) {
	return string.replace(/^\s+/, "").replace(/\s+$/, "");
}

function strip(string, stripChar) {
	var regExpString = stripChar + "+";
	var stripRegExp = new RegExp(regExpString, "g");

	return string.replace(stripRegExp, "");
}

function lpad(string, size, padChar) {
	var dif = size - string.length;

	if (dif > 0) {
		for (; dif != 0; dif--) {
			string = padChar + string;
		}
	}
	return string;
}

function forceUpper(field) {
	field.value = field.value.toUpperCase();
}

function formatMoney(money) {
	var outputStr;
	var chunkLength;

	outputStr = money.toString();
	
	var tempMoney = money;
	if (typeof(tempMoney) != "number")
		tempMoney = parseFloat(tempMoney);
	if (tempMoney.toFixed)
		outputStr = tempMoney.toFixed(2).toString();

	if (outputStr.indexOf(".") == -1)
		outputStr = outputStr + ".00";
	else if (outputStr.indexOf(".") == outputStr.length - 2)
		outputStr = outputStr + "0";

	if (outputStr.length > 6) {
		chunkLength = outputStr.length - 6;
		outputStr = outputStr.substr(0, chunkLength) + "," + outputStr.substring(chunkLength, outputStr.length);
	}
	if (outputStr.length > 10) {
		chunkLength = outputStr.length - 10;
		outputStr = outputStr.substr(0, chunkLength) + "," + outputStr.substring(chunkLength, outputStr.length);
	}
	return outputStr;
}

function print_page() {
	if (window.print)
		window.print();
}

function check_options() {
	var today = new Date();
	var expire = new Date(today.getTime() + 15000); // 15 seconds

	document.cookie = "TestCookie=TestValue; expires=" + expire.toGMTString();
	if (document.cookie.indexOf("TestCookie") != -1) {
    document.getElementById("error_msg").className = "hideerror";
		document.getElementById("login").disabled = false;
	}
}

///////////////////////////////////////////////////////////////////////////////
// Validation functions
///////////////////////////////////////////////////////////////////////////////
function validChars(theForm) {
	var invalidChars = "\\:*?\"<>|";
	var invalidCharsOutput = "\\ : * ? \" < > |";

	for (var i = 0; i < theForm.length; i++) {
		if (theForm.elements[i].tagName == "INPUT" && theForm.elements[i].type != "hidden") {
			for (var j = 0; j < theForm.elements[i].value.length; j++) {
				if (invalidChars.indexOf(theForm.elements[i].value.charAt(j)) != -1) {
					alert("Fields must not contain any of the following characters:\n" + invalidCharsOutput);
					theForm.elements[i].focus();
					theForm.elements[i].select();
					return false;
				}
			}
		}
	}
	return true;
}

function validField(field, regExp, name, format) {
	if (field && field.value.length > 0 && !regExp.test(field.value)) {
		if (format)
			alert("The " + name + " you have provided is invalid.\n" + format);
		else
			alert("The " + name + " you have provided is invalid.");
		field.focus();
		field.select();
		return false;
	}
	return true;
}

function formatTaxRef(field) {
	var taxRef = trim(field.value);
	var unformattedTaxRefRegExp = /^\d{8}$/;
	var formattedTaxRef;

	if (taxRef.length == 8 && unformattedTaxRefRegExp.test(taxRef)) {
		formattedTaxRef = taxRef.substring(0, 5) + "-" + taxRef.substring(5, 8);
		field.value = formattedTaxRef;
	}
	return field;
}

///////////////////////////////////////////////////////////////////////////////
// Form validation
///////////////////////////////////////////////////////////////////////////////
function check_user_form() {
	var theForm = document.getElementById("user_form");

	var postcodeRegExp = /^\d{4}$/;
	var streetPC = theForm.street_postcode;
	var postalPC = theForm.postal_postcode;

	var areaCodeRegExp = /^\d{1,5}$/;
	var telArea = theForm.tel_area;
	var faxArea = theForm.fax_area;

	var phoneRegExp = /^\d{6,15}$/;
	var telephone = theForm.telephone;
	var fax = theForm.fax;
	telephone.value = strip(telephone.value, " ");
	telephone.value = strip(telephone.value, "-");
	fax.value = strip(fax.value, " ");
	fax.value = strip(fax.value, "-");

	var emailRegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
	var email = theForm.email;

	var ASICRegExp = /^\d{1,5}$/;
	var ASIC = theForm.asic_reg;

	for (var i = 0; i < theForm.length; i++) {
		if (theForm.elements[i].type == "text" &&
			theForm.elements[i].className == "required" &&
			trim(theForm.elements[i].value) == "") {
			alert("A required field is blank.");
			theForm.elements[i].focus();
			return false;
		}
	}

	return (validChars(theForm) &&
		validField(streetPC, postcodeRegExp, "street address postcode") &&
		validField(postalPC, postcodeRegExp, "postal address postcode") &&
		validField(telArea, areaCodeRegExp, "telephone area code") &&
		validField(faxArea, areaCodeRegExp, "fax area code") &&
		validField(telephone, phoneRegExp, "telephone number") &&
		validField(fax, phoneRegExp, "fax number") &&
		validField(email, emailRegExp, "email address") &&
		validField(ASIC, ASICRegExp, "ASIC number"));
}

function check_purchase_form() {
	var theForm = document.getElementById("purchase_form");
	var taxRefRegExp = /^\d{5}-\d{3}$/;
	var cashRegExp = /^[0-9A-Z]*$/;

	for (var i = 1; i < theForm.length; i++) {
		if (theForm.elements[i].type == "text" && theForm.elements[i].name.substr(0, 7) == "ta_ref_") {
			formatTaxRef(theForm.elements[i]);
			if (!validField(theForm.elements[i], taxRefRegExp, "tax agent reference number", "eg: xxxxx-xxx"))
				return false;
		}
		else if (theForm.elements[i].type == "text" && theForm.elements[i].name.substr(0, 4) == "reg_") {
			if (!validField(theForm.elements[i], cashRegExp, "HandiCash reference code", "The code must consist of only uppercase letters and digits."))
				return false;
		}
	}

	return (validChars(theForm) && noneEmpty(theForm));
}

function noneEmpty(theForm) {
	for (var i = 0; i < theForm.length; i++) {
		if (theForm.elements[i].type == "text") {
			if (trim(theForm.elements[i].value) == "") {
				alert("Please fill in all fields.");
				theForm.elements[i].focus();
				theForm.elements[i].select();
				return false;
			}
		}
	}
	return true;
}

///////////////////////////////////////////////////////////////////////////////
// Page update/interaction functions
///////////////////////////////////////////////////////////////////////////////
function findElementIndex(theForm, code) {
	for (var i = 1; i <= theForm.num_products.value; i++) {
		if (theForm.elements["id_" + i] && theForm.elements["id_" + i].value == code)
			return i;
	}
	return -1;
}

function findDependentIndex(theForm, code) {
	for (var i = 1; i <= theForm.num_products.value; i++) {
		if (theForm.elements["prod_reqd_code_" + i] && theForm.elements["prod_reqd_code_" + i].value == code)
			return i;
	}
	return -1;
}

function setupCheckBoxes() {
	var theForm = document.getElementById("purchase_form");
	var testedArray = new Array(theForm.num_products.value);
	for (var i = 1; i <= theForm.num_products.value; i++)
		testedArray[i - 1] = "";
	for (var i = 1; i <= theForm.num_products.value; i++)
		testCheckBox(theForm, testedArray, i);
}

// prod_reqd_code - code of another product required to be checked to enable this product (only used for multiple purchase products, single purchase are assumed to be enabled)
// other_prod_reqd - for multiple purchase products - sets minimum qty to 1 if the other product is checked
//                 - for single purchase products - code of another product that is mutually exclusive with this product
function testCheckBox(theForm, testedArray, prodIndex) {
  var arrayIndex = prodIndex - 1;
  if (testedArray[arrayIndex] == "T")
    return;
  testedArray[arrayIndex] = "T";

  var doDisable = false; // elements with no reqd codes are always enabled
  if (theForm.elements["prod_reqd_code_" + prodIndex].value != "000" || theForm.elements["other_prod_reqd_" + prodIndex].value != "000") {
    var enablingCodes = theForm.elements["prod_reqd_code_" + prodIndex].value;
    if (enablingCodes != "000") {
      // check required products are checked and if none are then disable the product
      doDisable = true;
      for (var pos = 0; pos < enablingCodes.length && doDisable; pos += 3) {
        var theCode = enablingCodes.substr(pos, 3);
        var enablingProdIndex = findElementIndex(theForm, theCode);
        if (enablingProdIndex != -1 && enablingProdIndex != prodIndex) {
          testCheckBox(theForm, testedArray, enablingProdIndex);
          if (theForm.elements["product_" + enablingProdIndex].checked)
            doDisable = false;
        }
        else // the product requires itself or the required product isn't displayed which means it has already been purchased
          doDisable = false;
      }
    }
    // single purchase product
    if (theForm.elements["max_qty_" + prodIndex].value == "1") {
      var disablingCodes = theForm.elements["other_prod_reqd_" + prodIndex].value;
      if (disablingCodes != "000") {
        // check other mutually exclusive products, if any is checked then disable this product
        for (var pos = 0; pos < disablingCodes.length && !doDisable; pos += 3) {
          var theCode = disablingCodes.substr(pos, 3);
          var disablingProdIndex = findElementIndex(theForm, theCode);
          if (disablingProdIndex != -1) {
            testCheckBox(theForm, testedArray, disablingProdIndex);
            if (theForm.elements["product_" + disablingProdIndex].checked)
              doDisable = true;
          }
        }
      }
    }
    // multiple quantity product
    else {
      var enableSingleCodes = theForm.elements["other_prod_reqd_" + prodIndex].value;
      if (enableSingleCodes != "000") {
        // check other products, if any are checked then reduce the minimum quantity to 1
        var enableSingle = false;
        for (var pos = 0; pos < enableSingleCodes.length && !enableSingle; pos += 3) {
          var theCode = enableSingleCodes.substr(pos, 3);
          var enableSingleProdIndex = findElementIndex(theForm, theCode);
          if (enableSingleProdIndex != -1) {
            testCheckBox(theForm, testedArray, enableSingleProdIndex);
            if (theForm.elements["product_" + enableSingleProdIndex].checked)
              enableSingle = true;
          }
        }
        var updateSelect = theForm.elements["qty_" + prodIndex];
        if (updateSelect.length > 0) {
          if (enableSingle) {
            if (updateSelect.options[updateSelect.length - 1].value != "1") {
              var newOpt = document.createElement("option");
              newOpt.text = "1";
              newOpt.value = "1";
              try {
                updateSelect.add(newOpt, null);
              }
              catch (e) { // for IE - isn't standards compliant
                updateSelect.add(newOpt);
              }
            }
          }
          else {
            if (updateSelect.options[updateSelect.length - 1].value == "1") {
              var selectedValue = updateSelect.value;
              updateSelect.remove(updateSelect.length - 1);
              if (selectedValue == "1")
                updateSelect.selectedIndex = updateSelect.length - 1;
            }
          }
        }
      }
    }
  }
  if (doDisable) {
    theForm.elements["product_" + prodIndex].disabled = true;
    theForm.elements["product_" + prodIndex].checked = false;
  }
  else {
    theForm.elements["product_" + prodIndex].disabled = false;
  }
}

function refresh_inputs() {
	var theForm = document.getElementById("purchase_form");
	var done;
	var subTotal;
	var total = 0.0;

	var currRegValue;
	var currAgentRef;
	var currAgentName;

	if (!theForm.num_products)
		return;
	for (var i = 1; i <= theForm.num_products.value; i++) {
		// Populate on refresh/reload
		if (theForm.elements["product_" + i].checked)
			theForm.elements["product_" + i].checked = true;
	}
	
	setupCheckBoxes();

	for (var i = 1; i <= theForm.num_products.value; i++) {
		// add the individual products' costs
		if (theForm.elements["product_" + i].checked) {
			subTotal = parseInt(theForm.elements["qty_" + i].value) * parseFloat(strip(theForm.elements["cost_" + i].value, ","));
			document.getElementById("sub_" + i).innerHTML = "$" + formatMoney(subTotal);
			total += subTotal;
		}
		else
			document.getElementById("sub_" + i).innerHTML = "&nbsp;";

		// If the product is selected and needs rego numbers, output the text input fields
		if (theForm.elements["original_" + i]) {
			if (theForm.elements["product_" + i].checked &&
				theForm.elements["qty_" + i].value > 0) {
				if (document.getElementById("handitax_" + i)) {
					if (theForm.elements["ta_ref_" + i] && theForm.elements["ta_name_" + i]) {
						currAgentRef = theForm.elements["ta_ref_" + i].value;
						currAgentName = theForm.elements["ta_name_" + i].value;
					}
					else {
						currAgentRef = "";
						currAgentName = "";
					}
					extraText = "<br />Tax agent reference number and name :<br />" +
						"<input type=\"text\" maxlength=\"9\" name=\"ta_ref_" + i +
						"\" style=\"width: 70px; margin-right: 6px;\" value=\"" + currAgentRef + "\" />" +
						"<input type=\"text\" maxlength=\"45\" name=\"ta_name_" + i +
						"\" style=\"width: 190px;\" value=\"" + currAgentName + "\" onKeyUp=\"forceUpper(this)\" />";
					document.getElementById("handitax_" + i).innerHTML = theForm.elements["original_" + i].value + extraText;
				}
				else if (document.getElementById("reg_reqd_" + i)) {
					extraText = "<br />Reference code(s) :<br />";
					for (var j = 1; j <= theForm.elements["qty_" + i].value; j++) {
						if (theForm.elements["reg_" + i + "_" + j])
							currRegValue = theForm.elements["reg_" + i + "_" + j].value;
						else
							currRegValue = "";
						extraText += "<input type=\"text\" class=\"reg row_space\" maxlength=\"8\" name=\"reg_" + i + "_" + j +
							"\" value=\"" + currRegValue + "\" onKeyUp=\"forceUpper(this)\" />";
						if (j % 3 == 0)
							extraText += "<br />";
					}
					document.getElementById("reg_reqd_" + i).innerHTML = theForm.elements["original_" + i].value + extraText;
				}
				if (theForm.elements["prev_qty_" + i])
					theForm.elements["prev_qty_" + i].value = theForm.elements["qty_" + i].value;
			}
			else {
				if (document.getElementById("handitax_" + i))
					document.getElementById("handitax_" + i).innerHTML = theForm.elements["original_" + i].value;
				else if (document.getElementById("reg_reqd_" + i))
					document.getElementById("reg_reqd_" + i).innerHTML = theForm.elements["original_" + i].value;
				if (theForm.elements["prev_qty_" + i])
					theForm.elements["prev_qty_" + i].value = "0";
			}
		}
	}
	// Output the total costs
	document.getElementById("total").innerHTML = "$" + formatMoney(total);
	if (document.getElementById("grand_total")) {
		document.getElementById("grand_total").innerHTML = "$" + formatMoney(total + eval(theForm.upgrades_total.value));
	}
}

function enableNext() {
	document.getElementById("next").disabled = !document.getElementById("yesno").checked;
}

function logOut() {
	if (confirm("Any changes you have made up to this point will be lost.\nAre you sure you want to exit?"))
		document.getElementById('logout_form').submit();
}

function ccPrice() {
	var theForm = document.getElementById("card_form");
	var origCost = theForm.orig_cost.value;
	var costField = document.getElementById("total");

	// Note - we previously inspected cardtype[3].checked, but Bankcard has since been removed
	if (theForm.cardtype[2].checked)
		costField.innerHTML = "$" + formatMoney(Math.round(origCost * 100 + origCost * 100 * 0.015 * 1.1) / 100);
	else
		costField.innerHTML = "$" + formatMoney(origCost);
}
