/**************************************************************************
** $Id:$
** Company:		Sure Can Technology
** Author:		Ben Gillies
** Date:		10 November 2008
** Notes:
**************************************************************************/

function dom_browser() {
	// browser identification based on dom capabilities
	this.myNav = this.navigator;
	this.version = this.navigator.appVersion;
	this.name = this.navigator.appName;
	this.userAgt = this.navigator.userAgent;
	this.ns4 = (document.layers) ? true : false;
	this.ns6 = (this.navigator.userAgent.indexOf("Netscape6") != -1) ? true : false;
	this.dom = (document.getElementById) ? true : false;
	this.ie4 = (document.all) ? true : false;
	this.mac = (this.version.indexOf("Mac") != -1) ? true : false;
	this.ie = (this.version.indexOf("MSIE") != -1) ? true : false;
	this.windows = (this.version.indexOf("Windows") != -1) ? true : false;
	this.hasPlugins = (this.navigator.plugins) ? true : false;
	this.ie6 = (this.version.indexOf("MSIE") != -1 && this.version.indexOf("6") != -1) ? true : false;
	this.ie55 = (this.version.indexOf("MSIE 5.5") != -1) ? true : false;
	this.ie5 = (this.version.indexOf("MSIE 5.01") != -1) ? true : false;
	this.ns = (this.userAgt.indexOf("Netscape") != -1) ? true : false;
	this.ff = (this.userAgt.indexOf("Firefox") != -1) ? true : false;
	this.safari = (this.userAgt.indexOf("Safari") != -1) ? true : false;
}

dom_browser();

function trim(str) {
// removes white spaces from beginning and end of given string, str.
	return str.replace(/^\s*|\s*$/g,"");
}

function addClassName(myElement, myClass) {
	var currentClassName = trim(myElement.className);
	var myReg = new RegExp("(^" + myClass + "$)|( " + myClass + "$)|(^" + myClass + " )|( " + myClass + " )", "g");
	if (!myReg.test(currentClassName)) {
		// not currently set on element, so add class..
		if (currentClassName != "") {
			myElement.className += " " + myClass;
		} else {
			myElement.className = myClass;
		}
	}
}

function removeClassName(myElement, myClass) {
	var currentClassName = trim(myElement.className);
	var myReg = new RegExp("(^" + myClass + "$)|( " + myClass + "$)|(^" + myClass + " )|( " + myClass + " )", "g");
	myElement.className = currentClassName.replace(myReg, "");
}

function switchClassName(myElement, removeClass, addClass) {
	removeClassName(myElement, removeClass);
	addClassName(myElement, addClass);
}

function hasClassName(myElement, myClass) {
	var currentClassName = trim(myElement.className);
	var myReg = new RegExp("(^" + myClass + "$)|( " + myClass + "$)|(^" + myClass + " )|( " + myClass + " )", "g");
	if (myReg.test(currentClassName)) {
		// has class name set..
		return true;
	} else {
		return false;
	}
}

function setDefaultTxt(myInput, myTxt) {
	switch (myInput.type) {
		case 'text':
		default:
			if (myInput.value == myTxt) {
				myInput.value = "";
				removeClassName(myInput, "fontLighter");
			} else {
				if (myInput.value == "") {
					myInput.value = myTxt;
					addClassName(myInput, "fontLighter");
				}
			}
	}
}

