var emailEmpty = "Email cannot be empty";
var emailInvalid = "Invalid email address";
var temp = "";

function validEmail(email){
	var valid = false;
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(email)) valid = true;
	return valid;
}

function validate(){
	var valid		= true;
	var form		= document.getElementById("notifications");
	var email		= document.getElementById("email");
	var country = document.getElementById("country");				
	
	/* Clear any invalid classes from fields before testing */
	email.className = "";
	country.className = "";
	
	if(email.value == "" || email.value == null){ /* Email is empty */
		email.className = "invalid";
		email.value = emailEmpty;
		valid = false;
		
	}else if(email.value != emailEmpty && email.value != emailInvalid){ /* Make sure error text is NOT in email field */
		if( !validEmail(email.value) ){ /* Validate email address */
			email.className = "invalid";
			temp = email.value; /* Store users entry into temp var for re-use */
			email.value = emailInvalid;
			valid = false;
		}
		
	}else{ /* Error text in email field so re-instate invalid css class */
		email.className = "invalid";
		valid = false;
	}
	
	if(country.value == ""){ country.className = "invalid"; valid = false; }
	
	if(valid){ document.getElementById("notifications").submit(); } /* If form is valid */
}

function updateValue(field){				
	if(field.value == emailInvalid || field.value == emailEmpty){ /* Check if email has error text in */
		if(temp != "") /* If users previous entry is stored in temp */
			field.value = temp;
		else
			field.value = "";
	}
}