/******************************************
* AWD JS Library
* Author: Matthew Camp
* Created: 17th February 2009
* ________________________________________________________________________________
* MAIN FUNCTION LIST, call each function within the class attribute of the element
* ________________________________________________________________________________
* JavaScript:LightBox(width,height,link) - [a tag only] creates a lightbox and displays an external html document
* JavaScript:ExternalLink - [a tag only] opens a new window just like the old target _blank attribute
* JavaScript:ToolTip(x,y) - [* tags with rel attribute] displays a tooltip or speechmark and displays the rel content
*
* ________________________________________________________________________________
* GLOBAL FUNCTION LIST, these functions are shared with all the main functions
* ________________________________________________________________________________
* GetMouseLocation(e) - returns the [x,y] position of the clients mouse in an array - must be called from an event
* GetArgumentValues() - returns an array with all the arguments passed through a HTML class function call
* GetBodyDimensions() - returns an array with the [width,height] of the html body (entire page with scroll)
* GetWindowDimensions() - returns an array with the [width,height] of the clients internal window
* GetScrollPosition() - returns the position of the clients scrollbar
* DetectBrowser() - returns the name of the clients browser with the first letter of each word in uppercase, eg Internet Explorer
*******************************************/

/******************************************
* INITIATE GLOBAL VARIABLES AND ADD EVENT LISTENERS
*******************************************/
//changable variables
var IFRAME_FOLDER = "iframes/";
var MAX_CHARACTER_MESSAGE = "The text you've entered has exceeded the character limit!";
var REQUIRED_FIELD_MESSAGE = "This field is required";
var INVALID_EMAIL = "The email you've entered is invalid";
var INVALID_TELEPHONE = "The telephone number you've entered is invalid";

// Add events to html
window.onload = addEventListeners;
function addEventListeners(){
	PrepareLightBoxes();
	ExternalLink();
	PrepareToolTips();
	ClearDefaultText();
	SetFormValidation();
	ValidateFields();
	VerifySubmission();
	ResetClick();
}

//Strict Variables DO NOT CHANGE
var LIGHT_BOX_ACTIVATED = false;
var TOOLTIP_ACTIVATED = false;
var NUM_VALIDATION_ERRORS = 0;
if(DetectBrowser() == "Opera" || DetectBrowser() == "Internet Explorer"){
	var MESSAGE_SEPARATOR = "<BR>";	
}
else{
	var MESSAGE_SEPARATOR = "<br>";	
}

