/*=== WESLEY MISSION COMMON SCRIPTS ===*/


//	define main WM object
var WM = function () {
	//	define common variables here

	return {
		//	define 2nd-level function objects
		main:  function () {},	//	common functions
		form:  function () {},	//	forms
		maps:  function () {},	//	maps
		nav:   function () {},	//	navigation
		share: function () {} 	//	sharing/social
	};

} ();


//=== MAIN ===

/* Add onload events */
// - thanks http://www.brothercake.com/site/resources/scripts/onload/
WM.main.addLoadListener = function (fn) {
  if (typeof window.addEventListener !== 'undefined')  {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener !== 'undefined')  {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent !== 'undefined')  {
    window.attachEvent('onload', fn);
  }
  else  {
    var oldfn = window.onload;
    if (typeof window.onload !== 'function') {
      window.onload = fn;
    }
    else {
      window.onload = function() {
        oldfn();
        fn();
      };
    }
  }
};

//	add unload listener to remove code that may be leaky
//	Note: using unload events prevents Firefox (and maybe others) from caching the page in the in-memory bfcache (ie. will be slightly slower using Back-Forward buttons)
WM.main.addUnloadListener = function (fn) {
  if (typeof window.addEventListener !== 'undefined')  {
    window.addEventListener('unload', fn, false);
  }
  else if (typeof document.addEventListener !== 'undefined')  {
    document.addEventListener('unload', fn, false);
  }
  else if (typeof window.attachEvent !== 'undefined')  {
    window.attachEvent('onunload', fn);
  }
  else  {
    var oldfn = window.onunload;
    if (typeof window.onunload !== 'function') {
      window.onunload = fn;
    }
    else {
      window.onunload = function() {
        oldfn();
        fn();
      };
    }
  }
};

/* break out of rogue frames */
WM.main.breakFrames = function () {
  if ( window.top != window && !top.frames.editor ) { window.top.location = window.location; }
};


//=== FORM ===

//	set the visibility, etc of companion "_Other" field
WM.form.toggleFieldOther = function (parm_elem) {

	var selected_other_id, selected_other, selected_option, selected_option_value;

  //	get companion "_Other" field and selected option
  selected_other_id = parm_elem.id + "_Other";
  selected_other = document.getElementById(selected_other_id);
  selected_option = parm_elem.options[parm_elem.selectedIndex];
	//	bail out if missing info
	if (!selected_other || !selected_option) { return false; }

  //	show field if "other" option selected
	selected_option_value = selected_option.value.length > 0 ? selected_option.value : selected_option.text;
  if (selected_option_value.substr(0,5).toLowerCase() === "other") {
  	selected_other.style.display = "inline";
		//	focus the "other" field if editing
		if (parm_elem.timing === "edit") {
			selected_other.focus();
		}
  } else {
  	selected_other.style.display = "none";
  	selected_other.value = "";
  }

};

//	set initial visibility of "_Other" fields and attach function to select
WM.form.setupFieldsOther = function () {

	var i, selects, selects_length;
	//	bail out if bad browser
	if (!document.getElementsByTagName || !document.getElementById) { return false; }

	//	get list of select elements
	selects = document.getElementsByTagName("SELECT");
	selects_length = selects.length;
	for (i = 0; i < selects_length; i++) {
		var selected, selected_other, selected_other_id;
  	selected = selects[i];
		// determine if there's a companion _Other field
		selected_other_id = selected.id + "_Other";
		selected_other = document.getElementById(selected_other_id);
		
		if (selected_other !== null) {
			//	set function on select
			selected.onchange = function () {
				this.timing = "edit";
				WM.form.toggleFieldOther(this);
			};
			WM.form.toggleFieldOther(selected);

		}
	}	//	end loop

};

/* test email address */
WM.form.emailIsValid = function(email) {
	return /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/.test(email);
}


