var stores = new Array();

Ext.onReady(function() {
  var googleMap;
  var MAX_ZOOM_LEVEL = 14;
  var markers = new Object();

  GMap2.prototype.centerAndZoomOnBounds = function(bounds, maxZoom) {
    var largerBounds = bounds.extendByRatio(0.05);
    var center_lat = (largerBounds.getNorthEast().lat() + largerBounds.getSouthWest().lat()) / 2.0;
    var center_lng = (largerBounds.getNorthEast().lng() + largerBounds.getSouthWest().lng()) / 2.0;
    var zoom = googleMap.getBoundsZoomLevel(largerBounds);

    if (zoom > maxZoom) {
      zoom = maxZoom;
    }

    googleMap.setCenter(new GLatLng(center_lat, center_lng), zoom)
  }

  GLatLngBounds.prototype.extendByRatio = function(ratio) {
    // initialize bounds to be the same as original
    var largerBounds = new GLatLngBounds(this.getSouthWest(), this.getNorthEast());
    // get lat, lng of north east and south west
    var northEastLat = this.getNorthEast().lat();
    var northEastLng = this.getNorthEast().lng();
    var southWestLat = this.getSouthWest().lat();
    var southWestLng = this.getSouthWest().lng();
    var diffLat = northEastLat - southWestLat;
    var diffLng = northEastLng - southWestLng;
    // multiply with ratio
    northEastLat += diffLat * ratio;
    southWestLat -= diffLat * ratio;
    northEastLng += diffLng * ratio;
    southWestLng -= diffLng * ratio;
    // extend north east
    largerBounds.extend(new GLatLng(northEastLat, northEastLng));
    // extend south west
    largerBounds.extend(new GLatLng(southWestLat, southWestLng));

    return largerBounds;
  }

  function initMap() {
    googleMap = new GMap2(Ext.get("map").dom);
    googleMap.addControl(new GLargeMapControl());
    googleMap.addControl(new GMapTypeControl());
    googleMap.setCenter(new GLatLng(38, -90), 3);

    var bounds = new GLatLngBounds();
    for (i = 0; i < stores.length; i++) {
      var store = stores[i];
      addStoreToMap(store, googleMap, bounds);
    }

    zoomToState(null, true);
  }

  function zoomToState(event, showAll) {
    var selectedStateCode = "ALL";
    if (!showAll) {
      var select = event.target;
      selectedStateCode = select.options[select.selectedIndex].value;
      
    }
        
    //if we have an info window open for another state etc, close it now
    googleMap.closeInfoWindow();


    var bounds = new GLatLngBounds();
    for (i = 0; i < stores.length; i++) {
      var store = stores[i];
      var id = store.storeId;
      var stateElement = Ext.get("store_"+ id).dom;
      var stateHeaderElement = Ext.get("state_"+ store.state + "_header").dom;

      stateElement.style.display = (selectedStateCode == null || selectedStateCode == '' || stateElement.getAttribute('state') == selectedStateCode || selectedStateCode == "ALL") ? 'block' : 'none';
      stateHeaderElement.style.display = stateElement.style.display;

      if (store.state == selectedStateCode || selectedStateCode == "ALL") {
        var storeLocation = new GLatLng(store.latitude, store.longitude);
        bounds.extend(storeLocation);
        markers[store.storeId].show();
      } else {
        markers[store.storeId].hide();
      }
    }



    googleMap.centerAndZoomOnBounds(bounds, MAX_ZOOM_LEVEL);
  }

  function addStoreToMap(store, googleMap, bounds) {
    var point = new GLatLng(store.latitude, store.longitude);
    if (point) {
      bounds.extend(point);
      var marker = new GMarker(point);
      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(getInfoWindowHtmlForStore(store));
      });
      markers[store.storeId] = marker;
      googleMap.addOverlay(marker);
    }
    //else {
    //  alert("null point for store " + store.storeId);
    //}
  }

  function getInfoWindowHtmlForStore(store) {
    return '<div class="mapBubble">' +
            '<b>' + store.name + '</b><br/>' +
            store.address + '<br/>' +
            store.city + ', ' + store.state + ' ' + store.zip + '<br/>' +
            'Main Line: ' + store.phone + '<br/><br/>' +
            '<form action="http://maps.googleapis.com/maps/api/js?sensor=true" method="get" target="_blank">' +
            '<input type="text" size="20" maxlength="40" name="saddr" id="saddr" value=""/>&nbsp;' +
            '<input value="Get Directions" type="submit"/>' +
            '<input type="hidden" name="daddr" value="' + store.address + ' ' + store.city + ', ' + store.state + '"/>' +
            '</form>' +
            '</div>';
  }

  function popUpStoreInfoWindow(event) {

    var target = event.getTarget();
    var storeId = target.getAttribute("storemarkerid");

    if (!storeId) {
      storeId = target.getAttributeNS(null, "storemarkerid");
    }

    for (i=0; i<stores.length; i++) {
      var store = stores[i];
      if (storeId == store.storeId) {
        markers[store.storeId].openInfoWindowHtml(getInfoWindowHtmlForStore(store));
      } else {
        markers[store.storeId].closeInfoWindow();
      }
    }
  }
 
  //we use jquery change event model here since I couldn't get the Ext onchange event to work fast enough -Matias
  initMap();

  $("#states").change(zoomToState);
  
  var storeLinkElements = Ext.select("A[storemarkerid]", false, "storeAddressHolder");
  storeLinkElements.on("click", popUpStoreInfoWindow);
});


function openMap(add){
	var url = "http://www.google.com/maps?f=q&hl=en&q=" + add + "&ie=UTF8&om=1";
	var wingooglemap = window.open(url, 'googlemap', 'scrollbars=yes,status=no,scrollbars=no,menubar=no,location=no,resizable=yes');
	wingooglemap.focus();
}

function openDirection(add){
	var url = "http://www.google.com/maps?f=d&hl=en&saddr=&daddr=" + add + "&ie=UTF8&om=1";
	var wingooglemap = window.open(url, 'googlemap', 'scrollbars=yes,status=no,scrollbars=no,menubar=no,location=no,resizable=yes');
	wingooglemap.focus();
}



