/*
 * @author    Fred Ghosn (fred.ghosn@revolve.ca)
 * @date      12/7/2007
 * @revision  0.1
 */

var map = null;
var icon = null;
var bounds = null;
var manager = null;
var active = null;    // A reference of the activate store

var minZoom = 3;      // Hide all markers at a level less then this zoom level
var loadPos = 0;      // Marker currently being loaded
var loadAmount  = 20; // Amount of markers to load at each time out
var loadTimeOut = 50; // Timeout in ms after every loaded chunk

window.onload = function() { window.setTimeout(populate, loadTimeOut); } // Start creating markers after the google map and its resources have been completely loaded

$(document).ready(
  function()
  {
    init();
    $("#searchLocationSubmit").click(function(){searchLocation($("#searchLocationProvince").val(),$("#searchLocationCity").val());});
    $("#searchPostalSubmit").click(function(){searchLatLng($("#searchPostalValue").val());});
    $("#searchPostalResults a").click(resetPostalSearch);
  }
);

function init()
{
  map = new GMap2(document.getElementById("map"));
  geocoder = new GClientGeocoder();

  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
  map.disableInfoWindow();

  GEvent.addListener(map, "movestart", function()
    {
      resetMap();
    }
  );

  // Remove shadow from icon to increase load speeds since we are dealing with hundreds of markers
  icon = new GIcon(G_DEFAULT_ICON);
  icon.image = "/images/marker.png";
  icon.shadow = "";

  if ( startPoint.length == 0 )
  {
    defaultCenter();
  } else {
    applyBounds(startPoint);
  }

  manager = new GMarkerManager(this.map);
}

function populate()
{
  if ( loadPos < stores.length )
  {
    var loopCount = Math.min(loadPos + loadAmount, stores.length);
    while (loadPos < loopCount) 
    {
      var marker = new GMarker(new GLatLng(stores[loadPos][1], stores[loadPos][2]), icon);
      marker.store = stores[loadPos];
      GEvent.addListener(marker, "mouseover", function()
        {
          if ( active != null )
          {
            active.setImage("/images/marker.png");
          }
          active = this;
          this.setImage("/images/marker_green.png");
          var html = this.store[4] + "<br />" + this.store[5] + ", " + this.store[6] + "<br />" + this.store[7];
          if ( this.store[8].length > 0 )
          {
            html += "<br/><br/>" + this.store[8];
          }
          setStoreData(this.store[3], html);
        }
      );
      GEvent.addListener(marker, "click", function()
        {
          
          var url = "/?store_id=" + this.store[0];
          if (src != null)
             url += "&cid=66&src="+src;
          
          
           /*
          else if (cid != 0)
            url += "&cid=" + cid;
          */
          
          window.location = url;
        }
      );
      manager.addMarker(marker, minZoom);
      loadPos++;
    }

    $("#count").html(loadPos + " of " + stores.length + " (" + Math.floor((loadPos / stores.length) * 100) + "%)");
    window.setTimeout(populate, loadTimeOut);
  } else {
    $("#loading").css("display","none");
  }
}

function applyBounds(points)
{
  bounds = new GLatLngBounds(
    new GLatLng(points[0], points[1]),
    new GLatLng(points[2], points[3])
  );
  
  // mcam - restrict max zoom level
  var zoom = map.getBoundsZoomLevel(bounds);
  if (zoom > 10)
    zoom = 10;
  map.setCenter(bounds.getCenter(), zoom);
}

function searchLocation(province, city)
{
  resetMap();
  $.getJSON('/dataRequest.php?action=provinceCity&province=' + $("#searchLocationProvince").val() + '&city=' + $("#searchLocationCity").val(), 
    function(bounds)
    {
      if ( bounds.length == 0 )
      {
        geocoder.getLatLng($("#searchLocationProvince :selected").text() + ", Canada", 
          function(point)
          {
            map.setCenter(point, 6);
          }
        );
      } else {
        applyBounds(bounds);
      }
    }
  );
}

function searchLatLng(address)
{
  resetMap();
  geocoder.getLocations(address, 
    function(response)
    {
      if ( response.Status.code == G_GEO_SUCCESS )
      {
        var place = response.Placemark[0];
        $("#searchPostalOptions").css("display","none");
        $("#searchPostalResults").css("display","block");
        $("#searchPostalResults label").html(place.address);
        $.getJSON('/dataRequest.php?action=rangePostal&range=' + $("#searchPostalRange").val() + '&lat=' + place.Point.coordinates[1] + '&lng=' + place.Point.coordinates[0], 
          function(bounds)
          {
            applyBounds(bounds);
          }
        );
      } else {
        $("#searchPostalSubmit").attr("disabled","true");
        $("#searchPostalValue").attr("maxlength","9").attr("disabled","true").val("Not Found");
        window.setTimeout(resetPostalSearch, 1000);
      }
    }
  );
}

function resetPostalSearch()
{
  $("#searchPostalOptions").css("display","block");
  $("#searchPostalResults").css("display","none");
  $("#searchPostalResults label").html("");
  $("#searchPostalValue").attr("maxlength","7").attr("disabled","").val("");
  $("#searchPostalSubmit").attr("disabled","");
}

function setStoreData(title, address)
{
  $("#storeData h3").html(title);
  $("#storeData address").html(address);
}

function resetMap()
{
  resetPostalSearch();
  setStoreData("","");
  if ( active != null )
  {
    active.setImage("/images/marker.png");
    active = null;
  }
}

function defaultCenter()
{
  map.setCenter(new GLatLng(56.170023, -106.347656), 3);
}

function showHelp(){
  $("#help_overlay").css("display","block");
  $("#container").css("opacity", 0.4);
}

function hideHelp(){
  $("#help_overlay").css("display","none");
  $("#container").css("opacity", 1);
}

