//-------------------------------------------------------------------------------------
// newValidation.js
//
// Validates the form in a page based on custom attributes in the HTML
//
// v1.0 JEB 29-10-02
// v1.1 30-10-02 Support for select boxes of type multiple
// v1.2 31-10-02 Support for 'creditcard' validation type for text boxes.
// v1.21 12-11-02 creditcard type now focuses on + selects card field if invalid
// v1.3 14-11-02 support for 'phone' type for textboxes.
// v1.4 21-11-02 parseQueryString() function added.
// v1.5 22-11-02 toggleValidation(anElement) added.
//-------------------------------------------------------------------------------------

function validateForm()
{
 var isV6 = (document.forms[0].elements[0].attributes.getNamedItem != null) ? true : false;
 var dfe = document.forms[0].elements;
 var pageIsValid = true;
 for (var f=0; f<dfe.length && pageIsValid == true; f++)
 {
  currentElement = dfe[f];

  if (isV6) 
   needsValidation = (currentElement.attributes.getNamedItem("validate") != null) ? true: false;
  else
   needsValidation = (currentElement.validate != null) ? true : false;
  
  strRequired =  (needsValidation) ? ((isV6) ? String(currentElement.attributes.getNamedItem("validate").value).toLowerCase() : String(currentElement.validate.toLowerCase())) : "no";
  if (strRequired == "yes" || strRequired == "true")
  {
   var elementType = currentElement.type.toLowerCase();
   switch (elementType)
   { 
     case 'text':
     case 'textarea':
     case 'password':
        pageIsValid = (isV6) ?  checkTextBoxV6(currentElement.name) : checkTextBoxV5(currentElement.name);
        break;
    case 'radio' :
        pageIsValid = (isV6) ? checkRadioButtonsV6(currentElement.name) : checkRadioButtonsV5(currentElement.name);
        break;
    case 'checkbox' :
        pageIsValid = (isV6) ? checkCheckBoxV6(currentElement.name) : checkCheckBoxV5(currentElement.name);
        break;
    case 'select-one' :
        pageIsValid = (isV6) ? checkSelectV6(currentElement.name) : checkSelectV5(currentElement.name);
        break;
    case 'select-multiple' :
        pageIsValid = (isV6) ? checkSelectMultV6(currentElement.name) : checkSelectMultV5(currentElement.name);
        break;
   }
  }
 }
  return pageIsValid;
}

function checkTextBoxV5(aName)
{
 var dfe = document.forms[0].elements;
 var validationType = (dfe[aName].validationtype == null) ? "Alphanumeric" : dfe[aName].validationtype;
 var showmessage = (dfe[aName].showmessage != null) ? dfe[aName].showmessage.toLowerCase() : "yes";
 showmessage = ((showmessage == "yes") || (showmessage == "true")) ? true : false;
 var required = (dfe[aName].required != null) ? dfe[aName].required.toLowerCase() : false;
 required = ((required == "true") || (required == "yes")) ? true : false;
 var displayName = (dfe[aName].displayname == null) ? aName : dfe[aName].displayname;
 switch (validationType)
 {
  case 'creditcard':
    return (creditCard(aName, required, displayName, showmessage));
    break;
 case 'phone':
    return (phone(aName, required, displayName, showmessage));
    break;
 default:
    return isFieldValidAndFocus(document.getElementsByName(aName)[0], initCap(validationType), !(required), displayName, showmessage);
 }
}

function checkTextBoxV6(aName)
{
 var attribs = document.getElementsByName(aName)[0].attributes;
 var validationType = (attribs.getNamedItem("validationtype") == null) ? 'Alphanumeric' : attribs.getNamedItem("validationtype").value;
 var showmessage = (attribs.getNamedItem("showmessage") != null) ? (attribs.getNamedItem("showmessage").value.toLowerCase()) : "true";
 var showmessage = ((showmessage == "true") || (showmessage == "yes")) ? true : false;
 var required = (attribs.getNamedItem("required") != null) ? (attribs.getNamedItem("required").value.toLowerCase()) : true;
 required = ((required == "true") || (required == "yes")) ? true : false;
 var displayName = (attribs.getNamedItem("displayname") == null) ? aName : attribs.getNamedItem("displayname").value;
 switch (validationType)
 {
  case 'creditcard':
    return (creditCard(aName, required, displayName, showmessage));
    break;
  case 'phone':
    return (phone(aName, required, displayName, showmessage));
    break;
  default:
    return isFieldValidAndFocus(document.getElementsByName(aName)[0], initCap(validationType), !(required), displayName, showmessage);
 }
}

