/**
* Google maps store locator functions
*
*/

// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];

// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];

var map;

// for submit on enter
function submitenter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
  	{
	   searchLocations();
   	   return false;
   	}
	else
   	   return true;
}


function load() {
  if (GBrowserIsCompatible()) {
    geocoder = new GClientGeocoder();
    var mapElement = document.getElementById('map');
    
    map = new GMap2(mapElement);
    //map.disableDragging();
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(40, -100), 4); 
    showAllLocations();
  }
}

function searchLocations() {
 var address = document.getElementById('addressInput').value;
 geocoder.getLatLng(address, function(latlng) {
   if (!latlng) {
     alert(address + ' not found');
   } else {
     searchLocationsNear(latlng);
   }
 });
}

function searchLocationsNear(center) {
 var radius = document.getElementById('radiusSelect').value;
 var searchUrl = 'locator.php?showall=1&lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;

 GDownloadUrl(searchUrl, function(data) {
   var xml = GXml.parse(data);
   var markers = xml.documentElement.getElementsByTagName('marker');

   map.clearOverlays();

   if (markers.length == 0) {
	alert("Sorry, no stores were found near this location, please try again.");
	return;
   }

   var bounds = new GLatLngBounds();
   for (var i = 0; i < markers.length; i++) {
     var mname = markers[i].getAttribute('mname');
     var name = markers[i].getAttribute('name');
     var address = markers[i].getAttribute('address');
     var distance = parseFloat(markers[i].getAttribute('distance'));
     var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
			     parseFloat(markers[i].getAttribute('lng')));
     var city = markers[i].getAttribute('city');
     var state = markers[i].getAttribute('state');
     var zip = markers[i].getAttribute('zip');
     var phone = markers[i].getAttribute('phone');
     var website = markers[i].getAttribute('website');
     
     var marker = createMarker(point, name, address, city, state, zip, phone, website);
     map.addOverlay(marker);
     bounds.extend(point);
   }
   addSearchZipMarker(center);
   map.setCenter(bounds.getCenter(), Math.min(map.getBoundsZoomLevel(bounds),12));
 });
}

function showAllLocations() {
 var searchUrl = 'locator.php?showall=1&lat=39.8&lng=-98.55&radius=700';
 GDownloadUrl(searchUrl, function(data) {
   var xml = GXml.parse(data);
   var markers = xml.documentElement.getElementsByTagName('marker');
   map.clearOverlays();
   
//   if (markers.length == 0) {	
//	alert("Sorry, markers were 0.");
//	return;}

   var bounds = new GLatLngBounds();
   for (var i = 0; i < markers.length; i++) {
     var mname = markers[i].getAttribute('mname');
     var name = markers[i].getAttribute('name');
     var address = markers[i].getAttribute('address');
     var distance = parseFloat(markers[i].getAttribute('distance'));
     var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
			     parseFloat(markers[i].getAttribute('lng')));
     var city = markers[i].getAttribute('city');
     var state = markers[i].getAttribute('state');
     var zip = markers[i].getAttribute('zip');
     var phone = markers[i].getAttribute('phone');
     var website = markers[i].getAttribute('website');
     
     var marker = createMarker(point, name, address, city, state, zip, phone, website);
     //var tooltip = new Tooltip(marker, name, 4);
     //marker.tooltip = tooltip;
     map.addOverlay(marker);
     //map.addOverlay(tooltip);
     GEvent.addListener(marker,'mouseover',function(){ this.tooltip.show(); }); 
     GEvent.addListener(marker,'mouseout', function(){ this.tooltip.hide(); });

     bounds.extend(point);
   }
   map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
 });
}

function createMarker(point, name, address, city, state, zip, phone, website) {
  var marker = new GMarker(point, {title: name + " in " + city});

  var html = '<div id="locator-info">' + name + '<br/>' + 
	      address + '<br/>' +
	      city + ',' + state + ' ' + zip + '<br/>' +
	      phone + '<br/>';
  if (website.length) {
     html += '<a href="http://'+ website + '">' + website + '</a><br/>';
  }

  var i = gmarkers.length;

  // The info window version with the "to here" form open
  to_htmls[i] = html + 'Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
       '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT">' +
       '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
	      // "(" + name + ")" + 
       '"/></div>';

  // The inactive version of the direction info
  html = html + '<a href="javascript:tohere('+i+')">Get directions<\/a></div>';

  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });

  // save the info we need to use later for the side_bar
  gmarkers.push(marker);
  htmls[i] = html;
  return marker;
}

function addSearchZipMarker(center) {
    var tinyIcon = new GIcon();
    tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    tinyIcon.iconSize = new GSize(12, 20);
    tinyIcon.shadowSize = new GSize(22, 20);
    tinyIcon.iconAnchor = new GPoint(6, 20);
    tinyIcon.infoWindowAnchor = new GPoint(5, 1);

    var point = new GLatLng(center.lat(), center.lng());
    var marker = new GMarker(point, {title: document.getElementById('addressInput').value, icon: tinyIcon});
    map.addOverlay(marker);
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
    gmarkers[i].openInfoWindowHtml(htmls[i]);
}

// functions that open the directions forms
function tohere(i) {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}


function createSidebarEntry(marker, name, address, distance) {
  var div = document.createElement('div');
  var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address;
  div.innerHTML = html;
  div.style.cursor = 'pointer';
  div.style.marginBottom = '5px'; 
  GEvent.addDomListener(div, 'click', function() {
    GEvent.trigger(marker, 'click');
  });
  GEvent.addDomListener(div, 'mouseover', function() {
    div.style.backgroundColor = '#eee';
  });
  GEvent.addDomListener(div, 'mouseout', function() {
    div.style.backgroundColor = '#fff';
  });
  return div;
}
