/*
 This is just a temp. test file before putting it somewhere real...

 Greg Belote [gbelote@tripadvisor.com]
 03sep08
*/

// these correspond to the constants in tr/com/TripResearch/servlet/eatery/EateryOverviewServlet.java  If you change either, change the other
var ACTION_MAPCHANGED="MAP";
var ACTION_FILTERCHANGED="FILTER";

var updateList = function (offset, sortOrder, action) {
  // We need to 'pack' the price range into bits so we can pass to the URL
  var priceRange = 0;
  var checkboxes = $("PRICE_FORM").priceRange;
  if (checkboxes)
  {
    if(checkboxes.length)
    {
        for (i = 0; i < checkboxes.length; i++)
        {
             if (checkboxes[i].checked)
             {
                  var value = getSubValue(checkboxes[i]);
                  priceRange |= 1 << value;
                  if ($("priceAll"))
                  {
                      $("priceAll").checked = false;
                  }
              }
        }
    } else if (checkboxes.checked)
    {
        priceRange |= 1 << getSubValue(checkboxes);
    }
  }
  
  var filterForm = $("EATERY_FILTER_CONTROLS");
  var cuisine = getValues($("CUISINE_FORM").cuisine);
  var recFor = getValues($("RECFOR_FORM").recfor);
  var options = getValues($("OPTION_FORM").option);
  
  var url = window.location.protocol+'//'+window.location.host+'/RestaurantSearch';

  ops = {
    ajax: 1,
    geo: modelGeoId
  };
  
  var typeInput = filterForm.type;
  if (typeInput) {
    url = window.location.protocol+'//'+window.location.host+'/BusinessCenter';
    ops.t = typeInput.value;
  }

  if (action) ops.Action = action;
  if (offset) ops.o = 'a' + offset;
  if (sortOrder) ops.sortOrder = sortOrder;
  if (cuisine.length > 0) {
	  ops.cat = cuisine; 
	  $("cuisinesAll").checked = false;
  } 
  else {
	  $("cuisinesAll").checked = true;
  }
  if (recFor.length > 0) {
	  ops.src = recFor;
	  $("recforAll").checked = false;
  } 
  else {
	  $("recforAll").checked = true;
  }
  if (options.length > 0) {
	  ops.opt = options;
	  $("optionsAll").checked = false;
  } 
  else {
	  $("optionsAll").checked = true;
  }
  // Note that the price range filter uses the "p" short name parameter
  // in the URL, so we need to set the "pid" query parameter to our
  // packed price range value
  if (priceRange > 0) ops.pid = priceRange;
  
  var mapDiv = $('REST_MAP');
  if (mapDiv && mapDiv.moved) {
    var center = mapDiv.map.mapCenter();
    ops.mc = center.lat() + "," + center.lng();
    ops.mz = mapDiv.map.getZoom();
  }
  if (RESET_MAP_POSITION) {
    ops.mcr = RESET_MAP_POSITION.lat + "," + RESET_MAP_POSITION.lng;
    ops.mzr = RESET_MAP_POSITION.zoom;
  }

  getWaitingOverlay().show();
  
  new Ajax(url, {
    method: 'get',
    data: ops,
    evalScripts: true,
    onComplete: function (txt, xml) {
      $("EATERY_OVERVIEW_BODY").innerHTML = txt;
      getWaitingOverlay().hide();
      window.behavior.apply($("EATERY_OVERVIEW_BODY"));
      var mapDiv = $('REST_MAP');
      if (mapDiv) {
        mapDiv.map.replaceMarkers(REST_MAP_MARKERS, 'restaurant', $merge(ta.maps.MARKER_RESTAURANT, {pid: 1360, titlePID: 1360 }));
      }
    }
  }).request();
};

var eateryUpdateListByFilterChange = function(offset, sortOrder)
{
	updateList(offset, sortOrder, ACTION_FILTERCHANGED);
};

var pageList = function(e) {
  e = new Event(e || window.event).stop();
  var a = $(e.target);
  if (!a.getTag() == 'a') a = a.getParent('a');
  var offset = 0;
  if (a.href.match(/\-oa(\d+)/)) offset = RegExp.$1;
  if(offset > 0) {
      window.location.href=location.href + '#EATERY_OVERVIEW_BOX';
  }
  updateList(offset);
};

var sortList = function(e) {
  updateList(null, this.options[this.selectedIndex].value);
};

