//###########
//# Globals #
//###########
var hSingleWin          = null;
var g_iRows             = 0;
var g_aAllColours       = [];
var g_aAvailableColours = [];


// #####################
// # Support functions #
// #####################
function _toggleChildren(elParent, fEnabled)
{
  var elChild = null;
  
  elChild = elParent.firstChild;
  while (elChild)
  {
    if (elChild.childNodes.length > 0)
      _toggleChildren(elChild, fEnabled);
    if (elChild.nodeName.toUpperCase() == "INPUT" || elChild.nodeName.toUpperCase() == "SELECT")
    {
      if (elChild.getAttribute("type").toUpperCase() == "TEXT")
        elChild.style.backgroundColor = (fEnabled) ? "#ffffff" : "#d4d0c8";
      elChild.disabled = !fEnabled;
    }
    elChild = elChild.nextSibling;
  }
}

function _setAvailableColours()
{
  var elColourSelect = null;
  var fColourFound = false;
  
  g_aAvailableColours = [];
  for (i = 0; i < g_aAllColours.length; i++)
  {
    fColourFound = false;
    for (j = 1; j <= g_iRows; j++)
    {
      elColourSelect = $('#L' + j + '_col').get(0);
      if (elColourSelect)
      {
        if (elColourSelect.options)
        {
          for (k = 0; k < elColourSelect.options.length; k++)
          {
            if (elColourSelect.options[k].selected && elColourSelect.options[k].text == g_aAllColours[i])
              fColourFound = true;
          }
        }
        else
        {
          if (elColourSelect.value == g_aAllColours[i])
            fColourFound = true;
        }
      }
    }
    if (!fColourFound)
      g_aAvailableColours.push(g_aAllColours[i]);
  }
  return g_aAvailableColours.length;
}

function _swapSelectToText(iIndex)
{
  var elLastColourTD     = $('#TD_L' + iIndex + '_col').get(0);
  var elLastColourSelect = null;
  var strLastColour      = "";
  var elLastColourHidden = null;
  if (elLastColourTD)
  {
    elLastColourSelect = $('#L' + iIndex + '_col').get(0);
    if (elLastColourSelect)
    {
      for (n = 0; n < elLastColourSelect.options.length; n++)
      {
        if (elLastColourSelect.options[n].selected)
        {
          strLastColour = elLastColourSelect.options[n].text;
          break;
        }
      }
      elLastColourTD.removeChild(elLastColourSelect);
      elLastColourHidden = document.createElement("input");
      elLastColourHidden.setAttribute("name",  "L" + iIndex + "_col");
      elLastColourHidden.setAttribute("id",    "L" + iIndex + "_col");
      elLastColourHidden.setAttribute("type",  "hidden");
      elLastColourHidden.setAttribute("value", strLastColour);
      elLastColourTD.appendChild(elLastColourHidden);
      elLastColourTD.appendChild(document.createTextNode(strLastColour));
    }
  }
}

// ##################
// # Main functions #
// ##################
function GO_getDOMObject(strObjName)
{
  var obj;
  if (document.getElementById)
    obj = document.getElementById(strObjName);
  else if (document.all)
    obj = document.all[strObjName];
  else
    obj = null;
  return obj;
}

function GO_trim(strIn)
{
  strIn = strIn.replace(/^\s+/g, "");
  return strIn.replace(/\s+$/g, "");
}

function GO_swapImage(strElName, strNewImg)
{
  var el = $('#' + strElName).get(0);
  if (el)
    el.src = strNewImg;
}

function GO_setClass(el, strClassName)
{
  if (el != null)
  {
    el.setAttribute("class", strClassName);
    el.setAttribute("className", strClassName);
  }
}

function GO_validateUKPostcode(strPostcode)
{
   //Perform a simple check on the postcode.
   // The post code must start with 2 to 4 letters or digits, then have one possible space
   //  then end with a digit and two letters.
   // This isn't an exhaustive check.
  return strPostcode.match(/^[A-Za-z0-9]{2,4}\s?\d[A-Za-z]{2}$/);
}

function GO_validatePhoneNo(strPhoneNo)
{
   //Perform a simple check on the phone number.
   // Only numbers, brackets, whitespace and the + symbol should be allowed.
   // The entry should be at least 10 characters long.
  return strPhoneNo.match(/^[0-9\(\)\+\s]{10,}$/);
}