function checkRadioButtonsV5(aName)
{
 var dfe = document.forms[0].elements;
 var firstButton = dfe[aName][0];
 var validationMsg = (firstButton.valmsg == null) ? "" : firstButton.valmsg;
 var isChecked = false;
 for (f=0; f < dfe[aName].length; f++)
    isChecked = (dfe[aName][f].checked == true) ? true : isChecked;
 if (!isChecked)
 {
  if (validationMsg != "")
      alert(validationMsg);
  firstButton.focus();
  return false;
 }
 return true;
}
 
function checkRadioButtonsV6(aName)
{
 firstButtonID = document.getElementsByName(aName)[0].id;
 validationMsg = (document.getElementsByName(aName)[0].attributes.getNamedItem("valmsg") == null) ? "" : document.getElementsByName(aName)[0].attributes.getNamedItem("valmsg").value;
 isChecked = false;
 for (f=0; f< document.getElementsByName(aName).length; f++)
    isChecked = (document.getElementsByName(aName)[f].checked == true) ? true : isChecked;
 if (!isChecked) 
 {
  if (validationMsg != "")
      alert (validationMsg);
  document.getElementsByName(aName)[0].focus();
  return false;
 } 
 return true;
}

function checkCheckBoxV5(aName)
{
 var dfe = document.forms[0].elements;
 var isGroup = (dfe[aName].group != null) ? true : false;
 var validationMsg = (dfe[aName].valmsg == null) ? "" : dfe[aName].valmsg;
 var oneIsChecked = false;
 if (isGroup)
 {
  var groupName = dfe[aName].group;
  for (var f=0; f<dfe.length; f++)
  {
   if (dfe[f].type.toLowerCase() == "checkbox")
   {
    if ((dfe[f].group != null) && (dfe[f].group == groupName))
       oneIsChecked = (dfe[f].checked) ? true : oneIsChecked;
   }
  }
 }
 else
 {
  oneIsChecked = dfe[aName].checked;
 }
 if (oneIsChecked)
   return true;
 else
 {
  if (validationMsg != "")
   alert (validationMsg);
  dfe[aName].focus();
  return false;
 }
}   
 
function checkCheckBoxV6(aName)
{
 var checkBox = document.getElementsByName(aName)[0];
 var isGroup = (checkBox.attributes.getNamedItem("group") != null) ? true : false;
 var validationMsg = (checkBox.attributes.getNamedItem("valmsg") == null) ? "" : checkBox.attributes.getNamedItem("valmsg").value;
 var oneIsChecked = false;
 if (isGroup)
 {
  var groupName = checkBox.attributes.getNamedItem("group").value;
  var dfe = document.forms[0].elements;
  for (var f=0; f<dfe.length; f++)
  {
   if (dfe[f].type.toLowerCase() == "checkbox")
   {
    if ((dfe[f].attributes.getNamedItem("group")) != null && (dfe[f].attributes.getNamedItem("group").value == groupName))
         oneIsChecked = (dfe[f].checked) ? true : oneIsChecked;
   }
  }
 }
 else
 {
  oneIsChecked = document.getElementsByName(aName)[0].checked;
 }
 if (oneIsChecked)
   return true;
  else
  {
   if (validationMsg != "")
    alert (validationMsg);
    checkBox.focus();
   return false;
  }
}

function checkSelectV6(aName)
{
 var selectBox = document.getElementsByName(aName)[0];
 var validationMsg = (selectBox.attributes.getNamedItem("valmsg") == null) ? "" : selectBox.attributes.getNamedItem("valmsg").value;
 var firstIsSelected = (selectBox[0].selected) ? true : false;
 if (firstIsSelected)
 {
  if (validationMsg != "")
   alert (validationMsg);
  selectBox.focus();
  return false;
 }
 else
  return true;
}