/******************************************
* FORM FUNCTIONS
*******************************************/
function ClearDefaultText() {
	if(!document.getElementsByTagName){ 
		return false;
	}
	var fields = document.getElementsByTagName("*");
	for(var i = 0; i < fields.length; i ++){
		if(fields[i].className.match("JavaScript:ClearDefaultText")){
			fields[i].onfocus = function(){
				if(this.value == this.defaultValue){
					this.value = "";
				}
			}
		}
	}
}
// Resets the number of errors and removes all validation messages
function ResetClick(){
	var resetButtons = document.getElementsByTagName("input");
	for(var i = 0; i < resetButtons.length; i ++){
		if(resetButtons[i].type != "reset"){
			continue;
		}
		resetButtons[i].onclick = function(){
			NUM_VALIDATION_ERRORS = 0;
			var validationClass = document.getElementsByTagName("span");	
			for(var j = 0; j < validationClass.length; j ++){
				if(validationClass[j].className.match("validation_text")){
					validationClass[j].innerHTML = "";
				}
			}
			var formElements = document.getElementsByTagName("*");
			for(var k = 0; k < formElements.length; k ++){
				var resetClass = formElements[k].className.replace("required_error", "");
				var resetClass2 = resetClass.replace("email_error", "");
				var resetClass3 = resetClass2.replace("max_length_error", "");
				var resetClass4 = resetClass3.replace("validation_pass", "");
				var resetClass5 = resetClass4.replace("telephone_error", "");
				formElements[k].className = resetClass5;	
			}
		}
	}
}
/******************************************
* FORM VALIDATION FUNCTIONS
*******************************************/
// Verifies data before form submission, if any data is invalid the form will not submit
function VerifySubmission(){
	var submitButtons = document.getElementsByTagName("input");
	for(var i = 0; i < submitButtons.length; i ++){
		if(submitButtons[i].type != "submit"){
			continue;
		}
		submitButtons[i].onclick = function(){
			var fields = document.getElementsByTagName("*");
			for(var i = 0; i < fields.length; i ++){
				if(fields[i].className.match("JavaScript:ValidateMaxLength")){
					ValidateMaxLength(fields[i]);
				}
				if(fields[i].className.match("JavaScript:RequiredField")){
					RequiredField(fields[i]);
				}
				if(fields[i].className.match("JavaScript:ValidateEmail")){
					ValidateEmail(fields[i]);
				}
				if(fields[i].className.match("JavaScript:ValidateTelephone")){
					ValidateTelephone(fields[i]);
				}
			}
			if(NUM_VALIDATION_ERRORS > 0){
				alert("You have "+ NUM_VALIDATION_ERRORS +" field error/s, please review each field and try again!");
				return false;
			}
		}
	}
}
// Prepare all fields with a message placeholder ready for validation errors
function SetFormValidation(){
	var textInputs = document.getElementsByTagName("input");
	for(var i = 0; i < textInputs.length; i ++){
		if(textInputs[i].type == "submit" || textInputs[i].type == "reset"){
			continue;
		}
		var validationMessage = document.createElement("span");
		//validationMessage.innerHTML = "<br />hello";
		attr = document.createAttribute("class");
		if(DetectBrowser() == "Internet Explorer"){
			validationMessage.setAttribute("className","validation_text");
		}
		else{
			validationMessage.setAttribute("class","validation_text");
		}
		textInputs[i].parentNode.appendChild(validationMessage);
	}
	var textAreas = document.getElementsByTagName("textarea");
	for(var i = 0; i < textAreas.length; i ++){
		var validationMessage = document.createElement("span");
		//validationMessage.innerHTML = "<br />hello";
		attr = document.createAttribute("class");
		if(DetectBrowser() == "Internet Explorer"){
			validationMessage.setAttribute("className","validation_text");
		}
		else{
			validationMessage.setAttribute("class","validation_text");
		}
		textAreas[i].parentNode.appendChild(validationMessage);
	}
}
// Attaches All Validation checks to an OnBlur
function ValidateFields() {
	var fields = document.getElementsByTagName("*");
	for(var i = 0; i < fields.length; i ++){
		fields[i].onblur = function(){
			
			if(this.className && this.className.match("JavaScript:RequiredField")){
				RequiredField(this);
			}
			if(this.className && this.className.match("JavaScript:ValidateMaxLength")){
				ValidateMaxLength(this);
			}
			if(this.className && this.className.match("JavaScript:ValidateEmail")){
				ValidateEmail(this);
			}
			if(this.className && this.className.match("JavaScript:ValidateTelephone")){
				ValidateTelephone(this);
			}
		}
	}
}
// Validates telephone number
function ValidateTelephone(element){
	var allowedChars = "0123456789()-+ ";
	var telephone = element.value;
	var validationClass = element.parentNode.getElementsByTagName("span");
	var validTelephone = true;
	for(var i = 0; i < telephone.length; i ++){
		var char = telephone.charAt(i);
		if(allowedChars.indexOf(char) < 0){
			validTelephone = false;
			break;
		}
	}
	var hasError = element.className.indexOf("telephone_error");
	if(validTelephone == false && telephone != "") {
		if(hasError < 0){
			var replaceClass = element.className.replace("validation_pass", "");
			replaceClass += " telephone_error";
			element.className = replaceClass;
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				if(validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+INVALID_TELEPHONE) == -1){
					NUM_VALIDATION_ERRORS ++;
					validationClass[j].innerHTML += MESSAGE_SEPARATOR+INVALID_TELEPHONE;
				}
			}
		}
	}
	else{
		if(hasError >= 0){
			var replaceClass = element.className.replace("telephone_error", "");
			element.className = replaceClass;
		}
		if(element.className.indexOf("_error") < 0 && element.className.indexOf("validation_pass") < 0){
			element.className += " validation_pass";
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				var messageExists = validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+INVALID_TELEPHONE);
				if(messageExists != -1){
					NUM_VALIDATION_ERRORS --;
					var currentHTML = validationClass[j].innerHTML;
					var replaceMessage = currentHTML.replace(MESSAGE_SEPARATOR+INVALID_TELEPHONE, "");
					validationClass[j].innerHTML = replaceMessage;
				}
			}
		}
	}
}
// Validates email address
function ValidateEmail(element){
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = element.value;
	var validationClass = element.parentNode.getElementsByTagName("span");
	var hasError = element.className.indexOf("email_error");
	if(reg.test(address) == false && address != "") {
		if(hasError < 0){
			var replaceClass = element.className.replace("validation_pass", "");
			replaceClass += " email_error";
			element.className = replaceClass;
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				if(validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+INVALID_EMAIL) == -1){
					NUM_VALIDATION_ERRORS ++;
					validationClass[j].innerHTML += MESSAGE_SEPARATOR+INVALID_EMAIL;
				}
			}
		}
	}
	else{
		if(hasError >= 0){
			var replaceClass = element.className.replace("email_error", "");
			element.className = replaceClass;
		}
		if(element.className.indexOf("_error") < 0 && element.className.indexOf("validation_pass") < 0){
			element.className += " validation_pass";
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				var messageExists = validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+INVALID_EMAIL);
				if(messageExists != -1){
					NUM_VALIDATION_ERRORS --;
					var currentHTML = validationClass[j].innerHTML;
					var replaceMessage = currentHTML.replace(MESSAGE_SEPARATOR+INVALID_EMAIL, "");
					validationClass[j].innerHTML = replaceMessage;
				}
			}
		}
	}
}
// Validates required fields that cannot be left blank
function RequiredField(element){
	var validationClass = element.parentNode.getElementsByTagName("span");
	var hasError = element.className.indexOf("required_error");
	if(element.value.length < 1){
		if(hasError < 0){
			var replaceClass = element.className.replace("validation_pass", "");
			replaceClass += " required_error";
			element.className = replaceClass;
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				if(validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+REQUIRED_FIELD_MESSAGE) == -1){
					NUM_VALIDATION_ERRORS ++;
					validationClass[j].innerHTML += MESSAGE_SEPARATOR+REQUIRED_FIELD_MESSAGE;
				}
			}
		}
	}
	else{
		if(hasError >= 0){
			var replaceClass = element.className.replace("required_error", "");
			element.className = replaceClass;
		}
		if(element.className.indexOf("_error") < 0 && element.className.indexOf("validation_pass") < 0){
			element.className += " validation_pass";
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				var messageExists = validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+REQUIRED_FIELD_MESSAGE);
				if(messageExists != -1){
					NUM_VALIDATION_ERRORS --;
					var currentHTML = validationClass[j].innerHTML;
					var replaceMessage = currentHTML.replace(MESSAGE_SEPARATOR+REQUIRED_FIELD_MESSAGE, "");
					validationClass[j].innerHTML = replaceMessage;
				}
			}
		}
	}
}
// Validates the length of inputted data
function ValidateMaxLength(element){
	maxString = GetArgumentValues(element.className, "JavaScript:ValidateMaxLength")[0];
	var maxLength = parseInt(maxString);
	var validationClass = element.parentNode.getElementsByTagName("span");
	var hasError = element.className.indexOf("max_length_error");
	if(element.value.length > maxLength){
		if(hasError < 0){
			var replaceClass = element.className.replace("validation_pass", "");
			replaceClass += " max_length_error";
			element.className = replaceClass;
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){	
				if(validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+MAX_CHARACTER_MESSAGE) == -1){
					NUM_VALIDATION_ERRORS ++;
					validationClass[j].innerHTML += MESSAGE_SEPARATOR+MAX_CHARACTER_MESSAGE;
				}
			}
		}
	}
	else{
		if(hasError >= 0){
			var replaceClass = element.className.replace("max_length_error", "");
			/*if(replaceClass.indexOf("_error") < 0){
				replaceClass += " validation_pass";
			}*/
			element.className = replaceClass;
		}
		if(element.className.indexOf("_error") < 0 && element.className.indexOf("validation_pass") < 0){
			element.className += " validation_pass";
		}
		for(var j = 0; j < validationClass.length; j ++){
			if(validationClass[j].className.match("validation_text")){
				var messageExists = validationClass[j].innerHTML.indexOf(MESSAGE_SEPARATOR+MAX_CHARACTER_MESSAGE);
				if(messageExists != -1){
					NUM_VALIDATION_ERRORS --;
					var currentHTML = validationClass[j].innerHTML;
					var replaceMessage = currentHTML.replace(MESSAGE_SEPARATOR+MAX_CHARACTER_MESSAGE, "");
					validationClass[j].innerHTML = replaceMessage;
				}
			}
		}
	}
}