rules['#EATERY_LIST_CONTENTS .js_pageLinks a'] = function(elmt) {
  elmt.addEvent('click', pageList);
};

rules['#sortOrder'] = function(elmt) {
  elmt.onchange = null;
  elmt.addEvent('change', sortList.bindAsEventListener(elmt));
};

rules['#REST_MAP_RECENTER'] = function(elmt) {
  elmt.addEvent('click', function() {
    $('REST_MAP').map.reset();
  });
};

var assetDeferFM2 = function(e) {
  var evnt = new Event(e || window.event).stop();
  var src = $(evnt.target);
  fmOnShow(src, true);
  assetDeferFM();
  fmOnShow(src);
};

rules['#REST_OVER'] = function(elmt) {
  var lnks = elmt.getElements('div.floatMap a');
  if (typeof fmThumb != "undefined") {
    var mapDiv = $(mapDivId);
    if (!mapDiv.map) { // haven't built floatable map yet
      fmThumb.addtl = new Array();
      fmThumb.addtl.push(lnks.addEvent('click', fmThumb.myDeferFn));
    }
    else {
      lnks.each(function(l) {fmThumb.fwin.addSource(l);});
    }
  }
  else {
    mapDivId = "mapFMDiv";
    fmThumb = $('REST_FM');
    fmThumb.myDeferFn = assetDeferFM2;
    fmThumb.delay = true;
    fmThumb.addtl = [lnks.addEvent('click', fmThumb.myDeferFn)];
    fmThumb.onShow = fmOnShow;
  }
};

window.addEvent('load', function() {
  if ($('REST_MAP')) {
    (function(){
      // show the loading overlay
      $('REST_MAP').getElement('.loading').show();
      // convert static map into google map
      new Asset.javascript(mapsJs);

      ta.util.load.GMaps(initNearbyMap2);
    }).delay(100);
  }
});

var initNearbyMap2 = function() {
  var mapDiv = $('REST_MAP');
  var ops = window[mapDiv.id];
  if (GBrowserIsCompatible() && ops) {
    mapDiv.empty();
    mapDiv.map = new ta.maps.Map(mapDiv, {
      origLat: ops.lat,
      origLng: ops.lng,
      zoom: ops.zoom,
      smallMap: true,
      typeControl: false,
      //scaleControl: false,
      homeIcon: false
    })
    .addEvent('onMove', mapMoved)
    .addEvent('onZoom', mapZoomed)
    .addEvent('onReset', mapReset)
    .addEvent('homePinOnly', function() {$('REST_ZOOM_ERR').show()})
    .addEvent('allPins', function() {$('REST_ZOOM_ERR').hide();});
    mapDiv.map.origOps = ops;
    
    mapDiv.map.addMarkers(REST_MAP_MARKERS, 'restaurant', $merge(ta.maps.MARKER_RESTAURANT, {pid: 1360, titlePID: 1360 }));
  }
};

var mapMoved = function(zoomChanged) {
  if (zoomChanged || this.gmap2.getZoom() < 10) return; // zoom handled separately; zoomed out too far
  $('REST_MAP_RECENTER').show();
  $('REST_MAP').moved = true;
  updateList(null, null, ACTION_MAPCHANGED);
};

var mapZoomed = function(oldZoom, newZoom) {
  $('REST_MAP_RECENTER').show();
  $('REST_MAP').moved = true;
  if (newZoom < 10) return; // zoomed out too far
  updateList(null, null, ACTION_MAPCHANGED);
};

var mapReset = function() {
  $('REST_MAP_RECENTER').hide();
  $('REST_MAP').moved = false;
  $('add_location_input').value = map_enteraddress;
  ta.maps.Sidebar._clearLocationError();
  $('REST_MAP').map.replaceMarkers([],'location',[]);
  updateList(null, null, ACTION_MAPCHANGED);
};

var _findFirstMarker = function(type, map) {
  if (!map.markers[type]) {
    return;
  }
  var markers = map.markers[type].markers;
  if (!markers || markers.length<=0) {
    return;
  }
  return markers[0];
};

