var PZMaps = {};

PZMaps.pz_maps = {};
PZMaps.pz_all_bricks = {};
PZMaps.brick_markers = {};
PZMaps.reletter_bricks_on_sort = true;
PZMaps.have_maps = true;

PZMaps.alerts = false;
PZMaps.alert = function(msg) {
  if (PZMaps.alerts) {
    alert(msg);
  }
}

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
PZMaps.createBaseIcon = function() {
  bicon = new GIcon(G_DEFAULT_ICON);
  bicon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  //      baseIcon.iconSize = new GSize(20, 34);
  bicon.iconSize = new GSize(35, 35);
  bicon.shadowSize = new GSize(37, 34);
  bicon.iconAnchor = new GPoint(9, 34);
  bicon.infoWindowAnchor = new GPoint(9, 2);
  return bicon
}

PZMaps.getBaseIcon = function() {
  if (! PZMaps.memoBaseIcon) {
    PZMaps.memoBaseIcon = PZMaps.createBaseIcon();
  }
  return PZMaps.memoBaseIcon;
}

PZMaps.createMarker = function(marker_info) {

  // var letter = String.fromCharCode("a".charCodeAt(0) + marker_info.index);
  var letteredIcon = new GIcon(PZMaps.getBaseIcon());
  //	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
  if (PZMaps.click_overlay) {
    letteredIcon.iconSize = new GSize(49, 42);

    letteredIcon.image = "/images/etailer/map_marker.png" 
  } else {
    letteredIcon.image = PZMaps.icon_for_letter(marker_info.map_marker);
  }

  // Set up our GmarkerOptions object
  markerOptions = { icon:letteredIcon };

  var marker = new GMarker(marker_info.point, markerOptions);
  GEvent.addListener(marker,"click",function() {
    PZMaps.focusPoint(marker,marker_info);
    //      marker.openInfoWindowHtml(marker_info.msg);
  });
  return marker;
}

PZMaps.focusPoint = function(marker,marker_info) {
  marker.openInfoWindowHtml(marker_info.msg);
  if (currentFocus) {
    Element.hide("brick-details-"+currentFocus);
    Element.removeClassName("sidebar-item-"+currentFocus,"current");
  }
  Element.addClassName("sidebar-item-"+marker_info.id,"current");
  Element.show("brick-details-"+marker_info.id);
  currentFocus = marker_info.id;
}


PZMaps.initialize_map = function(dom_id, in_bricks_map, map_location) {
  if (GBrowserIsCompatible() && typeof in_bricks_map != 'undefined') {
    var map = new GMap2(document.getElementById(dom_id));
    map.setCenter( new GLatLng(42.3448,-71.0865), 14);
    map.addControl(new GSmallMapControl());


    // Clicking the marker will hide it



    var bounds = new GLatLngBounds;
    var bricks_for_map = jQuery.grep(in_bricks_map, function(el) {
      return ((map_location == 'all') || (el.map == map_location))
    });
    jQuery.each(bricks_for_map, function(i, brick) {
      var marker_info = new Object();
      marker_info.point = new GLatLng(brick.lat, brick.lng);
      marker_info.msg = "<div id=\"gpopup\">" +
      "<div class=\"popup_fees_container\"><span class=\"popup_fees\">" + brick.fee_text + "</span>";
      if (brick.package_fees == 'y') {
        marker_info.msg += "<br/>Pay at store<br/>" +
         "1st package<span class=\"popup_fees\"> FREE</span>";
       }
      marker_info.msg += "</div>" +
      "<b>" + brick.display_name  + "</b><br />" +
        brick.street + "<br /><br />" +
        
        "Hours:<br />" + brick.link + brick.hours + "</div>";
      marker_info.id = brick.id;
      marker_info.index = i;
      marker_info.map_marker = brick.map_marker;
      PZMaps.pz_all_bricks[brick.id] = marker_info;
      bounds.extend(marker_info.point);
      var new_marker = PZMaps.createMarker(marker_info);
      PZMaps.brick_markers[brick.id] = new_marker;
      map.addOverlay(new_marker);
    });
    PZMaps.recenter_map(map, bounds);
  }
  return [map, bounds];
}