/******************************************
* LIGHTBOX FUNCTIONS
*******************************************/
function PrepareLightBoxes(){
	var elements = document.getElementsByTagName("a");
	for(var i = 0; i < elements.length; i ++){
		if(elements[i].className && elements[i].className.match("JavaScript:LightBox")){
			elements[i].onclick = function(){
				LightBox(this);
				return false;
			}
		}
	}
}
function LightBox(element){
	if(! LIGHT_BOX_ACTIVATED){
		var lightBoxHtml = "<div id=\"overlay\"></div>";
		lightBoxHtml += "<div id=\"light_box\"><iframe id=\"iframe_placeholder\" frameborder=\"0\" border=\"0\" scrolling=\"auto\"></iframe>";
		lightBoxHtml += "<p class=\"close_light_box\"><a href=\"#\" onclick=\"HideLightBox(); return false;\"><span>close</span></a></p>";
		lightBoxHtml += "</div>";
		document.body.innerHTML += lightBoxHtml;
		LIGHT_BOX_ACTIVATED = true;
	}
	else{
		document.getElementById("iframe_placeholder").style.display = "block";
		document.getElementById("light_box").style.display = "block";
		document.getElementById("overlay").style.display = "block";
	}
	// get class arguements
	var argumentArray = GetArgumentValues(element.className, "JavaScript:LightBox");
	var elementWidth = argumentArray[0];
	var elementHeight = argumentArray[1];
	var pageURL = argumentArray[2];
	// set overlay
	var bodyWidth = GetBodyDimensions()[0];
	var bodyHeight = GetBodyDimensions()[1];
	document.getElementById("overlay").style.height = bodyHeight + "px";
	// set iframe position
	document.getElementById("iframe_placeholder").style.height = elementHeight + "px";
	document.getElementById("iframe_placeholder").style.width = elementWidth + "px";
	document.getElementById("iframe_placeholder").src = IFRAME_FOLDER + pageURL;
	//set lightbox content placeholder
	document.getElementById("light_box").style.width = elementWidth + "px";
	var lightHeight = document.getElementById('light_box').offsetHeight;
	var lightWidth = document.getElementById("light_box").offsetWidth;
	var windowHeight = GetWindowDimensions()[1];
	var scrollLocation = GetScrollPosition();
	document.getElementById("light_box").style.top = ((windowHeight / 2) + scrollLocation) - (lightHeight / 2) + "px";
	document.getElementById("light_box").style.left = (bodyWidth / 2) - (lightWidth / 2) + "px";
	
}
function HideLightBox(){
	document.getElementById("iframe_placeholder").src = "";
	document.getElementById("iframe_placeholder").style.display = "none";
	document.getElementById("light_box").style.display = "none";
	document.getElementById("overlay").style.display = "none";
	addEventListeners();
}