//=== MAPS ===
WM.maps = function () {

	return {

    //	set map defaults
    default_zoom:	9,
    markers:			[],
  
    //	add the map
    //		usage: eg. http://www.wesleymission.org.au/Centres/lifeforce/Life_Networks/
    addMap:			function (options) {
    	//	create the map
    	WM.maps.map = new google.maps.Map(
    		document.getElementById(options.id),
    		{
    			zoom:				options.zoom ? options.zoom : this.default_zoom,
    			center:			WM.maps.getCentre(options),
    			mapTypeId: 	google.maps.MapTypeId.ROADMAP
    		}
    	);
    	WM.maps.addMarkers(options.markers);
    	WM.maps.infowindow = new google.maps.InfoWindow({content: ""});

    },
  
    //	set map centre
    getCentre:	function (o) {

    	var lat, lng, lats = [], lngs = [];
			//	check if centre has been specified
    	if (o.lat && o.lng) {	//	set specified centre
    		lat = o.lat;
    		lng = o.lng;
    	} else {	//	determine centre of given markers
    		//	make an array of latitudes and longitudes
    		for (var i=0, ii=o.markers.length; i<ii; i++) {
    			lats.push(o.markers[i].lat);
    			lngs.push(o.markers[i].lng);
    		}
    		//	sort arrays and calculate centre
    		lats.sort();
    		lngs.sort();
    		lat = (lats[0] + lats[lats.length-1]) / 2;
    		lng = (lngs[0] + lngs[lngs.length-1]) / 2;
    	}
    	return new google.maps.LatLng(lat, lng);

    },
  
    //	add markers to the map
  	addMarkers: function (mm) {
			//	cycle through markers
      for (var i=0, ii=mm.length; i<ii; i++) {
    		var m = mm[i];
				//	add the marker and save it in the object
        WM.maps.markers.push(new google.maps.Marker({
          position: new google.maps.LatLng(m.lat,m.lng),
          map:			WM.maps.map,
          title:		m.title,
  				content:	[	//	contents of the InfoWindow
    					"<div class='info'><div class='vcard'>",
    					"<h4 class='fn'>", m.title, "</h4>",
    					"<p class='adr'>",
    					m.address ? "<span class='street-address'>" + m.address.replace(/,/gi, "<br />") + "</span><br />" : "",
    					"<span class='locality'>", m.suburb , "</span>",
							(m.suburb) ? "," : "",
    					" <span class='region'>", (m.state ? m.state : "NSW") , "</span>",
    					" <span class='postal-code'>", m.postcode , "</span>",
    					"</p>",
    					m.phone ? "<p class='tel'>Ph: " + m.phone + "</p>" : "",
    					"</div>", m.content, "</div>"
  				].join("")
        }));
  			WM.maps.setInfoWindow(WM.maps.markers[i]);
    	}
    },

		//	set the InfoWindow for a marker
    setInfoWindow: function(mk) {
			//	the InfoWindow is connected to the marker when clicked
    	google.maps.event.addListener(mk, 'click', function(mk) {
    		WM.maps.infowindow.content = this.content;
    		WM.maps.infowindow.open(WM.maps.map, this);
    	});
    }

	};

}();


//=== NAV ===

/* Navigation functions (from nav.js) */
WM.nav.sfHover = function() {
	var sfNav = document.getElementById("mainnav");
	if (!sfNav) return false;	//	exit if not found
	var sfEls = sfNav.getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=(this.className.length>0? " ": "") + "sfhover";
		};
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
		};
	}
};

WM.nav.mcAccessible = function() {
	var mcNav = document.getElementById("mainnav");
	if (!mcNav) return false;	//	exit if not found
	var mcEls = mcNav.getElementsByTagName("A");
	for (var i=0; i<mcEls.length; i++) {
		mcEls[i].onfocus=function() {
			this.className+=(this.className.length>0? " ": "") + "sffocus"; //a:focus
			this.parentNode.className+=(this.parentNode.className.length>0? " ": "") + "sfhover"; //li < a:focus
			if(this.parentNode.parentNode.parentNode.nodeName == "LI") {
				this.parentNode.parentNode.parentNode.className+=(this.parentNode.parentNode.parentNode.className.length>0? " ": "") + "sfhover"; //li < ul < li < a:focus
				if(this.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "LI") {
					this.parentNode.parentNode.parentNode.parentNode.parentNode.className+=(this.parentNode.parentNode.parentNode.parentNode.parentNode.className.length>0? " ": "") + "sfhover"; //li < ul < li < ul < li < a:focus
				}
			}
		};
		mcEls[i].onblur=function() {
			this.className=this.className.replace(new RegExp("( ?|^)sffocus\\b"), "");
			this.parentNode.className=this.parentNode.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
			if(this.parentNode.parentNode.parentNode.nodeName == "LI") {
				this.parentNode.parentNode.parentNode.className=this.parentNode.parentNode.parentNode.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
				if(this.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "LI") {
					this.parentNode.parentNode.parentNode.parentNode.parentNode.className=this.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
				}
			}
		};
	}
};


//=== SHARE ===

//	add javascript to sharing icons
WM.share.enhanceShareIcons = function () {

	var share_links, i;

	// check for capable javascript
	if (document.getElementById("social") && document.getElementsByTagName) {

		//	get social links
  	share_links = document.getElementById("social").getElementsByTagName("a");
		//	process all but the first and last items
		for (i = 1; i < share_links.length - 1; i++) {
			//	attach an event handler to open a new window
			share_links[i].onclick = function() {
				if (typeof(pageTracker) !== "undefined") {
					pageTracker._trackPageview(this.href + '&amp;w=1');
				}
				//	open a new window using an extra parameter
        window.open(this.href,'share','toolbar=0,status=0,resizable,scrollbars,width=800,height=600');
        return false;
			};
		}	//	loop
	}

};


//=== COMPATIBILITY ===

//	make aliases for backwards compatibility
var addLoadListener = WM.main.addLoadListener;
var addUnloadListener = WM.main.addUnloadListener;


//=== INIT ===

//	start on page load
WM.init = function () {

	WM.main.breakFrames();
	WM.nav.sfHover();
	WM.nav.mcAccessible();
	WM.form.setupFieldsOther();
	WM.share.enhanceShareIcons();
	
};

/* add page load events */
addLoadListener(WM.init);

