
/*

	global javascript functions
	
	dependencies: jQuery
	
*/

function isNotInt(int) {
	var regEx = /^\d+$/;
	return !regEx.test(int);
}

function isNotNum(int) {
	var regEx = /^\d*\.?\d+$/;
	return !regEx.test(int);
}

function isNotDollar(int) {
	var regEx = /^\$?\d+(\.(\d{2}))?$/;
	return !regEx.test(int);
}

function isBadPhone(phone) {
	var regEx = /[^0-9\(\)\-\+ ]/;
	return regEx.test(phone);
}

function isBadZip(zip) {
	var regEx = /[^0-9A-Za-z\- ]/;
	return regEx.test(zip);
}

function isBadDate(date) {
	var results = date.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/);
	if (results) {
		// remove leading zeros
		var m = Number(results[1]);
		var d = Number(results[2]);
		var y = Number(results[3]);
		if (y < 100) y += 2000;	// force 2-digit values to 4
		// year must be 4 digits
		if (/^\d{4}$/.test(y)) {
			// valid year; month must be:
			//   a) 1 or 2 digits
			//   b) less than or equal to 12 
			//   c) greater than or equal to 1
			if (/^\d{1,2}$/.test(m) && m >= 1 && m <= 12) {
				// valid month; day must be:
				//   a) 1 or 2 digits
				//   b) less than or equal to last day of month 
				//   c) greater than or equal to 1
				var lastDay =
					m == "4" || m == "6" || m == "9" || m == "11" ? 30 :
					m == "2" && (y / 4) != Math.floor(y / 4) ? 28 :
					m == "2" && (y / 4) == Math.floor(y / 4) ? 29 :
					31;	// defaults to 31
				if (/^\d{1,2}$/.test(d) && d >= 1 && d <= Number(lastDay)) {
					return false;	
				}
			}
		}
	}
	
	return true;
}

