var the_hotel = {
  is_the_hotel: true,
  id: 0,
  list_name: 'New York Marriott East Side',
  name: 'New York Marriott East Side',
  caption: '2011 PACA Conference Site',
  addr1: '525 Lexington Avenue at 49th Street',
  addr2: '',
  zip: '10017',
  phone: '(212) 755-4000',
  url: 'http://www.marriott.com/hotels/travel/nycea-new-york-marriott-east-side/',
  durl: 'www.marriott.com',
  lat: 40.7556200,
  lng: -73.9728770,
  polyline: null,
  distance_meters: null,
  distance_html: null,
  duration_seconds: null,
  duration_html: null
};
var map;
var hotel_marker;
var tt;

// create a sort function for jQuery ... why is this not standard??
jQuery.fn.sort = function() {
  return this.pushStack(jQuery.makeArray([].sort.apply(this,arguments)));
};

var icons = [];
icons[0] = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_purple.png');
icons[1] = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_blue.png');
icons[2] = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_yellow.png');
icons[3] = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_green.png');
icons[4] = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_orange.png');
icons[5] = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_gray.png');

$(document).ready(function() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(40.7556200, -73.9728770), 13);
  
    setupGetMarkers(map);
    setupZoomToMarkers(map);
    setupSetTooltip(GMarker);
    setupGetInfoWindowOpener(map); // GMarker by default
  
    tt = new BpTooltip();
    map.addOverlay(tt);

    var hotel_icon = new GIcon(G_DEFAULT_ICON, '/map/images/icons/marker_default.png');
    hotel_marker = new GMarker(new GLatLng(the_hotel.lat, the_hotel.lng), { icon: hotel_icon });
    map.addOverlay(hotel_marker);
    hotel_marker.setTooltip(tt, the_hotel.name);
    hotel_marker._data = the_hotel;
    GEvent.addListener(hotel_marker, 'click', function(){
      this.openInfoWindowHtml(get_info_window_content(this));
    });


    $.ajax({
      type: 'GET',
      url: '/map/js/config.js',
      error: function(){alert('There has been an error.\nPlease try back again later.')},
      success: function(js){
        try {
          window.paca = eval(js)[0];
          // load the sidebar, await further instructions
          $(paca.categories).each(function(i,cat){
            // add the category to the sidebar
            var p = document.createElement('p');
            // p.innerHTML = '<a href="javascript:void(0)" title="Show all..." onclick="return show_category(' + this.id + ');">' + this.name + '</a>';
            p.innerHTML = this.name + '<span style="font-weight:normal"> (<a href="javascript:void(0)" onclick="return show_category(' + this.id + ');">' + 'show all</a>)</span>';
            $('#list')[0].appendChild(p);
            var ul = document.createElement('ul');
            ul.setAttribute('id', 'group_' + (i+1));
            $('#list')[0].appendChild(ul);
            
            // add the locations for this category
            if (typeof this.locations == 'undefined')
              this.locations = [];
            $(this.locations).sort(function(a,b){
              return parseInt(a.distance_meters) - parseInt(b.distance_meters);
            }).each(function(){
              var li = document.createElement('li');
              var a = document.createElement('a');
              a.setAttribute('href', 'javascript:show_one_marker(' + this.id + ');');
              if (this.caption != '')
                a.setAttribute('title', this.caption);
              a.setAttribute('onmouseover', 'onOver(' + this.id + ')');
              a.setAttribute('onmouseout',   'onOut(' + this.id + ')');
              a.innerHTML = this.list_name;
              var txt = document.createTextNode(this.distance_meters == 0 ? ' (onsite)' : ' (' + this.distance_html + ')');
              li.appendChild(a);
              li.appendChild(txt);
              ul.appendChild(li);

              // add the marker to the map
              var m = new GMarker(new GLatLng(this.lat, this.lng), {icon: icons[i]}); // icon based on group
              map.addOverlay(m);
              m.setTooltip(tt, this.name);
              m.hide();
              m._data = this;
              m._data.category = cat.id;
              GEvent.addListener(m, 'click', function(){
                this.openInfoWindowHtml(get_info_window_content(m));
              });
              this._marker = m;
            });
          });
          map.checkResize();
        }
        catch (e) {
          alert(e); //'There has been an error.\nI cannot understand the configuration file.\nTry refreshing your browser a few times, or come back later.');
        }
      }
    });
  }
  else {
    alert('Your browser does not support Google Maps.\nPlease consider upgrading.');
  }
});

