var orderError = false;
var voucherError = false;
var xmlHttp, poller, basketData;

function pollBasket() {
  xmlHttp = GetXmlHttpObject();
  if (xmlHttp != null) {
     xmlHttp.onreadystatechange = loadFile;
     try {
     // NB: GET will cache, so ensure unique ID added to the URL
     xmlHttp.open("GET", "http://www.raymears.com/Bushcraft_Products/pollBasket.cfm?nocache=" + new Date().getTime(), true);
     } catch(e) {
       alert("Error opening Ajax GET request.");
     }
     xmlHttp.send(null);
  }
}

function loadFile() {
  var thisID;
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") { 
     basketData = eval(xmlHttp.responseText);
     if (basketData[0][0] == "SESSIONEXPIRED") {
        alert("Sorry, your shopping session expired at " + basketData[0][3] + "\n\n. Please click OK and continue shopping.");
        location.href = "http://www.raymears.com/Bushcraft_Products/";
     } else {  
       for (i=0; i < basketData.length; i++) {
           thisID = "inStockNow_" + (i+1);
           if (basketData[i][1] > basketData[i][2]) {
             orderError = true;
             document.getElementById(thisID).innerHTML = "<a title='Out of stock: "  + basketData[i][2] + " currently in stock' href='Basket.cfm'><img border='0' alt='Out of stock: "  + basketData[i][2] + " currently in stock' src='/images/div_alert.png'/></a>";
           } else {
             document.getElementById(thisID).innerHTML = "<img alt='"  + basketData[i][2] + " currently in stock' src='/images/tick.png'/>";
           }
           document.getElementById("lastchecked").innerHTML = "<font size='1'>Stock levels last checked at: " + basketData[i][3] + "</font>";
       }
    }
  }
}

function GetXmlHttpObject() { 
  var objXMLHttp = null;
  try {
    objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Later IE
  } catch (e) {
    try {
      objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); // Earlier IE
    } catch (e) {
       objXMLHttp = null;
    }
  }
  if (objXMLHttp == null) {
     objXMLHttp = new XMLHttpRequest(); // IE7, Firefox, Safari et al
  }
  return(objXMLHttp);
}

function allTrim(cValue) {
  var lDone = false;
  while (lDone == false) {
       if (cValue.length == 0) {
          return(cValue);
       }
       if (cValue.indexOf(' ') == 0) {
          cValue = cValue.substring(1);
          lDone = false; 
          continue;
       } else {lDone=true;}
         if (cValue.lastIndexOf(' ') == cValue.length-1) { 
            cValue = cValue.substring(0, cValue.length-1);
            lDone = false;
            continue;
         } else {
            lDone = true;
         }
  }
  return(cValue);
}

function showVoucherDetails(id) {
  var _v = window.open("showVoucher.cfm?id="+id, "_voucher", "width=700,height=600,scrollbars=no,resizable=no,menubar=yes");
}

function ordertotalerror() {
  alert("Your order total must be above 0.00 UKP to proceed, unless you are using one or more vouchers to the exact value of your order. You may have used too many vouchers. If this is the case, please remove one or more of the vouchers from your order.\n\nWe cannot give you a voucher-refund for orders where your total voucher reduction exceeds the total cost of the items in your basket.");
}

function allok() {
  return(confirm("Please check the following before sending your order:\n\n" +
                 "1. That your EMAIL ADDRESS is correct and WORKING, so that we can send you a receipt (please test it yourself first.)\n\n" +
                 "2. That your DELIVERY ADDRESS is correct and includes a FULL POST/ZIP CODE (and Country, if not UK-based), and does not contain any abbreviations. Your address should be formatted like this:\n\n" +
                 "Street Name\n" +
                 "Town/City\n" +
                 "Postcode\n\n" +
                 "3. That your DELIVERY CHARGE Country, if applicable, is correctly selected. Incorrectly specified delivery destinations will result in a delayed order.\n\n" +
                 "4. That your ORDER BASKET is correct and you want to purchase the goods and quantities selected.\n\n" +
                 "IMPORTANT NOTE: If an error occurs AFTER sending your credit card details, or if a blank page is unexpectedly returned, " +
                 "please DO NOT make a duplicate order or refresh the page in your browser. Exit immediately, and contact us first to see " +
                 "if the order was actually received. This will avoid duplicate orders.\n\n\n" +
                 "Click OK to proceed to our Secure Payment page, or CANCEL to halt this process and check the above details."));
}

function submitform(url) {
  document.dataform.action = url;
  document.dataform.target = "_self";
  document.dataform.submit();
} 				

function submitCountry(url, c) {
  if (c != "") {
     document.dataform.countrycode.value = c;
     document.dataform.action = url;
     document.dataform.method = "POST";
     document.dataform.target = "_self";
     document.dataform.submit();
  }
} 				

