window.onload = function() {
	// get all anchors with class 'ext',
	// loop through them and assign the handler
	var extlinks = $$('a.ext');
	for (var i = 0; i < extlinks.length; i++) {
		var link = extlinks[i];
		link.onclick = extLinkHandler;
	}
	
	if ($('buildform')) {
		$('buildform').onsubmit = checkForm;
	}
}

// external link handler
function extLinkHandler() {
	// open a new window
	open (this.href);
	return false;
}

// big form handler
function checkForm() {
	if (!this.firstname.value) {
		alert ('Please enter your first name');
		this.firstname.focus();
		return false;
	}

	if (!this.surname.value) {
		alert ('Please enter your surname');
		this.surname.focus();
		return false;
	}

	if (!isEmail(this.email.value)) {
		alert ('Please enter a valid e-mail address.');
		this.email.focus();
		return false;
	}
	
	if (!this.address1.value) {
		alert ('Please enter at least one address line');
		this.address1.focus();
		return false;
	}

	if (!this.town.value) {
		alert ('Please enter your town');
		this.town.focus();
		return false;
	}

	if (!this.postcode.value) {
		alert ('Please enter your post code');
		this.postcode.focus();
		return false;
	}

	if (!this.country.value) {
		alert ('Please enter your country');
		this.country.focus();
		return false;
	}

	if (!this.tandc.checked) {
		alert ('You must accept our terms and conditions before this form can be accepted.');
		return false;
	}
	
	return true;
}

function isEmail (str) {
	if (!str) {
		return false;
	}

	var iChars = "*|,\"<:>[]{}`\';()&$#%";
	for (var i = 0; i < str.length; i++) {
		if (iChars.indexOf(str.charAt(i)) != -1) {
			return false;
		}
	}
	
	var iAt = str.indexOf('@');
	var jAt = str.indexOf('@', iAt + 1);
	var iDot = str.lastIndexOf('.');
	if (iAt < 1 || jAt != -1 || iDot > str.length - 3 || iDot - iAt < 2) {
		return false;
	}
	
	return true;
}



function noSpam() {
	var link = noSpam.arguments[0];
	var pre = noSpam.arguments[1];

	var myat = String.fromCharCode(64);
	var mydot = String.fromCharCode(46);
	var addr = '';
	var i;
	for (i = 2; i < noSpam.arguments.length; i++) {
		if (addr) {
			addr += (i == pre + 2) ? myat : mydot;
		}
		addr += noSpam.arguments[i];
	}
	
	var str = '';
	if (link) {
		str = '<a href="mailto:' + addr + '">';
		str += (link == 'addr') ? addr : link;
		str += '<\/a>';
	}
	else {
		str = addr;
	}
	
	document.write (str);
}

