var map;
var geocoder;
var gmarkers = [];
var htmls = [];
var j = 0;
var gdir;
var mapCenterAddress;
var tempDir;

function loadMapOnStartUp(lat, lng, zoom) {
	
	if (GBrowserIsCompatible()) {
		if (map != null) return;
		map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		
		map.setCenter(new GLatLng(lat, lng), zoom);
		
		geocoder = new GClientGeocoder();
	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
}

function createMarkers() {
	
	for (var i = 0; i < markers.length; i++) {
		var lat = parseFloat(markers[i]["lat"]);
		var lng = parseFloat(markers[i]["lng"]);
		var point = new GLatLng(lat,lng);
		
		var providerName = markers[i]["name"];
		var address = markers[i]["address"];
		var phone = markers[i]["phone"];
		var city = markers[i]["city"];
		var state = markers[i]["state"];
		var zip = markers[i]["zip"];
		var degree = markers[i]["degree"];
		var specialties = markers[i]["specialties"];
		var link = markers[i]["link"];
		
		html = getMarkerBubbleBody(providerName, address, phone, city, state, zip, degree, specialties, link);
		
    map.addOverlay(createMarker(point, html, i));
	}
}


function createMarker(latlng, msg, index) {
	
  // Create a base icon for all of our markers that specifies the
  // shadow, icon dimensions, etc.
  var baseIcon = new GIcon(G_DEFAULT_ICON);
  baseIcon.shadow = "/images/markers/shadow50.png";
  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
	
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	var letteredIcon = new GIcon(baseIcon);
  letteredIcon.image = "/images/markers/marker" + letter + ".png";
  // Set up our GMarkerOptions object
  markerOptions = { icon:letteredIcon }; 
          
	var marker = new GMarker(latlng, markerOptions);
	marker.value = msg;
	GEvent.addListener(marker,"click", function() {
		var myHtml = msg;
		map.openInfoWindowHtml(latlng, myHtml);
	});
	
	gmarkers[j] = marker;
	htmls[j] = html;
	j++;
	return marker;
}

function profileClearMarkers()
{
  map.clearOverlays();
  
  gmakers = [];
  htmls = []
  j = 0;
}

function getMarkerBubbleBody(providerName, address, phone, city, state, zip, degree, specialties, link) {
	var html = "";
	
	html += "<P align = 'left'>";
	
	if (providerName != null && providerName != "") {
		html += "<BR>&nbsp;&nbsp;<font style = 'font-size: 11px;'><b><a href = '"+link+"'>"+providerName+", "+degree+/*" | "+specialties+*/"</a></b></font>";
	}
	
	if (address != null && address != "") {
		html += "<BR>&nbsp;&nbsp;<font style = 'font-size: 11px;'>"+address+"</font>";
	}
	
	if (city != null && city != "") {
		html += "<BR>&nbsp;&nbsp;<font style = 'font-size: 11px;'>"+city+", "+state+" "+zip+"</font>";
	}
	
	if (phone != null && phone != "") {
		html += "<BR>&nbsp;&nbsp;<font style = 'font-size: 11px;'>"+phone+"</font>";
	}
	
	html += "<BR><font style = 'font-size: 11px;'>&nbsp;</font>";
	html += "</P>";
	
	return html;
}

// This function picks up the click and opens the corresponding info window
function displayMarkerInfoWindow(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}


function showAddress(address) {
  
  geocoder = new GClientGeocoder();
  alert("Second + " + geocoder);
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, 12);
        }
      }
    );
  }
}

function showDrivingDirections(index) {
	
	fromAddress = "";
	toAddress = "";
	
	var address = markers[index]["address"];
	var city = markers[index]["city"];
	var state = markers[index]["state"];
	var zip = markers[index]["zip"];
	
	finalAddress = address + ", " + city + ", " + state + " " + zip;
	if (document.getElementById('from_to_' + index).value == "from") {
		fromAddress = document.getElementById('direction_address_' + index).value;
		toAddress = finalAddress;
	} else if (document.getElementById('from_to_' + index).value == "to") {
		fromAddress = finalAddress;
		toAddress = document.getElementById('direction_address_' + index).value;
	}
	
	document.getElementById("route").innerHTML = "";
	gdir = new GDirections(map, document.getElementById("route"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    setDirections(fromAddress, toAddress, "en_US");
	
	HideContent('provider_' + index)
	
}

function setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,
            { "locale": locale });
}
 
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 onGDirectionsLoad(){ 
    //alert(gdir);
    var distance = gdir.getDistance();
	//alert(distance);
	var duration = gdir.getDuration();
	//alert(duration);
	var numRoutes = gdir.getNumRoutes();
	//alert(numRoutes);
	
	for (var r = 0 ; r < numRoutes ; r++ ) {
		var route = gdir.getRoute(r);
		var startGeoCode = gdir.getGeocode(r);//route.getStartGeocode();
		var endGeoCode = gdir.getGeocode(r+1);//route.getEndGeocode();
		var endLatLng = route.getEndLatLng();
		var routeSummaryHTML = route.getSummaryHtml();
		var routeDistance = route.getDistance();
		var routeDuration = route.getDuration();
		//alert(routeDistance.html);
	}
	
}