function checkSelectV5(aName)
{
 var dfe = document.forms[0].elements;
 var selectBox = dfe[aName];
 var validationMsg = (selectBox.valmsg == null) ? "" : selectBox.valmsg;
 var firstIsSelected = (selectBox[0].selected) ? true : false;
 if (firstIsSelected)
 {
  if (validationMsg != "")
   alert (validationMsg);
  selectBox.focus();
  return false;
 }
 else
    return true;
}

function checkSelectMultV5(aName)
{
 var dfe = document.forms[0].elements;
 var selectBox = dfe[aName];
 var validationMsg = (selectBox.valmsg == null) ? "" : selectBox.valmsg;
 var minimum = (selectBox.minimum == null) ? 1 : selectBox.minimum;
 var maximum = (selectBox.maximum == null) ? selectBox.options.length : selectBox.maximum;
 var numSelected = 0;
 for (var f=0; f < selectBox.options.length; f++)
   numSelected += (selectBox.options[f].selected) ? 1 : 0;
 
  if ((numSelected < minimum) || (numSelected > maximum))
  {
    if (validationMsg != "")
       alert (validationMsg);
     selectBox.focus();
     return false;
  }
  else
    return true;
}

function checkSelectMultV6(aName)
{
 var selectBox = document.getElementsByName(aName)[0];
 var validationMsg = (selectBox.attributes.getNamedItem("valmsg") == null) ? "" : selectBox.attributes.getNamedItem("valmsg").value;
 var minimum = (selectBox.attributes.getNamedItem("minimum") == null) ? 1 : selectBox.attributes.getNamedItem("minimum").value;
 var maximum = (selectBox.attributes.getNamedItem("maximum") == null) ? selectBox.options.length : selectBox.attributes.getNamedItem("maximum").value;
 var numSelected = 0;
 for (var f=0; f< selectBox.options.length; f++)
  numSelected += (selectBox.options[f].selected) ? 1 : 0;
 if ((numSelected < minimum) || (numSelected > maximum))
 {
   if (validationMsg != "")
      alert (validationMsg);
    selectBox.focus();
    return false;
 }
 else
   return true;
}


//-----------------------------------------------------------------------
// initCap Capitalises The First Letter of The Text and Uncapitalises the
// Rest. This Is Because Isfieldvalidandfocus Needs Its Validation Type
// Parameter This Way.
//-----------------------------------------------------------------------
function initCap(theText)
{
  firstLetter = theText.substring(0,1).toUpperCase();
  theRest = theText.substring(1, theText.length).toLowerCase();
  theText = firstLetter + theRest;
  if (theText == "Sortcode") theText = "SortCode";
  
  return theText;
}

//Credit Card validation

function creditCard(aName, required, displayName, showMessage)
{
 var theNumber = document.forms[0].elements[aName].value;
 var theLength = theNumber.length;
 var justDigits = "";
 if ((theLength == 0) && (required))
 {
  if (showMessage)
    alert (displayName +  " cannot be left blank.");
    document.forms[0].elements[aName].focus();
    document.forms[0].elements[aName].select();
  return false;
 }
 if ((theLength == 0) && (!required))
    return true;
 if (theLength < 13)
 {
  if (showMessage)
    alert (displayName + " appears to be invalid.");
    document.forms[0].elements[aName].focus();
    document.forms[0].elements[aName].select();
  return false;
 }
 
 for (var f=0; f<theNumber.length; f++)
    justDigits += ((theNumber.charCodeAt(f) >= 48) && (theNumber.charCodeAt(f) <= 57)) ? theNumber.charAt(f) : "";
 expandedDigits = "";   
 for (f=0; f<justDigits.length; f++)
    expandedDigits += (f % 2 == 1) ? justDigits.charAt(f) : 2 * justDigits.charAt(f);
 total = 0;
 for (f=0; f<expandedDigits.length; f++)
    total +=  1 * expandedDigits.charAt(f); // 1 * to cast to integer otherwise it just appends!
 var isValid = (total % 10 == 0) ? true : false;
 if (isValid)
   return true;
 else
 {
  if (showMessage)
    alert(displayName +  " appears to be invalid.");
  document.forms[0].elements[aName].focus();
  document.forms[0].elements[aName].select();
  return false;
 }
}


