// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Aug 2004: have tested that IE 5.0 and IE 5.5 both support DOM model
// sufficiently well, so innerHTML option removed (redundant).
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message))
    dispmessage = String.fromCharCode(nbsp);
  else
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;

  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed),
//         false (validation failed) or
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById)
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node

  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "*");
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;
    }
  }
  return proceed;
}

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;
  msg (ifld, "warn", "");
  return true;

};

// -----------------------------------------

//              compareEmail

// -----------------------------------------


function compareEmail  (vfld,   // 1st email

                        vfld2,  // 2nd email

                        ifld)   // id of element to receive info/error msg

{

  if (vfld.value==vfld2.value) {

    return true;

  }

  msg (ifld, "error", "No match");

  return false;

};


// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "*");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld))
    msg (ifld, "warn", "Unusual");
  else
    msg (ifld, "warn", "");
  return true;
};


// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "ERROR: not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (ifld, "error", "ERROR: " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "warn", numdigits + " digits - check if correct");
  else {
    if (numdigits<10)
      msg (ifld, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "warn", "");
  }
  return true;
};

// -----------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK
// -----------------------------------------

function validateAge    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg (ifld, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (ifld, "warn", "Bit young for this, aren't you?");
    else        msg (ifld, "warn", "");
  }
  return true;
};



function checkNumeric(objName,period)
{
	var numberfield = objName;
	if (chkNumeric(objName,period) == false)
	{
		numberfield.select();
		numberfield.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function chkNumeric(objName,period)
{
var checkOK = "0123456789" + period ;
var checkStr = objName;
var allValid = true;
var decPoints = 0;
var allNum = "";

for (i = 0;  i < checkStr.value.length;  i++)
{
ch = checkStr.value.charAt(i);
for (j = 0;  j < checkOK.length;  j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
if (ch != ",")
allNum += ch;
}
if (!allValid)
{
alertsay = "This field requires numerical input  "
alert(alertsay);
return (false);
}
}


function openPic(page,winName,xWidth,yHeight){
  	window.open(page,winName,'width='+xWidth+',height='+yHeight+',toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,top=0,left=0');
  }

function doButtons(textimage, picimage, imageid)
	{
	var txt
	txt = "txt"+imageid;
//	document.all[txt].innerHTML = textimage+"";
	document['picture'+imageid].src=picimage;
}


function doUrl(select){
										document.location = select.options[select.selectedIndex].value;
									}

									function lets_goToURL() { //v3.0
									  var i, args=lets_goToURL.arguments; document.lets_returnValue = false;
									  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
									}

function compute(obj) {
										if (setnum(obj)){
											fprice = parseFloat(obj.price.value)
											fdeposit = parseFloat(obj.deposit.value)
											fmonths =  parseFloat(get_selection(obj.period).value);
											finterest = parseFloat(obj.interest.value)
											ffinal_payment = parseFloat(obj.final_payment.value)
											fpayments = parseFloat(obj.payments.value)
											var intermediate = new MakeArray(fmonths);
											var i
											var fdaily_rate = finterest/36500;
											var famount = fprice - fdeposit;
											var ftotal = 0;
											for (i = 0; i <= fmonths -1; i++) {
												intermediate[i] =1+30.42*fdaily_rate
											}

											for (i = fmonths - 2; i >= 0; i--) {
												intermediate[i] = intermediate[i] * intermediate[i+1];
											}

											for (i = 0; i <= fmonths-1; i++ ) {
												ftotal = ftotal  + intermediate[i];
											}
											if (fpayments == 0) {
												fpayments = ((famount*intermediate[0]-ffinal_payment)/(ftotal+1-intermediate[0]));
												obj.payments.value = Math.round(fpayments)
											}else if (fprice == 0) {
												famount =((fpayments*(ftotal+1-intermediate[0]))+ffinal_payment)/intermediate[0];
												fprice = famount + fdeposit;
												obj.price.value = Math.round(fprice)
											}else if (fdeposit == 0) {
												famount =((fpayments*(ftotal+1-intermediate[0]))+ffinal_payment)/intermediate[0];
												fdeposit = fprice - famount;
												obj.deposit.value = Math.round(fdeposit)
											}else if (ffinal_payment == 0) {
												ffinal_payment = (famount*intermediate[0])-(fpayments*(ftotal+1-intermediate[0]));
												obj.final_payment.value = Math.round(ffinal_payment)
											}else{
												fpayments = ((famount*intermediate[0]-ffinal_payment)/(ftotal+1-intermediate[0]));
												obj.payments.value = Math.round(fpayments)
											}
										}
									}

									function MakeArray(n) {
										this.length = n;
										for (var i = 1; i <= n; i++) {
											this[i] = 0
										}
										return this;
									}

									function select_item(name, value) {
										this.name = name;
										this.value = value;
									}

									function get_selection(select_object) {
										contents = new select_item("w","w");
										for(var i=0;i<select_object.options.length;i++)
											if(select_object.options[i].selected == true) {
												contents.name = select_object.options[i].text;
												contents.value = select_object.options[i].value;
											}
										return contents;
									}



									function setnum(obj) {
										if (obj.payments.value == ""){
											obj.payments.value = "0"
										}
										if (obj.price.value == ""){
											obj.price.value = "0"
										}
										if (obj.deposit.value == ""){
											obj.deposit.value = "0"
										}
										if (obj.interest.value == ""){
											obj.interest.value = "0"
										}
										if (obj.final_payment.value == ""){
											obj.final_payment.value = "0"
										}
										if (obj.payments.value == 0 && obj.price.value == 0){
											alert("Please enter either the price or the monthly payments.")
											return false;
										}
										if (isnum(obj.payments.value,"payments") && isnum(obj.price.value,"price") && isnum(obj.deposit.value,"deposit") && isnum(obj.interest.value,"interest") && isnum(obj.final_payment.value,"final payment")){
											return true;
										}else{
											return false;
										}
									}

									function isnum(str,strname) {
										for (var i = 0; i < str.length; i++) {
										var ch = str.substring(0,1)
											if (ch < "0" || ch > "9") {
												alert("Try a number for "+strname+", please.");
												return false;
											}
										}
										return true;
									}

var c = 1;
function addSame()
	{
	if(c == 1)
		{
		xForm.deliveryAdd.value = xForm.postAdd.value;
		xForm.deliveryProvinceID.value = xForm.provinceID.value;
		//myForm.ShipStateProv.value = xForm.StateProv.value;
		xForm.deliveryPostCode.value = xForm.postCode.value;
		//myForm.ShipCountry.value = xForm.Country.value;
		c = 0;
		}
	else
	if(c == 0)
		{
		xForm.deliveryAdd.value = "";
		//xForm.ShipCity.value = "";
		xForm.deliveryProvinceID.value = "";
		xForm.deliveryPostCode.value = "";
		//xForm.ShipCountry.value = "";
		c = 1;
		}
	}

function checkTerms()
{
	if (xForm.terms.checked == 1)
	return true;
    //alert("Thank You");
  else
    alert("You must read the terms and conditions before proceeding")
    //chk.checked = 1;
    return false;
	}
