/*    File: WM+A Javascript
    Author: Hybrid Visions - Copyright 2008	*/


	function empty( mixed_var ) {
		// http://kevin.vanzonneveld.net
		// +   original by: Philippe Baumann
		// *     example 1: empty(null);
		// *     returns 1: true
		return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false  ||  ( is_array(mixed_var) && mixed_var.length === 0 ) );
	}

	function showFAQ(selfObj, faqFocus) {
		faqViewport = document.getElementById("FAQs");
		faqViewport.className = ((faqFocus)?faqFocus:"direct");
		faqViewportIndicator = document.getElementById("currentView");
		faqViewportIndicator.innerHTML = ((faqFocus)?( faqFocus.substring(0,1).toUpperCase() + faqFocus.substring(1,faqFocus.length) ):"&nbsp;");
		return false;
	}

	function showHide(selfObj) {
		targetObj = $(selfObj.id + "List");
		if (targetObj.className.test("hideMe")) {
			targetObj.removeClass("hideMe");
		   } else {
			targetObj.addClass("hideMe");
		}
		return false;
	}

	function toggleFAQ(selfObj) {
		if (selfObj.parentNode.className == "question") {
			selfObj.parentNode.className = "answer";
		   } else {
			selfObj.parentNode.className = "question";
		}
		return false;
	}


	function toggleCareer(selfObj) {
		if (selfObj.parentNode.parentNode.className == "job") {
			selfObj.parentNode.parentNode.className = "show job";
		   } else {
			selfObj.parentNode.parentNode.className = "job";
		}
		return false;
	}

//<![CDATA[
	var map;
	var geocoder;
	var address = "";
	var locationsOfInterest = new Array();
	    locationsOfInterest[0] = ({ name: 'Head Office', url: "", address: "Suite 303, 703 Evans Ave", logo: "themes/default/images/logos/wma.png", city: "Toronto, Ontario", sponsor: '', point: "", marker: "" , markerUp: "" });
	var locationIndex = 0;
	var stuffOfThings= new Array();
	var stanleyHomeObj;
	var lockeShoppes;
	
	function createMarker(point, content) {     // Creates a marker at the given point with the given number label
	  var marker = new GMarker(point);
	  GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml(content.toString());
	  });
	  return marker;
	}
	
	function createMarkerContent (activeIndex) {
	    //alert("Attempting to create a marker for activeIndex" + activeIndex);
	    return ('<img src="' + baseURL + locationsOfInterest[activeIndex].logo + '" alt="wm+a" class="logo" /><div class="details"><b>' + locationsOfInterest[activeIndex].name + '</b><br />Suite 303,<br />703 Evans Ave<br />' + locationsOfInterest[activeIndex].city + "<br />M9C 5E9</div>");
	}
	
	function addToMap(response) {
	  //alert ("response.Placemark.length = " + response.Placemark.length);
	  if (response.Placemark.length > 0) {
//	  	prompt("google points value = ", (response.Placemark[0].Point.coordinates[1] + ", " + response.Placemark[0].Point.coordinates[0]) );
	          locationsOfInterest[0].point = new GLatLng(43.607719, -79.557399);// response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);                              // Retrieve the latitude and longitude
	          locationsOfInterest[0].markerUp = createMarkerContent(0);
	          stanleyHome = new GMarker(locationsOfInterest[0].point);
	          map.addOverlay( stanleyHome );
	          stanleyHomeObj = stanleyHome;
	          GEvent.addListener(stanleyHome, "click", function() { stanleyHome.openInfoWindow(locationsOfInterest[0].markerUp); });
	          stanleyHome.openInfoWindow( locationsOfInterest[0].markerUp.toString() ); 
	  	  //locationIndex++;
	  }
	}
	
	function loadGoogleMap() {
	  if (GBrowserIsCompatible()) {
	    map = new GMap2(document.getElementById('map'));                                // Load DOM object into variable
	    geocoder = new GClientGeocoder();                                               // Create new geocoding object
	    if (locationsOfInterest.length > 0) {
	        locationArray = new Array();
	        for (x = 0; x < locationsOfInterest.length; x++) {
	            geocoder.getLocations( (locationsOfInterest[x].address + ", " + locationsOfInterest[x].city), addToMap);               // Retrieve location information, pass it to addToMap()
	        }
	        map.setCenter(new GLatLng(43.607719, -79.557399), 17);
	    }
	    map.setZoom(17);
	    map.addControl(new GLargeMapControl());
	    map.setMapType(G_HYBRID_MAP);
	  }
	}
	
	function resetMap() {           // special case: remove all markers (removeOverlays will remove paths as well)
	    var marker = map.getFirstMarker();
	    while (marker != null) {
	        marker.remove();    
	        marker = map.getFirstMarker();
	    }
	    if (locationsOfInterest.length > 0) {               // If there is a list of locations, always include the default(initial one)
	        geocoder.getLocations(locationsOfInterest[0].address, addToMap);
	    }
	}
	
	function ie6Hover() {
		menuArray = new Array("textAboutUs", "textCareers", "textFAQs");
		for (x=0; x < menuArray.length; x++) {
			document.getElementById(menuArray[x]).onmouseover = function() { this.className = "hover"; }
			document.getElementById(menuArray[x]).onmouseout = function() { this.className = ""; }
		}
	}
