
/*----
 * Author: Greg Davidson (syncopated.ca) for Edge Marketing Corp.
 * Use Google's geocoding service to geocode each address in the page,
 * add a marker to the map and an info window with the Company details.
 *
--*/
jQuery(function(){

var retailers = [];
var geocoder = new GClientGeocoder();
var bounds = new GLatLngBounds();

soleIcon = new GIcon();
soleIcon.image = "/media/images/maps/map-pin.png";
soleIcon.shadow = "/media/images/maps/map-pin-shadow.png";
soleIcon.iconSize = new GSize(36, 36);
soleIcon.shadowSize = new GSize(56, 36);
soleIcon.iconAnchor = new GPoint(18, 36);
soleIcon.infoWindowAnchor = new GPoint(18,0);
 

  var retailerCount = $('.adr').length;
  if(retailerCount > 0 ) {
	  var map = new google.maps.Map2(document.getElementById('map'));
	  map.addControl(new GSmallMapControl());
  } else {
    $('#retailer-map-canvas').hide();
  }


	$('.adr').each(function(i){
		var retailer = $(this);
		var company = retailer.find('.name').text();
		var address = retailer.find('.address').text();
		var address2 = retailer.find('.address2').text();
		var city = retailer.find('.city').text();
		var province = retailer.find('.state').text();
		var zip = retailer.find('.zip').text();
    var telephone = retailer.find('.phone').text();
    var address_combined = address + ', ' + address2; 
		var fullAddress = address_combined + ', ' + city + ', ' + province + ', ' + zip;

    setTimeout(function(){
      geocoder.getLocations(fullAddress, function(response){
        if(!response || response.Status.code != 200){
          // put the status code in the page (but keep it hidden)
          $('.address').eq(i).after('<p class="error" style="display: none;">Address: ' + fullAddress + ' not found. Google status code: ' + response.Status.code + '</p>');
        } else {
          place = response.Placemark[0];
          point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
          geo_address = place.address;
          bounds.extend(point); 
          map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
          marker = createMarker(point, company, geo_address, telephone, i);
          map.addOverlay(marker);
        }
		  });
    }, i * 300); //Seems to work well with 300ms delay to allow for geocoding on the fly
	});
});

function createMarker(point, company, geo_address, telephone, index) {
  var markerOptions = { icon:soleIcon };
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, 'click', function(){
		var html = '<div class="bubble"><h4>' + company + '</h4><p>' + geo_address + '<br />' + telephone +'</p></div>';
		marker.openInfoWindow(html);
	});

	GEvent.addListener(marker, 'infowindowopen', function(i){
		$('.adr').eq(index).addClass('hilite');
	});
	GEvent.addListener(marker, 'infowindowclose', function(i){
		$('.adr').eq(index).removeClass('hilite');
	});
	return marker;
}

$(window).unload(GUnload());

