var map;
var bounds;
var icon;

$(document).ready(function() {
  map = new GMap2(document.getElementById("productMap"));
  defaultCenter();
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  
  icon = new GIcon(G_DEFAULT_ICON);
  icon.image = 'images/marker.png';
  icon.shadow = '';
  icon.iconSize = new GSize(40, 27);
  
  bounds = new GLatLngBounds();

  $(".productList > li > a.header").click(function(e) { 
    $(this).find("+ ul").slideToggle("fast");
  });

  $(".productList > li > a.header").hover(function() { 
    $(this).addClass("hover");
  },function() {
    $(this).removeClass("hover");
  });

  $(".productList ul li").hover(function() { 
    $(this).addClass("hover");
  },function() {
    $(this).removeClass("hover");
  });
  
  $(".productList ul").click(function(e) { 
    var t = getTarget(e);
    if ( t.nodeName.toLowerCase() === "li" ) {
      $("a#statusBar").html(t.innerHTML);
      loadStoreMarkers(t.id.substr(1));
      window.location = "#pmap";
    }
  });
});

function defaultCenter() {
  map.setCenter(new GLatLng(45.305803, -63.017578), 7);
}

function createMarker(point, json) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "mouseover", function() {
    marker.openInfoWindowHtml("<strong>" + json.name + "</strong><br />" + json.city + ", NS<br /><br /><a href=\"?cid=12&id=" + json.id + "\">View this Store</a>");
  });
  return marker;
}

function loadStoreMarkers(productId) {
  $.getJSON("dr.php?a=GetStoresByProduct&id=" + productId, function(json) {
    map.clearOverlays();
    bounds = new GLatLngBounds();

    if ( json.length == 0 ) {
      defaultCenter();
      alert("We currently have no producers in our database who have this product.");
      return false;
    }

    for( i = 0; i < json.length; i++ ) {
      var point  = new GLatLng(json[i].lat, json[i].lng);
      var marker = createMarker(point, json[i]);
      bounds.extend(point);
      map.addOverlay(marker);
    }

    defaultCenter();
    //ss.smoothScroll();
  });
}