PZMaps.change_brick_icon = function(map, brick_id, letter) {
  var marker_info = PZMaps.pz_all_bricks[brick_id];
  marker_info.map_marker = letter;
  var new_marker = PZMaps.createMarker(marker_info);
  old_marker = PZMaps.brick_markers[brick_id];
  if (old_marker) {
    map.removeOverlay(old_marker);
  }
  PZMaps.brick_markers[brick_id] = new_marker;
  map.addOverlay(new_marker);
}

PZMaps.icon_for_letter = function(letter) {
  return "/images/mapicons/" + letter + ".gif";
}

PZMaps.recenter_map = function(map, bounds) {
  // NB: If/when offset is 1, remove one from the zoom level to zoom out a bit more; sometimes it's too tightly cropped
  var offset = 0;
  var new_bounds = map.getBoundsZoomLevel(bounds) - offset;
  if (new_bounds < 0) {
    new_bounds = 0;
  }
  map.setCenter(bounds.getCenter(), new_bounds);
}

PZMaps.pz_selected_map_key = null;

PZMaps.selected_map = function() {
  return PZMaps.pz_selected_map_key;
}

PZMaps.switch_map_code = function(key) {

	PZMaps.pz_selected_map_key = key;
	
  // the rows of bricks
    if (key == 'all') {
      jQuery('.map_row').show()
    } else {
      jQuery('.map_row').hide();
      jQuery('.map_row_' + key).show();
    }
	
  PZMaps.reset_alternate_bricks_table();
}

PZMaps.reset_alternate_bricks_table = function() {
  jQuery('#bricks_table .brick_body:visible:odd').addClass('odd');
  jQuery('#bricks_table .brick_body:visible:even').removeClass('odd');
  
  // e-Tailer
  jQuery('#bricks_table .brick_body:odd').addClass('listrow');
  jQuery('#bricks_table .brick_body:even').removeClass('listrow');
  jQuery('#bricks_table .brick_body:even').addClass('listrow_alt');
  jQuery('#bricks_table .brick_body:odd').removeClass('listrow_alt');
}

PZMaps.switch_map = function(key) {

	// the map itself
	jQuery('.map').hide();
	jQuery('#map_' + key).show();

	// tabs
	jQuery('.mktab_link').removeClass('selected');
	jQuery('#mktab_' + key).addClass('selected');
	
	if (PZMaps.have_maps) {
		PZMaps.alert("switch_map running with key " + key);
		var pz_map_info = PZMaps.pz_maps[key];
		var map = pz_map_info[0];
		var bounds = pz_map_info[1];
		map.checkResize();
  		PZMaps.recenter_map(map, bounds);
	}
}

PZMaps.map_for_key = function(key) {
	var pz_map_info = PZMaps.pz_maps[key];
	var map = pz_map_info[0];
  return map;
}


PZMaps.add_search_marker_and_recenter_current_map = function(lat, lng, closest_brick_ids) {
	var pz_map_info = PZMaps.pz_maps[PZMaps.pz_selected_map_key];
	var map = pz_map_info[0];
	var old_user_marker = pz_map_info.old_user_marker;
	if (old_user_marker) {
		map.removeOverlay(old_user_marker);
	}

	var bounds = new GLatLngBounds;
	var index = 0; // sigh... do we have a slice in jquery?
	jQuery.each(closest_brick_ids, function(i, brick_id) {
		 if (index < 2) {  // first two
       var marker_info = PZMaps.pz_all_bricks[brick_id];
       if (marker_info) {
         bounds.extend(marker_info.point);
     		 index += 1;
       }
     }
	});
	var marker = PZMaps.add_search_marker(map, bounds, lat, lng);
	pz_map_info.old_user_marker = marker;
	// which also recenters...

}