function isBadEmail(str) {
	// validates format of email address
	// returns true if email address is 'bad'
	if (/@.*@/.test(str)) return true;
	if (/[\000-\037 ()<>,;:\\"[\]\177]/.test(str)) return true;
	if (/.+@[A-Za-z0-9\-]+\.[A-Za-z0-9\-.]*/.test(str)) return false;
	return true;
}

function ParseErrorMsg() {
	// if an error message is displayed, try to parse the error message
	// extract the links and if the link targets an input field,
	// 		send focus to the input field on click
	var errorMsg = jQuery(".ErrorMsg");
	if (errorMsg) {
		errorMsg.find("a").each(function() {
			jQuery(this).click(function (evt) {
				var startPos = this.href.indexOf("#");
				if (startPos != -1) {
					evt.preventDefault();
					var hash = this.href.substring(startPos);
					var targetElm = $(hash);
					if (targetElm.get(0).tagName.toLowerCase() == "input" ||
						targetElm.get(0).tagName.toLowerCase() == "select" ||
						targetElm.get(0).tagName.toLowerCase() == "textarea") {
						// target is a form field; set focus to field
						$(targetElm).focus();
					}
					else if (targetElm.hasClass("RadioGroup")) {
						// target is a radio group; set focus to first radio button
						$(hash + " input[type=radio]:first").focus();
					}
					else {
						// target is a element; scroll to element
						ScrollToElm(targetElm);
					}
				}
			});
		});
	}	
}

function ClearErrors() {
	// error message clean-up
	$(".Error").removeClass("Error").find(".ErrorPrefix").remove();
	$("#ErrorMsg").empty();	
}

function ClearForm(form) {
	// iterate over all of the inputs for the form
	// element that was passed in
	$(':input', form).each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		// it's ok to reset the value attr of text inputs,
		// password inputs, and textareas
		if (type == 'text' || type == 'password' || tag == 'textarea') {
			this.value = "";
		}
		// checkboxes and radios need to have their checked state cleared
		// but should *not* have their 'value' changed
		else if (type == 'checkbox' || type == 'radio') {
			this.checked = false;
		}
		// select elements need to have their 'selectedIndex' property set to -1
		// (this works for both single and multiple select elements)
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};

function ScrollToElm(elm, offsetTop, offsetLt) {
	// calculates the element's top and left offset
	// 		and scrolls viewport to element's position
	elm = $(elm).get(0);
	var top = offsetTop ? offsetTop : 0;
	var left = offsetLt ? offsetLt : 0;
	do {
		top += elm.offsetTop  || 0;
		// left += elm.offsetLeft || 0;
		elm = elm.offsetParent;
	} while (elm);
	window.scrollTo(left, top);
}

jQuery(function($) {
	
	// development guides
	//$("#LayoutGrid").css("opacity", 0.3);
	//$("#PageTemplate").css("opacity", 0.3);
	
	// load custom stylesheet for screens smaller than 1024x768
	if (screen.width < 1024) {
		$("head").append('<link rel="stylesheet" type="text/css" href="/css/800x600.css" />\n');
	}
	
	// hide all no-script content
	$('.NoScript').hide();
	
	// initialize all tabbed panels
	$(".TabbedPanel").tabs();
	
	// initialize contact widgets
	var contactWidget = $("#ContactWidget");
	if (contactWidget.length) {
		// this must be executed before the collapsible regions are parsed
		
		// create a reference to the link
		var link = contactWidget.find("a.StandardLink");
		// capture the contact form's URL
		var contactFormURL = link.attr("href");
		// remove the link
		link.remove();
		// append the collapsible region
		contactWidget.append('<div class="CollapsibleRegion">' + 
			'<h3><a href="' + contactFormURL + '" id="ContactFormActuator">Complete this form</a></h3>' + 
			'<div id="ContactFormContainer"></div>' + 
			'</div>');
		// wrap the widget within a shadowbox
		contactWidget.html(			  
			'<div class="ShadowBox FullPage">\n' +
			'<div class="BoxHead">\n' +
			'<div class="Header">&nbsp;</div>\n' +
			'</div>\n' +
			'<div class="BoxBody">\n' +
			contactWidget.html() +
			'</div>\n' +
			'<div class="BoxFoot">\n' +
			'<div class="Footer">&nbsp;</div>\n' +
			'</div>\n' +
			'</div>\n');
		// configure the contact form actuator link
		$("#ContactFormActuator").click(function() {
			var contactForm = $("#ContactForm");
			if ($(this).parent("h3").hasClass("Opened") && contactForm.length > 0) {
				// the collapsible region is open and the contact form is embedded
				// reset the form
				ClearForm(contactForm);
				// error message clean-up
				ClearErrors();
			}
			else if ($(this).parent("h3").hasClass("Closed") && contactForm.length == 0) {
				// the collapsibl region is closed and/or the contact form has not been loaded
				// temporarily embed the loader animation
				$("#ContactFormContainer").html('<img src="/images/global/loader24_shadowbox.gif" alt="Loading Contact Form..." />');
				// load the contact form
				$.ajax({ 
					url: contactFormURL,
					type: "post",
					dataType: "html",
					data: { ajax_response: "html" },
					success: function(data) {
						// embed the contact form
						var contactFormContainer = $("#ContactFormContainer");
						contactFormContainer.html(data);
						// scroll to the top of the contact form
						ScrollToElm("#ContactWidget", 0 - $("#emGuide").height());
						// initialize the contact form
						initContactForm();	
					},
					error: function(data) {
						// redirect to standard contact form on error
						window.location.href = contactFormURL;
					}
				});
			}
		});
	}
	
	// format the collapsible regions
	// <div class="CollapsibleRegion">
	//		<h3><a href="[...]">[...]</a></h3>
	//		<div>[...]</div>
	// </div>
	// the h3 > a tag is optional
	$(".CollapsibleRegion").each(function() {
		// the actuator is optional; if the actuator does not exist create it
		var h3 = $(this).children("h3");
		if (h3.children("a").length == 0) {
			// wrap the h3 text in an link anchor
			h3.wrapInner('<a href="#"></a>');
		}
		// get the actuator; identified by child h3 > a element
		h3.addClass("Heading").addClass("Closed").children("a").each(function() {
			var actuator = $(this);
			actuator.addClass("Actuator").click(function(evt) {
				// prevent the link's default behavior
				evt.preventDefault();
				// create reference to heading
				var heading = actuator.parent("h3");
				// create reference to content
				var content = heading.next("div");
				// create reference to region
				var region = heading.parent();
				
				// toggle the content unless it is already tweening
				if (!region.hasClass("isTweening")) {
					if (heading.hasClass("Closed")) {
						// toggle the actuator's classname
						heading.removeClass("Closed").addClass("Opened");
						// expand the content
						region.addClass("isTweening");
						content.show("blind", {}, "fast", function() {
							region.removeClass("isTweening");
							// toggle the actuator's classname
							heading.removeClass("Closed").addClass("Opened");
						});
					}
					else {
						// collapse the content
						region.addClass("isTweening");
						content.hide("blind", {}, "fast", function() {
							region.removeClass("isTweening");
							// toggle the actuator's classname
							heading.removeClass("Opened").addClass("Closed");
						});
					}
				}
			});
			
			// get the content; identified by the next sibling div element
			// hide the content on load; the display of the content is triggered
			//		by the actuator link
			$(this).parent("h3").next("div").addClass("Content").hide();
		});
	});
	
	// initialize the contact form; if applicable
	initContactForm();
	
	// setup Solutions By Industry Sector picklist
	var industryForm = $("#IndustryPicklist form");
	if (industryForm.length) {
		industryForm.find(".GoBtn").click(function(evt) {
			// prevent the form from submitting
			evt.preventDefault();
			// go to the URL specified by the selection option's value
			var url = industryForm.find("select").val();
			if (url != "") window.location.href = url;
		});
	}
	
	// setup Product ("I need...") picklist
	var productForm = $("#ProductPicklist form");
	if (productForm.length) {
		productForm.find(".GoBtn").click(function(evt) {
			// prevent the form from submitting
			evt.preventDefault();
			// go to the URL specified by the selection option's value
			var url = productForm.find("select").val();
			if (url != "") window.location.href = url;
		});
	}
	
	// initialize the accordion widgets
	$(".AccordionWidget.Collapsed").accordion({
		autoHeight: false,
		collapsible: true,
		icons: {
			"header" : "ui-icon-plus",
			"headerSelected" : "ui-icon-minus"
		},
		header: "h3",
		active: false
	});
	$(".AccordionWidget").accordion({
		autoHeight: false,
		collapsible: true,
		icons: {
			"header" : "ui-icon-plus",
			"headerSelected" : "ui-icon-minus"
		},
		header: "h3"
	});
	
	// format the accordion headings
	// <div class="AccordionWidget">
	//		<h3><a href="[...]">[...]</a></h3>
	//		<div>[...]</div>
	// </div>
	// the h3 > a tag is optional
	$(".AccordionWidget").each(function() {
		// the actuator is optional; if the actuator does not exist create it
		var h3 = $(this).children("h3");
		if (h3.children("a").length == 0) {
			// wrap the h3 text in an link anchor
			h3.wrapInner('<a href="#"></a>');
		}
	});
	
	// make Fuel Surcharge Amendments more accessible
	//$(".DataTable.FuelSurcharge tr.Highlight th.FirstCol").prepend("CHANGE: ");
});

function initContactForm() {
	var contactForm = $("#ContactForm");
	if (contactForm.length) {
		
		// parse error message; adds click event handlers
		ParseErrorMsg();
		
		$("#ClearBtn").click(function(evt) {
			// prevent form from submitting
			evt.preventDefault();
			// clear button focus
			$(this).blur();
			// reset the form
			contactForm.get(0).reset();
			// error message clean-up
			ClearErrors();
			// scroll to top of page
			ScrollToElm("#PageTop");
		});
		
		contactForm.submit(function(evt) {

			var errorMsg = "";
	
			var errorPrefix = '<span class="ErrorPrefix">Error: </span>';
			
			var firstName = jQuery.trim($("#FirstNameFld").val());
			var lastName = jQuery.trim($("#LastNameFld").val());
			var jobTitle = jQuery.trim($("#JobTitleFld").val());
			var company = jQuery.trim($("#CompanyFld").val());
			var country = jQuery.trim($("#CountryFld").val());
			var email = jQuery.trim($("#EmailFld").val());
			var question = jQuery.trim($("#QuestionFld").val());
			
			ClearErrors()
			
			if (firstName == "") {
				$("label.FirstName").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#FirstNameFld">First Name</a>: Your first name is required.</li>\n';
			}
			
			if (lastName == "") {
				$("label.LastName").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#LastNameFld">Last Name</a>: Your last name is required.</li>\n';	
			}
			
			if (jobTitle == "") {
				$("label.JobTitle").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#JobTitleFld">Job Title</a>: Your job title is required.</li>\n';
			}
			
			if (company == "") {
				$("label.Company").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#CompanyFld">Company Name</a>: Your company name is required.</li>\n';
			}
			
			if (country == "") {
				$("label.Country").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#CountryFld">Please select your country</a>: Your country is required.</li>\n';
			}
			
			if (email == "") {
				$("label.Email").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#EmailFld">Email Address</a>: Your email address is required.</li>\n';
			}
			else if (isBadEmail(email)) {
				$("label.Email").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#EmailFld">Email Address</a>: Your email address is not a valid format.</li>\n';
			}
			
			if (question == "") {
				$("label.Question").addClass("Error").prepend(errorPrefix);
				errorMsg += '<li><a href="#QuestionFld">Your Enquiry</a>: Your enquiry is required.</li>\n';
			}
			
			if (errorMsg != "") {
				// prevent the form from submitting
				evt.preventDefault();
				// insert error message
				errorMsg = '<h2 class="Error">Please check the following fields for missing or invalid input:</h2>\n' +
					'<ul class="ErrorMsg">' + errorMsg + '</ul>\n';
				$("#ErrorMsg").append(errorMsg);
				// parse error message; adds click event handlers
				ParseErrorMsg();
				// scroll to top of page
				ScrollToElm("#ContactForm");
			}
			else if ($("#ContactFormContainer").length) {
				// submit the contact form via AJAX
				// prevent the form from submitting
				evt.preventDefault();
				// get the contact form's URL
				var contactFormURL = $(this).attr("action");
				// serialize the contact form's field values
				var contactFormParams = $(this).serialize();
				// submit the contact form via AJAX
				$.ajax({ 
					url: contactFormURL,
					type: "post",
					dataType: "json",
					data: contactFormParams,
					success: function(data) {
						var status = data.response.status;
						var message = data.response.message;
						if (status == "success") {
							// replace the contact form with the response message
							var contactFormContainer = $("#ContactFormContainer");
							contactFormContainer.html(message);
							// scroll to top of page
							ScrollToElm(".ShadowBox.ContactForm", 0 - $("#emGuide").height());
						}
						else if (status == "error") {
							$("#ErrorMsg").append(message);
							// parse error message; adds click event handlers
							ParseErrorMsg();
							// scroll to top of form
							ScrollToElm("#ContactForm");
						}	
					},
					error: function(data) {
						// submit the form manually
						$(this).get(0).submit();
					}
				}); 
			}
		});
	}	
}