function phone(aName, required, displayName, showMessage)
{
 var theNumber = document.forms[0].elements[aName].value;
 var theLength = theNumber.length;
 if ((theLength == 0) && (!required))
    return true;
 if (theLength < 10)
 {
  if (showMessage) alert (displayName + " must be a valid telephone number");
  document.forms[0].elements[aName].focus();
  document.forms[0].elements[aName].select();
  return false;
 }
 else
    return (isFieldValidAndFocus(document.getElementsByName(aName)[0], 'Numeric', !(required), displayName, showMessage));
}


function parseQueryString()
{
 var queryString = new Array();
 var theString = window.location.search.substring(1);
 var theParts = theString.split("&");
 for (i=0; i < theParts.length; i++)
 {
  var pos = theParts[i].indexOf('=');
  if (pos >= 0)
  {
   theKey = theParts[i].substring(0,pos);
   theValue = theParts[i].substring(pos+1);
   queryString[theKey] = theValue;
  }
 }
 return queryString;
}

function toggleValidation(anElement, yayOrNay) 
{
 var isV6 = (document.forms[0].elements[0].attributes.getNamedItem != null) ? true : false;
 var re = /\s*/g; //Regular expression that matches every space
 var directArrays = (arguments[0].name == null) ? true : false;
 
 if (directArrays)
 {
    theDependentElements = anElement;
    yesOrNo =  (arguments.length == 2) ? yayOrNay : "yes";
 }
 else
 {
     if (isV6)
     {
      var theDependentElements = (anElement.attributes.getNamedItem("dependentElements") == null) ? new Array() : anElement.attributes.getNamedItem("dependentElements").nodeValue.replace(re, "").split(",");
      var theToggledElements = (anElement.attributes.getNamedItem("toggledElements") == null) ? new Array() : anElement.attributes.getNamedItem("toggledElements").nodeValue.replace(re, "").split(",");  
     }
     else
     {
      var theDependentElements = (anElement.dependentElements == null) ? new Array() : anElement.dependentElements.replace(re, "").split(",");
      var theToggledElements = (anElement.toggledElements == null) ? new Array() : anElement.toggledElements.replace(re, "").split(",");
     }
     var yesOrNo = (anElement.value.length > 0) ? "yes" : "no";
 }
 for (element in theDependentElements)
 {
  if (isV6)
  {
   elementToSwitch = document.getElementsByName(theDependentElements[element])[0];
   attributeToSwitch = (elementToSwitch.type == "text") ? "required" : "validate";
   elementToSwitch.attributes.getNamedItem(attributeToSwitch).nodeValue = yesOrNo;
  }
  else
  {
   elementToSwitch = document.getElementsByName(theDependentElements[element])[0];
   attributeToSwitch = (elementToSwitch.type == "text") ? "required" : "validate";
   elementToSwitch[attributeToSwitch] = yesOrNo;
  }
 }
 
 yesOrNo = (yesOrNo == "yes") ? "no" : "yes";
 
 for (element in theToggledElements)
 {
  if (isV6)
  {
   elementToSwitch = document.getElementsByName(theToggledElements[element])[0];
   attributeToSwitch = (elementToSwitch.attributes.getNamedItem("type").nodeValue == "text") ? "required" : "validate";
   elementToSwitch.attributes.getNamedItem(attributeToSwitch).nodeValue = yesOrNo;
  }
  else
  {
   elementToSwitch = document.getElementsByName(theToggledElements[element])[0];
   attributeToSwitch = (elementToSwitch.type == "text") ? "required" : "validate";
   elementToSwitch[attributeToSwitch] = yesOrNo;
  }
 }
}

