var W3CDOM = (document.getElementsByTagName && document.createElement);


function validate() {
	validForm = true;
	firstError = null;
	errorstring = '';
	var x = document.forms['for_sale'].elements;
	if (isEmpty(x['name']))
		writeError(x['name'],'Please enter your name');
	if (isEmpty(x['email']))
		writeError(x['email'],'Please enter your email address');
	if (x['email'].value.indexOf('@') == -1)
		writeError(x['email'],'This is not a valid email address');
	if (isEmpty(x['price']) && x[0].checked)
		writeError(x['price'],'Please enter a price');
	if (isEmpty(x['title']))
		writeError(x['title'],'Please enter a title');
	if (x['desc'].value.indexOf('http:') > -1)
		writeError(x['desc'],'Web addresses are not allowed in the description');
	if (!W3CDOM)
		alert(errorstring);
	if (firstError)
		firstError.focus();
	return validForm;
}

function writeError(obj,message) {
	validForm = false;
	if (obj.hasError) return;
	if (W3CDOM) {
		obj.className += ' error';
		obj.onchange = removeError;
		var sp = document.createElement('span');
		sp.className = 'error';
		sp.appendChild(document.createTextNode(message));
		obj.parentNode.appendChild(sp);
		obj.hasError = sp;
	}
	else {
		errorstring += obj.name + ': ' + message + '\n';
		obj.hasError = true;
	}
	if (!firstError)
		firstError = obj;
}

function removeError()
{
	this.className = this.className.substring(0,this.className.lastIndexOf(' '));
	this.parentNode.removeChild(this.hasError);
	this.hasError = null;
	this.onchange = null;
}

function isEmpty(mytext) {
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if ((mytext.value.length==0) || (mytext.value=="") || ((mytext.value.search(re)) > -1)) {
		return true;
	}
	else {
		return false;
	}
}
