var regICountry = 0;
var regDCountry = 0;

function SetClass(obj, state) {
   if (state == 0 && obj.className == "")
      obj.className = "selected";
   else if (state == 1 && obj.className == "selected")
      obj.className = "";
   else if (state == 2)
      obj.className = "focused";
   else if (state == 3)
      obj.className = "";
}

function ValidateRegistration(formID, objSubmit) {
   var filterStandard = /^([ 0-9a-zA-Z\_\@\-\.áéíóúÁÉÍÓÚ])+$/;
   var filterEmail = /^([a-zA-ZáéíóúÁÉÍÓÚ0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   var filterPhone = /^([ 0-9()+\-\.])+$/;
   var filterPostcode = /^([ 0-9a-zA-Z])+$/;
   var filterOther = /^([ a-zA-ZáéíóúÁÉÍÓÚ()\',+-\.])+$/;

   // Set wait cursor
   objSubmit.style.cursor = "wait";
   objSubmit.disabled = true;
   document.getElementById("formMessage").innerHTML = "<em>Checking form validation</em>";
   
   // Trim all fields, Build address compare string and reset class names
   var strIAddress = ""; var strDAddress = "";
   objFields = document.getElementById("registration").getElementsByTagName("*");
   for (intX in objFields) {
      if (objFields[intX].value) objFields[intX].value = Trim(objFields[intX].value);
      if (objFields[intX].id && objFields[intX].value) {
         if (objFields[intX].id.substr(0, 4) == "regI") strIAddress += objFields[intX].value;
         if (objFields[intX].id.substr(0, 4) == "regD") strDAddress += objFields[intX].value;
      }
      objFields[intX].className = "";
   }
   
   // Reformat postcode if it is a UK one
   document.getElementById("regIPostcode").value = document.getElementById("regIPostcode").value.replace(/ /g, "");
   document.getElementById("regDPostcode").value = document.getElementById("regDPostcode").value.replace(/ /g, "");
   if (document.getElementById("regIPostcode").value.length == 7) document.getElementById("regIPostcode").value = document.getElementById("regIPostcode").value.substr(0, 4) + ' ' + document.getElementById("regIPostcode").value.substr(4, 3);
   if (document.getElementById("regIPostcode").value.length == 6) document.getElementById("regIPostcode").value = document.getElementById("regIPostcode").value.substr(0, 3) + ' ' + document.getElementById("regIPostcode").value.substr(3, 3);
   if (document.getElementById("regIPostcode").value.length == 5) document.getElementById("regIPostcode").value = document.getElementById("regIPostcode").value.substr(0, 2) + ' ' + document.getElementById("regIPostcode").value.substr(2, 3);
   if (document.getElementById("regDPostcode").value.length == 7) document.getElementById("regDPostcode").value = document.getElementById("regDPostcode").value.substr(0, 4) + ' ' + document.getElementById("regDPostcode").value.substr(4, 3);
   if (document.getElementById("regDPostcode").value.length == 6) document.getElementById("regDPostcode").value = document.getElementById("regDPostcode").value.substr(0, 3) + ' ' + document.getElementById("regDPostcode").value.substr(3, 3);
   if (document.getElementById("regDPostcode").value.length == 5) document.getElementById("regDPostcode").value = document.getElementById("regDPostcode").value.substr(0, 2) + ' ' + document.getElementById("regDPostcode").value.substr(2, 3);

   // Check account information
   if (document.getElementById("regMandatory")) {
      document.getElementById("regUsername").className = (filterStandard.test(document.getElementById("regUsername").value) ? "pass" : "fail");
      document.getElementById("regPassword").className = (filterStandard.test(document.getElementById("regPassword").value) ? (document.getElementById("regPassword").value.length > 5 ? "pass" : "fail") : "fail");
   }
   
   document.getElementById("regEmailAddress").className = (filterEmail.test(document.getElementById("regEmailAddress").value) ? "pass" : "fail");

   // Check invoice address
   document.getElementById("regIContactName").className = (filterOther.test(document.getElementById("regIContactName").value) ? "pass" : "fail");
   document.getElementById("regIAddressLine1").className = (filterStandard.test(document.getElementById("regIAddressLine1").value) ? "pass" : "fail");
   if (document.getElementById("regIAddressLine2").value != "") document.getElementById("regIAddressLine2").className = (filterStandard.test(document.getElementById("regIAddressLine2").value) ? "pass" : "fail");
   if (document.getElementById("regIAddressLine3").value != "") document.getElementById("regIAddressLine3").className = (filterStandard.test(document.getElementById("regIAddressLine3").value) ? "pass" : "fail");
   document.getElementById("regITown").className = (filterOther.test(document.getElementById("regITown").value) ? "pass" : "fail");
   document.getElementById("regICounty").className = (filterOther.test(document.getElementById("regICounty").value) ? "pass" : "fail");
   document.getElementById("regIPostcode").className = (filterPostcode.test(document.getElementById("regIPostcode").value) ? "pass" : "fail");
   document.getElementById("regICountry").className = (filterOther.test(document.getElementById("regICountryValue").value) ? "pass" : "fail");
   document.getElementById("regITelephone").className = (filterPhone.test(document.getElementById("regITelephone").value) ? "pass" : "fail");

   // Check delivery address
   if (strIAddress != strDAddress && strDAddress != document.getElementById("regDCountryValue").value) {
      document.getElementById("regDContactName").className = (filterOther.test(document.getElementById("regDContactName").value) ? "pass" : "fail");
      document.getElementById("regDAddressLine1").className = (filterStandard.test(document.getElementById("regDAddressLine1").value) ? "pass" : "fail");
      if (document.getElementById("regDAddressLine2").value != "") document.getElementById("regDAddressLine2").className = (filterOther.test(document.getElementById("regDAddressLine2").value) ? "pass" : "fail");
      if (document.getElementById("regDAddressLine3").value != "") document.getElementById("regDAddressLine3").className = (filterOther.test(document.getElementById("regDAddressLine3").value) ? "pass" : "fail");
      document.getElementById("regDTown").className = (filterOther.test(document.getElementById("regDTown").value) ? "pass" : "fail");
      document.getElementById("regDCounty").className = (filterOther.test(document.getElementById("regDCounty").value) ? "pass" : "fail");
      document.getElementById("regDPostcode").className = (filterPostcode.test(document.getElementById("regDPostcode").value) ? "pass" : "fail");
      document.getElementById("regDCountry").className = (filterOther.test(document.getElementById("regDCountryValue").value) ? "pass" : "fail");
      document.getElementById("regDTelephone").className = (filterPhone.test(document.getElementById("regDTelephone").value) ? "pass" : "fail");
   }
   
   document.getElementById("regTerms_chk").className = (document.getElementById("regTerms").value == "1" ? "pass" : "fail");
   
   // If no errors, send form to the server
   var blnPass = true;
   objFields = document.getElementById("registration").getElementsByTagName("*");
   for (intX in objFields) if (objFields[intX].className == "fail") blnPass = false;
   if (blnPass) {
      document.getElementById("formMessage").innerHTML = "<em style=\"color: #00aa00\">Submitting registration form ... Please wait</em>";
      var strPOST = "";
      var e = document.getElementById("registration").elements;
      for (var i = 0; i < e.length; i++) {
         strPOST += e[i].name + "=" + Url.encode(e[i].value) + "&";
      }
      HTTPRequest(document.domain, "/updateaccount.php", strPOST);
      return true;
   }
   
   // Set normal cursor
   objSubmit.disabled = false;
   objSubmit.style.cursor = "default";
   document.getElementById("formMessage").innerHTML = "<em style=\"color: #aa0000\"><img src=\"/shop_images/img_alert.png\" align=\"absMiddle\"> Registration form contains errors, please check and try again.</em>";
}

function CheckboxToggle(obj) {
   document.getElementById(obj).value = (document.getElementById(obj).value == "0" ? "1" : "0");
   document.getElementById(obj + "_chk").src = "shop_images/img_checkbox_" + document.getElementById(obj).value + ".png";
   document.getElementById(obj + "_chk").className = "selected";
}

function DropDown(obj, intHide) {
   if (regICountry == intHide && document.getElementById(obj.id).className == "" || regDCountry == intHide && document.getElementById(obj.id).className == "") { 
      document.getElementById(obj.id + "Dropdown").style.display = "none";
      return false; 
   }
   if (intHide) return false;
   
   if (document.getElementById(obj.id + "Dropdown").style.display == "none" || document.getElementById(obj.id + "Dropdown").style.display == "") {
      document.getElementById(obj.id + "Dropdown").style.height = "auto";
      document.getElementById(obj.id + "Dropdown").style.width = document.getElementById(obj.id).offsetWidth - 2 + "px";
      document.getElementById(obj.id + "Dropdown").style.display = "block";
      document.getElementById(obj.id + "Dropdown").style.height = "10px";
      document.getElementById(obj.id).className = "selected";
      DropDownAnim(obj, 120);
      
      Items = document.getElementById(obj.id + "Dropdown").getElementsByTagName("a");
      for (var x = 0; x < Items.length; x++)
         if (Items[x].innerHTML == document.getElementById(obj.id + "Value").value)
            document.getElementById(obj.id + "Dropdown").scrollTop = Items[x].offsetTop;
   } else
      document.getElementById(obj.id + "Dropdown").style.display = "none";
}

function DropDownAnim(obj, max) {                                
   document.getElementById(obj.id + "Dropdown").style.height = document.getElementById(obj.id + "Dropdown").offsetHeight + 10 + "px";
   
   if (document.getElementById(obj.id + "Dropdown").offsetHeight > max) 
      document.getElementById(obj.id + "Dropdown").style.height = max + "px";
   else
      setTimeout("DropDownAnim(document.getElementById('" + obj.id + "'), " + max + ")", 10);
}

function DropDownSelect(obj) {
   document.getElementById(obj.parentNode.id.replace("Dropdown", "")).innerHTML = obj.innerHTML;
   document.getElementById(obj.parentNode.id.replace("Dropdown", "") + "Value").value = obj.innerHTML;
   document.getElementById(obj.parentNode.id.replace("Dropdown", "") + "Dropdown").style.display = "none";
}

function Trim(str, chars) {
   return LTrim(RTrim(str, chars), chars);
}
 
function LTrim(str, chars) {
   chars = chars || "\\s";
   return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function RTrim(str, chars) {
   chars = chars || "\\s";
   return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function HTTPRequest(strHost, strURI, strPost) { 
   var http = false;
   
   try {
      http = new ActiveXObject('Msxml2.XMLHTTP'); 
   } catch (e) {
      try {
         http = new ActiveXObject('Microsoft.XMLHTTP');
      } catch (e2) {
         try {
            http = new XMLHttpRequest();
         } catch (e3) {
            http = false;
         }
      }
   }
  
  if (http) {
      http.onreadystatechange = function() {
         if (http.readyState == 4) {
            if (http.status == 200) {
               try { 
                  eval(http.responseText);
               } catch (e3) {
                  alert(http.responseText);
                  alert("Response from server has caused an error.");
               }
            } else if (http.status > 0) {
               alert("An error has occured while communicating with the server.");
            }
         }
      }; 

      strMethod = (strPost != "" ? "POST" : "GET");
      http.open(strMethod, strURI,  true); 
      if (strPost) {
         http.setRequestHeader("Host", strHost);
         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
         if (strSession) http.setRequestHeader("Cookie", "PHPSESSID=" + strSession + "; path=/");
         http.setRequestHeader("Content-length", strPost.length);
      }
      http.setRequestHeader("Connection", "close");
      http.send(strPost);
   }
} 

var Url = {
   // public method for url encoding
   encode : function (string) {
      return escape(this._utf8_encode(string));
   },
 
   // public method for url decoding
   decode : function (string) {
      return this._utf8_decode(unescape(string));
   },
 
   // private method for UTF-8 encoding
   _utf8_encode : function (string) {
      string = string.replace(/\r\n/g,"\n");
      var utftext = "";
      for (var n = 0; n < string.length; n++) {
         var c = string.charCodeAt(n);
         if (c < 128) {
            utftext += String.fromCharCode(c);
         }
         else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
         }
         else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
         }
 
      }
      return utftext;
   },
 
   // private method for UTF-8 decoding
   _utf8_decode : function (utftext) {
      var string = "";
      var i = 0;
      var c = c1 = c2 = 0;
      while ( i < utftext.length ) {
         c = utftext.charCodeAt(i);
         if (c < 128) {
            string += String.fromCharCode(c);
            i++;
         }
         else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
         }
         else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
         }
      }
      return string;
   }
}