function onOver(id){
  var m = map.getMarkerById(id,'id','_data');
  if (m && !m.isHidden())
    m.showTooltip();
}

function onOut(id){
  var m = map.getMarkerById(id,'id','_data');
  if (m && !m.isHidden())
    m.hideTooltip();
}

function show_category(cid) {
  // hide the old markers and remove the polylines
  $(map.getMarkers()).each(function(){
    if (this !== hotel_marker) {
      if (map.getInfoWindowOpener() === this)
        map.closeInfoWindow();
      this.hide();
    }
  });
  $(map.getPolylines()).each(function(){
    map.removeOverlay(this);
  });

  // add this category
  $(map.getMarkers()).each(function(){
    if (this._data.category == cid) {
      this.show();
    }
  });

  map.zoomToMarkers(.1);
}

function show_polyline(m) {
  if (!m._data.polyline) {
    var points = [];
    $(m._data.polyline_points).each(function(){
      points.push(new GLatLng(parseFloat(this.lat), parseFloat(this.lng)));
    });
    m._data.polyline = new BpPolyline(points);
  }
  map.addOverlay(m._data.polyline);
}

function hide_polyline() {
  if (this._data.polyline && this._data.polyline.isMapped())
    map.removeOverlay(this._data.polyline);
}

var current_location = null;
function get_info_window_content(m) {
  var d = m._data;
  current_location = m._data;

  var addr = d.addr1 + ', New York, NY ' + d.zip;

  var links = '<p class="links"><a href="http://maps.google.com/maps?f=d&saddr=525+Lexington+Avenue,+New+York,+NY+10017&daddr=' + addr.replace(/ /g, '+') + '&layer=c&dirflg=w&cbll=40.7556200,-73.9728770&panoid=Hl_e_c2w79gCRyyPtF46bw&cbp=1,0,,0,5" target="_blank">Get directions</a> - <a href="mailto:?Subject=' + escape(d.name) + '&Body=' + escape(get_info_window_content_txt(m)) + '">Send</a></p>';

  var html =
    '<div class="mapInfo">' +
    '<h1>' + d.name + '</h1>' +
    (d.caption ? '<h2>(' + d.caption + ')</h2>' : '') +

    '<p>' + d.addr1 + '<br />' +
    (d.addr2 ? d.addr2 + '<br/>' : '') + 
    'New York, NY ' + d.zip + '<br />' +
    d.phone + '<br />' +
    '<a href="' + d.url + '" target="_blank">' + d.durl + '</a></p>' +
    links +
    '</div>';

  return html;
}

function get_info_window_content_txt(m) {
  var d = m._data;
  current_location = m._data;

  var html =
    d.name + '\n' +
    (d.caption ? '(' + d.caption + ')\n' : '\n') +
    d.addr1 + '\n' +
    (d.addr2 ? d.addr2 + '\n' : '') + 
    'New York, NY ' + d.zip + '\n' +
    d.phone + '\n' +
    d.url;

  return html;
}

function getEmailBody(d) {
  var txt = '';
  return txt;
}

function hide_markers() {
  map.closeInfoWindow();

  $(map.getMarkers()).each(function(){
    if (this !== hotel_marker) {
      this.hide();
      if (this._data.polyline && this._data.polyline.isMapped())
        map.removeOverlay(this._data.polyline);
    }
  });
}

function show_one_marker(m) {
  if (/^\d+$/.test(m)) { // it's an id
    $(map.getMarkers()).each(function(){
      if (this._data.id == m)
        m = this;
    });
  }

  hide_markers();
  m.show();
  show_polyline(m);
  map.zoomToMarkers(.1);
}


