// variables for holding pop up window information
	var popupInfo= [];
	var popupImage= [];

	// custom icons
    var iconClinics = new GIcon();
    iconClinics.image = 'images/icons/clinics.png';
    iconClinics.shadow = 'images/icons/logo_shadow.png';
    iconClinics.iconSize = new GSize(32, 32);
    iconClinics.shadowSize = new GSize(47, 29);
    iconClinics.iconAnchor = new GPoint(0, 25);
    iconClinics.infoWindowAnchor = new GPoint(30, 5);

    var iconHospitals = new GIcon();
    iconHospitals.image = 'images/icons/hospitals.png';
    iconHospitals.shadow = 'images/icons/logo_shadow.png';
    iconHospitals.iconSize = new GSize(32, 32);
    iconHospitals.shadowSize = new GSize(47, 29);
    iconHospitals.iconAnchor = new GPoint(0, 25);
    iconHospitals.infoWindowAnchor = new GPoint(5, 1);

	var iconEducation = new GIcon();
    iconEducation.image = 'images/icons/education.png';
    iconEducation.shadow = 'images/icons/logo_shadow.png';
    iconEducation.iconSize = new GSize(32, 32);
    iconEducation.shadowSize = new GSize(47, 29);
    iconEducation.iconAnchor = new GPoint(0, 25);
    iconEducation.infoWindowAnchor = new GPoint(5, 1);

	var iconCorporate = new GIcon();
    iconCorporate.image = 'images/icons/corporate.png';
    iconCorporate.shadow = 'images/icons/logo_shadow.png';
    iconCorporate.iconSize = new GSize(32, 32);
    iconCorporate.shadowSize = new GSize(47, 29);
    iconCorporate.iconAnchor = new GPoint(0, 25);
    iconCorporate.infoWindowAnchor = new GPoint(5, 1);
	
	var iconService = new GIcon();
    iconService.image = 'images/icons/corporate.png';
    iconService.shadow = 'images/icons/logo_shadow.png';
    iconService.iconSize = new GSize(32, 32);
    iconService.shadowSize = new GSize(47, 29);
    iconService.iconAnchor = new GPoint(0, 25);
    iconService.infoWindowAnchor = new GPoint(5, 1);

    var customIcons = [];
    customIcons["clinics"] = iconClinics;
    customIcons["hospitals"] = iconHospitals;
    customIcons["educationalinstitutions"] = iconEducation;
    customIcons["corporateoffices"] = iconCorporate;
    customIcons["servicelocations"] = iconService;
	var markers = [];
	var activeTypes = {};
	var map;
	var typeSelected = false;
    function load() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
		// Set Map Center
		map.setCenter(new GLatLng(0,0),0);

		// Add Controls
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		// Add Physical map button type to controls
		map.addMapType(G_PHYSICAL_MAP);
		// Set the initial map to physical
		map.setMapType(G_PHYSICAL_MAP);
		doDisplay();
		reloadXML("","");
      }
    }
	
	function reloadXML(type) {
		map.clearOverlays();
		// Import marker data from xml file
		var querystring = "?type=" + type;
        GDownloadUrl("markerdata.cfm" + querystring, function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
		  var bounds = new GLatLngBounds();
          for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var type = markers[i].getAttribute("type");
			var thumb = markers[i].getAttribute("thumb");
			var large = markers[i].getAttribute("large");
			var phone = markers[i].getAttribute("phone");
			var additionalinfo = markers[i].getAttribute("additionalinfo");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
			bounds.extend(point);
            var marker = createMarker(point, name, address, type, thumb, phone, large, additionalinfo);
            map.addOverlay(marker);
			var l = marker.type.split(",");
			var mlocation = l[0];
			//console.log(mlocation);
			if (marker.type.indexOf(variables.service) < 0
									&& variables.service != "allservices"
									|| variables.locations.indexOf(mlocation) < 0) marker.hide();
			if (name == variables.name) GEvent.trigger(marker, "click");
	  //console.log(variables.name);
          }
		  map.setZoom(map.getBoundsZoomLevel(bounds));
		  map.setCenter(bounds.getCenter());
		if (variables.full == "yes") openWindow();

        });
	} //end function reloadXML


    function createMarker(point, name, address, type, thumb, phone, large, additionalinfo) {
	itype = type.split(",");
	itype = itype[0];
      var marker = new GMarker(point, customIcons[itype]);
	  	marker.type = type;
	    marker.globaltype = itype;
	  markers.push(marker);
	  if (thumb == "") {
	  	thumb = large;
		if (thumb == "") {
		  	thumb = "images/photos/thumb/noLocationPhoto_thumb.gif";
		}
	  }
	  if (large == "") {
	  		large = "images/photos/large/noLocationPhoto_large.gif";
	  }
      var html = '<div class="infowindow"><div class="name">' + name + '</div>' + '<img src="http://mhsdoctors.com/' + thumb + '" width="110" />' + address + '<br />' + phone + '<br />' + '<a class="slider" href="#" onClick="openWindow();return false;">View Location Details</a>' + '<div class="clear"></div></div>';
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
		newHash();
		window.location.hash = window.location.hash + "/name=" + name;
		// collect data to be parsed into the popup window
	  	popupInfo = '<div class="description"><div class="name">' + name + '</div><p>' + address + '<br/>' + phone + '</p><p><form action="http://maps.google.com/maps" method="get" target="_blank">Get Directions from 						<input name="daddr" value="' + address.replace('<br />', ', ') + '" type="hidden">						<input name="f" value="d" type="hidden">						<input name="hl" value="en" type="hidden">						&nbsp;<input name="saddr" id="saddr" type="text">&nbsp; to ' + name + '. <button type="submit" tabindex="2">Go</button></form></p><p>' + additionalinfo + '</p></div>';
      	popupImage = '<img src="http://mhsdoctors.com/' + large + '" alt="' + name +'" width="220" />';
	  });
	  
      return marker;
    }


