/* addEvent handler for IE and other browsers */
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
	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].type=='text') {
		if (elements[i].id=='search-input') {
			elements[i].setAttribute('value',elements[i].getAttribute('title'));
			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++) {
		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='';
	}
	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');
	}

	return true;
}

/* add functions to the page's onload handler */
addEvent (window,'load',prepopulate)