/******************************************
* NEW WINDOW FUNCTIONS
*******************************************/
function ExternalLink() {
	if(!document.getElementsByTagName){ 
		return false;
	}
	var links = document.getElementsByTagName("a");
	for(var i = 0; i < links.length; i ++){
		if(links[i].className.match("JavaScript:ExternalLink")){
			links[i].onclick = function(){
				window.open(this.href);
				return false;
			}
		}
	}
}

/******************************************
* TOOL TIP FUNCTIONS
*******************************************/
function PrepareToolTips(){
	var elements = document.getElementsByTagName("*");
	for(var i = 0; i < elements.length; i ++){
		if(elements[i].className.match("JavaScript:ToolTip")){
			elements[i].removeAttribute("title");
			elements[i].onmouseover = function(){
				ShowToolTip(this);
			}
			elements[i].onmouseout = function(){
				HideToolTip(this);
			}
		}
	}
}
function ShowToolTip(element){
	if(! TOOLTIP_ACTIVATED){
		var toolContainer = document.createElement("div");
		toolContainer.setAttribute("id","tool_tip");
		document.getElementsByTagName("body")[0].appendChild(toolContainer);
		var topDiv = document.createElement("div");
		topDiv.setAttribute("class","top");
		toolContainer.appendChild(topDiv);
		var bottomDiv = document.createElement("div");
		bottomDiv.setAttribute("class","bottom");
		topDiv.appendChild(bottomDiv);
		if(DetectBrowser() == "Internet Explorer"){
			topDiv.setAttribute("className","top");
			bottomDiv.setAttribute("className","bottom");
		}
		TOOLTIP_ACTIVATED = true;
	}
	element.onmousemove = UpdateToolTip;
	var toolChild = document.getElementById("tool_tip").firstChild;
	var contentDiv = document.getElementById("tool_tip").firstChild.firstChild;
	var titleText = element.getAttribute("rel");
	contentDiv.innerHTML = titleText;
	document.getElementById("tool_tip").style.display = "block";
}
function HideToolTip(element){
	document.getElementById("tool_tip").style.display = "none";
	element.onmousemove = null;
}
function UpdateToolTip(e){
	var mousePosition = GetMouseLocation(e);
	var additionalCoords = GetArgumentValues(this.className, "JavaScript:ToolTip");
	var mouseX = parseInt(mousePosition[0]) + parseInt(additionalCoords[0]) + 3;
	var mouseY = parseInt(mousePosition[1]) + parseInt(additionalCoords[1]) + 3;
	document.getElementById("tool_tip").style.left = mouseX + "px";
	document.getElementById("tool_tip").style.top = mouseY + "px";
}


