function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function focusLabels() {
  if (!document.getElementsByTagName) return false;
  var labels = document.getElementsByTagName("label");
  for (var i=0; i<labels.length; i++) {
    if (!labels[i].getAttribute("for")) continue;
    labels[i].onclick = function() {
      var id = this.getAttribute("for");
      if (!document.getElementById(id)) return false;
      var element = document.getElementById(id);
      element.focus();
    }
  }
}

function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.type == "submit") continue;
		element.onfocus = function() {
		    if ( (this.name == "m3username") && (this.value == "Your Name") ) {
		      this.value = "";
		    }
			if ( (this.name == "m3email") && (this.value == "Your Email Address") ) {
		      this.value = "";
		    }
	    }
	    element.onblur = function() {
	      if (this.value == "") {
	        if(this.name == "m3username") {
				this.value = "Your Name";
			}
			if(this.name == "m3email") {
				this.value = "Your Email Address";
			}
	      }
    }
  }
}

function validateForm(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.name.indexOf("m3username") != -1) {
      if (!isFilled(element)) {
        alert("Please fill in your name.");
        return false;
      }
    }
    if (element.name.indexOf("m3email") != -1) {
      if (!isEmail(element)) {
        alert("Your email address must be valid.");
        return false;
      }
    }
  }
  return true;
}

function isFilled(field) {
  if (field.value.length < 1 || field.value == field.defaultValue || field.value == "Your Name") {
    return false;
  } else {
    return true;
  }
}

function isEmail(field) {
  if (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1) {
    return false;
  } else {
    return true;
  }
}

function prepareForms() {
  if (!document.getElementById) return false;
  if (!document.getElementById("m3username")) return false;
  if (!document.getElementById("m3email")) return false;
  var yourName = document.getElementById("m3username");
  yourName.value = "Your Name";
  var yourEmail = document.getElementById("m3email");
  yourEmail.value = "Your Email Address";  
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
	resetFields(thisform);
    thisform.onsubmit = function() {
      return validateForm(this);
    }
  }
}

//addLoadEvent(focusLabels);
addLoadEvent(prepareForms);
