function trim(param) {
    return param.replace(/^\s+|\s+$/g,"");
}

function hasClassName(obj, name) {
	var list = obj.className.split(' ');
	
	var check = name.toLowerCase();
	
	// find all instances and remove them
	for (var i = 0; i < list.length; i++ ) {
		if (list[i].toLowerCase() == check) {
			return true;
		}           
	}
	
	return false;
}

function checkForm(obj) {
	var failed = false;
	for (i = 0; i < obj.elements.length; i++) {
		input = obj.elements[i];
		if (!validateInput(input)) {
			failed = true;
		}
	}
	
	if (failed) {
		showError('Some fields are either missing or incorrectly filled out. Please re-check your form.');
		
		return false;
	} else {
		hideError();
		
		return true;
	}
}

function validateInput(input) {
	var failed = false;
	
	if (hasClassName(input, 'required')) {
		if (input.value == null || trim(input.value) == '') {
			if (document.getElementById('cross-' + input.id) == null) {
				document.getElementById(input.id + '-status').innerHTML = '';
				image = document.createElement('img');
				image.src = 'http://www.mspoints.co.za/profiles/msp/images/cross.gif';
				image.id = 'cross-' + input.id;
				
				document.getElementById(input.id + '-status').appendChild(image);
			}
			
			failed = true;
		}
	}
	
	if (hasClassName(input, 'validate-email')) {
		var reg = /^([A-Za-z0-9_\-\.]+)\@([A-Za-z0-9_\-]+)\.[A-Za-z]{2,4}(\.[A-Za-z]{2,4})?$/;
		if (reg.test(input.value) == false) {
			failed = true;
		}
	}
	
	if (hasClassName(input, 'validate-password')) {
		if (input.value.length < 6) {
			failed = true;
		}
		
		var reg = /^[a-zA-Z0-9]+$/;
		if (reg.test(input.value) == false) {
			failed = true;
		}
	}
	
	if (failed) {
		if (document.getElementById('cross-' + input.id) == null) {
			document.getElementById(input.id + '-status').innerHTML = '';
			image = document.createElement('img');
			image.src = 'http://www.mspoints.co.za/profiles/msp/images/cross.gif';
			image.id = 'cross-' + input.id;
			
			document.getElementById(input.id + '-status').appendChild(image);
		}
		return false;
	} else {
		if (document.getElementById('cross-' + input.id) != null) {
			document.getElementById(input.id + '-status').innerHTML = '';
			image = document.createElement('img');
			image.src = 'http://www.mspoints.co.za/profiles/msp/images/tick.gif';
			image.id = 'tick-' + input.id;
			
			document.getElementById(input.id + '-status').appendChild(image);
		}
		
		return true;
	}
}

function showError(error) {
	errorDiv = document.getElementById('error');
	errorDiv.innerHTML = error;
	errorDiv.style.display = '';
}

function hideError() {
	errorDiv.style.display = 'none';
}