//]]>


	function createMenuAccordion() {
		var menuItems = $$("#associateType .menuSection");
		var menuNavObj = document.getElementById("associateType");
		var menuWidth = menuNavObj.offsetWidth;
		var menuItemCount = menuItems.length;
		//var menuItemCollection = menuNavObj.getElementsByClassName("menuItem");
		var SoW = "";
		var szSmall = 20;
		var sunkSpace = 10;
		for (x = 0; x < menuItems.length; x++) {
			//SoW += "\n" + x + " - " + menuItems[x].id + "'s text is " + menuItems[x].offsetWidth + " wide.";
			if (menuItems[x].offsetWidth > szSmall) {
				szSmall = menuItems[x].offsetWidth;
			}
			sunkSpace += menuItems[x].offsetWidth;
		}
/*		szSmall = szSmall - 75;*/
		sunkSpace = sunkSpace - szSmall;		//(szSmall * 0.9);
		var szNormal = (menuWidth/menuItemCount) - 2;
		var szFull = menuWidth - (szSmall * 2) - 20;		//menuWidth - sunkSpace - 50;
		//SoW += "\n\n[Summary]\n\t menuItemCount = " + menuItems.length + "\n\t menuNav.width = " + menuNavObj.offsetWidth + "\n\t szNormal = " + szNormal + "\n\t szSmall = " + szSmall + "\n\t szFull = " + szFull + "\n\t sunkSpace = " + sunkSpace;
		//alert(SoW);
		var associateType = $$("#associateType .menuItem");
		var fx = new Fx.Elements(associateType, {wait:  false, duration:  300, transition:  Fx.Transitions.Back.easeOut});
		associateType.each(function(menuItem, i) {
			menuItem.addEvent("mouseenter", function(event) {
				var o = {};
				o[i] = {width:  [menuItem.getStyle("width").toInt(), szFull]}
				associateType.each(function(other, j) {
					if(i != j) {
						other.removeClass('showSubMenu');
						var w = other.getStyle("width").toInt();
						if(w != szSmall) o[j] = {width:  [w, szSmall]};
					}
				});
				fx.start(o);
				menuItem.addClass('showSubMenu');
			});
		});
		$("associateType").addEvent("mouseleave", function(event) {
			var o = {};
			associateType.each(function(menuItem, i) {
				menuItem.removeClass('showSubMenu');
				o[i] = {width:  [menuItem.getStyle("width").toInt(), szNormal]}
			});
			fx.start(o);
		});
	}
	
	validationArray = new Array();
		validationArray["EmailAddress"] = new RegExp("^(\\w+)@(\\w+)(\\.)(\\w+)$"); 
		validationArray["Graduation"] = validationArray["CPIExpiration"] = validationArray["UMABExpiration"] = validationArray["OESCExpiration"] = validationArray["FirstAidExpiration"] = validationArray["PTIBIExpiration"] = new RegExp(/^(0[1-9]|1[012])\/(19|20)\d\d+$/);
		validationArray["ContactNumber"] = validationArray["FaxNumber"] = new RegExp(/^[0-9\s().-]+$/);
		validationArray["PostalCode"] = new RegExp(/^[A-Za-z]\d[A-Za-z](\s)*\d[A-Za-z]\d$/);


	function validateForm() {
		formCheck = false;
		formCheck = $$("#tabContainer .tabSection");
		formObj = ( (formCheck.length > 0)?(formCheck):($$("form")) );
		//alert("Validating " + formObj.length + " items in " + formObj.id);
		validForm = true;	// Assume form is valid until proven otherwise
		formObj.each (
			function(section) {
				//alert("Validating " + formObj.length + " items in " + formObj.id);
				validSection = true;
				$ES('.required', section).each (
					function(element) {
						validElement = false;
						switch ( element.tagName.toLowerCase() ) {
							case "input":
								switch ( element.type.toLowerCase() ) {
									case "checkbox":
									case "radio":
										validElement = element.checked;
										break;
									case "text":
									default:
										if (element.value != "") {
											if ( validationArray[element.name] ) {	// if a validation rule exists, and the element isn't empty
												validElement = ( (validationArray[element.name].exec(element.value))?true:false );
											   } else {				// otherwise assume it's valid
												validElement = true;
											}
										}
								}
								break;
							case "select":
							case "select-one":
							case "select-multiple":
								validElement = (element.options[element.selectedIndex].value != "");
								break;
							case "textarea":
								validElement = (element.value != "");
								break;
						}
						if (!validElement) {
							element.addClass("error");
						   } else {
							element.removeClass("error");
						}
						if (validSection) {
							validSection = validElement;
						}
					} // section.each()
				);
				sectionObj = $( section.className.replace(' tabSection','') );
				if (sectionObj) {
					if (validSection) {
						sectionObj.removeClass("invalid");
					   } else {
						sectionObj.addClass("invalid");
					}
				}

				if (validForm) {
					validForm = validSection;
				}
			}
		);
		if (!validForm) {
			alert("Sorry but this form contains missing or erroneous fields, which are highlighted with a yellow background.");
		}
		return validForm;
	}

	function submitForm(selfObj) {
		showButtons(false);
		if ( validateForm() ) {
			var actionIndicatorObj = $('SummaryPane');
			var summaryPaneObj = $('pageForm');
			summaryPaneObj.addClass('working');
			summaryPaneObj.send({   update: actionIndicatorObj,
			                        onComplete: function() {
			                            summaryPaneObj.removeClass('working');
			                            $("tabContainer").className = "thankYou";
			                        }
			                   });
		   } else {
			showButtons(true);
		}
		return false;
	}	
	
	function showButtons(showThem) {
		buttonArray = new Array("reset", "back", "next", "submit");
		buttonArray.each (
			function(button) {
				if (showThem) {
					$( (button + "Button") ).removeClass("hideMe");
				   } else {
					$( (button + "Button") ).addClass("hideMe");
				}
			}
		);
		showingButtons = showThem;
	}


	function toggleTab(selfObj) {
		newTab = "";
		if (!showingButtons) {
			showButtons(true);
		}
		if (selfObj) {
			switch ( typeof(selfObj) ) {
				case "object":
					if (selfObj.id != "") {
						newTab = selfObj.id;
					   } else {
						alert("something messed up because selfObj.id = " + selfObj.id);
					}
					break;
				case "string":
				case "number":
					arrayIndex = -1;
					if (activeTab != "") {
						for (x=0; x < tabArray.length; x++) {
							if ( activeTab == tabArray[x] ) {
								arrayIndex = x;
							}
						}
						if (selfObj == "next") {
							arrayIndex++;
							if (arrayIndex >= tabArray.length) {
								arrayIndex = (tabArray.length - 1);
							}
						   } else {
							arrayIndex--;
							if (arrayIndex <= 0) {
								arrayIndex = 0;
							}
						}
					   } else {
						arrayIndex = 0;
					}
					//alert("tabArray[" + arrayIndex + "] = " + tabArray[arrayIndex]);
					newTab = tabArray[arrayIndex];
					break;
			}
			if (activeTab != "") {
				$(activeTab).removeClass("active");
				$("tabContainer").removeClass(activeTab);
			}
			$(newTab).addClass("active");
			$("tabContainer").addClass(newTab);

			activeTab = newTab;
		}
		return false;
	} 
	
	
	var activeTab = "";


	function toggleRequest(selfObj, toggleElementSomething) {
		if (toggleElementSomething) {
			toggleObj = $(selfObj.id + toggleElementSomething);
		   } else {
			toggleObj = $(selfObj.id + "Copy");
		}
		//alert("toggleObj.id = " + toggleObj.id + ", activeRequest = " + activeRequest );
		if (activeRequest != toggleObj.id) {
			if ( toggleObj.className != "" ) {
				toggleObj.removeClass("hideMe");
				if ( activeRequest ) {
					$(activeRequest).addClass("hideMe");
				}
			   } else {
				toggleObj.addClass("hideMe");
			}
		}
		//$("listContentTitle").innerHTML = selfObj.innerHTML;
		activeRequest = toggleObj.id;
		return false;
	}

	var activeRequest = "introCopy";

	/**************************************
	* diff Function v1.0                 *
	* Autor: Carlos R. L. Rodrigues      *
	**************************************/
	diff = function(v, c, m){
		var d = [], e = -1, h, i, j, k;
		for (i = c.length, k = v.length; i--;) {
			for(j = k; j && (h = c[i] !== v[--j]););
			h && (d[++e] = m ? i : c[i]);
		}
		return d;
	};

	function declareIntention() {
		signupListObj = $("signupList");
		inputCollection = $$("#requests input");
		signupListArray = new Array();

		//requestedObj = $("requested");
		//requestedObj.innerHTML = "&nbsp;";
		//alert("inputCollection.length = " + inputCollection.length);

		listOfRequests.each(
			function (requestDObj) {
				if (typeof(requestDObj) != "undefined") {
					requestDObj.intention = "";
				}
			}
		)
		inputCollection.each(	
					function(element) {
						switch ( element.tagName.toLowerCase() ) {
							case "input":
								switch ( element.type.toLowerCase() ) {
									case "checkbox":
									case "radio":
										if (element.checked) {
											//alert ("element.alt = " + element.alt);
											//if ( (element.value != "")&&(element.defaultChecked != element.checked)&&(element.defaultValue != element.value) ) {
											if (element.value != "") {
												if (element.alt != "") {
													tempObject = eval(element.alt);
													//alert("listOfRequests[" + tempObject.workshopID + "].title = " + listOfRequests[tempObject.workshopID].title + ", tempObject.workshopID = " + tempObject.workshopID + ", tempObject.message = " + tempObject.message);
													if (listOfRequests.length > 0) {
														//alert("listOfRequests[" + tempObject.workshopID + "].title = " + listOfRequests[tempObject.id].title + ", tempObject.id = " + tempObject.id + ", tempObject.message = " + tempObject.message);
														if (listOfRequests[tempObject.id]) {
															listOfRequests[tempObject.id].intention += "<li>" + tempObject.message + "</li>";
															listOfRequests[tempObject.id].message = tempObject.message;
														   } else {
															alert("Somehow you managed to create a .id (" + tempObject.id + ") that isn't synched with listOfRequests(count = " + listOfRequests.length + "). Please fix this issue.");
														}
													}
												   } else {
													//alert("tempObject.workshopID = " + tempObject.workshopID + ", tempObject.message = " + tempObject.message);
													//signupListArray[tempObject.id] = ({id: tempObject.id, intention: false});
													//signupListMarkup += "<li>" + tempObject.message + "</li>";
													signupListArray.push(element.value);
												}
											}
											//signupListMarkup = true;
										//} else {
										//	alert("element.value is blank");
										}
										break;
									case "text":
									default:
										if (element.value != "") {
											if ( validationArray[element.name] ) {	// if a validation rule exists, and the element isn't empty
												validElement = ( (validationArray[element.name].exec(element.value))?true:false );
											   } else {				// otherwise assume it's valid
												validElement = true;
											}
										}
								}
								break;
						}
					}
		)
		showSignUp = false;
		if ( (signupListArray.length > 0)&&(oldIntentionList.length > 0) ) {
			// find the shared id's between the two arrays, and assume they need to remain on
			// where the left over IDs in oldIntentionList need to be "turned off"
			// alert ("diff(signupListArray, oldIntentionList) = " + diff(signupListArray, oldIntentionList));
			oldIntentionList.each(
				function(removeElementID) {
					if (removeElementID != "on") {
						//alert("removeElementID = " + removeElementID + ", and as a result will search for optionItem" + removeElementID); 
						$("optionItem" + removeElementID).removeClass("boldMe pinkText");
					}
				}
			)
		}
		//alert("oldIntentionList = " + oldIntentionList + ", oldIntentionList.length = " + oldIntentionList.length);
		processArray = ( (listOfRequests.length > 0)?listOfRequests:((signupListArray.length > 0)?signupListArray:0));//(oldIntentionList.length > 0)?oldIntentionList:"")
		//$("dumpVar").innerHTML = dump(processArray);
		if ( processArray.length > 0) {
			processArray.each(
				function (requestDObj) {
					//alert("requestDObj = " + requestDObj + ", requestDObj.id = " + requestDObj.id + ", requestDObj.intention = " + requestDObj.intention);
					//alert("requestDObj = " + requestDObj + ", typeof(requestDObj) == " + typeof(requestDObj));
					if (typeof(requestDObj) != "undefined") {
						//alert("typeof(requestDObj) == " + typeof(requestDObj) + "/" + requestDObj);
						entityElementID = ( (typeof(requestDObj) == "object")?requestDObj.id:requestDObj );
						updateEntityElementIDSummary = ( (typeof(requestDObj) == "object")?true:false );
						optionItemMenuEl = $("optionItem" + entityElementID);
						optionItemSummaryEl = $("optionItem" + entityElementID + "Summary");
						//alert("requestDObj = " + requestDObj + ", typeof(requestDObj) == " + typeof(requestDObj) + "/" + "\n optionItemMenuEl = " + optionItemMenuEl + ", typeof(optionItemMenuEl) == " + typeof(optionItemMenuEl));
						if ( requestDObj.intention != "" ) {
							/*if ( (oldIntentionList.length > 0) && (signupListArray.length == 0) ) {
								if (oldIntentionList[entityElementID]) {
									unset oldIntentionList[entityElementID];
								}
								optionItemMenuEl.removeClass("boldMe pinkText");
							   } else {*/
								optionItemMenuEl.addClass("boldMe pinkText");
								//alert("if { updateEntityElementIDSummary = " + updateEntityElementIDSummary);
								if (updateEntityElementIDSummary) {
									optionItemSummaryEl.innerHTML = requestDObj.intention;
									optionItemSummaryEl.removeClass("hideMe");
								}
								showSignUp = true;
							//}
						   } else {
							optionItemMenuEl.removeClass("boldMe pinkText");
							//alert("} else { updateEntityElementIDSummary = " + updateEntityElementIDSummary);
							try {
								if (updateEntityElementIDSummary) {
									//alert("optionItemSummaryEl = " + optionItemSummaryEl + ", optionItemSummaryEl.id = " + optionItemSummaryEl.id);
									optionItemSummaryEl.addClass("hideMe");
									optionItemSummaryEl.innerHTML = "";
								} else {						
									alert("line 486 - updateEntityElementIDSummary = " + updateEntityElementIDSummary);
								}
							}catch(e) {
								alert("Fucking IE failed because " + e);
							}
						}
					}
				}
			)
		}
		if (showSignUp) {
			signupListObj.removeClass("hideMe");
		   } else {
			signupListObj.addClass("hideMe");
		}
		oldIntentionList = signupListArray;
	}
	var oldIntentionList = new Array();
	
	function confirmPolicy(selfObj) {
		//alert("selfObj.checked = " + ((selfObj.checked)?"true":"false"));
		conditionalElements = new Array("authenticateRequest", "submitButton");
		conditionalElements.each (
			function(conditionalElement) {
				elementObj = $(conditionalElement);
				if ( elementObj ) {
					if (selfObj.checked) {
						elementObj.removeClass("hideMe");
					   } else {
						elementObj.addClass("hideMe");
					}
				}
			}
		)
		return false;


		workshopObj = $("workshops");
		labelCollection = workshopObj.getElementsByTagName("label"); /*.each (
					function(element) {
						alert("element.for = " + element.for);
					}
		)*/
		alert("labelCollection[0] = " + labelCollection[0].htmlFor);
		return false;
		workshopObj.getElementByTagName("input").each (
					function(element) {
						validElement = false;
						switch ( element.tagName.toLowerCase() ) {
							case "input":
								switch ( element.type.toLowerCase() ) {
									case "checkbox":
									case "radio":
										validElement = element.checked;
										break;
									case "text":
									default:
										if (element.value != "") {
											if ( validationArray[element.name] ) {	// if a validation rule exists, and the element isn't empty
												validElement = ( (validationArray[element.name].exec(element.value))?true:false );
											   } else {				// otherwise assume it's valid
												validElement = true;
											}
										}
								}
								break;
							case "select":
							case "select-one":
							case "select-multiple":
								validElement = (element.options[element.selectedIndex].value != "");
								break;
							case "textarea":
								validElement = (element.value != "");
								break;
						}
					}
		)
	}
	function showSection(elementID, displaySection) {
		toggleRequest( ({ id: elementID }) );

		$(elementID + 'Applicants').addClass("hideMe");
		$(elementID + 'Posting').addClass("hideMe");
		$(elementID + displaySection).removeClass("hideMe");
	}

	function submitRequestForm(selfObj) {
		//showButtons(false);
		//if ( validateForm() ) {
			var actionIndicatorObj = $('confirmationPrompt');
			actionIndicatorObj.addClass('working');
			//$("outcome").addClass('hideMe');
			$("outcome").removeClass('hideMe');
			$("confirmation").removeClass('hideMe');
			var summaryPaneObj = $('requests');
			//summaryPaneObj.addClass('working');
			summaryPaneObj.send({   update: actionIndicatorObj,
			                        onComplete: function() {
							actionIndicatorObj.removeClass('working');
							//summaryPaneObj.removeClass('hideMe');
							//$("tabContainer").className = "thankYou";
			                        }
			                    });
		/*   } else {
			showButtons(true);
		}*/
		return false;
	}


/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
	function dump(arr,level) {
		var dumped_text = "";
		if(!level) level = 0;
		
		//The padding given at the beginning of the line.
		var level_padding = "";
		for(var j=0;j<level+1;j++) level_padding += "    ";
		
		if(typeof(arr) == 'object') { //Array/Hashes/Objects 
			for(var item in arr) {
				var value = arr[item];
				
				if(typeof(value) == 'object') { //If it is an array,
					dumped_text += level_padding + "'" + item + "' ...\n";
					dumped_text += dump(value,level+1);
				} else {
					dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
				}
			}
		} else { //Stings/Chars/Numbers etc.
			dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
		}
		return dumped_text;
	}