function wn_formValidator(myFormId) {
	this.myForm = document.getElementById(myFormId);
	this.listen = function(evnt, elem, func) {
		if (elem.addEventListener) // W3C DOM
			elem.addEventListener(evnt,func,false);
		else if (elem.attachEvent) { // IE DOM
			var r = elem.attachEvent("on"+evnt, func);
			return r;
		}
	}
	// first setup onsubmit event on form..
//	this.listen("submit",this.myForm,document.getElementById(myFormId).checkForm());

	this.checkEmail = function(myEmail) {
		var myReg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
		if (myReg.test(myEmail)) {
			return true;
		} else {
			return false;
		}
	}
	this.showError = function(myErrorObj, myMessage) {
		try {
			myErrorObj.style.display = "block";
			myErrorObj.innerHTML += myMessage + " ";
		} catch (Exception) {}
	}
	this.clearErrors = function() {
		try {
			myErrorObj = document.getElementById(this.myForm.id + "_error");
			myErrorObj.innerHTML = "";
			myErrorObj.style.display = "none";
		} catch (Exception) {}
	}
	this.checkForm = function() {
		var errorFound = false;
		var showGenericError = true;
		var isMandatory = false;
		this.clearErrors();
		for (var i=0; i < this.myForm.elements.length; i++) {
			try {

				// clear existing errors..
				if(this.myForm.elements[i].type == "radio") {
					myErrorElement = document.getElementById(this.myForm.elements[i].name + "_error");
				} else {
					myErrorElement = document.getElementById(this.myForm.elements[i].id + "_error");
				}
				if (myErrorElement != null && typeof(myErrorElement) != "undefined") {
					myErrorElement.innerHTML = "";
				}

				// mandatory check..
				if (hasClassName(this.myForm.elements[i], "mandatory")) {
					isMandatory = true;
					switch (this.myForm.elements[i].type) {
						case "text":
							if (this.myForm.elements[i].value == "") {
								this.showError(myErrorElement, "Required.");
								errorFound = true;
							}
							break;
						case "select":
						case "select-one":
							if (this.myForm.elements[i].options.selectedIndex == 0) {
								this.showError(myErrorElement, "Required.");
								errorFound = true;
							}
							break;
						case 'radio':
							var radioSelected = false;
							if (!this.myForm.elements[i].checked) {
								var radioElement = this.myForm.elements[i].name;
								for (k=0; k < this.myForm.elements.length; k++) {
									if (radioElement == this.myForm.elements[k].name && i != k) {
										if (this.myForm.elements[k].checked) {
											radioSelected = true;
										}
									}
								}
								if (radioSelected == false) {
									// showError(myErrorElement, "You are required to make a selection.");
									// showGenericError = false;
									if(myErrorElement) this.showError(myErrorElement, "You are required to make a selection.");
									errorFound = true;
								}
							}
							break;
						default:
					}
				} else {
					isMandatory = false;
				}

				// integer check..
				if (hasClassName(this.myForm.elements[i], "integer")) {
					var integerRegExp = /^[\d]+$/;
					if (!(!isMandatory && this.myForm.elements[i].value == "")) {
						// do not check the field if it doesn't have a value and is not mandatory..
						if (!this.myForm.elements[i].value.match(integerRegExp)) {
							try {
								this.showError(myErrorElement, "Must be a valid number. ");
							} catch (Exception) {}
							errorFound = true;
						}
					}
				}

				// email check..
				if (hasClassName(this.myForm.elements[i], "email")) {
					var emailRegExp = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
					if (!(!isMandatory && this.myForm.elements[i].value == "")) {
						// do not check the field if it doesn't have a value and is not mandatory..
						var myTempEmail = this.myForm.elements[i].value;
						if (!emailRegExp.test(myTempEmail)) {
							this.showError(myErrorElement, "Please supply a valid email address.");
							errorFound = true;
						}
					}
				}



				// custom check..
				if (hasClassName(this.myForm.elements[i], "custom")) {
					var customRegExp = this.myForm.elements[i].rel;
					if (!(!isMandatory && this.myForm.elements[i].value == "")) {
						// do not check the field if it doesn't have a value and is not mandatory..
						var myTempValue = this.myForm.elements[i].value;
						if (!customRegExp.test(myTempValue)) {
							this.showError(myErrorElement, "Custom error");
							errorFound = true;
						}
					}
				}

			} catch (Exception) {
				// prob error div not existing - do nothing..
			}
		}
		if (errorFound) {
			var errorObj = document.getElementById(this.myForm.id + "_error");
			if(showGenericError && errorObj) this.showError(errorObj, "Please fill out all fields as marked below.");
			return false;
		}
		return true;

	}

}

