/* addEvent handler for cross-browser IE and other browsers */
function addEvent(elm, evType, fn, useCapture)
{
  if (elm.addEventListener) {

    elm.addEventListener(evType, fn, useCapture);
    return true;

  } else if (elm.attachEvent) {

    var r = elm.attachEvent("on"+evType, fn);
    return r;

  }
}

/* pre-fill the inputs and textareas with their title attribute value, and add relevant onfocus/onblur handlers */
function prepopulate()
{
  /* get all inputs */
  elements = document.getElementsByTagName('input');
  
  /* loop through the array of elements */
  n_elements = elements.length;
  for (i = 0; i < n_elements; i++)
  {
    if(elements[i].getAttribute('title')!=''){
      if (elements[i].type=='text') {
        elements[i].setAttribute('value',elements[i].getAttribute('title'));
        elements[i].style.color='#B1B1B1';
        addEvent(elements[i],'focus',input_focus);
        addEvent(elements[i],'blur',input_blur);
      }
    }
  }

  /* get all textareas */
  elements = document.getElementsByTagName('textarea');
  
  /* loop through the array of elements */
  n_elements = elements.length;
  for (i = 0; i < n_elements; i++)
  {
    if(elements[i].getAttribute('title')!=''){
      elements[i].value=elements[i].getAttribute('title');
      addEvent(elements[i],'focus',input_focus);
      addEvent(elements[i],'blur',input_blur);
    }
  }
}

function input_focus(e)
{
  // This is an event handler; get the clicked on element, in a cross-browser fashion
	if (window.event) {
          target = window.event.srcElement;
	}
        else if (e) {
          target = e.target;
	} else return;
	
	// Make sure that the target is an element, not a text node
	// within an element
	if (target.nodeType == 3) {
          target = target.parentNode;
	}
	
	// Paranoia; check this is an input tag
	if ((target.nodeName.toLowerCase() != 'input')&&(target.nodeName.toLowerCase() != 'textarea')) return false; 
	
	if (target.value==target.getAttribute('title')) {
		target.value='';
		target.style.color='#555555';
	}
	return true;
}

function input_blur(e) {
	// This is an event handler; get the clicked on element,
	// in a cross-browser fashion
	if (window.event) {
		target = window.event.srcElement;
	} else if (e) {
		target = e.target;
	} else return;
	
	// Make sure that the target is an element, not a text node
	// within an element
	if (target.nodeType == 3) {
		target = target.parentNode;
	}
	
	// Paranoia; check this is an input tag
	if ((target.nodeName.toLowerCase() != 'input')&&(target.nodeName.toLowerCase() != 'textarea')) return false; 
	

	if (target.value=='') {
		target.value=target.getAttribute('title');
		target.style.color='#B1B1B1';
	}

	return true;
}

/* add functions to the page's onload handler */
addEvent (window,'load',prepopulate)