var fmOnShow = function(src, locOnly) {
  if (typeof(src) == "undefined") src = $(new Event(window.event).target);
  if (src.id.match(/restmap(\d+)/)) {
    // Selected restaurant
    var num = RegExp.$1;
    var x = -1;
    for (i = 0; i < REST_MAP_MARKERS.length && x < 0; i++) {
      if (REST_MAP_MARKERS[i].num == num) x = i;
    }
    if (x < 0) return;
    if (locOnly) { // before map is initialized
      window[mapDivId].locId = REST_MAP_MARKERS[x].locId;
      window[mapDivId].lat = REST_MAP_MARKERS[x].lat;
      window[mapDivId].lng = REST_MAP_MARKERS[x].lng;
      return;
    }
    var mapDiv = $(mapDivId);
    mapDiv.map.origOps.locId = REST_MAP_MARKERS[x].locId;
    mapDiv.map.setHome(REST_MAP_MARKERS[x]);
    mapDiv.recenter.setContent(REST_MAP_MARKERS[x].customHover.title);
  } else if (src.id.match(/restmap/)) {
    // No restaurant selected
    var mapDiv = $(mapDivId);
    var smallMapDiv = $('REST_MAP');
    
    if (smallMapDiv) {
      // Change large map to be like the small map
      var center = smallMapDiv.map.mapCenter();
      var lat = center.lat();
      var lng = center.lng();
      var zoom = smallMapDiv.map.getZoom();
      window[mapDivId].lat = lat;
      window[mapDivId].lng = lng;
      window[mapDivId].zoom = zoom;
      if (locOnly) { 
        // before large map is initialized
        return;
      }
      
      // after large map is initialized
      var lgMap = mapDiv.map;
      var homeMarker = _findFirstMarker('location', smallMapDiv.map);
      var title = null;
      if (homeMarker && homeMarker.has_been_added) {
        // There is a home in small map
        title = homeMarker.options.customHover.title;
        lgMap.options.origLat = homeMarker.options.lat;
        lgMap.options.origLng = homeMarker.options.lng;
        // Set home
        var homeMarkerOptions = homeMarker.options;
        homeMarkerOptions.customHover.contents = homeMarker.options.customHover.address+'<br><a target="_blank" rel="nofollow" href="'+homeMarker.options.customHover.titleUrl+'">'+map_drivingdirections+'<a/>';
        lgMap.setHome(homeMarkerOptions);
      } else {
        // There is no home in small map, remove home from large map, reset home title
        lgMap.removeHome();
        title = geoName;
        lgMap.options.origLat = smallMapDiv.map.origOps.lat;
        lgMap.options.origLng = smallMapDiv.map.origOps.lng;
      }
      // Set title in large map sidebar
      mapDiv.recenter.setContent(title);
      // Move large map just like small map
      lgMap._move(lat, lng, zoom);
    }
  }
};

var _newBookingSortValue = function(checked, val) {
  var tmp = val;
  tmp = tmp.replace(/be_/,"");
  if (checked) {
    tmp = "be_" + tmp;
  }
  return tmp;
};

var bookingChanged = function() {
  var sortForm = $('SORT_FORM');
  var checked = $('BOOKING_FORM').sortGroup.checked;

  var sortOrder = null;
  var options = sortForm.getElements('option'); // may be empty if drop down not used
  for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    if (opt.selected) {
      sortOrder = _newBookingSortValue(checked,opt.value);
      break;
    }
  }
  updateList(null,sortOrder,ACTION_FILTERCHANGED);
};

var bookingChanged_Rev1 = function() {
  var fld = $('SORT_FORM').sortOrder;
  var checked = $('BOOKING_FORM') && $('BOOKING_FORM').sortGroup.checked;
  var sortOrder = _newBookingSortValue(checked,fld.value);
  updateList(null,sortOrder,ACTION_FILTERCHANGED);
};

var clearEateryFilters = function() {
    unCheckCheckboxes($("PRICE_FORM").priceRange);
    unCheckCheckboxes($("CUISINE_FORM").cuisine);
    unCheckCheckboxes($("RECFOR_FORM").recfor);
    unCheckCheckboxes($("OPTION_FORM").option);
    $("priceAll").checked = true;
    updateList(null,null,ACTION_FILTERCHANGED);
}

function clearField(elmt)
{
	elmt.value='';
}

function selectAllPrices()
{
	var checkboxes = $("PRICE_FORM").priceRange;
	unCheckCheckboxes(checkboxes);
	updateList(null,null,ACTION_FILTERCHANGED);
}

var selectAllCuisines = function ()
{
	var checkboxes = $("CUISINE_FORM").cuisine;
	unCheckCheckboxes(checkboxes);
	updateList(null,null,ACTION_FILTERCHANGED);
}

function selectAllRecFor()
{
	var checkboxes = $("RECFOR_FORM").recfor;
	unCheckCheckboxes(checkboxes);
	updateList(null,null,ACTION_FILTERCHANGED);
}

