/* ----- Empty form field validation function --------*/
function BlankField( stringValue ){
	if( stringValue.replace(/(^\s+)|(\s+$)/g, '').length < 1 )
		return true;
	else
		return false;
}


/* ----- Email address validation function -----------*/
function ValidEmail(strValue){
    var valid = true;
    var regExp = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
    var regExp2 = /(\s+)|(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;

    if ( (strValue.search(regExp)) == -1 || strValue.search(regExp2) != -1)
            valid = false;

    return valid;
}


/* ----- Generic validation function -----------------*/
function append_warning( elem ) {
	var img = document.createElement( "img" );
	img.src = "images/icon-warning.gif";
	img.style.margin = "0 0 0 5px";
	img.className = "validation-error";
	document.getElementById( elem ).parentNode.appendChild( img );
}

function validate() {
	var invalidElements = new Array();
	
	for ( var i = 0; i < requiredElements.length; i++ ) {
		var elem = document.getElementById( requiredElements[i] ).parentNode;
		if ( elem.lastChild.className == "validation-error" ) {
			elem.removeChild( elem.lastChild );
		}
	}
	
	for ( var i = 0; i < requiredElements.length; i++ ) {
		if ( requiredElements[i].indexOf( "email" ) != -1 ) {
			if ( !ValidEmail( document.getElementById( requiredElements[i] ).value ) ) {
				append_warning( requiredElements[i] );
				invalidElements.push( requiredElements[i] );
			}
		} else {
			if ( BlankField( document.getElementById( requiredElements[i] ).value ) ) {
				append_warning( requiredElements[i] );
				invalidElements.push( requiredElements[i] );
			}
		}
		
	}
	
	if ( invalidElements.length > 0 ) {
		alert( "One or more fields were not supplied. Please scroll back up and double-check the noted fields." );
		return false;
	}
}