function GO_validateEMailAddress(strEMailAddr)
{
  var fResult = true;
  
   //Check that the address has the correct number of characters and one @ symbol (RFC 2822)
   // The local part should be between 1 and 64 characters long
   // The domain should be between 1 and 255 characters long
  fResult = strEMailAddr.match(/^[^@]{1,64}@[^@]{1,255}$/);
  if (!fResult)
    return false;

   //Extract local and domain parts of the e-mail address
  var aEMailParts = strEMailAddr.split("@");
  var strLocalPart = aEMailParts[0];
  var strDomainPart = aEMailParts[1];
  
   //Check validity of local part
  fResult = strLocalPart.match(/^[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]*(\.[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]*)*$/);
  if (!fResult)
    return false;
  
   //Check if the domain part is a valid IP address
  if (strDomainPart.match(/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/))
    fResult = true;
  else //If it's not a valid IP address, try a standard check
    fResult = strDomainPart.match(/^[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]*(\.[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]+)*?(\.[A-Za-z]{2,6})+$/);

  return fResult;

  //This is the old complete e-mail address regex
  // /^[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]*(\.[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]*)*@[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]*(\.[A-Za-z0-9][A-Za-z0-9!#$%&'*+\/=?^`{|}~._-]+)*?(\.[A-Za-z0-9]{1,6})+$/);
}

function GO_confirmBack(strURL)
{
  if (confirm("Any changes you have made to this page will be lost if you go back.\n\nAre you sure you want to go back?"))
    if (strURL)
      document.location.href = strURL;
    else
      history.go(-1);
  else
    return false;
}

function GO_popupSingleWindow(strURL, iWidth, iHeight)
{
  flLeft = (screen.availWidth  / 2) - (iWidth  / 2);
  flTop  = (screen.availHeight / 2) - (iHeight / 2);
  iScreenHeight = screen.availHeight;
  if (hSingleWin)
  {
    hSingleWin.close();
    hSingleWin = null;
  }
  hSingleWin = window.open(strURL, "GO_singlePopup", "left=" + flLeft + ",top=" + flTop + ",width=" + iWidth + ",height=" + iHeight + ",scrollbars=yes,toolbar=no,resizable=yes");
  hSingleWin.focus();
}

function GO_popupNewWindow(strURL, iWidth, iHeight)
{
  var hWin = null;

  flLeft = (screen.availWidth  / 2) - (iWidth  / 2);
  flTop  = (screen.availHeight / 2) - (iHeight / 2);
  iScreenHeight = screen.availHeight;
  hWin = window.open(strURL, "GO_singlePopup", "left=" + flLeft + ",top=" + flTop + ",width=" + iWidth + ",height=" + iHeight + "scrollbars=yes,toolbar=no,resizable=yes");
  hWin.focus();
}

function GO_validateSendBasketForm(strFormID)
{
  var objForm = $('#' + strFormID).get(0);
  var fResult = true;

  var objTxtName        = $('#txtName').get(0);
  var objTxtCompanyName = $('#txtCompanyName').get(0);
  var objTxtAddr1       = $('#txtAddr1').get(0);
  var objTxtAddr2       = $('#txtAddr2').get(0);
  var objTxtTown        = $('#txtTown').get(0);
  var objTxtCounty      = $('#txtCounty').get(0);
  var objTxtPostcode    = $('#txtPostcode').get(0);
  var objTxtTelephoneNo = $('#txtTelephoneNo').get(0);
  var objTxtFaxNo       = $('#txtFaxNo').get(0);
  var objTxtEMailAddr   = $('#txtEMailAddr').get(0);

  if (objForm)
  {
    if (!objTxtName)
      fResult = false;
    if (!objTxtCompanyName)
      fResult = false;
    if (!objTxtAddr1)
      fResult = false;
    if (!objTxtAddr2)
      fResult = false;
    if (!objTxtTown)
      fResult = false;
    if (!objTxtCounty)
      fResult = false;
    if (!objTxtPostcode)
      fResult = false;
    if (!objTxtTelephoneNo)
      fResult = false;
    if (!objTxtFaxNo)
      fResult = false;
    if (!objTxtEMailAddr)
      fResult = false;

    if (!fResult)
    {
      alert("ERROR: Form elements could not be referenced");
      fResult = true;
    }

    if (objTxtName && GO_trim(objTxtName.value) == "")
    {
      alert("You must enter your name");
      objTxtName.focus();
      return false;
    }

    if (objTxtAddr1 && GO_trim(objTxtAddr1.value) == "")
    {
      alert("You must enter the first line of your address");
      objTxtAddr1.focus();
      return false;
    }

    if (objTxtTown && GO_trim(objTxtTown.value) == "")
    {
      alert("You must enter your town or city name");
      objTxtTown.focus();
      return false;
    }

    if (objTxtCounty && GO_trim(objTxtCounty.value) == "")
    {
      alert("You must enter your county");
      objTxtCounty.focus();
      return false;
    }

    if (objTxtPostcode && GO_trim(objTxtPostcode.value) == "")
    {
      alert("You must enter your Postcode");
      objTxtPostcode.focus();
      return false;
    }
    
    if (objTxtPostcode && !GO_validateUKPostcode(GO_trim(objTxtPostcode.value)))
    {
      alert("The postcode you entered is invalid - please try again.\n\nPlease note that the postcode must only have one space at the most (e.g. \"AB12 3CD\")");
      objTxtPostcode.focus();
      return false;
    }

    if (objTxtTelephoneNo && GO_trim(objTxtTelephoneNo.value) == "")
    {
      alert("You must enter your telephone number");
      objTxtTelephoneNo.focus();
      return false;
    }
    
    if (objTxtTelephoneNo && !GO_validatePhoneNo(objTxtTelephoneNo.value))
    {
      alert("The telephone number you entered is invalid - please try again (make sure that you have entered the full area code)");
      objTxtTelephoneNo.focus();
      return false;
    }
    
    if (objTxtFaxNo && GO_trim(objTxtFaxNo.value) > "" && !GO_validatePhoneNo(objTxtFaxNo.value))
    {
      alert("The fax number you entered is invalid - please try again (make sure that you have entered the full area code)");
      objTxtFaxNo.focus();
      return false;
    }

    if (objTxtEMailAddr && GO_trim(objTxtEMailAddr.value) == "")
    {
      alert("You must enter your e-mail address");
      objTxtEMailAddr.focus();
      return false;
    }

    if (objTxtEMailAddr && !GO_validateEMailAddress(objTxtEMailAddr.value))
    {
      alert("The e-mail address you entered is invalid - please try again");
      objTxtEMailAddr.focus();
      return false;
    }
  }

  return fResult;
}


