

$(document).ready(function() {
  load();
	searchLocations();
  $("#hide-directions").click(function() {
    $("#store-locator-directions").slideToggle("fast");
  });
})

$(document).unload(function() {
  GUnload()  
})

var map;
var geocoder;
var htmls = [];
var gmarkers = [];
var to_htmls = [];
var from_htmls = [];
var reasons = [];
var gdir;

function searchLocations() {
 //inputLoading($('#load-point'));
 if (document.getElementById('addressInput').value == "") {
 	var address = "M2 6DN, UK";
 	
 } else {
 	var address = document.getElementById('addressInput').value + ", UK";
 }
 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 = '/inc/phpsqlsearch_genxml.php?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();

   var sidebar = document.getElementById('store-locator-sidebar');
   sidebar.innerHTML = '';
   if (markers.length == 0) {
     sidebar.innerHTML = 'No results found.';
     map.setCenter(new GLatLng(53, -2), 7);
     //inputLoading($('#load-point'));
     return;
   }

   var bounds = new GLatLngBounds();
   for (var i = 0; i < markers.length; i++) {
     map.setCenter(new GLatLng(53, -2), 7);
     var name = markers[i].getAttribute('name');
     var address = markers[i].getAttribute('address');
     var city = markers[i].getAttribute('city');
     var store_hours = markers[i].getAttribute('store_hours');
     var contact = markers[i].getAttribute('contact');
     var fax = markers[i].getAttribute('fax');
     var email = markers[i].getAttribute('email');
     var postcode = markers[i].getAttribute('postcode');

     var distance = parseFloat(markers[i].getAttribute('distance'));
     
     if(markers[i].getAttribute('lng') == "-2.244591")
     { 
       var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                             parseFloat("-2.245691"));

     }
     else
     {
       var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                             parseFloat(markers[i].getAttribute('lng')));
     }
     var marker = createMarker(point, name, address, store_hours);
     map.addOverlay(marker);
     // reverse geocode to get the city name
     /*
     geocoder.getLocations(point, function (response)
     {
       place = response.Placemark[0];
       city = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
     });
     */
     var sidebarEntry = createSidebarEntry(marker, name, address, distance, city, store_hours, contact, fax, postcode, email);
     sidebar.appendChild(sidebarEntry);
     bounds.extend(point);             
   }
   //inputLoading($('#load-point'));
   $('#store-locator-count').html(markers.length + " Stores in your area");
   map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-1);
 });
 
}

function createMarker(point, name, address, store_hours) {
  var marker = new GMarker(point);
  var i = gmarkers.length;
  
  var html = '<strong>' + name + '</strong><br />' + address;
  to_htmls[i] = html + '<br /><br /><a href="javascript:tohere('+i+')">Repeat directions to here<\/a><input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + '"/>';
 
 	if (document.getElementById("addressInput").value != "" ) {
  	html = html + '<br /><br /><a href="javascript:tohere('+i+')">Get directions to here<\/a>';
  }

  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });
  gmarkers.push(marker);
  htmls[i] = html;
  return marker;
}

function getDirections() {
  var opts = {};
  var saddr = document.getElementById("addressInput").value + ", UK";
  var daddr = document.getElementById("daddr").value
  gdir.load("from: "+saddr+" to: "+daddr, opts);
}

function myclick(i) {
  gmarkers[i].openInfoWindowHtml(htmls[i]);
}

function tohere(i) {
  gmarkers[i].openInfoWindowHtml(to_htmls[i]);
  $("#store-locator-directions").html("").hide();
  getDirections();
  var close_link = "<a id='hide-directions'>Hide directions</a>";
  $("#store-locator-directions").prepend(close_link).slideDown("slow");
  $(document).ready(function() {
    $("#hide-directions").click(function() {
      $("#store-locator-directions").slideToggle("slow").html("");
    });
  })    
}

function createSidebarEntry(marker, name, address, distance, city, store_hours, contact, fax, postcode, email) {
  $("#map").show();$("#store-locator-count").show();
  var div = document.createElement('div');
  var html = '<h4>' + name + '</h4>' + address + '<br />' + city + '<br />' + postcode +  
             '<br /><br /> Tel: ' + contact + '<br /> Fax: ' + fax + '<br /> Email: <a href="mailto:' + email +'" title="Email Us">' + email + '</a>'
             + '<br />(' + distance.toFixed(1) + ' miles)<br/>';
  div.innerHTML = html;
  div.style.cursor = 'pointer';
  div.style.marginBottom = '5px'; 
  $(div).addClass("store-locator-result");
  $(div).attr("id",name);
    
  GEvent.addDomListener(div, 'click', function() {
    GEvent.trigger(marker, 'click');
    
    $('#store-locator-address').html("<h3>" + name + "</h2><strong>Address</strong><br /> " + address);
    if (store_hours != "") {$('#store-locator-store-times').html("<strong>Store times</strong><br /> " + store_hours);}
    if (contact != "") {$('#store-locator-contact').html("<br /><strong>Contact</strong><br /> " + contact);}
    $('#store-locator-details').show("slow");      

  });
  GEvent.addDomListener(div, 'mouseover', function() {
    //div.style.backgroundColor = '#eee';
  });
  GEvent.addDomListener(div, 'mouseout', function() {
    //div.style.backgroundColor = '#fff';
  });
  return div;
}


function load() {
  if (GBrowserIsCompatible()) {
    geocoder = new GClientGeocoder();
    map = new GMap2(document.getElementById('map'));
    map.addControl(new GSmallMapControl());
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    //map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(53, -2), 7);
    gdir = new GDirections(map, document.getElementById("store-locator-directions"));
       
    reasons[G_GEO_SUCCESS]            = "Success";
    reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
    reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
    reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";    
  }
   
  GEvent.addListener(gdir, "error", function() {
    var code = gdir.getStatus().code;
    var reason="Code "+code;
    if (reasons[code]) {
      reason = reasons[code]
    } 
  
    alert("Failed to obtain directions, "+reason);
  });  

}
