/*=== 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
		nav:   function () {},	//	navigation
		maps:	 function () {}, 	//	gmaps
		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);
}


//=== 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"), "");
				}
			}
		};
	}
};

//=== 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 ? options.id : "map_canvas"),
    		{
    			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]);
    	}
    },

		// strip out static gmap and replace with dynamic one
		// relies on jQuery
		queryStToMarkers: function (querystring) {
      var build = {  };
			if (querystring.indexOf('?') > 0) {
				 querystring = querystring.split('?')[1];
			}
			pairs = querystring.split("&");
      for (i=0;i<pairs.length;i++) {
			  ft = pairs[i].split("=");
        if (ft[0] == 'markers') {
          //build['marker'+i] = ft[1] ;
					var mkpairs = ft[1].split('|');
          var markerset = {} ;
						for (j=0;j<mkpairs.length;j++) {
						  var mkeach = mkpairs[j].split(":");
							if (mkeach[1]) {
							markerset[mkeach[0]] = mkeach[1];
							} else {
							markerset['loc'] = mkeach[0];
							}
						}
					build['markersp'+i] = markerset;
        }
			}
			return build;
		},
		
    querySt: function (ji,querystring) {
      if (querystring.indexOf('?') > 0) {
				 querystring = querystring.split('?')[1];
			}
			pairs = querystring.split("&");
      for (i=0;i<pairs.length;i++) {
        ft = pairs[i].split("=");
        if (ft[0] == ji) {
          return ft[1];
        }
      }
    },

		replaceStatic : function () {
      //check to see if there is a static map. if not, move along.
			if ($('.staticgmap').length > 0) {
         //lazy load the maps script
				 var s = document.createElement("script");
         s.type = "text/javascript";
         s.src  = "http://maps.google.com/maps/api/js?v=3&sensor=true&callback=gmap_draw&c&async=2";
         window.gmap_draw = function(){

        //get the static images and loop through them
        $('.staticgmap').each(function (index) {
					
					//pull out the static maps options and separate them via the querystring parser
          //sample: http://maps.google.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&amp;zoom=14&amp;size=512x512&amp;maptype=roadmap&amp;markers=color:blue|label:S|40.702147,-74.015794&amp;markers=color:green|label:G|40.711614,-74.012318&amp;markers=color:red|color:red|label:C|40.718217,-73.998284&amp;sensor=false
					var querystring = $(this).attr('src');
					var atts = {
    					zoom: WM.maps.querySt('zoom', querystring),
    					center: WM.maps.querySt('center', querystring),
    					maptype: WM.maps.querySt('maptype', querystring),
    					markers: WM.maps.querySt('markers', querystring),
    					height: $(this).css('height'),
    					width: $(this).css('width')
					};
					
					var gmapsimg = $(this);
					//if the attribute centre is not nothing, send it to the geolocator to find the lat/long
					if (atts.center.length > 0) {
             var geocoder = new google.maps.Geocoder();
             geocoder.geocode({ 'address': atts.center }, function(results, status) {
                 if (status == google.maps.GeocoderStatus.OK) {
										//save the geolocated location to the atts object
										atts.location = results[0].geometry.location;
            					//give the image a new parent, as the image will get clobbered
											$(gmapsimg).wrap('<div id="map_container'+index+'" />');
            					var mparent = $(gmapsimg).parent();
            					$(gmapsimg).remove();
            					$(mparent).css( { 'width': atts.width, 'height': atts.height } );
											//set the map options
                      var opts = {
                                id: $(mparent).attr('id'),
            										zoom: parseInt(atts.zoom),
                                center: results[0].geometry.location,
																mapTypeId: google.maps.MapTypeId[atts.maptype.toUpperCase()]
                      };
											//get the new map parent (can't use jQuery for this)
            					var mapdiv = document.getElementById('map_container'+index);
            					var map = new google.maps.Map(mapdiv, opts);

							// add markers
							var allmarkers = WM.maps.queryStToMarkers(querystring);
                for(var markername in allmarkers) {
                    if(allmarkers.hasOwnProperty(markername))
												var onemarker = allmarkers[markername];
												var mkopts = {};
        								//save the position into the gmaps LatLng 
												mkopts['position'] = new google.maps.LatLng( onemarker['loc'].split(',')[0] , onemarker['loc'].split(',')[1] );
												// static api lets you set a label and colour, dynamic doesn't. so pop the label in the title instead
												mkopts['title'] = onemarker['label'];
												//write out the rest of the static API options in case they are supported (they aren't yet)
												for (var prop in onemarker) {
  												mkopts[prop] = onemarker[prop];
												}
												mkopts['map'] = map;
                        //set the marker
												var marker = new google.maps.Marker( mkopts );						
                  }
								 }
							});//finish geoencode callback
							
					}
				});				 //finish jQuery loop .each()
				 };
         //attach the script to the head and let it run
				 $("head").append(s);  
      }
    },
		
		//	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);
    	});
    }

	};

}();



//=== 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
	}

};

WM.nav.clearTopNavBorder = function () {
  if (document.getElementById) {
	  var divextras = document.getElementById("extras");
		var extraslist = divextras.getElementsByTagName("ul");
		var extrasli = extraslist[0].getElementsByTagName("li");
		extrasli[extrasli.length-1].className = "last";
	}	
}


WM.nav.clearSearch = function () {
  if (document.getElementById) {
	  var searchBox = document.getElementById("searchQ");
  		searchBox.onclick = function () {
  			if (searchBox.value == "Site Search...") {
  			  searchBox.value = "";
  			}		
		}
	}
}


//=== 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.nav.clearSearch();
  WM.nav.clearTopNavBorder();
	WM.main.breakFrames();
	WM.nav.sfHover();
	WM.nav.mcAccessible();
	WM.form.setupFieldsOther();
	WM.share.enhanceShareIcons();
	WM.maps.replaceStatic();
};

/* add page load events */
addLoadListener(WM.init);


