
	/*
	** Cookie cutting code by PPK: quirksmode.org
	*/

	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

	/*
	** Make external links open in a new window
	*/

	function externalLinks() {
		if (!document.getElementsByTagName) return;
		var anchors = document.getElementsByTagName("a");
		for (var i=0; i < anchors.length; i++) {
			var anchor = anchors[i];
			if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
				anchor.target = "_blank";
			}
		}
	}

	/*
	** Send article email validation
	*/

	function validateEmail()
	{
		var messageBox = document.getElementById("article-message");
		var messageText =
				messageBox.getElementsByTagName("span")[0].firstChild;
		var submitButton = document.getElementById("article-submit");
		var email = document.getElementById("email").value;

		if (isValidEmail(email)) {
			submitButton.disabled = false;
			messageText.data = "Thank you!";
			messageBox.className = "accepted";
		} else if (email == "") {
			messageText.data = "Please enter your email address to continue";
			submitButton.disabled = true;
			messageBox.className = "alert";
		} else if (email != "") {
			messageText.data = "Please enter a valid email address \
					to continue.";
			submitButton.disabled = true;
			messageBox.className = "alert";
		}

	}

	function isValidEmail(address) {
		return (/^(\w[-\w'\.]*\w|"[^"\\\n]+")@(\w+[-\w\.]*\.[-\w]{2,})$/).test(address);
	}
	
/*
**	Validate aced signup email
*/
	function validateSignupEmail() {

		var messageBox = document.getElementById("signup-message");
		var messageText = messageBox.getElementsByTagName("span")[0].firstChild;
		var submitButton = document.getElementById("signup-submit");
		var email = document.getElementById("signup-email-input").value;
		if (isValidEmail(email)) {
			submitButton.disabled = false;
			messageText.data = "";
			removeElementClass(messageBox, "signup-alert");
		} else if (email == "") {
			messageText.data = "Please enter your email address to continue.";
			submitButton.disabled = true;
			addElementClass(messageBox, "signup-alert");
		} else if (email != "") {
			messageText.data = "This email address is not formed properly. Please enter a valid email address to continue.";
			submitButton.disabled = true;
			addElementClass(messageBox, "signup-alert");
		}

	}
	
/*
**	Validate enquiry form
*/
	function validateEnquiryForm() {
		var validationBox = document.getElementById("inquiry-validation-message");
		var validationText = validationBox.getElementsByTagName("span")[0].firstChild;
		var submitButton = document.getElementById("inquiry-submit");
		var email = document.getElementById("email").value;
		var description = document.getElementById("description").value;
		var emailValidationText, descriptionValidationText

		if(isValidEmail(email)) {
			emailValidationText = "";
		} else if (email == "") {
			emailValidationText = "your email address";
		} else if (email != "") {
			emailValidationText = "a valid email address";
		}
		
		if(description == "") {
			descriptionValidationText = "your message";
		} else {
			descriptionValidationText = "";
		}		


		if (emailValidationText == "" && descriptionValidationText == "" ) {
			submitButton.disabled = false;
			validationText.data = "";
			validationBox.className = "inquiry-accepted";
		} else {
			submitButton.disabled = true;
			validationBox.className = "inquiry-alert";	
			validationText.data = "Please enter " +
									(emailValidationText != ""? emailValidationText :"") + 
									(emailValidationText != "" &&  descriptionValidationText != ""? " and ":"") +
									(descriptionValidationText != ""? descriptionValidationText:"") +
									" to continue.";
		}

	}	
	
	function fadeSwitchImage(image, fromSrc, toSrc)
	{
		if (image) {
			Opacity(image, {
				from: 1,
				to: 0,
				beforeStart: function() {
					image.src = fromSrc;
				},
				afterFinish: function() {
					image.src = toSrc;
					Opacity(image, {
						from: 0,
						to: 1,
						duration: 2
					});
				}
			});
		}
	}




	window.onload =
	function() {
		externalLinks();

		// redirect fading
		var redirectLogo = $$("#redirect-image")[0];
		if (redirectLogo) {
			fadeSwitchImage(redirectLogo, redirectLogo.src,
				"../Images/Insync-Surveys-Logo.png")
		}

	/*	// banner fading
		if (readCookie("bannerFade") != "played") {
			fadeSwitchImage($$("#header img")[0], "/Images/Header.gif",
					"/Images/Header-Insync.gif")
			createCookie("bannerFade", "played", 5);
		}*/

		if (document.getElementById) {
			if (document.getElementById("article-submit")) {
				validateEmail();
				document.getElementById("email").onblur =
						validateEmail;
				document.getElementById("email").onkeyup =
						validateEmail;
			}

			if (document.getElementById("signup-submit")) {
				validateSignupEmail();
				document.getElementById("signup-email-input").onblur =
						validateSignupEmail;
				document.getElementById("signup-email-input").onkeyup =
						validateSignupEmail;
			}
			
			if (document.getElementById("inquiry-submit")) {
				validateEnquiryForm();
				document.getElementById("email").onblur =
						validateEnquiryForm;
				document.getElementById("email").onkeyup =
						validateEnquiryForm;
				document.getElementById("description").onblur =
						validateEnquiryForm;
				document.getElementById("description").onkeyup =
						validateEnquiryForm;
			}

			
		}
	}

	function openLinkInPopup(heigthPercent, widthPercent){
		var _defaultHeightPercent = 60;
		var _defaultWidthPercent = 50;
		var _h = typeof heigthPercent != "undefined"?heigthPercent:_defaultHeightPercent;
		var _w = typeof widthPercent != "undefined"?widthPercent:_defaultWidthPercent;	
		openPopup(this.href, _h, _w);
		return false;
	}

	/*
	** Opens a popup with specified height/width
	*/

	function openPopup(url,heigthPercent, widthPercent, features)
	{
		var _popupName = "";
		var _defaultHeightPercent = 80;
		var _defaultWidthPercent = 75;
		var _h = screen.height * (typeof heigthPercent != "undefined"?heigthPercent:_defaultHeightPercent) / 100;
		var _w = screen.width * (typeof widthPercent != "undefined"?widthPercent:_defaultWidthPercent) /100;
		var _features = (typeof features != "undefined"?features:"resizable=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
		var _settings= "";
		var _winl;
		var _wint;
		if(screen.width) {
			_winl = (screen.width-_w)/2;
			_wint = (screen.height-_h)/2 - 50;
		}else {
			_winl = 0;
			_wint = 0;
		}

		if(_winl < 0) _winl = 0;
		if(_wint < 0) _wint = 0;

		_settings += "height=" + _h + ",";
		_settings += "width=" + _w + ",";
		_settings += "top=" + _wint + ",";
		_settings += "left=" + _winl + ",";
		_settings += _features;
		window.open(url,_popupName,_settings).focus();
	}


/*
**	Salesforce related functions
*/

	function attachSalesforceReturnUrlScript() {

		forEach(getSalesforceForms(), function(sfForm) {
			sfForm.sfgaOnSubmit = sfForm.onsubmit;
			sfForm.onsubmit = setSalesforceReturnUrl;
		});
	}
	
	function setSalesforceReturnUrl(e) {

		var sfForm = this;
		// first_name and last_name are compulsory for salesforce, so substitute <UNKNOWN> for blanks
		var sfMandatoryFields = ["first_name","last_name"];

		setEmailOptOut(sfForm); 
		ensureFieldsExistWithValues(sfForm, sfMandatoryFields);
		var retURL = $('retURL');
		if(retURL) {
			var urlParams = packFormValues(sfForm);
			var insyncUrl = window.location.protocol 
								+ "//" 
								+ window.location.hostname
								+ $('formAction').value
								+ (/\?/.test(window.location.hostname)?"":"?")
								+ "&" + urlParams
								+ "&sfgaRetUrl=true";
			retURL.value = insyncUrl;
		}
		
		return sfForm.sfgaOnSubmit.call(sfForm, e);
	}
	
	function ensureFieldsExistWithValues(form, mandatoryFields) {
		forEach(mandatoryFields, function(fieldName) {
			var mandatoryField = $(fieldName);
			if(!mandatoryField) {
				createHiddenField(form, fieldName, "<UNKNOWN>");
			} else {
				if(mandatoryField.value == "") {
					mandatoryField.value = "<UNKNOWN>";
				}				
			}
		});
	}

	function setEmailOptOut(form) {
		if($('subscribe')) {
			var emailOptOut = $('subscribe').checked? "0":"1"; 
			createHiddenField(form, "emailOptOut",	emailOptOut);		
		}	
	}

	function createHiddenField(form, fieldName, value) {
		var hiddenField = document.createElement("input");
		hiddenField.type = "hidden";
		hiddenField.id = fieldName;
		hiddenField.name = fieldName;
		hiddenField.value = value;
		form.appendChild(hiddenField);
	}

	function getSalesforceForms() {
		return $$('form[action*=www.salesforce.com]');
	}	

//  This function does not handle multiple checkbox values and assumes that only checkbox is selected.

	function packFormValues(form) {

		var query  = '';
		var formFields = {};
		var fields = form.elements;

		forEach(fields, function(field) {

			var name = field.getAttribute('name');
			if( name && ((name != 'retURL' && name != 'submit' && name != 'oid' )) ) {

				var tagName = field.tagName.toLowerCase();
				if(tagName == 'input') {
					switch(field.type.toLowerCase()) {
						case "checkbox": // not handling multiple checkbox values
						case "radio":
							if(field.checked) {
								formFields[field.name] = field.value;
							}
							break;
						default:
							formFields[field.name] = field.value;
					}
				}
				else if(tagName == "select") {
					if(field.selectedIndex != -1) {
						formFields[field.name] = field[field.selectedIndex].value;
					}				
				}
				else if(tagName == "textarea") {
					formFields[field.name] = field.value;
				}
			}
		});
		
		return urlEncodeDictionary(formFields);
	}
	
	function urlEncodeDictionary (dictionary) {
		var expressionList = [];
		for (var key in dictionary) {
			expressionList.push(encodeURIComponent(key) + "=" + encodeURIComponent(dictionary[key]));
		}
		return expressionList.join("&");
	}
