// JavaScript Document

var map = null;
    var geocoder = null;
 	var gdir;
	var from = null;

	var marker;
        var providerInfoList = [];
        var curPoint = null;

 	var iconBlue = new GIcon(); 
    	iconBlue.image = 'images/mm_20_blue.png';
    	iconBlue.shadow = 'images/mm_20_shadow.png';
    	iconBlue.iconSize = new GSize(12, 20);
    	iconBlue.shadowSize = new GSize(22, 20);
    	iconBlue.iconAnchor = new GPoint(6, 20);
    	iconBlue.infoWindowAnchor = new GPoint(5, 1);

 	var iconGreen = new GIcon(); 
		iconGreen.image = 'images/mm_20_green.png';
		iconGreen.shadow = 'images/mm_20_shadow.png';
		iconGreen.iconSize = new GSize(12, 20);
		iconGreen.shadowSize = new GSize(22, 20);
		iconGreen.iconAnchor = new GPoint(6, 20);
		iconGreen.infoWindowAnchor = new GPoint(5, 1);

 	var iconRed = new GIcon(); 
		iconRed.image = 'images/mm_20_red.png';
		iconRed.shadow = 'images/mm_20_shadow.png';
		iconRed.iconSize = new GSize(12, 20);
		iconRed.shadowSize = new GSize(22, 20);
		iconRed.iconAnchor = new GPoint(6, 20);
		iconRed.infoWindowAnchor = new GPoint(5, 1);

 	var iconHere = new GIcon(); 
		iconHere.image = 'images/down.png';
		iconHere.iconSize = new GSize(18, 30);
		iconHere.iconAnchor = new GPoint(6, 20);

	var customIcons = [];
		customIcons["UCC"] = iconBlue;
		customIcons["WIDO"] = iconRed;
		customIcons["RHC"] = iconGreen;
		customIcons["here"] = iconHere;	

    function initialize() {
    	if (GBrowserIsCompatible()) {
			document.getElementById('directions').innerHTML = "";
        	map = new GMap2(document.getElementById("map_canvas"));
        	gdir = new GDirections(map, document.getElementById("directions"));
	
		gdir.clear();
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(gdir, "error", handleErrors);
		map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(37.89958, -79.24837), 6);
			geocoder = new GClientGeocoder();
	        curPoint = null;
                providerInfoList = [];

		setMarkers();
		}
		}

 	function setDirections(fromAddress, toAddress, locale) {

          document.getElementById('directions').innerHTML = "";
        gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
            var regExp = /\s+/g;
                var srcAddr = fromAddress.replace(regExp,'+');
                var dstAddr = toAddress.replace(regExp,'+');
                var printURL = "http://maps.google.com/maps?pw=2&q="+srcAddr+"+to+"+dstAddr;
                $("directions").insert("<a href='"+printURL+"' target='_blank'>Printable Instructions</a>");
		}

  	function handleErrors(){

 	   if (from == null)	
	   alert ("You did not specify your address");
       else
	   {	
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	   alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	   alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
 
	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   }
	   }

	function onGDirectionsLoad(){ 
		// Use this function to access information about the latest load()
        // results.
        // e.g.
        // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	   }

        function ProviderInfoComparator(a, b) {

                return a.point.distanceFrom(curPoint) - b.point.distanceFrom(curPoint);
        }

  
	var youmarker;
   	function showAddress(address) {
      	if (geocoder) {
        	geocoder.getLatLng(
          	address,
          	function(point) {
				if (!point) {
					  alert("The address you entered could not be found");
				} 
				else {
					//map.setCenter(point, 12);
					from = address;   
					curPoint = point;
					document.getElementById('directions').innerHTML = "";
					setMarkers();
					//Sort markers							
					if (youmarker) {
						map.removeOverlay(youmarker);
					}	      	       
					youmarker = new GMarker(point,customIcons["here"]);     
					map.addOverlay(youmarker);	
					
					gdir.clear(); 

				}
          	}
        );
      }
    }

 	function setMarkers()
	{	
		GDownloadUrl("gis_xml_state.php?state=VA", function(data) {
	providerInfoList = [];
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
			var city = markers[i].getAttribute("city");
			var state = markers[i].getAttribute("state");
			var zip = markers[i].getAttribute("zip");
            var type = markers[i].getAttribute("type");
	    	var web = markers[i].getAttribute("web");
			var notes = markers[i].getAttribute("notes");
			var xray = markers[i].getAttribute("xray");
			var phone = markers[i].getAttribute("phone");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            var Sun = markers[i].getAttribute("Sun");
	    	var Mon = markers[i].getAttribute("Mon");
	    	var Tue = markers[i].getAttribute("Tue");
			var Wed = markers[i].getAttribute("Wed");
			var Thu = markers[i].getAttribute("Thu");
			var Fri = markers[i].getAttribute("Fri");
			var Sat = markers[i].getAttribute("Sat");
	 		marker = createMarker(point,name,address,city,state,zip,type,Sun,Mon,Tue,Wed,Thu,Fri,Sat,web,phone,notes,xray);
            map.addOverlay(marker);
			var providerInfo = new ProviderInfo(name, type, point, marker, phone, web);
            providerInfoList.push(providerInfo);
          }

                 if(curPoint) {
                         $("directions").insert("<b>Nearby Locations</b><br/>");
                               providerInfoList.sort(ProviderInfoComparator);
                       
                               var latlngbounds = new GLatLngBounds( );

                              for(var i = 0; i < 10; i++) {
                                       latlngbounds.extend(providerInfoList[i].point);
                                       var distMiles = (providerInfoList[i].point.distanceFrom(curPoint) * 0.000621371192).toFixed(2);
                                       var t = "";
                                      if(providerInfoList[i].type == "UCC") {
                                               t = "Urgent Care Center";
                                       } else if(providerInfoList[i].type == "RHC") {
                                               t = "Retail Health Clinic";
                                       } else if(providerInfoList[i].type == "WIDO") {
                                               t = "Walk-In Center";
                                       }
                                       map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
                                       var websiteLink = "";
                                       if(providerInfoList[i].web.length > 0) {
                                            websiteLink = "<br/><a href='http://" + providerInfoList[i].web +"' target='_blank'>Website</a>";
                                       }
                                       var phoneText = "";
                                       if(providerInfoList[i].phone.length > 0) {
                                            phoneText = "<br/><i>" + providerInfoList[i].phone + "</i>";
                                       }
                                       $("directions").insert("<div class='nearbyItem'  onclick=\"GEvent.trigger(providerInfoList["+ i +"].marker, 'click');\"><div class='icon'><img src='" +customIcons[providerInfoList[i].type].image + "'/></div><div class='foo'><b>" + providerInfoList[i].name +"</b><br/>"  + t + phoneText + "<br/><i>"+ distMiles + " Miles</i>" + websiteLink + "</div></div>");
                                                                   
                               }
                               
                               
                               //GEvent.trigger(providerInfoList[0].marker, 'click');
                               //alert(ProviderInfoComparator(providerInfoList[0], providerInfoList[1]));
                       }

        });
	}

    function createMarker(point,name,address,city,state,zip,type,Sun,Mon,Tue,Wed,Thu,Fri,Sat,web,phone,notes,xray) {

		var loc = 'en';	
      	var marker = new GMarker(point, customIcons[type]);
      	
      	var website_link = "";
        if(web.length > 0)
            website_link = "<b>Website: </b>"+"<a href=http://"+web+" target='_blank'>"+web+"</a><br/>";
        var toAddr = point.lat()+","+point.lng();//+"+address="+address + ", " + city + ", " + state + ", " + zip;
        var html = "<div class='infotab''><b>"+name+"</b><br/>"+address+"<br/>"+city+", "+state+" "+zip+"<br/><br/>"+"<b>Phone: </b>"+phone+"<br/>"+ website_link +"<input type='button' value='Get Directions'onClick=\"setDirections('"+from+"','"+toAddr+"','"+loc+"');\"/></div>";
       	
        var html_plans = "<div class='infotab'><b>Accepted Plans: </b><br/>"+notes+"<br/><br/>Call to verify that your<br/>insurance plan will be accepted.";


	var tabs = [];  

	tabs.push(new GInfoWindowTab('Address', html));  
	tabs.push(new GInfoWindowTab('Plans', html_plans)); 

    GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowTabsHtml(tabs);
    });
    return marker;
    }

	function MM_preloadImages() { //v3.0
  	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}