// Product order section functions

function GO_setAllColours(aColours)
{
  g_aAllColours = aColours;
}

function GO_addQMRow(aSizeCodes)
{
  var elTBody   = $('#QM_container').get(0);
  var elRows    = $('#lines').get(0);
  var elToFocus = null;
  var iQPR      = aSizeCodes.length;
  
  if (elTBody && elRows)
  {
    if (_setAvailableColours() > 0)
    {
      if (g_iRows > 0)
        _swapSelectToText(g_iRows);

      elRows.value = ++g_iRows;
      
      var elTR    = document.createElement("tr");
      var elTD    = null;
      var elInput = null;
    
      var elColourSelect = document.createElement("select");
      elColourSelect.setAttribute("name", "L" + g_iRows + "_col");
      elColourSelect.setAttribute("id",   "L" + g_iRows + "_col");
      var elColourOption = null;
      for (n = 0; n < g_aAvailableColours.length; n++)
      {
        elColourOption = document.createElement("option");
        elColourOption.appendChild(document.createTextNode(g_aAvailableColours[n]));
        elColourSelect.appendChild(elColourOption);
      }
      elTD = document.createElement("td");
      elTD.setAttribute("name", "TD_L" + g_iRows + "_col");
      elTD.setAttribute("id",   "TD_L" + g_iRows + "_col");
      elTD.setAttribute("width", (100 / (iQPR + 1)) + "%");
      elTD.appendChild(elColourSelect);
      elTR.appendChild(elTD);
      elToFocus = elColourSelect;

      for (n = 1; n <= iQPR; n++)
      {
        elTD = document.createElement("td");
        elTD.setAttribute("width", (100 / (iQPR + 1)) + "%");
        elTD.setAttribute("align", "left");
        elInput = document.createElement("input");
        elInput.setAttribute("name",  "L" + g_iRows + "_Q" + n + "_code");
        elInput.setAttribute("id",    "L" + g_iRows + "_Q" + n + "_code");
        elInput.setAttribute("type",  "hidden");
        elInput.setAttribute("value", aSizeCodes[n - 1]);
        elTD.appendChild(elInput);
        elInput = document.createElement("input");
        elInput.setAttribute("size",  "5");
        elInput.setAttribute("name",  "L" + g_iRows + "_Q" + n + "_value");
        elInput.setAttribute("id",    "L" + g_iRows + "_Q" + n + "_value");
        elInput.setAttribute("type",  "text");
        elInput.setAttribute("value", "0");
        elTD.appendChild(elInput);
        elTR.appendChild(elTD);
      }
      
      elTBody.appendChild(elTR);
      if (elToFocus)
        elToFocus.focus();
    }
    else
      alert("More rows cannot be added as there are no more available colours");
  }
  else
    alert("ERROR: QM_container and/or the lines field are not present");
}

function GO_toggleMethodGroup(strGroup, fEnabled)
{
  if (strGroup == "SP")
  {
    var elSPTable = $("#tbOS_Method_SP").get(0);
    if (elSPTable)
      _toggleChildren(elSPTable,  fEnabled);
  }
  else if (strGroup == "EMB")
  {
    var elEMBTable = $("#tbOS_Method_EMB").get(0);
    if (elEMBTable)
      _toggleChildren(elEMBTable, fEnabled);
  }
}