function selectAllOptions()
{
	var checkboxes = $("OPTION_FORM").option;
	unCheckCheckboxes(checkboxes);
	updateList(null,null,ACTION_FILTERCHANGED);
}

function unCheckCheckboxes(checkboxes)
{
    if (!checkboxes)
    {
        return;
    }
	if (checkboxes.length)
	{
		for (i = 0; i < checkboxes.length; i++)
		{
		  checkboxes[i].checked = false;
		}	
	} 
	else {
		checkboxes.checked = false;
	}
}

function getWaitingOverlay()
{
	var dialog = ta.retrieve('filters.waitDialog');
    if (!dialog) {
      dialog = new ta.overlays.CenteredOverlay({
        style:'mg s1 fatNotice',
        showCloseButton: false,
        autoShow: false
      });
      dialog.inner.setHTML('<b>'+JS_UpdatingYourResults+'</b>');
      ta.store('filters.waitDialog', dialog);
    }
    return dialog;
}

function getValues(checkboxes)
{
	var value = '';
	//if it's a list of checkboxes, iterate through list
	if (checkboxes && checkboxes.length)
	{
		for (i = 0; i < checkboxes.length; i++)
		{
			if (checkboxes[i].checked)
			{					
				var subValue = getSubValue(checkboxes[i]);
				if (value.length == 0)
				{
					value += subValue;
				} 
				else {
					value += ","+subValue;
				}
			}
		}
	} 
	//if it's just a single checkbox, get value
	else if (checkboxes && checkboxes.checked){
		value = getSubValue(checkboxes);
	}
	//else return null
	return value;
}

function getSubValue(checkbox)
{	
	var idx = checkbox.id.lastIndexOf('_');
	return checkbox.id.substring(idx+1,checkbox.id.length);	
}

/**
 * @class
 * Support functions used for a map sidebar controls
 */
