﻿var map = null;
var firstload = 1;
var home = null;
var tooz = new Array();
var trafficInfo;
var maxdist = 0;
    var toggleState = 0;
    function initialize() {
      if (GBrowserIsCompatible()) {
         map = new GMap2(document.getElementById("map_canvas"));
        
         gdir = new GDirections(map, document.getElementById("directions"));
        map.setCenter(new GLatLng(40.4419, -102.1419), 3);
        var mapControl = new GMenuMapTypeControl();
        map.addControl(mapControl);
        map.addControl(new GSmallZoomControl());
        var trafficOptions = {incidents:true};
        trafficInfo = new GTrafficOverlay(trafficOptions);
        getpharms();
      }
    }
function createMarker(pnt,markers,increment){
if(markers['dist']> maxdist){
	maxdist = markers['dist'];
}
var destin = markers['address']+" "+markers['city']+" "+markers['state']+" "+markers['zip'];
tooz[increment] = new Array(home,destin);
if( parseInt(markers['highlight']) == 1){
var newIcon = MapIconMaker.createMarkerIcon({width: 35, height: 35, primaryColor: "#cc0000"});	
}else{
var newIcon = MapIconMaker.createMarkerIcon({width: 25, height: 25, primaryColor: "#3161ac"});	
}
var mtl = "<span style=\"color:#880000;font-size:12px;font-weight:bold;\" >"+markers['name']+"</span><br />"+markers['address']+"<br />"+markers['city']+" "+markers['state']+" "+markers['zip']+"<br />Phone: "+markers['phone']+'<br /><a href="javascript:setDirections('+increment+')">Directions<\/a>';
        var marker = new GMarker(pnt, newIcon);	
         GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(mtl);
      });
        return marker;
} 
function setDirections(increment) {
	locale = "en_US";
      gdir.load("from: " + tooz[increment][0] + " to: " + tooz[increment][1],{ "locale": locale });
    }  
 function getpharms(){
 	if(!firstload){
 		map.clearOverlays();
 		maxdist = 0;
		$('directions').update('');
	home = $F('address');
	home2 = home;	
   
 	var params = 'address=' + escape(home2);
//alert(params);
 			var	 request = new Ajax.Request('getpharms.php', {
          method:'get',
          parameters: params,
          onSuccess: function(transport){
          var datasets = evalResponse(transport);
          if(datasets){
          markers = datasets[0];
          info = datasets[1];
          var marks = [];
          //alert("MARKS:"+markers.length);
          if(!info[2]){
          for (var i = 0; i < markers.length; i++) {
               var pnt = new GLatLng(parseFloat(markers[i]['lat']),parseFloat(markers[i]['lng']));
               var marker = createMarker(pnt,markers[i],i);
               marks.push(marker);

                map.addOverlay(marker);                                
               }
               var mcOptions = { gridSize: 20, maxZoom: 15};

              var markerCluster = new MarkerClusterer(map, marks,mcOptions);
                 
             //  map.setCenter(new GLatLng(info[0],info[1]),16);
              // alert("N:"+maxnorth+" E:"+maxeast+" S:"+maxsouth+" W:"+maxwest)
             //  sw = new  GLatLng(maxwest,maxsouth);
		//	ne = new GLatLng(maxeast,maxnorth);					
          // var contains = new GLatLngBounds(sw, ne);
          newzoom = 10;
         if(maxdist < 2){
			newzoom = 13;
		}
		if((maxdist > 2) && (maxdist < 5)){
			newzoom = 12;
		}
		if((maxdist > 5) && (maxdist < 20)){
			newzoom = 11;
		}
		if((maxdist > 20) && (maxdist < 50)){
			newzoom = 10;
		}
		if((maxdist > 50) && (maxdist < 100)){
			newzoom = 5;
		}
         if((maxdist > 100) && (maxdist < 200)){
			newzoom = 3;
		}
		if((maxdist > 200)){
			newzoom = 2;
		}
         // var  newzoom =  map.getBoundsZoomLevel(contains);
           //alert(maxdist);
            map.setCenter(new GLatLng(info[0],info[1]), newzoom );
              }else{alert(info[2]);}             			
          }
 		}
 	});
 	}
	 firstload = 0; 
}
evalResponse = function(request) {
    try {
        return eval('('+request.responseText+')');
    } catch (e) {}
}
function handleErrors(){
	   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_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\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 toggleTraffic() {
      if (toggleState == 1) {
        map.removeOverlay(trafficInfo);
        toggleState = 0;
      } else {
        map.addOverlay(trafficInfo);
        toggleState = 1;
      }
    }
var MapIconMaker={};
MapIconMaker.createMarkerIcon=function(a){var b=a.width||32;var c=a.height||32;var d=a.primaryColor||"#ff0000";var e=a.strokeColor||"#000000";var f=a.cornerColor||"#ffffff";var g="http://chart.apis.google.com/chart?cht=mm";var h=g+"&chs="+b+"x"+c+"&chco="+f.replace("#","")+","+d.replace("#","")+","+e.replace("#","")+"&ext=.png";var j=new GIcon(G_DEFAULT_ICON);j.image=h;j.iconSize=new GSize(b,c);j.shadowSize=new GSize(Math.floor(b*1.6),c);j.iconAnchor=new GPoint(b/2,c);j.infoWindowAnchor=new GPoint(b/2,Math.floor(c/12));j.printImage=h+"&chof=gif";j.mozPrintImage=h+"&chf=bg,s,ECECD8"+"&chof=gif";var h=g+"&chs="+b+"x"+c+"&chco="+f.replace("#","")+","+d.replace("#","")+","+e.replace("#","");j.transparent=h+"&chf=a,s,ffffff11&ext=.png";j.imageMap=[b/2,c,(7/16)*b,(5/8)*c,(5/16)*b,(7/16)*c,(7/32)*b,(5/16)*c,(5/16)*b,(1/8)*c,(1/2)*b,0,(11/16)*b,(1/8)*c,(25/32)*b,(5/16)*c,(11/16)*b,(7/16)*c,(9/16)*b,(5/8)*c];for(var i=0;i<j.imageMap.length;i++){j.imageMap[i]=parseInt(j.imageMap[i])}return j}