// JavaScript Document
/*
* New Medio Form Trickery
* By Alex Welch
*/


function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function getTheClass(the_elem) {
	//IE Way
	var get_class = the_elem.getAttribute("className");
	if(get_class == "" || get_class == null) {
		//FireFox way
		get_class = the_elem.getAttribute("class");
	}
	//"" is standard (I think), but most browsers use null, 
	//so we will just convert standard "" to null
	if(get_class == "") {
		return null;
	} else {
		return get_class;
	}
}

// rewrite to trigger this by DOM
var field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != field_length) {
			field_length=obj.value.length;
			if (field_length == len) {
				next_field.focus();
				}
			}
		}
	}

function setClass(the_element, the_class) {
	if (the_element.getAttribute('class') != null) {
	  var current_class = the_element.getAttribute('class');
	} else if (the_element.getAttribute('className') != null) {
		var current_class = the_element.getAttribute('className');
	} else {
		var current_class = null;
	}
	if (current_class == null) {
		the_element.setAttribute('className', the_class);
		the_element.setAttribute('class',  the_class);
	} else {
		//GROSE, clean this up with a better regular exp to take out the default and focus class, then add the_class
		var new_class = current_class.replace(/default/, " ");
		var new_class1 = new_class.replace(/focus/, " ") + ' ' + the_class;

		the_element.setAttribute('className', new_class1);
		the_element.setAttribute('class', new_class1);
	}
}

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() {
				setClass(this, 'focus');
				if (getTheClass(this) != 'new focus') { //eventually add reg exp to match new.
					if (this.value == this.defaultValue) {
					this.value = '';
					}
				}
			}
		if (getTheClass(element) != 'new') {
			setClass(element, 'default');
		}
		
    element.onblur = function() {		
		  setClass(this, '');

				if (this.value == '') {
					this.value = this.defaultValue;
					setClass(this, 'default');
				}
		}
  }
}


function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
	  var thisform = document.forms[i];
		resetFields(thisform);
	}
}

addLoadEvent(prepareForms);
