// JavaScript Document
//This Script file is made to validate forms

function checkFields(){
	//outputs error if there is a blank
	if (!checkBlankFields()){
		document.getElementById('form-error').innerHTML = "All highlighted fields must are required";
		return false;
	}
		
	//checks if email addresses math
	with(document.forms[0]){
		email.style.background = "#222";		
		contact_phone.style.background = "#222";
		
		email.style.color = "#d9b67e";		
		contact_phone.style.color = "#d9b67e";
		

		if(!validEmail(email.value)) {			
			alert("Invalid email address");
			email.style.background = "#f96";
			email.style.color = "#000";		
			return false;
		}
		if(!checkPhone(contact_phone.value)) {
			alert("Invalid Phone Number");
			contact_phone.style.background = "#f96";	
			contact_phone.style.color = "#000";				
			return false;
		}
  }

	 return true;
}	

//Checks for blank fields in the form
//This will check all fields 
function checkBlankFields(){
		var filled = true;
		
			//restores the color of the input elements to white
			required = getElementsByStyleClass("required")
			for (x=0; x < required.length; x++){
				required[x].style.background = "#222";
				if (required[x].value == ""){
					required[x].style.background = "#f96"; 
					filled = false;
					}
			}

		if(!filled){
			document.getElementById('form-error').innerHTML = "The highlighted fields are required.";				
			alert("The highlighted fields are required.");
		}
				
	return filled;
	}			

function validEmail(email){
	//This script checks fora valid email address
	//It does NOT search for illegal email characters yet
	//1. checks for an @ in the email
	//2. splits everthing before and after @
	//3. makes sure before and after @ aren't empty
	//4. makes sure there is only 1 @
	//5. checks the last four characters for a 'dot', and makes sure it doesn't end on a 'dot'

	//checks for valic characters
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) return false;

	if(getChar("@",email) > -1){ //1
		emailAt = email.split("@"); //2
		if(emailAt[1].length > 0 && emailAt[0].length > 0){ //3
				if(getChar("@",emailAt[1]) > -1) //4
					return false;
				else{
					lastFour = emailAt[1].substring(emailAt[1].length - 5);
					if(getChar(".",lastFour)> -1 && lastFour.charAt(4) != ".") //5
						return true;
				}
		}
	}
	
}

function getChar(char, str){
	return str.indexOf(char);
}

function  checkPhone(phone){
   if(phone.length <10) return false;

   if (phone.substring(0,3) == "778" || phone.substring(0,3) == "604")
   		if(parseInt(phone) > 6040000000)
			return true;

	return false;
}

function getElementsByStyleClass (className) {
  var all = document.all ? document.all :
    document.getElementsByTagName('*');
  var elements = new Array();
  for (var e = 0; e < all.length; e++)
    if (all[e].className == className)
      elements[elements.length] = all[e];
  return elements;
}