var map, geocoder, startAddress;
var markerImg = [
"http://www.cabdepot.com/imgs/markers/red_a.png",
"http://www.cabdepot.com/imgs/markers/red_b.png",
"http://www.cabdepot.com/imgs/markers/yellow_a.png",//3 yellow
"http://www.cabdepot.com/imgs/markers/yellow_b.png"
];
var markerList = [];
var markerHTML = [];
var markerInfoShown, markerOnTop;
var sidebar, sidebarEntries = [], directions='';

var n=1; // for z indexing
function count()
{
	n++;
	return n;
}

function searchLocations()
{
  var address = document.getElementById('address').value;
  startAddress = address;
  geocoder.getLatLng(address, function(latlng) {
    if (!latlng) {
      alert('Specified address not found (' + address + ')');
    } else {
      searchLocationsNear(latlng, address);
    }
  });
}
function searchLocationsNear(center, startAddress)
{
  var searchUrl = 'controller.php?action=dealerlocator&lat=' + center.lat() + '&long=' + center.lng();
  GDownloadUrl(searchUrl, function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName('marker');
    map.clearOverlays();

    sidebar = document.getElementById('sidebar');
	// set global variables to blank
    sidebar.innerHTML = '';
	markerList = [];
	markerHTML = [];
	sidebarEntries = [];
	directions = '';	
	
    if (markers.length == 0) {
      sidebar.innerHTML = 'No results found.';
      map.setCenter(new GLatLng(40, -100), 4);
      return;
    }
	
    var bounds = new GLatLngBounds();
	var i;
    for (i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute('name');
      var address1 = markers[i].getAttribute('address');
	  var city = markers[i].getAttribute('city');
	  var state = markers[i].getAttribute('state');
	  var zip = markers[i].getAttribute('zip');
	  var phone = formatPhone(markers[i].getAttribute('phone'));
      var distance = parseFloat(markers[i].getAttribute('distance'));
      var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
	  	var address = new Array(address1, city, state, zip, phone);
      markerList[i] = createMarker(point, name, address, i);
	  markerList[i].setImage(markerImg[1]); // end img
	  sidebarEntries[i] = createSidebarEntry(markerList[i], name, address, distance, i);
      sidebar.appendChild(sidebarEntries[i]);
      bounds.extend(point);
    }
	
	point = new GLatLng(parseFloat(center.lat()), parseFloat(center.lng()));
	markerList[i] = createMarker(point, name, startAddress, i, 'start');
	map.addOverlay(markerList[i]);
	markerList[i].setImage(markerImg[0]);
	bounds.extend(point);
	
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
  });
}
function createMarker(point, name, address, i, type)
{
	function sendBack(marker,b)
	{
		return count()*1000;
	}
	
	var marker = new GMarker(point,{zIndexProcess:sendBack});
	map.addOverlay(marker);
	var elem = document.getElementById("sidebar").getElementsByTagName("div")[i];
	if (type == undefined) // end
	{
		GEvent.addListener(marker, 'mouseout', function()
			{
				marker.setImage(markerImg[1]);
				if (elem != undefined)
					document.getElementById("sidebar").getElementsByTagName("div")[i].style.background="none";
			}
		);
		GEvent.addListener(marker, 'mouseover', function()
			{
				marker.setImage(markerImg[3]);
				if (elem != undefined)
					elem.style.background="#fcee21";
			}
		);
		if (markerHTML[i] == undefined)
		{
			for (var k=0; k<address.length; k++)
			{
					address[k].replace("'", "");
			}
			markerHTML[i] = '<b>' + name + '</b><br>' + address[0] + '<br>' + address[1] + ', ' + address[2] + ' ' + address[3] + '<br>' + address[4] + '<br><a href="javascript:getDirections(\'from: ' + startAddress + ' to: ' + address[0] + ', ' + address[1] + ', ' + address[2] + ', ' + address[3] + '\');">Get Directions</a>';
		}
	}
	else if (type == 'start') // start
	{
		GEvent.addListener(marker, 'mouseout', function()
			{
				marker.setImage(markerImg[0]);
			}
		);
		GEvent.addListener(marker, 'mouseover', function()
			{
				marker.setImage(markerImg[2]);
			}
		);
		markerHTML[i] = address;
	}

	GEvent.addListener(marker, 'click', function()
		{
			marker.openInfoWindowHtml(markerHTML[i]);
			markerInfoShown = i;
		}
	);
	GEvent.addListener(marker, "infowindowclose", function()
		{
			markerInfoShown = -1;
		}
	);

	return marker;
}
function createSidebarEntry(marker, name, address, distance, i)
{
  var div = document.createElement('div');
  var html = "<span style='display: block;' ";
  	if (i != undefined)
	{
	  html += "onclick='GEvent.trigger(markerList["+i+"],\"click\")' ";
	  html += "onmouseover='GEvent.trigger(markerList["+i+"],\"mouseover\")' ";
	  html += "onmouseout='GEvent.trigger(markerList["+i+"],\"mouseout\")' ";
	}
	  html += ">";
      html += name + ' (' + distance.toFixed(1) + ' km)<br>' + address[0] + '<br>' + address[1] + ', ' + address[2] + ' ' + address[3] + '<br>' + address[4];
	  html += "<hr></span>";
  div.innerHTML = html;
  div.style.cursor = 'pointer';
  div.style.marginBottom = '5px';
  GEvent.addDomListener(div, 'click', function() {
	GEvent.trigger(markerList[i], 'mouseover');
    GEvent.trigger(markerList[i], 'click');
  });
  GEvent.addDomListener(div, 'mouseover', function() {
	var infowindowopen = false;
	if (markerInfoShown == i)
	{
		infowindowopen = true;
	}

	if (markerOnTop != i)
	{
		map.removeOverlay(marker);
		marker = createMarker(marker.getPoint(), undefined, undefined, i, undefined);
		marker.setImage(markerImg[1]);
		markerList[i] = marker;
		markerOnTop = i;
	}
    GEvent.trigger(markerList[i], 'mouseover');
	if (infowindowopen)
	{
		GEvent.trigger(markerList[i], 'click');
	}
  });
  GEvent.addDomListener(div, 'mouseout', function() {
    GEvent.trigger(markerList[i], 'mouseout');
  });
  return div;
}
function load()
{
	if (GBrowserIsCompatible())
	{
		geocoder = new GClientGeocoder();
		map = new GMap2(document.getElementById('map'));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(40, -100), 4);
	}
}
function getDirections(instructions)
{
	sidebar.innerHTML = '<a href="javascript:removeDirections()">Return to Dealer List</a>';
	directionsPanel = sidebar;
	directions = new GDirections(map, directionsPanel);
	GEvent.addListener(directions, "error", handleDirectionErrors) 	
	directions.load(instructions);
}
function handleDirectionErrors(obj)
{
	var code = obj.getStatus().code;
	var error;
	switch (parseInt(code))
	{
		case 400:
			error = 'A directions request could not be successfully parsed. For example, the request may have been rejected if it contained more than the maximum number of waypoints allowed.';
			break;
		case 500:
			error = 'A geocoding, directions or maximum zoom level request could not be successfully processed, yet the exact reason for the failure is not known.';
			break;
		case 601:
			error = 'The HTTP q parameter was either missing or had no value. For geocoding requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.';
			break;
		case 602:
			error = 'No corresponding geographic location could be found for the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect.';
			break;
		case 603:
			error = 'The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.';
			break;
		case 604:
			error = 'The GDirections object could not compute directions between the points mentioned in the query. This is usually because there is no route available between the two points, or because we do not have data for routing in that region.';
			break;
		case 610:
			error = 'The given key is either invalid or does not match the domain for which it was given.';
			break;
		case 620:
			error = 'The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time.';
			break;
		default:
			error = 'An unknown error has occured.';
			break;
	}
	sidebar.innerHTML += '<br>'+error;
}
function removeDirections()
{
	directions.clear();
	directions = '';
	sidebar.innerHTML='';
	for(var i=0; i<sidebarEntries.length; i++)
	{
		sidebar.appendChild(sidebarEntries[i]);	
	}
}