function clearValue(myObjId, clear) {
	if (clear) {
		myObj = document.getElementById(myObjId);
		switch(myObj.type) {
			case "select":
			case "select-one":
				myObj.selectedIndex = -1;
				break;
			case "text":
			default:
				myObj.value = "";

		}
	}
}

// nb. if you want to close other group items when a member item is clicked, then make sure keepOpen is assigned "false"..
function toggleExtra(myClickedItem, keepOpen) {
	var myObj = document.getElementById(myClickedItem.id + "_extra");
	if (myObj != null && typeof(myObj) != "undefined") {
		// firstly, close other extras if required..
		if (keepOpen == null) {
			keepOpen = true;
		} else {
			// if keepOpen is false then close all other extras belonging to the group of items..
			if (!keepOpen) {
				if (myClickedItem.id.indexOf("_") > 0) {
					var groupId = myClickedItem.id.substr(0, myClickedItem.id.indexOf("_"));
					var groupIdLength = groupId.length;
					var myElements = document.getElementsByTagName(myObj.nodeName);
					for (i = 0; i < myElements.length; i++) {
						if (myElements[i].id != null) {
							if (myElements[i] != myObj && myElements[i].id.substr(0, groupIdLength) == groupId) {
								if (myElements[i].id.substr(myElements[i].id.length - 6) == "_extra") {
									switchClassName(myElements[i], "show", "hide");
								}
							}
						}
					}
				}
			}
		}
		// toggle the view of the extra relating to the clicked item..
		if (myClickedItem.checked == null) {
			// if myClickedItem is not a checkbox or radiobtn..
			if (hasClassName(myObj, "hide")) {
				switchClassName(myObj, "hide", "show");
			} else {
				switchClassName(myObj, "show", "hide");
			}
		} else {
			// if myClickedItem is a checkbox or radiobtn..
			if (myClickedItem.checked == true) {
				switchClassName(myObj, "hide", "show");
			} else {
				switchClassName(myObj, "show", "hide");
			}
		}
	}
}

// nb. if you want to close other group items when a member item is clicked, then make sure keepOpen is assigned "false"..
function toggleExtra_withEffects(myClickedItem, keepOpen) {
	var myObj = document.getElementById(myClickedItem.id + "_extra");
	if (myObj != null && typeof(myObj) != "undefined") {
		// firstly, close other extras if required..
		if (keepOpen == null) {
			keepOpen = true;
		} else {
			// if keepOpen is false then close all other extras belonging to the group of items..
			if (!keepOpen) {
				if (myClickedItem.id.indexOf("_") > 0) {
					var groupId = myClickedItem.id.substr(0, myClickedItem.id.indexOf("_"));
					var groupIdLength = groupId.length;
					var myElements = document.getElementsByTagName(myObj.nodeName);
					for (i = 0; i < myElements.length; i++) {
						if (myElements[i].id != null) {
							if (myElements[i] != myObj && myElements[i].id.substr(0, groupIdLength) == groupId) {
								if (myElements[i].id.substr(myElements[i].id.length - 6) == "_extra") {
									switchClassName(myElements[i], "jshow", "jhide");
									new Effect.BlindUp(myElements[i].id, {duration: 0.25});
								}
							}
						}
					}
				}
			}
		}
		// toggle the view of the extra relating to the clicked item..
		if (myClickedItem.checked == null) {
			// if myClickedItem is not a checkbox or radiobtn..
			if (hasClassName(myObj, "jhide")) {
				switchClassName(myObj, "jhide", "jshow");
				new Effect.BlindDown(myObj.id, {duration: 0.25});
				new Effect.Appear(myObj.id, {duration: 0.25});
			} else {
				switchClassName(myObj, "jshow", "jhide");
				//new Effect.Fade(myObj.id);
				new Effect.BlindUp(myElements[i].id, {duration: 0.25});
			}
		} else {
			// if myClickedItem is a checkbox or radiobtn..
			if (myClickedItem.checked == true) {
				switchClassName(myObj, "jhide", "jshow");
				new Effect.BlindDown(myObj.id, {duration: 0.25});
				new Effect.Appear(myObj.id, {duration: 0.25});
			} else {
				switchClassName(myObj, "jshow", "jhide");
				//new Effect.Fade(myObj.id);
				new Effect.BlindUp(myElements[i].id, {duration: 0.25});
			}
		}
	}
}