PZMaps.reorder_listing = function(closest_brick_ids) {

	var pz_map_info = PZMaps.pz_maps[PZMaps.pz_selected_map_key];

	var pz_sorter = function(x, y) {
		xid = jQuery(x).attr('id').replace('brick_id_', '');
		yid = jQuery(y).attr('id').replace('brick_id_', '');
		x_index = jQuery.inArray(parseInt(xid), closest_brick_ids);
		y_index = jQuery.inArray(parseInt(yid), closest_brick_ids);
		if (x_index > y_index) {
			return 1;
		}
		if (y_index > x_index) {
			return -1
		}
		return 0;
	}
	
  
	// now re-order the listing
  jQuery('#bricks_table .brick_body').sort(pz_sorter).appendTo('#bricks_table'); 
  
	PZMaps.reset_alternate_bricks_table();

  if ((PZMaps.have_maps) && (PZMaps.reletter_bricks_on_sort)) {
    // NB: Without the :visible, we'd be assigning letters to stores that are hidden because they are in other maps/markets/metro-regions
    jQuery('#bricks_table .brick_body:visible').each(function(index, tbody) {
      var brick_id = parseInt(jQuery(tbody).attr('id').replace('brick_id_', ''));
      var letter = String.fromCharCode("a".charCodeAt(0) + index);
      var letter_uppercase = String.fromCharCode("A".charCodeAt(0) + index);
	  var map = pz_map_info[0];
      PZMaps.change_brick_icon(map, brick_id, letter);
      jQuery("#brick_letter_" + brick_id).html(letter_uppercase);
    });
  }
}


PZMaps.add_search_marker = function(map, bounds, lat, lng) {
    var marker_info = new Object();
    marker_info.point = new GLatLng(lat, lng);
    markerOptions = {};

    var marker = new GMarker(marker_info.point, markerOptions);

    bounds.extend(marker_info.point);
    map.addOverlay(marker);

    PZMaps.recenter_map(map, bounds);
    return marker;
}


PZMaps.reset_ui = function() {
	jQuery('#no_location_close_enough').hide();
	jQuery('input#entered_zip').attr({'value': ''});
}

PZMaps.set_location = function(location) {
	jQuery('input#entered_zip').attr({'value': location});
}

PZMaps.have_map_tab = function() {
  return (jQuery('#map_tab').get().length > 0);
}

PZMaps.map_tab_visible = function() {
  return (jQuery('#map_tab:visible').get().length > 0);
}

PZMaps.results_deferred = {};

PZMaps.results_callback = function(data) {
  var brick_id = data['closest_brick_id'];

    jQuery('#no_location_close_enough').hide();
    if (brick_id == null) {
      jQuery('#no_location_close_enough').show();
    } else {

      var closest_brick_ids = data['brick_ids'];
      var lat = data['lat'];
      var lng = data['lng'];
      var map_code = data['map'];

      PZMaps.switch_map_code(map_code);

      PZMaps.reorder_listing(closest_brick_ids);

      PZMaps.alert('have ' + PZMaps.have_map_tab().toString());
      PZMaps.alert('visible ' + PZMaps.map_tab_visible().toString());
      if ((PZMaps.have_map_tab()) && (! PZMaps.map_tab_visible())) {
        PZMaps.alert('going to defer... have map tab and not visible. map_code = ' + map_code);
        PZMaps.results_deferred = {
          'lat' : lat,
          'lng' : lng,
          'closest_brick_ids' : closest_brick_ids,
          'map_code' : map_code
        }
      } else {
        PZMaps.results_callback_map(lat, lng, closest_brick_ids, map_code)
      }

    }
}

PZMaps.restore_map_tab = function() {
  var d = PZMaps.results_deferred;
  if ($H(d).keys().size() > 0) {
    PZMaps.alert('running deferred... map_code is ' + d['map_code'] + d.toString());
    PZMaps.results_callback_map(d['lat'], d['lng'], d['closest_brick_ids'], d['map_code']);
    PZMaps.results_deferred = {};
  } else {
    PZMaps.alert('Nothing to run deferred...');
  }
}

PZMaps.results_callback_map = function(lat, lng, closest_brick_ids, map_code) {
//  if (map_code != PZMaps.selected_map()) {
  PZMaps.switch_map(map_code);
//  }
  if (PZMaps.have_maps) {
  	var new_marker = PZMaps.add_search_marker_and_recenter_current_map(lat, lng, closest_brick_ids);
  }
}

PZMaps.zip_callback = function(data) {
	//alert(data); 
	var brick_id = data;
	var dom_id = '#brick_id_' + brick_id;
	jQuery('.map_row').removeClass('selected');  // unselect all the rows
	jQuery(dom_id).addClass('selected'); // select our row
}