var variables = {};
	
	function doDisplay() {
		//get hash
		var hash = window.location.hash;
		if (hash.length <= 0) {
			hash = "#service=allservices/locations=clinics,servicelocations,hospitals,educationalinstitutions,corporateoffices";
			window.location.hash = hash;
		}
		hash = hash.substring(1, hash.length);
		//console.log(hash);
		//grab variables - we need location types and service type
		var s = hash.split("/");
		for (var i = 0; i < s.length; i++ ) {
			var x = s[i].split("=");
			variables[x[0]] = unescape(x[1]);
		}
		if (!variables.name) variables.name = "";
		if (!variables.full) variables.full = "";
		$('input.subGroup').each( function() {
			if (this.value.indexOf(variables.service) >= 0) {
				this.checked = true;
			} else {
				this.checked = false;
			}
		});
		
		$('input.Groups').each( function() {
			this.checked =  (variables.locations.indexOf(this.value) >= 0)
			activeTypes[this.value] = this.checked;
		});
		
	}
	function newHash() {
		var s = getServiceType();
		var l = getLocationList();
		window.location.hash = "#service=" + s + "/locations=" + l;
		//console.log(window.location.hash);
	}
	
	function getServiceType() {
		var type = "allservices";
		$('input:checkbox.subGroup'). each( function() {
			if (this.checked) type = this.value;
		});	
		return type;
	}
	function getLocationList() {
		var list = "";
		$('input:checkbox.Groups'). each( function() {
			if (this.checked) list += this.value + ",";
		});	
		
		return list;	
	}
	function toggleGlobalGroup(type, show) {
		activeTypes[type] = show;
		for (var i = 0; i < markers.length; i++) {
			var marker = markers[i];
		
			if (marker.type.indexOf(type) >= 0 ) {
				if (show) {
					if (marker.type.indexOf( getServiceType() ) >= 0 || getServiceType() == "allservices") {
				  		marker.show();
						
					}
				} else {
				  marker.hide();
				} // end if (show)
			} // end if (marker.type.indexOf)
		} // end for
		newHash();
	}
	function toggleGroup(type, show) {
		if (type == 'allservices') {
			for (var i = 0; i < markers.length; i++) {
				if (show && activeTypes[markers[i].globaltype]) {
					markers[i].show();
				} else {
					markers[i].hide();
				}
			}
			$('input:checkbox.subGroup').not('#allservices').each( function() {
				this.checked = false;
			});
		} else {
			if (!typeSelected) {
				typeSelected = true;
			}
				$('#allservices').attr('checked', false);
				for (var i = 0; i < markers.length; i++) {
					var marker = markers[i];
				
					if (marker.type.indexOf(type) >= 0 ) {
						if (show && activeTypes[marker.globaltype]) {
						  marker.show();
						} else {
						  marker.hide();
						} // end if (show)
					} else {// end if (marker.type.indexOf)
						if (typeSelected) marker.hide();
					}
				} // end for
			$('input:checkbox.subGroup').not('#allservices').each( function() {
				if(this.value != type ) this.checked = false;
			});
			if(!show) {
				$('input#allservices').attr('checked', true);
				toggleGroup('allservices', true);
			}
		} //end else
		newHash();
	} // end function toggleGroup
	
	
	// Function for opening the info window
	 function openWindow(){
		//$("#overlay").fadeIn("slow");
      	$(".description").replaceWith(popupInfo);
		$("#overlay img").replaceWith(popupImage);

		$("#overlay").toggle("slide", {
        	direction: "down"
		},
		500);
		window.location.hash = window.location.hash + "/full=yes";
	}

   $(document).ready(function(){
  	// Close the info window
	 $(".closebutton").click(function() {
		 $("#overlay").toggle("slide", {
        	direction: "down"
		  },
		  400);
				return false;
	 });
	 
	 $('input.Groups').click(function(){  // Location Types
	 	toggleGlobalGroup(this.value, this.checked);
	 });
	 
	 $('input.subGroup').click(function(){ // Service Types
	 	toggleGroup(this.value, this.checked);
	 });
	 
	 $('a[rel="external"]').click(function(){
	 	window.open(this.href);
		return false;
	 });
	 $('#emailtofriend a').click(function() {
		window.location = this.href + "?q=" + window.location.hash.substring(1, window.location.hash.length);
		return false;
	 });
	  var cookieOpt = { path: '/' };
	if($.cookie('FETDISPLAY') ) {
		if ($.cookie('FETDISPLAY') == 'on') {
			$('#frontEndTools').show();
		} else {
			$('#frontEndTools').hide();
		}
	} else {
		$.cookie('FETDISPLAY', 'on', cookieOpt);
	}
	$('#frontEndToolsHandle').click(function() {
		if($('#frontEndTools').is(':visible')){
			$.cookie('FETDISPLAY','off', cookieOpt);
		} else {
			$.cookie('FETDISPLAY','on', cookieOpt);
		}
		$('#frontEndTools').toggle('slow');
		
	
	});
	
  });