// Validation of contact forms throughout all SGDG pages. All forms should have an id="contactForm"

/*global cleanOutJunk,isEmail,checkInternationalPhone,CheckMaxLength, addValidation, validateForm */

function addValidation()
{
	//adds validation to any form called #contactForm
	if (document.getElementById("contactForm"))
	{
		document.getElementById("contactForm").onsubmit=function(){return(validateForm());};
	}
}

function validateForm()
{
	var form = document.getElementById("contactForm");

	//A bit of clean up. Add any fields here to be cleaned up of weird punctuation or white space. Run through cleanOutJunk()
	//****************************************************************************************************
	form.message.value = cleanOutJunk(form.message.value); // without this the form can be submitted with a blank message (mainly if the user accidentally adds one space)

	//Check if all the required fields are filled in
	//****************************************************************************************************
	if (form.name.value === "")
	{
		form.name.parentNode.className = "error";
		alert ("Please provide your name.");
		form.name.focus();
		form.name.parentNode.removeAttribute("class");
		return false;	
	}
	
	
	if (form.phone.value === "" && form.email.value === "")
	//make sure there is either a phone number or an email address provided
	{
		form.phone.parentNode.className = "error";
		form.email.parentNode.className = "error";
		alert("Please enter either your phone number or your email address");
		form.phone.focus();
		form.phone.parentNode.removeAttribute("class");
		form.email.parentNode.removeAttribute("class");
		return false;
	}
	else
	{
		//Check Phone Number
		if (form.phone.value && (!checkInternationalPhone(form.phone.value)))
		{
			form.phone.parentNode.className = "error";
			alert("The phone nuber you've provided is not in a proper format.");
			form.phone.focus();
			form.phone.parentNode.removeAttribute("class");
			return false;
		}	
		
		//Check whether the email address is in the proper format
		if (form.email.value && ((form.email.value === "") || (!isEmail(form.email.value))))
		{
			form.email.parentNode.className = "error";
			alert("Your email address is not in the proper format (e.g. name@provider.com).");		
			form.email.focus();		
			form.email.parentNode.removeAttribute("class");
			return false;
		}
	}

	//Check message	
	if (form.message.value === "")
	{
		form.message.parentNode.className = "error";
		alert ("Please provide a message.");
		form.message.focus();
		form.message.parentNode.removeAttribute("class");
		return false;	
	}
	//End checking for filled in forms
	//****************************************************************************************************

	form.validated.value = "true";
	return true;
}

// cleans any string of unwanted junk input and also changes certain characters to words
function cleanOutJunk(str)
{
	if(str !== "")
	{
		str = str.replace(/\s+|^\s|\s$/g," "); //remove multiple white spaces
		str = str.replace(/&/g," and "); //replaces & with and
		str = str.replace(/'/g,"`"); //replaces ' with `
		str = str.replace(/;+/g,","); //replaces ; or . with ,
		str = str.replace(/\.+/g,"."); //replaces multiple . with only one
		str = str.replace(/\s+,|\s+\./g,","); //replaces ' ,' or ' .' with ','
		str = str.replace(/,+/g,","); //replaces multiple , characters with only 1
		str = str.replace(/,\b/g,", "); //replaces , with no space after it with , with a space after it
		str = str.replace(/^\s+|\s+$|^,+|,+$|^\.|^\b\s+|\.$/g,""); //removes white space at beginning and end along with commas at the beginning.
		str = str.replace(/^\s+|\s+$|^,+|,+$|^\.|^\b\s+/g,""); //removes white space at beginning and end along with commas at the beginning.
		str = str.replace(/\s+|^\s|\s$/g," "); //remove multiple white spaces
	}
	return str;
}

//checks if the email address is proper format
function isEmail(str)
{
	var regex =/^[\-_.a-z0-9]+@(([\-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
	return regex.test(str);
}

// Phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
//****************************************************************************************************
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone number.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{
	var i;
	for (i = 0; i < s.length; i++)
	{   
		// Check that current character is number.
   	var c = s.charAt(i);
   	if (((c < "0") || (c > "9"))){return false;}
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag)
{   
	var i;
   var returnString = "";
   // Search through string's characters one by one.
   // If character is not in bag, append to returnString.
   for (i = 0; i < s.length; i++)
   {   
   	// Check that current character isn't whitespace.
   	var c = s.charAt(i);
   	if (bag.indexOf(c) == -1){returnString += c;}
   }
   return returnString;
}

function checkInternationalPhone(strPhone)
{
	var s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}


// Form length counter. Lets the user know how many characters they have left in their message
//****************************************************************************************************
var currentLength;
var maxLength = 250; //global textarea length
function SetMaxLength()
{
	var textAreas = document.getElementsByTagName('textarea');
	var lengthCounter = document.createElement('div'); // create p to put the counter in
	lengthCounter.className = 'instructions, counter'; // give the div the "counter" class
	for (var i=0;i<textAreas.length;i++)
	{
			var lengthCounterClone = lengthCounter.cloneNode(true);
			lengthCounterClone.relatedElement = textAreas[i];
			lengthCounterClone.innerHTML = "<p>" + maxLength + " of " + maxLength + " characters left.</p>";
			textAreas[i].parentNode.insertBefore(lengthCounterClone,textAreas[i].nextSibling);
			textAreas[i].relatedElement = lengthCounterClone.getElementsByTagName('p')[0];

			textAreas[i].onkeyup = textAreas[i].onchange = CheckMaxLength;
			textAreas[i].onkeyup();
	}
}

function CheckMaxLength()
{
	var extraNote = "They";
	currentLength = this.value.length;
	if (currentLength > maxLength)
	{
		this.relatedElement.className = 'error'; // if there is too much text, apply this class to the span
		
		if (currentLength-maxLength==1) {extraNote = "It";}
		
		this.relatedElement.firstChild.nodeValue = (currentLength - maxLength) + " too many characters. " + extraNote +" will be removed when you submit this form.";
	}
	else
	{
		this.relatedElement.className = '';
		
		if (currentLength==maxLength) {this.relatedElement.className = 'error';} //Changes the text when the maxLenght is reached.
		
		this.relatedElement.firstChild.nodeValue = maxLength - currentLength + " of  " + maxLength + " characters left."; // changes the text inside the span to this
	}
}



// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
    	window.onload = func;
	} 
	else 
	{
		window.onload = function(){oldonload();func();};
	}
}

addLoadEvent(SetMaxLength); // run SetMaxLength() onLoad
addLoadEvent(addValidation); // run addValidation() onLoad 