(function(){ // wrapping in a lambda function so this function can be out of the way of other scripts
	// don't attempt to render the map if the browser won't support it
	Event.observe(window, "load", mapLoad);	
	// overall function for loading the map
	function mapLoad() {
	
		// identify the elements on the page used to generate the map
		var maptable = document.getElementById("maptable");
		if(!maptable) return false;
		// if the domain is an fsnhospitals domain, use those settings, otherwise, use the funeralhome settings
		if(document.domain.search(/fsnhospitals/) >= 0) {
			var elname = "hospital";
			var noun = "Hospital";
		} else {
			var elname = "funeralhome";
			var noun = "Funeral Home";
		}
		// unhide the jump link if it was hidden
		if(document.getElementById("mapjumplink")) document.getElementById("mapjumplink").style.display = "";
		if(document.body.textContent) v = "textContent";  // the name of the DOM property that has the text inside an element
		else if(document.body.innerText) v = "innerText";
		
		
		// do an xml http request to get all the hospitals/florists/funeralhome based on the given ids
		// using using the data from the http request, build arrays that will be used to build the map
		var currentCityId = '';
		var listings = [];
		var florists = [];
		var latsum = 0;
		var longsum = 0;
		var northLat = null;
		var southLat = null;
		var westLon = null;
		var eastLon = null;
		var querystring = "";
		var tables = document.getElementsByTagName("span"); 
		for(var i = 0; i < tables.length; i++) {
			if(tables[i].getAttribute("__" + elname + "_id")) {
				listings.push(tables[i]);
				querystring += elname + "_id[]=" + tables[i].getAttribute("__" + elname + "_id") + "&";
			}
		}
		var links = document.getElementsByTagName("a");
		for(var i = 0; i < links.length; i++) {
			if(links[i].getAttribute("__florist_id")) {
				florists.push(links[i]);
				querystring += "florist_id[]=" + links[i].getAttribute("__florist_id") + "&";
			}
		}
		currentCityId = document.getElementById('directory_city');
		if (currentCityId) currentCityId = currentCityId.getAttribute("__city_id");

		var req = new Ajax.Request("/scripts/xhr/get_nearby_florists.xml.php", {
			"method": "post",
			"postBody": querystring,
			"onSuccess": function(o) {  try {
				var xdoc = o.responseXML;
				var els = xdoc.getElementsByTagName(elname);
				for(var i = 0; i < listings.length; i++) {
					var found = false;
					for(var j = 0; j < els.length && !found; j++) {
						if(els[j].getAttribute("id") == listings[i].getAttribute("__" + elname + "_id")) {
							found = true;
							if(els[j].getAttribute("longitude") != "" && els[j].getAttribute("latitude") != "") {
								listings[i].setAttribute("__name", els[j].getAttribute("name"));
								listings[i].setAttribute("__address", els[j].getAttribute("address1"));
								listings[i].setAttribute("__city", els[j].getAttribute("city"));
								listings[i].setAttribute("__state", els[j].getAttribute("state"));
								listings[i].setAttribute("__zip_code", els[j].getAttribute("zipCode"));
								listings[i].setAttribute("__phone_number", els[j].getAttribute("phoneNumber"));
								listings[i].setAttribute("__tollfree_number", els[j].getAttribute("tollfreeNumber"));
								listings[i].setAttribute("__latitude", els[j].getAttribute("latitude"));
								listings[i].setAttribute("__longitude", els[j].getAttribute("longitude"));
								listings[i].setAttribute("__premium", els[j].getAttribute("premiumListing"));
								listings[i].setAttribute("__city_id", els[j].getAttribute("cityId"));
							} 
						}
					}
				}
				
				var listings2 = [];
				for(var i = 0; i < listings.length; i++) {
					var lat = parseFloat(listings[i].getAttribute("__latitude"));
					var long = parseFloat(listings[i].getAttribute("__longitude"));
					if((lat > 0 || lat < 0) && (long > 0 || long < 0)) {
						latsum += lat;
						longsum += long;
						if(lat > northLat || northLat === null) northLat = lat;
						if(lat < southLat || southLat === null) southLat = lat;
						if(long < westLon || westLon === null) westLon = long;
						if(long > eastLon || eastLon === null) eastLon = long;
						listings2.push(listings[i]);
					}
				}
				listings = listings2;
				var els = xdoc.getElementsByTagName("florist");
				for(var i = 0; i < florists.length; i++) {
					var found = false;
					for(var j = 0; j < els.length && !found; j++) {
						if(els[j].getAttribute("id_num") == florists[i].getAttribute("__florist_id")) {
							found = true;
							if(els[j].getAttribute("longitude") != "" && els[j].getAttribute("latitude") != "") {
								florists[i].setAttribute("__name", els[j].getAttribute("name_shop"));
								florists[i].setAttribute("__address", els[j].getAttribute("address"));
								florists[i].setAttribute("__city", els[j].getAttribute("addr_city"));
								florists[i].setAttribute("__state", els[j].getAttribute("addr_state"));
								florists[i].setAttribute("__zip_code", els[j].getAttribute("addr_zip"));
								florists[i].setAttribute("__phone_number", els[j].getAttribute("id_num"));
								florists[i].setAttribute("__tollfree_number", els[j].getAttribute("tel_tollfree"));
								florists[i].setAttribute("__latitude", els[j].getAttribute("latitude"));
								florists[i].setAttribute("__longitude", els[j].getAttribute("longitude"));
							}
						}
					}
				}
				var florists2 = [];
				for(var i = 0; i < florists.length; i++) {
					var lat = parseFloat(florists[i].getAttribute("__latitude"));
					var long = parseFloat(florists[i].getAttribute("__longitude"));
					if((lat > 0 || lat < 0) && (long > 0 || long < 0)) {
						florists2.push(florists[i]);
					}
				}
				florists = florists2;
				
				// sort the items from north to south to be displayed on the map
				if(listings.length + florists.length == 0) return false; // there's nothing to display
				listings.sort(function(a,b) { 
					if (a.getAttribute("__premium") == b.getAttribute("__premium")) {
						if (a.getAttribute("__city_id") == b.getAttribute("__city_id"))
							return parseFloat(b.getAttribute("__latitude")) - parseFloat(a.getAttribute("__latitude"));
						else
							return (b.getAttribute("__city_id") == currentCityId);
							
					} else return (b.getAttribute("__premium") == "1");
				});
				florists.sort(function(a,b) { return parseFloat(b.getAttribute("__latitude")) - parseFloat(a.getAttribute("__latitude")); });
				// var length = listings.length + florists.length;
				var length = listings.length;
				
				
				// begin rendering the map itself by creating the map object and creating the map legend with icons
				var maptable = document.getElementById("maptable");
				maptable.style.display = "block";
				// create a bounds object that represents an area covering all the map points
				var mapbounds = new google.maps.LatLngBounds(new google.maps.LatLng(northLat, westLon), new google.maps.LatLng(southLat, eastLon));
				if(maptable.className.search(/\bno-header\b/i) == -1) {
					var tableHead = document.createElement("thead");
					var tableRow = document.createElement("tr");
					var tableCell = document.createElement("th");
					tableCell.appendChild(document.createTextNode("Area " + noun + "s and Florists"));
					tableRow.appendChild(tableCell);
					tableHead.appendChild(tableRow);
					var tableCell = document.createElement("td");
					tableCell.style.textAlign = "center";
					tableCell.appendChild(document.createTextNode("(From North to South)"));
					tableRow.appendChild(tableCell);
					maptable.insertBefore(tableHead, maptable.firstChild);
				}
				var mapinfo = document.getElementById("mapinfo");
				var mapdiv = document.getElementById("map");
				var mapoptions = {
					scaleControl: true,
					navigationControl: true,
					mapTypeControl: false, 
					navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
					center: mapbounds.getCenter(), 
					zoom: 10,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				};
				var map = new google.maps.Map(mapdiv, mapoptions);
				map.fitBounds(mapbounds);
				if(document.domain.search(/fsnhospitals/) >= 0) {
					var funeralMarkerOptions = { 'map': map };
					funeralMarkerOptions.iconUrl = '/images/cross.png';
					funeralMarkerOptions.icon = new google.maps.MarkerImage(funeralMarkerOptions.iconUrl,
						undefined,
						undefined,
						new google.maps.Point(14, 28),
						new google.maps.Size(28, 28)
					);
					funeralMarkerOptions.shadow = new google.maps.MarkerImage('/images/shadow.png',
						undefined,
						undefined,
						new google.maps.Point(14, 28),
						new google.maps.Size(45, 30)
					);
				} else {
					var premiumMarkerOptions = { 'map': map, iconUrl: '/images/premiumfuneralicon.png' };
					premiumMarkerOptions.icon = new google.maps.MarkerImage(premiumMarkerOptions.iconUrl,
						undefined,
						undefined,
						new google.maps.Point(10, 34),
						new google.maps.Size(20, 34));
					premiumMarkerOptions.shadow = new google.maps.MarkerImage('/images/shadow3.png',
						undefined,
						undefined,
						new google.maps.Point(0, 34),
						new google.maps.Size(27, 34));
					
					var funeralMarkerOptions = { 'map': map, iconUrl: '/images/funeralicon.png' };
					funeralMarkerOptions.icon = new google.maps.MarkerImage(funeralMarkerOptions.iconUrl,
						undefined,
						undefined,
						new google.maps.Point(10, 34),
						new google.maps.Size(20, 34));
					funeralMarkerOptions.shadow = new google.maps.MarkerImage('/images/shadow3.png',
						undefined,
						undefined,
						new google.maps.Point(0, 34),
						new google.maps.Size(27, 34));
				}
				var floristMarkerOptions = {'map': map };
				floristMarkerOptions.iconUrl = '/images/flower2.gif';
				floristMarkerOptions.icon = new google.maps.MarkerImage(floristMarkerOptions.iconUrl ,
					undefined,
					undefined,
					new google.maps.Point(15, 30),
					new google.maps.Size(30, 30)
				);
				floristMarkerOptions.shadow = new google.maps.MarkerImage('/images/shadow2.png',
					undefined,
					undefined,
					new google.maps.Point(10, 30),
					new google.maps.Size(44, 30)
				);
				var makeMarkerFromElement = function(el, options) {
					var lat = el.getAttribute("__latitude");
					var lng = el.getAttribute("__longitude");
					options.position = new google.maps.LatLng(lat, lng);
					return new google.maps.Marker(options);
				}
				var makeWindowNodeFromElement = function(el) {
					var n = document.createElement("div");
					n.style.fontSize = "11px";
					if(el.tagName.toUpperCase() == "A") var link = el;
					else if(el.getElementsByTagName("a").length) var link = el.getElementsByTagName("a")[0];
					if(link) {
						var a = document.createElement("a");
						a.href = link.href;
					} else var a = document.createElement("span");
					var b = document.createElement("b");
					b.appendChild(document.createTextNode(el.getAttribute("__name")));
					a.appendChild(b);
					n.appendChild(a);
					n.appendChild(document.createElement("br"));
					n.appendChild(document.createTextNode(el.getAttribute("__address")));
					n.appendChild(document.createElement("br"));
					n.appendChild(
						document.createTextNode(
							el.getAttribute("__city") + ", " +
							el.getAttribute("__state") + " " + 
							el.getAttribute("__zip_code")
						)
					);		
					if(el.getAttribute("__phone_number")) {
						n.appendChild(document.createElement("br"));
						num = el.getAttribute("__phone_number").replace(/[^\d]/g,'');
						n.appendChild(document.createTextNode("Local: "+"("+num.substr(0,3)+") "+num.substr(3,3)+"-"+num.substr(6)));
					}
					if(el.getAttribute("__tollfree_number") != "") {
						n.appendChild(document.createElement("br"));
						num = el.getAttribute("__tollfree_number").replace(/[^\d]/g,'');
						n.appendChild(document.createTextNode("Tollfree: "+"("+num.substr(0,3)+") "+num.substr(3,3)+"-"+num.substr(6)));
					}
					
					return n;
				}
				var activeInfoWindow = false;
				var activateMapInfoItem = function(el) {
					if(activeInfoWindow) activeInfoWindow.close();
					var nodes = mapinfo.childNodes;
					for(i = 0; i < nodes.length; i++) {
						nodes[i].id = "";
					}
					activeInfoWindow = el._marker._infoWindow;
					el.id = "mapInfoActiveItem";
				}
				// variables below starting with _ are non-standard custom properties attached to objects for convenience
				// for example m._infoWindow attaches the InfoWindow to the Marker because there's no standard way to do so
				var lastListingPremium = false;
				for(var i = 0; listings && (i < listings.length); i++) {
					var l = listings[i];
					var premium = (l.getAttribute("__premium") == "1");
					
					var markerObj = Object.clone(funeralMarkerOptions);
					if (premium) markerObj = Object.clone(premiumMarkerOptions);
	
					l._marker = makeMarkerFromElement(l, markerObj);
					var m = l._marker;
					m._windowNode = makeWindowNodeFromElement(l);
					m._windowNode.className = "listingNode";
					m._infoWindow = new google.maps.InfoWindow({
						content: m._windowNode
					})
					m._listNode = document.createElement("div");
					m._listNode.className = "listingNode";
					if (premium)
						m._listNode.className += " listingPremium";
					else if (lastListingPremium && !premium)
						m._listNode.className += " listingBreak";
					m._listNode._marker = m;
					m._listNode._image = document.createElement("img");
					if(document.domain.search(/fsnhospitals/) >= 0) { 
						m._listNode._image.style.height = "15px";
						m._listNode._image.style.width = "15px";
					} else {
						m._listNode._image.style.height = "15px";
						m._listNode._image.style.width = "8px";
					}
					m._listNode._image.src = markerObj.iconUrl;
					m._listNode._image.style.verticalAlign = "middle";
					m._listNode.appendChild(m._listNode._image);
					var b = document.createElement("b");
					b.appendChild(document.createTextNode(String.fromCharCode(160,160) + 	l.getAttribute("__name")));
					m._listNode.appendChild(b);
					mapinfo.appendChild(m._listNode);
					
					google.maps.event.addListener(m, "click", function() { 
						this._infoWindow.open(map, this);
						activateMapInfoItem(this._listNode);
					});
					Event.observe(m._listNode, "click", function() { 
						google.maps.event.trigger(this._marker, "click"); 
					});
					// map.addOverlay(m);
					lastListingPremium = premium;
				}
				for(var i = 0; florists && i < florists.length; i++) {
					var f = florists[i];
					f._marker = makeMarkerFromElement(f, Object.clone(floristMarkerOptions));
					var m = f._marker;
					m._windowNode = makeWindowNodeFromElement(f);
					m._windowNode.className = "floristNode";
					m._infoWindow = new google.maps.InfoWindow({
						content: m._windowNode
					});
					m._listNode = document.createElement("div");
					m._listNode.className = "listingNode";
					m._listNode._marker = m;
					m._listNode._image = document.createElement("img");
					m._listNode._image.style.height = "15px";
					m._listNode._image.style.width = "15px";
					m._listNode._image.src = floristMarkerOptions.iconUrl;
					m._listNode._image.style.verticalAlign = "middle";
					m._listNode.appendChild(m._listNode._image);
					var b = document.createElement("b");
					b.appendChild(document.createTextNode(String.fromCharCode(160,160) + 	f.getAttribute("__name")));
					m._listNode.appendChild(b);	
					mapinfo.appendChild(m._listNode);
					
					google.maps.event.addListener(m, "click", function() { 
						this._infoWindow.open(map, this);
						activateMapInfoItem(this._listNode);
					});
					Event.observe(m._listNode, "click", function() { 
						google.maps.event.trigger(this._marker, "click"); 
					});
					// map.addOverlay(m);
				}
				if(mapdiv.className.search(/autoheight/) >= 0) {
					if(mapdiv.offsetHeight < mapdiv.parentNode.offsetHeight) {
						mapdiv.style.height = mapdiv.parentNode.offsetHeight + "px";
					}
				}
				// find the zoomlevel for the map that covers all the map points
				// don't zoom closer than 11
				mapLoad = null;
			} catch(ex) { console.log(ex); } }
		});
	}
})();