function openTab(myClickedItem) {
	var myObj = document.getElementById(myClickedItem.id + "_tabContent");
	if (myObj != null && typeof(myObj) != "undefined") {
		// hide all other tabs first..
		indexOfUnderscore = myClickedItem.id.indexOf("_");
		myPrefix = myClickedItem.id.substr(0, indexOfUnderscore);
		i = 0;
		while (myOtherObj = document.getElementById(myPrefix + "_" + i + "_tabContent")) {
			switchClassName(myOtherObj, "show", "hide");
			i++;
		}
		// then show the correct tab..
		switchClassName(myObj, "hide", "show");
		// then remove the selectded state from all the old tab items..
		i = 0;
		while (myOtherObj = document.getElementById(myPrefix + "_" + i)) {
			removeClassName(myOtherObj.parentNode, "selected");
			i++;
		}
		// then finally set the current tab to be selected..
		addClassName(myClickedItem.parentNode, "selected");
	}

}

function highLightRow(highlight, myRow) {
	if (highlight) {
		addClassName(myRow, "highlight");
	} else {
		removeClassName(myRow, "highlight");
	}
}

var myPageLinks = new Array();
var submittingForm = false;
function disableLinks() {
	for (var i=0; i < document.links.length; i++) {
		myPageLinks[i] = document.links[i].href;
		document.links[i].href = "javascript: void(0);";
	}
}
function enableLinks() {
	if (myPageLinks.length > 0) {

		for (var i=0; i < document.links.length; i++) {
			document.links[i].href = myPageLinks[0];
			myPageLinks.shift();
		}
	}
}
function disablePageOnSubmit() {
	if (submittingForm) {
		return false;
	} else {
		submittingForm = true;
		disableLinks();
	}
}

function showGrid() {
	myGrid = document.getElementById("grid");
	if (myGrid == null || typeof("myGrid") == "undefined") {
		myDiv = document.createElement("DIV");
		myDiv.setAttribute("id", "grid");
		myDiv.style.display = "block";
		myParent = document.getElementById("globalWrap");
		myParent.appendChild(myDiv);
	} else {
		myGrid.style.display = "block";
	}
}

function hideGrid() {
	myGrid = document.getElementById("grid");
	if (myGrid != null && typeof("myGrid") != "undefined") {
		myGrid.style.display = "none";
	}
}

function selectFootprintsProject(projectId, originalwithsign, originallesssign, totalwithsign, totallesssign, dollarimagesrc) {
    $$(".proj-" + projectId)[0].hide();
    var s = $$(".proj-" + projectId)[0].siblings();
    for(i=0; i<s.length; i++){
        s[i].show();
    }    
	var myLabel = document.getElementById("footprints_donate_label");
	myLabel.innerHTML = "Give $2 to "
		+ footprintsProjects[projectId]['name']
		+ "<br /><span>" + footprintsProjects[projectId]['country'] + "&nbsp;|&nbsp;" + footprintsProjects[projectId]['partner'] + "</span>"
		+ "<br /><a href=\"" + footprintsProjects[projectId]['link'] + "\" target=\"footprints_win\"><span>View details</span></a>";

	var projectsList = document.getElementById("footprints_donate_extra");
	projectsList.style.display = "none";
	var callToAction = document.getElementById("fpw_callToAction");
	var myChkbox = document.getElementById("footprints_donate");
	if (!myChkbox.checked) {
		myChkbox.checked = true;
		chooseFootprintsProject(originalwithsign, originallesssign, totalwithsign, totallesssign, dollarimagesrc);
	}
	document.getElementById("footprints_donationamount").value = "2";
	document.getElementById("footprints_charityprojectid").value = projectId;
	document.getElementById("footprints_charityproject").value = footprintsProjects[projectId]['name'];
	document.getElementById("footprints_charitypartner").value = footprintsProjects[projectId]['partner'];
	document.getElementById("footprints_charitycountry").value = footprintsProjects[projectId]['country'];
}