function getMapCenterAddress() {
    latitude = map.getCenter().lat();
    longitude = map.getCenter().lng();
    
    point = new GLatLng(latitude, longitude);
    getAddress(point);
}

function getAddress(latlng) {
  if (latlng != null) {
    address = latlng;
    geocoder.getLocations(latlng, getAddress2);
  }
}

function getAddress2(response) {
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    
    mapCenterAddress = place.address;
    //alert(mapCenterAddress);
  }
}

function getAllDrivingDistance() {
	//getMapCenterAddress();
	//alert("Deepak");
	//alert(mapCenterAddress);
	
	latitude = map.getCenter().lat();
    longitude = map.getCenter().lng();
    
    fromAddress = latitude + "," + longitude;
    
    for (var i = 0; i < markers.length; i++) {
		var lat = parseFloat(markers[i]["lat"]);
		var lng = parseFloat(markers[i]["lng"]);
		
		toAddress = lat + "," + lng;
		
		tempDir = new GDirections(map);
	    GEvent.addListener(tempDir, "load", onGDirectionsLoad2);
	    
	    //alert("from: " + fromAddress + " to: " + toAddress);
	    //tempDir.load("from: " + fromAddress + " to: " + toAddress);
	    
	}
    //map.clearOverlays();
}

function onGDirectionsLoad2(){ 
    //alert(tempDir);
    var distance = tempDir.getDistance();
	
	var duration = tempDir.getDuration();
	//alert(duration);
	var numRoutes = tempDir.getNumRoutes();
	//alert(numRoutes);
	
	for (var r = 0 ; r < numRoutes ; r++ ) {
		var route = tempDir.getRoute(r);
		var startGeoCode = tempDir.getGeocode(r);//route.getStartGeocode();
		var endGeoCode = tempDir.getGeocode(r+1);//route.getEndGeocode();
		var endLatLng = route.getEndLatLng();
		var routeSummaryHTML = route.getSummaryHtml();
		var routeDistance = route.getDistance();
		var routeDuration = route.getDuration();
		alert("Route : " + routeDistance.html);
	}
	
}

function showDrivingDirectionsForProviderProfilePage(index) {
	
	fromAddress = "";
	toAddress = "";
  profileClearMarkers();
	
	var address = markers[index]["address"];
	var city = markers[index]["city"];
	var state = markers[index]["state"];
	var zip = markers[index]["zip"];
	toAddress = address + ", " + city + ", " + state + " " + zip;
	
	providerAddress = document.getElementById('providerAddress').value;
	providerCity = document.getElementById('providerCity').value;
	providerState = document.getElementById('providerState').value;
	providerZip = document.getElementById('providerZip').value;
	
	fromAddress = providerAddress + ", " + providerCity + ", " + providerState + " " + providerZip;
	
	fromAddress = "";
	if (providerAddress != "") {
		fromAddress += providerAddress;
	}
	if (providerCity != "") {
		if (fromAddress != "") {
			fromAddress += ", " + providerCity;
		} else {
			fromAddress += providerCity;
		}
	}
	if (providerState != "") {
		if (fromAddress != "") {
			fromAddress += ", " + providerState;
		} else {
			fromAddress += providerState;
		}
	}
	if (providerZip != "") {
		if (fromAddress != "") {
			fromAddress += " " + providerZip;
		} else {
			fromAddress += providerZip;
		}
	}
	
	document.getElementById("route").innerHTML = "";
	gdir = new GDirections(map, document.getElementById("route"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    setDirections(fromAddress, toAddress, "en_US");
    
}

 