function parseName(fieldName) {
  var newName = "";
  var obj = fieldName.value;
  for (i=0; i < obj.length; i++) {
      if (i == 0) {
         newName += obj.substring(i,i+1).toUpperCase();
      } else if (obj.substring(i,i+1) == " ") {
         i ++; newName += " " + obj.substring(i,i+1).toUpperCase();
      } else if (obj.substring(i,i+1) == "-") {
         i ++; newName += "-" + obj.substring(i,i+1).toUpperCase();
      } else {
         newName += obj.substring(i,i+1).toLowerCase();
      }
  }
  // document.dataform.p_name.value = newName;
  fieldName.value = newName;
}

function parseNameUC(fieldName) {
  fieldName.value = fieldName.value.toUpperCase();
}

function checkMailAddress(email) {
  var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
  if (filter.test(email)) 
     return(true);  
  else  
     return(false);
}

function validate() {
  if (orderError) {
     alert("Please check the stock levels for your order and alter it accordingly.\n\nThe quantity of some items that you require are no longer available due to " +
           "other customer purchases that have occured before you have checked out.");
     return(false);
  }
 
  if (allTrim(document.dataform.p_name.value) == "") {
     alert("Please enter your full name.");
     document.dataform.p_name.focus();
     return(false);
  }
  if (allTrim(document.dataform.p_houseno.value) == "") {
     alert("Please enter your House/Flat number or House Name.");
     document.dataform.p_houseno.focus();
     return(false);
  }
  if (allTrim(document.dataform.p_street.value) == "") {
     alert("Please enter your Street name.");
     document.dataform.p_street.focus();
     return(false);
  }
  if ((!isNaN(document.dataform.p_city.value) && document.dataform.p_city.value == 0) || allTrim(document.dataform.p_city.value.toLowerCase()) == "none") {
     document.dataform.p_city.value = "";
  }
  if (document.dataform.p_country.selectedIndex == 0) {
     alert("Please select a Country for your delivery address.");
     return(false);
  }
  if (document.dataform.p_name.value    != "" &&
      document.dataform.p_email.value   != "" &&
      document.dataform.p_email2.value  != "") {

     if (document.dataform.p_address.value.indexOf("#") != -1) {
        document.dataform.p_address.value = document.dataform.p_address.value.replace("#", "");
     }

     if (navigator.userAgent.indexOf("Gecko") != -1) {
        if (document.dataform.p_email.value.indexOf("@") == -1 || 
            document.dataform.p_email.value.indexOf(".") == -1) {
            alert("Please enter a valid email address.");
            document.dataform.p_email.focus();
            return(false);
        }
     } else {
       if (document.dataform.p_email.value != document.dataform.p_email2.value) {
          alert("Your email addresses are not the same. Please confirm your e-mail address.");
          document.dataform.p_email.focus();
          return(false);
       }
       if (!checkMailAddress(document.dataform.p_email.value)) {
          alert("Please enter a valid email address.");
          document.dataform.p_email.focus();
          return(false);
       }
     }

     // Has customer used a RM email address in the checkout page?
     if (document.dataform.p_email.value.indexOf("raymears.com") != -1) {
        if (confirm("Please provide your own email address otherwise you will not receive your order confirmation details. Press OK to correct this or CANCEL to proceed.")) {
          document.dataform.p_email.focus();
           return(false);
        }
     }

     // Terms & Conditions accepted?
     if (!document.dataform.accepttandc.checked) {
        alert("Please accept our Terms & Conditions by ticking the checkbox at the end of the page. You can then proceed to the secure payment area.");
        return(false);
     } else {       
	// Ensure non-duplication of town/county fields:
	if (allTrim(document.dataform.p_town.value) != "" && (allTrim(document.dataform.p_town.value) == allTrim(document.dataform.p_city.value))) {
           document.dataform.p_city.value = "";
        }

	// Create the address out the constituent parts:
	var preamble = "";
 	if (isNaN(document.dataform.p_houseno.value)) {
           preamble = document.dataform.p_houseno.value + "\n" + 
                      document.dataform.p_street.value;
        } else {
           preamble = document.dataform.p_houseno.value + " " + 
                      document.dataform.p_street.value;
        }
	document.dataform.p_address.value = (preamble + "\n" +
                                             (allTrim(document.dataform.p_town.value) == "" ? "" : (document.dataform.p_town.value + "\n")) +
                                             (allTrim(document.dataform.p_city.value) == "" ? "" : (document.dataform.p_city.value + "\n")) + 
					     (allTrim(document.dataform.p_postcode.value) == "" ? "" : (document.dataform.p_postcode.value + "\n")) +
                                             document.dataform.p_country.options[document.dataform.p_country.selectedIndex].value);
        return(true);
     }
  } else {
     alert("Please complete and check all required (*) fields before proceeding. Thank you.");
     document.dataform.p_name.focus();
     return(false);
  }
} 

function removeVoucher(n) {
  document.dataform.delv.value = n; 
  submitform("Checkout.cfm");
}