ta.maps.Sidebar = {
  icons: {
    "hotel": "/img2/maps/icons/pinHotel.gif",
    "restaurant": "/img2/maps/icons/pinRestaurant.gif",
    "attraction": "/img2/maps/icons/pinThingToDo.gif"
  },

  _addHotelRestaurantAttraction: function(type, number) {
    var map = ta.retrieve('maps.map');

    var zft = ta.retrieve('zft') || [];
    if (!zft.contains(number)) {
      zft.push(number);
      ta.store('zft', zft);
    }
    ta.servlet.HACSearch.filtersChanged();
    if (map) map.showType(type);
  },

  hotels: function(event, elmt) {
    var map = ta.retrieve('maps.map');

    var zft = ta.retrieve('zft') || [];
    if ($(elmt).checked) {
      ta.maps.Sidebar._addHotelRestaurantAttraction('hotel', 1);
    }
    else {
      zft.remove(1);
      ta.store('zft', zft);
      map.hideType('hotel');
    }

    ta.servlet.HACSearch.filter.update();
    return true;
  },

  restaurants: function(event, elmt) {
    var map = ta.retrieve('maps.map');

    var zft = ta.retrieve('zft') || [];
    if ($(elmt).checked) {
      ta.store('lma', 'BCACMap_Restaurants');
      ta.maps.Sidebar._addHotelRestaurantAttraction('restaurant', 3);
    }
    else {
      zft.remove(3);
      ta.store('zft', zft);
      map.hideType('restaurant');
    }

    ta.servlet.HACSearch.filter.update();
    return true;
  },

  attractions: function(event, elmt) {
    var map = ta.retrieve('maps.map');

    var zft = ta.retrieve('zft');
    if ($(elmt).checked) {
      ta.store('lma', 'BCACMap_ThingsToDo');
      ta.maps.Sidebar._addHotelRestaurantAttraction('attraction', 2);
    }
    else {
      zft.remove(2);
      ta.store('zft', zft);
      map.hideType('attraction');
    }

    ta.servlet.HACSearch.filter.update();
    return true;
  },

  /**
   * Object storing data for each landmark type.
   */
  landmarkData: {
    "coffee": {query: "Coffee", iconIndex: 4, action: 'BCACMap_Coffee'},
    "copy": {query: "Copy Center", iconIndex: 5, action: 'BCACMap_Copy'},
    "shipping": {query: "Fedex, Shipping", iconIndex: 6, action: 'BCACMap_Shipping'},
    "rail": {query: "Rail stations", iconIndex: 10, action: 'BCACMap_Rail'}
  },

  _landmarkSearchCallback: function(type, searcher, click) {
    var map = ta.retrieve('maps.map');
    var bounds = map.mapBounds();

    var lst = [];
    for (var i = 0; i < searcher.results.length; i++) {
      var x = searcher.results[i];
      var contents = new Element('div');
      var query = x.titleNoFormatting;
      if (x.addressLines) {
        x.addressLines.each(function(l) {
          contents.adopt(new Element('div').setText(l));
        });
        query = x.addressLines.join(", ");
      }
      contents.adopt(new Element('a', { 'href': map_gmaps_address_url + encodeURIComponent(query) }).setText(map_drivingdirections));

      var opt = {
        lat: x.lat,
        lng: x.lng,
        customHover: {
          title: x.titleNoFormatting,
          titleUrl: x.url,
          contents: contents
        }
      };
      var point = new GLatLng(x.lat, x.lng);
      if (bounds.containsLatLng(point)) {
        lst.push(opt);
      }
    }

    map.replaceMarkers(lst, type,
                       $merge(ta.maps.MARKER_HOTEL, {
                         anchorX: 5, anchorY: 30,
                         pinIndex: 7, iconIndex: ta.maps.Sidebar.landmarkData[type].iconIndex
                       }));
  },

  _landmarkSearch: function(type, click) {
    var map = ta.retrieve('maps.map');

    if (!$defined(google.search.LocalSearch)) {
      ta.maps.Sidebar._landmarkSearch.delay(1000, this, [type,click]);
      return;
    }

    var searcher = new google.search.LocalSearch();
    searcher.setCenterPoint(map.mapCenter());
    searcher.setResultSetSize(google.search.Search.LARGE_RESULTSET);
    searcher.setSearchCompleteCallback(this, function() { ta.maps.Sidebar._landmarkSearchCallback(type, searcher, click); });

    var fn = function() {searcher.execute(ta.maps.Sidebar.landmarkData[type].query);};
    fn.delay(250);
  },

  addLandmark: function(type) {
    var landmarks = ta.retrieve('maps.landmarks');
    var map = ta.retrieve('maps.map');

    if (map) map.showType(type);
    if (!landmarks.contains(type)) {
      landmarks.push(type);
    }
    ta.store('maps.landmarks', landmarks);
    ta.maps.Sidebar._landmarkSearch(type, 1);
  },

  /**
   * Event handler called when a landmark that involves Google Local Search is clicked,
   * and handles either hiding the existing markers or calling out to Google and putting
   * the search results on the map.
   */
  toggleLandmark: function(event, elmt) {

    var map = ta.retrieve('maps.map');
    var landmarks = ta.retrieve('maps.landmarks');
    var type = elmt.getProperty('id').substr(8);

    if ($(elmt).checked) {
      new Ajax('/ActionRecord?action=' + ta.maps.Sidebar.landmarkData[type].action).request();
      ta.maps.Sidebar.addLandmark(type);
    }
    else {
      landmarks.remove(type);
      ta.store('maps.landmarks', landmarks);
      map.hideType(type);
    }

    ta.servlet.HACSearch.filter.update();

    return true;
  },
  
  reloadLandmarks: function() {
    var landmarks = ta.retrieve('maps.landmarks');
    landmarks.each(function(type) {
      ta.maps.Sidebar._landmarkSearch(type);
    });
  },

  togglePOI: function(event, elmt) {

    var map = ta.retrieve('maps.map');
    var marker = elmt.marker;
    var type = elmt.poiType;
    var pois = ta.retrieve('maps.' + type);
    var point = null;
    var iconIndex = -1;
    var source = '';

    if (type == 'airports') {
      iconIndex = 9;
      source = 'BCACMap_Airport';
    }
    else {
      iconIndex = 8;
      source = 'BCACMap_ConventionCtr';
    }

    if ($(elmt).checked) {
      if (!pois.contains(marker)) {
        pois.push(marker);
        point = new GLatLng(marker.lat, marker.lng);
      }
      new Ajax('/ActionRecord?action=' + source).request();
    }
    else {
      pois.remove(marker);
    }

    if (map) {
      map.replaceMarkers(pois, type,
                         $merge(ta.maps.MARKER_HOTEL, {
                           anchorX: 5, anchorY: 30,
                           pinIndex: 7,
                           iconIndex: iconIndex
                         }));

      if (point != null) {
        map.zoomAndPanToFit(point.lat(), point.lng());
      }

      map.showType(type);
    }
    ta.servlet.HACSearch.filter.update();
  },

  _openAccordion: function(accordionElmt, poiType, prefix) {
    if (!accordionElmt.hasClass('on')) {
      accordionElmt.toggleClass('on');
    }

    if (!ta.retrieve('maps.' + poiType)) {
      ta.store('maps.' + poiType, []);      
    }

    var listElmt = accordionElmt.getNext("div");
    listElmt.removeClass("hidden");

    if (!listElmt.init) {
      var pois = ta.retrieve('maps.nearbyPOIs')[poiType];
      if (pois != null) {
        pois.markers.each(function(p) {
          var airportCode = '_' + p.customHover.title.match(/[A-Z]{3}/);
          var input = new Element('input', {'type': 'checkbox',
                                            'name': prefix + p.locId + airportCode,
                                            'id':   prefix + p.locId + airportCode })
                              .addEvent('click', function(e) { ta.call('ta.maps.Sidebar.togglePOI', e); });
          var label = new Element('label', {'for': prefix + p.locId + airportCode}).setText(p.customHover.title);
          var divContainer = new Element('div', {'class': 'poiContainer'});
          var div1 = new Element('div', {'class': 'checkbox'});
          var div2 = new Element('div', {'class': 'label'});
          div1.adopt(input);
          div2.adopt(label);

          input.marker = p;
          input.poiType = poiType;
          divContainer.adopt(div1);
          divContainer.adopt(div2);
          listElmt.adopt(divContainer);
        });
      }
      listElmt.init = true;
    }
  },

  _closeAccordion: function(accordionElmt, type) {
    if (accordionElmt.hasClass('on')) {
      accordionElmt.toggleClass('on');
    }

    var listElmt = $(accordionElmt.getNext("div"));
    listElmt.addClass("hidden");
  },

  /**
   * Event handler called when the airports accordion is clicked on, which handles
   * either opening or closing the accordion.  If opening the accordion, it automatically
   * closes the convention centers accordion if open.
   */
  toggleAirports: function(event, elmt) {
    if (elmt.getTag() != "div") {
      elmt = elmt.getParent("div");
    }

    if (!elmt.hasClass('on')) {
      ta.maps.Sidebar._closeAccordion($('toggle_convention_centers'), 'conventionCenters');
      if($('toggle_nearby_cities')) ta.maps.Sidebar._closeAccordion($('toggle_nearby_cities'), 'nearbyCities');
      ta.maps.Sidebar._openAccordion($('toggle_airports'), 'airports', 'airport_');
    }
    else {
      ta.maps.Sidebar._closeAccordion($('toggle_airports'), 'airports');
    }

    ta.servlet.HACSearch.filter.update();
  },

  /**
   * Event handler called when the convention centers accordion is clicked on, which handles
   * either opening or closing the accordion.  If opening the accordion, it automatically
   * closes the airports accordion if open.
   */
  toggleConventionCenters: function(event, elmt) {
    if (elmt.getTag() != "div") {
      elmt = elmt.getParent("div");
    }

    if (!elmt.hasClass('on')) {
      ta.maps.Sidebar._closeAccordion($('toggle_airports'), 'airports');
      if($('toggle_nearby_cities')) ta.maps.Sidebar._closeAccordion($('toggle_nearby_cities'), 'nearbyCities');
      ta.maps.Sidebar._openAccordion($('toggle_convention_centers'), 'conventionCenters', 'convention_center_');
    }
    else {
      ta.maps.Sidebar._closeAccordion($('toggle_convention_centers'), 'conventionCenters');
    }

    ta.servlet.HACSearch.filter.update();
  },

  toggleNearbyCities: function(event, elmt) {
    if (elmt.getTag() != "div") {
      elmt = elmt.getParent("div");
    }

    if (!elmt.hasClass('on')) {
      ta.maps.Sidebar.openNearbyCities();
    }
    else {
      ta.maps.Sidebar._closeAccordion($('toggle_nearby_cities'), 'nearbyCities');
    }

    ta.servlet.HACSearch.filter.update();
  },

  openNearbyCities: function(event, elmt) {
    ta.maps.Sidebar._closeAccordion($('toggle_airports'), 'airports');
    ta.maps.Sidebar._closeAccordion($('toggle_convention_centers'), 'conventionCenters');
    ta.maps.Sidebar._openAccordion($('toggle_nearby_cities'), 'nearbyCities', 'cities_');
  },


  /**
   * Event handler called when the map is morphed.
   */
  mapMorphed: function(idx, map) {
    if (idx == 0) {  // changing to thumbnail
      var landmarks = ta.retrieve('maps.landmarks');
      landmarks.each(function(type) {
        map.hideType(type);
      });
      $('MAPPROMO').setStyle('display', 'block');
      new Ajax('/ActionRecord?action=BCACMap_close').request();
    }
    else if (idx == 1) {  // changing to large map
      var landmarks = ta.retrieve('maps.landmarks');
      landmarks.each(function(type) {
        map.showType(type);
      });
      $('MAPPROMO').setStyle('display', 'none');
      var source = ta.remove('maps.morphBigSource') || 't';
      ta.store('lma', 'BCACMap_' + source + '_open');

    }

    var ret = ta.servlet.HACSearch.mapMorphed(idx, map);

    if (idx == 1 && ta.has('maps.queuedSidebar')) {
      var queuedFunctions = ta.remove('maps.queuedSidebar');
      queuedFunctions.each(function(fn) { fn(); });
    }

    return ret;
  },

  /**
   * Event handler called when the map is moved.
   */
  mapMoved: function(zoomChanged, zoom) {
    ta.maps.Sidebar.reloadLandmarks();

    return ta.servlet.HACSearch.mapMoved(zoomChanged, zoom);
  },

  /**
   * Event handler called when the map is zoomed.
   */
  mapZoomed: function(oldZoom, newZoom) {
    ta.maps.Sidebar.reloadLandmarks();

    return ta.servlet.HACSearch.mapZoomed(oldZoom, newZoom);
  },

  /**
   * Event handler called when the map is reset.
   */
  mapReset: function() {
    ta.maps.Sidebar.reloadLandmarks();

    // for non-business center, the location bar gets cleared by a map reset
    if (pageServlet != 'BusinessCenter') {      
      ta.maps.Sidebar._clearLocation();
    }

    return ta.servlet.HACSearch.mapReset();
  },

  _removeLocation: function() {
    var map = ta.retrieve('maps.map');
    map.hideType('location');
  },
  
  addLocationPopup: function(event, elmt) {
    if ($("add_location_text").getText() == map_removeaddress) {
      ta.maps.Sidebar._removeLocation();
      $("add_location_text").setText(map_addaddress);                
    }
    else {
      $('add_location').removeClass('hidden');
    }
  },

  closeAddLocationPopup: function(event, elmt) {
    $('add_location').addClass('hidden');
    var input = $("add_location_input");
    if(input)
    {
      input.value = map_addresstemplate;
      input.addClass('unfocused'); 
    }
    var input_filter = $("add_location_input_filter");
    if(input_filter)
    {
      input_filter.value = "";
      input_filter.addClass('unfocused'); 
    }   
    $("add_location_error").setText('');
    $("add_location_error").addClass("hidden");
    $("add_location_header").removeClass("error");
  },

  clearAddLocationBox: function(event, elmt) {
    if (elmt.hasClass('unfocused')) {
      elmt.value = '';
      elmt.removeClass('unfocused');
    }
  },

  _addLocation: function(address) {
    var map = ta.retrieve('maps.map');
    // if we aren't using popup version of add location, we need to write
    // the address into the search box
    if (!$("add_location")) {
      var input = $("add_location_input");
      if(input)
      {
        input.value = address;
        input.removeClass("unfocused");
      }
      var input_filter = $("add_location_input_filter");
      if(input_filter)
      {
        input_filter.value = address;
        input_filter.removeClass("unfocused");
      }
    }
    if (!map)
    {
      	map = $('REST_MAP').map;
        ta.store('maps.map',map);
    }

    // send off to geocoding
    var geocoder = new GClientGeocoder();
    geocoder.setViewport(map.mapBounds());
    geocoder.getLatLng(address, ta.maps.Sidebar._addLocationCallback);
  },

  addLocation: function(event, elmt) {
    var text = "";
    var input = $("add_location_input");
    if(input)
    {
      text = input.value;
    }
    var input_filter = $("add_location_input_filter");
    if(input_filter)
    {
      text = input_filter.value;
    }   
    
    // if not popup version of add location, then empty address means remove marker
    if (!$("add_location") && (text.length == 0 || text == map_enteraddress)) {
      ta.maps.Sidebar._clearLocation();
      if (!$("REST_MAP"))
      {
    	  ta.servlet.HACSearch.filter.update();
      }
      return false;
    }

    if (text != map_enteraddress) {
        ta.store('maps.address', text);
        ta.maps.Sidebar._addLocation(text);
        if (!$("REST_MAP"))
        {
        	new Ajax('/ActionRecord?action=BCACMap_MapIt').request();
        	ta.servlet.HACSearch.filter.update();
        }
    }
    return false;
  },
  
  _clearLocation: function() {
    ta.maps.Sidebar._removeLocation();
    ta.maps.Sidebar._clearLocationError();
    var input = $("add_location_input");
    if(input)
    {
      input.value = map_enteraddress;
      input.addClass("unfocused");
    }
    var input_filter = $("add_location_input_filter");
    if(input_filter)
    {
      input_filter.value = "";
      input_filter.addClass("unfocused");
    }   
 },
  
  _setLocationError: function(errorMsg) {
    $("add_location_error").setText(errorMsg);
    $("add_location_error").removeClass("hidden");
    if ($("add_location_header")) {
      $("add_location_header").addClass("error");
    } else {
      var input = $("add_location_input");
      if(input)
      {
        input.addClass("error");
      }
      var input_filter = $("add_location_input_filter");
      if(input_filter)
      {
        input_filter.addClass("error");
      }   
      if ($("add_location_text"))
      {
         $("add_location_text").addClass("error");
      }   
    }    
  },
  
  _clearLocationError: function() {
    $("add_location_error").addClass("hidden");
    if ($("add_location")) {
      if ($("add_location_text"))
      {
         $("add_location_text").setText(map_removeaddress);
      }
      $("add_location").addClass("hidden");
      $("add_location_header").removeClass("error");
      var input = $("add_location_input");
      if(input)
      {
        input.value = map_addresstemplate;
      }
      var input_filter = $("add_location_input_filter");
      if(input_filter)
      {
        input_filter.value = "";
      }   
    } else {
      var input = $("add_location_input");
      if(input)
      {
        input.removeClass("error");
      }
      var input_filter = $("add_location_input_filter");
      if(input_filter)
      {
        input_filter.removeClass("error");
      }   
      if ($("add_location_text"))
      {
         $("add_location_text").removeClass("error");      
      }    
    }    
  },

  _addLocationCallback: function(point) {
    if (point == null) {
      ta.maps.Sidebar._setLocationError(map_addressnotfound);
      return;
    }

    var map = ta.retrieve('maps.map');
    var center = map.mapCenter();
    var dist = center.distanceFrom(point) / 1609.344;  // meter -> mile

    if (dist > 100) {
      ta.maps.Sidebar._setLocationError(map_addressnotfound2.replace('{0}', geoName));
      return;
    }

    var address = ta.retrieve('maps.address');
    var titleUrl = map_gmaps_address_url + encodeURIComponent(address);

    ta.maps.Sidebar._clearLocationError();
    var marker = [{
                    lat: point.lat(),
                    lng: point.lng(),
                    customHover: {
                      title: map_myaddress,
                      address: address,
                      titleUrl: titleUrl,
                      contents: new Element('div').setText(address)
                        .adopt(new Element('br'))
                        .adopt(new Element('a', {'target': '_blank', 'rel': 'nofollow', 'href': titleUrl}).setText(map_drivingdirections))
                    }}];
    var options = { anchorX: 5, anchorY: 30, 
      pinSize: new ta.support.Size(23,28), pinOffset: 102, pinIndex: 1, hoverIndex: 2,
      shadowSize: new ta.support.Size(23,28), shadowOffset: 102, shadowIndex: 0,
      iconSize: new ta.support.Size(19,23), iconOffset: 18, iconIndex: 0,
      iconOffsetX: 2, iconOffsetY: 2
    }
    
    if (ta.has('storeLocation')) {
      ta.store('map.location.marker', marker);
      ta.store('map.location.options', options);
    }
   
    map.replaceMarkers(marker ,'location', options);
    map.showType('location');
    
    if ($('REST_MAP_RECENTER'))
    {
    	$('REST_MAP_RECENTER').show();
    }

    map._move(point.lat(), point.lng(), map.getZoom());
    
    if ($('REST_MAP'))
    {
    	updateList(null,null,ACTION_MAPCHANGED);
    }
  },

  morphBigPromo: function(event, elmt) {
    ta.store('maps.morphBigSource', 'p');
    return ta.servlet.HACSearch.morphBig(event, elmt);
  }
};