function showFootprintsProjects() {
	var myCheckbox = document.getElementById("footprints_donate_extra");
	switchClassName(myCheckbox, "jhide", "jshow");
	new Effect.BlindDown(myCheckbox.id, {duration: 0.5});
	new Effect.Appear(myCheckbox.id, {duration: 0.7});
}

function chooseFootprintsProject(originalwithsign, originallesssign, totalwithsign, totallesssign, dollarimagesrc) {
	var myCheckbox = document.getElementById("footprints_donate");
	var actualTotal = document.getElementById("actual_total");
	var myQuoteTotal = document.getElementById("quote_total");
	var myQuoteTotalBottom = document.getElementById("quote_total_bottom");
	var callToAction = document.getElementById("fpw_callToAction");
	var footprintsList = document.getElementById("footprints_donate_extra");
	var myLabel = document.getElementById("footprints_donate_label");
	var imageurl = '<img src="' + dollarimagesrc + '" alt="" title="" />';

	if (!myCheckbox.checked) {
		totalwithsign = originalwithsign;
		totallesssign = originallesssign;

		if (footprintsList != null && typeof(footprintsList) != "undefined") {
			footprintsList.style.display = "none";
		}
	}

	// this is so the confirm box can access the actual value
	if (actualTotal != null && typeof(actualTotal) != "undefined") {
		actualTotal.value = totalwithsign;
	}
	if (myQuoteTotal != null && typeof(myQuoteTotal) != "undefined") {
		myQuoteTotal.innerHTML = imageurl + totallesssign;
	}
	if (myQuoteTotalBottom != null && typeof(myQuoteTotalBottom) != "undefined") {
		myQuoteTotalBottom.innerHTML = imageurl + totallesssign;
	}
}

// for restricting forms from submitting before page fully loads..
var pageLoaded = false; // initialise the global var whether page onload event has run or not.
function notifyMessage(myMsg) {
	var myObj = document.getElementById("error");
	if (myObj != null && typeof(myObj) != "undefined") {
		myObj.innerHTML = "<p>" + myMsg + "</p>";
		switchClassName(myObj, "hide", "show");
	}
}
function warnNoSubmit(waitMessage, continueMessage) {
	notifyMessage(waitMessage);
	// notify when page is loaded fully..
	if (continueMessage != null) {
		if (ie) {
			window.attachEvent("onload", function(){ notifyMessage(waitmessage + " " + continueMessage); });
		} else {
			window.addEventListener('load', function(e){ notifyMessage(waitmessage + " " + continueMessage); }, true);
		}
	}
}
function restrictFormUntilLoaded(myFormId, waitMessage, continueMessage) {
	var myForm = document.getElementById(myFormId);
	if (ie) {
		myForm.attachEvent('onsubmit', function(e){
			if (!pageLoaded) {
				warnNoSubmit(waitMessage, continueMessage);
				return false;
			}
		});
	} else {
		myForm.addEventListener('submit', function(e){
			if (!pageLoaded) {
				e.stopPropagation();
				e.preventDefault();
				warnNoSubmit(waitMessage, continueMessage);
			}
		}, true);
	}
}
function setPageLoaded() {
	pageLoaded = true;
}
if (ie) {
	window.attachEvent("onload", function(){ setPageLoaded(); });
} else {
	window.addEventListener('load', function(e){ setPageLoaded(); }, true);
}
// end restricted forms.

function submitForm(myFormId) {
	myObj = document.getElementById(myFormId);
	if (myObj != null && typeof(myObj) != "undefined") {
		myObj.submit(true);
	}
}
