// --------------------------------------------------------------------
// File: orderCommon.js
// Desc: Simple Order System library routine
//
// Audit Trail:
// 28-Nov-2008 John Grover
//   Adapted from custom SPF order logic
// ----------------------------------------------------------------------------
browser_name = navigator.appName;
browser_version = parseFloat(navigator.appVersion); 
subnum = 0;
count = 0;
var suggestion = "";
roll = 'false';

if (browser_name == "Netscape" && browser_version >= 2.0) {
  roll = 'true';
}
else if (browser_name == "Microsoft Internet Explorer" && browser_version >= 2.0) {
  roll = 'true';
}
else if (browser_version >= 4.0) {
  roll = 'true';
}
else {
  roll = 'false';
}

// Verify input is numeric
function isanumber(e) {
  var ok = true;
  for (var i = 0; ((i < e.length) && ok); i++) {
    var chr = e.charAt(i);
    ok = (ok && (chr >= "0") && (chr <= "9"));
  }
  return ok;
}

// Verify input is a float
function isfloat(str) {
  var ok = true;
  var periods = 0;
  for (var i = 0; ((i < str.length) && ok); i++) {
    var chr = str.charAt(i);
    if (chr == ".") {
      periods++;
    }
    else {
      ok = (ok && (chr >= "0") && (chr <= "9"));
    }
  }
  return (ok && (periods <= 1));
}

// Verify input is properly formatted dollar amount
function testdollar(e) {
  if (roll == 'true') {
    if (e.value != "") {
      if (isfloat(e.value)) {
          e.value = strdollars(sfloat(e.value));
      } else {
        alert("Sorry, " + e.value + " isn't a valid dollar amount. You must enter the amount like this: 1.23 or .45 or 6.");
        e.focus();
        e.select();
      }
    }
  }
}

// Convert string to integer
function sint(e) {
  var number = parseInt(e, 10);
  if (!(number>0) || (number==0)) { return 0 } else { return number }
}

// Convert string to float
function sfloat(e) {
  var number = parseFloat(e);
  if (!(number>0) || (number==0)) { return 0 } else { return number }
}

// Format amount to 999999.99
function strdollars(amount) {
  var t = 0;
  var d = 0;
  var c = 0;
  var strtotal = "";

  t = Math.floor(amount * 100);
  c = t % 100;
  c = (c < 10) ? ("0" + c) : ("" + c);
  d = (t - c) / 100;

  return "$" + d + "." + c;
}

// Only allow numeric characters in input, recalc when ok
function test(e, form) {
  if (roll == 'true') {
    if (!isanumber(e.value)) {
      alert("Please enter only numbers in this box");
      e.focus();
      e.select();
    }
    else {
      additems(form); 
    }
  }
}

// Change text in div element
function chgDivText(divID, contents) {
  DivEl = document.getElementById(divID);
  if (DivEl) {
    DivEl.innerHTML = contents;
  }
}

function showDiv(divID) {
  DivEl = document.getElementById(divID);
  if (DivEl) {DivEl.style.display='block'}
}

function hideDiv(divID) {
  DivEl = document.getElementById(divID);
  if (DivEl) { DivEl.style.display='none' }
}

// Calulate and update shipping for order
function calcShipping(form){
  var country = new String();
  
  if (form.sameship.checked){
    country = form.billcountry.value
  } else {
    country = form.shipcountry.value
  }
  
  country = country.toUpperCase();
  prevShp = sfloat(form.orderShipping.value);
  prevTot = sfloat(form.form_amount.value);
  
  if (country != "USA" && country != "UNITED STATES" && country != "US" && country != "" ) {
    txt = "You have indicated you want your order shipped outside the United States (to " + country + ")\n" +
          "For shipping to Canada, we require an additional minimum of $5.00 plus $1 (USD) per item "+
          "or for shipping outside the US and Canada we require an additional $7.00 plus $2 per item (USD).\n"+
          "The shipping amount and order total have been automatically updated"
    alert(txt);
    if (country == "CANADA") {
      currShip = 5 + ( form.form_item_count.value * 1 )
    }else{
      currShip = 7 + ( form.form_item_count.value * 2 )
    }
  } else {
    currShip = 0
  }
  
  // Ah.. but shipping may change 
  currTot = prevTot - prevShp + currShip;
  form.orderShipping.value = currShip
  form.form_amount.value   = currTot
  
  chgDivText('show_shipping', strdollars(currShip))
  chgDivText('show_amount',   strdollars(currTot))
}

//
function validateClick(form) {
  additems;
  if (sint(form.form_item_count.value)==0){
    alert ("You have not ordered anything yet")
  }else{
    if (submitclick(form)) form.submit()
  }
}

// Avoid multiple form submissions
function submitclick(form) {
 if (subnum==0) {
  subnum++;
  return true;
 } else {
  alert("This order is already submitted. Please wait briefly for your receipt.");
  return false;
 }
}

// Validate credit card number format
function MycheckCreditCard (cardnumber, cardname) {
  txt = "The Credit card number you have entered is not a valid " +
         cardname.value + " number, please correct it and try again"
  if (cardnumber.value != ""){
    if (!checkCreditCard(cardnumber.value, cardname.value)) alert (txt)
    cardnumber.focus()
    cardnumber.select()
  } 
}

// Validate the expiration date
function checkExpiration (expDate) {

  if (expDate.value == "") return
  msg=""
  err=false
  
  s = new String (expDate.value)
  i = s.indexOf("/")
  a = new Array ();
  a=s.split("/")
  
  if ((i<=0) || (a.length != 2)){
    err=true
    msg="Invalid date format"
  } else {
  
    if (!isanumber(a[0]) || !isanumber(a[1])){
      err=true
      msg="Invalid date!"
    } else {
  
      mm = sint(a[0]) - 1; 
      yy = sint(a[1])
      yy = (yy > 40) ? yy += 1900 : yy += 2000
    
      if ((!err) && (mm < 0 || mm > 11)){
        err=true
        msg="Invalid month!"
      } else {
  
        t = new Date()
        d = new Array(31,28,31,30,31,30,31,31,30,31,30,31)
        x = new Date( yy, mm, d[mm]) // leap year issues ...

        if ( x < t ){
          err=true
          msg="Expired!?\nThe expiration date entered is past!"
        }
      }
    }
  }

  if (err) {
    msg += "\nplease enter in MM/YY format i.e. 12/06 for December 2006"
    alert(msg)
    expDate.focus()
    expDate.select()
  }
}


function validEmail(addy) {
// validate email address format
  var at="@"
  var dot="."
  var lat=addy.indexOf(at)
  var lstr=addy.length
  var ldot=addy.indexOf(dot)
		
  if (addy.indexOf(at)==-1 || addy.indexOf(at)==0 || addy.indexOf(at)==lstr){ return false }
  if (addy.indexOf(dot)==-1 || addy.indexOf(dot)==0 || addy.indexOf(dot)==lstr){ return false }
  if (addy.indexOf(at,(lat+1))!=-1){ return false }
  if (addy.substring(lat-1,lat)==dot || addy.substring(lat+1,lat+2)==dot){ return false }
  if (addy.indexOf(dot,(lat+2))==-1){ return false }
  if (addy.indexOf(" ")!=-1){ return false }

  return true					
}
