function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.type == "submit") continue;
    if (!element.defaultValue) continue;
    element.onfocus = function() {
    if (this.value == this.defaultValue) {
      this.value = "";
     }
    }
    element.onblur = function() {
      if (this.value == "") {
        this.value = this.defaultValue;
      }
    }
  }
}

function validateForm(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.className.indexOf("mustbeticked") != -1) {
      if(!element.checked) {
        var thisfield = element.id;
        thisfield = thisfield.replace(/_/g, " ");
        alert("The box labelled ["+thisfield+"] must be ticked.");
        return false;
      }
    }
    if (element.className.indexOf("required") != -1) {
      if (!isFilled(element)) {
        var thisfield = element.id;
        thisfield = thisfield.replace(/_/g, " ");
        alert("Please fill in the box labelled ["+thisfield+"].");
        return false;
      }
    }
    if (element.className.indexOf("email") != -1) {
      if (!isEmail(element)) {
        var thisfield = element.id;
        thisfield = thisfield.replace(/_/g, " ");
        alert("The field labelled ["+thisfield+"] must contain a valid email address.");
        return false;
      }
    }
  }

  var matchcount = 0;
  var rMatch = new Array();
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.className.indexOf("mustmatch") != -1) {
      rMatch[matchcount] = element.value;
      matchcount++;
    }
  }

  if(rMatch.length>1) {
    for(var j=1; j<rMatch.length; j++) {
      if(rMatch[j]!=rMatch[j-1]) {
        alert("The two passwords you entered must be the same.");
        return false;
      }
    }
  }

  return true;
}

function isFilled(field) {
  if (field.value.length < 1 || field.value == field.defaultValue) {
    return false;
  } else {
    return true;
  }
}

function isEmail(field) {
  if (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1) {
    return false;
  } else {
    return true;
  }
}

function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
    resetFields(thisform);
    thisform.onsubmit = function() {
      return validateForm(this);
    }
  }
}

addLoadEvent(prepareForms);