/******************************************
* GLOBAL FUNCTIONS
*******************************************/

 // Returns the coordinates of the mouse, NEEDS TO BE CALLED FROM AN EVENT TO WORK
function GetMouseLocation(e){
	if(DetectBrowser() == "Internet Explorer"){ 
		mouseX = event.clientX + document.documentElement.scrollLeft;
		mouseY = event.clientY + document.documentElement.scrollTop;
	} 
	else{
		mouseX = e.pageX;
		mouseY = e.pageY;
	}  
	if(mouseX < 0){mouseX = 0;}
	if(mouseY < 0){mouseY = 0;}
	mouseArray = new Array(mouseX,mouseY);
	return mouseArray;
}
// Retrieves the parameter from a class JavaScript call
function GetArgumentValues(currentClass, classString){
	var getValuePosition = currentClass.indexOf(classString + "(");
	var classLength = classString.length;
	var getString = true;
	var stringCount = 0;
	var maxString = "";
	var variableArray = new Array();
	var count = 0;
	while(getString){
		stringCount ++;
		currentCharacter = currentClass.charAt(classLength + getValuePosition + stringCount);
		if(currentCharacter == " "){
			continue;	
		}
		else if(currentCharacter == ","){
			variableArray[count] = maxString;
			maxString = "";
			count ++;
		}
		else if(currentCharacter == ")"){
			variableArray[count] = maxString;
			maxString = "";
			count ++;
			getString = false;
			break;
		}
		else{
			maxString += currentCharacter;
		}
	}
	return variableArray;
}
// Returns the width and height of the body tag within an array
function GetBodyDimensions(){
	if(DetectBrowser() == "Firefox"){
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} 
	else if(DetectBrowser() == "Safari"){
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} 
	else{
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	return arrayPageSizeWithScroll;
}
// Returns the clients window size as an array, not including scroll
function GetWindowDimensions(){ 
	if(DetectBrowser() == "Internet Explorer"){
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} 
	else{
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	}
	var dimensions = new Array(windowWidth, windowHeight);
	return dimensions;
}
// Returns the scroll location of the clients browser
function GetScrollPosition(){
	if(DetectBrowser() == "Safari"){
		scrollOffset = document.body.scrollTop;
	}
	else{
		scrollOffset = document.documentElement.scrollTop;
	}
	return scrollOffset;
}
// Detects and returns the name of the clients browser
function DetectBrowser(){
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1){ 
		return 'Opera';
	}
	if (agt.indexOf("firefox") != -1){
		return 'Firefox';
	}
	if (agt.indexOf("safari") != -1){
		return 'Safari';
	}
	if (agt.indexOf("chrome") != -1){
		return 'Chrome';
	}
	if (agt.indexOf("msie") != -1){
		return 'Internet Explorer';
	}
	if (agt.indexOf("netscape") != -1){
		return 'Netscape';
	}
	if (agt.indexOf("mozilla/5.0") != -1){
		return 'Mozilla';
	}
	if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
			return navigator.userAgent.substr(0,agt.indexOf('\/'));
		}
		else{
			return 'Netscape';
		}
	}
	else if (agt.indexOf(' ') != -1){
		return navigator.userAgent.substr(0,agt.indexOf(' '));
	}
	else{
		return navigator.userAgent;
	}
}