/*
  copyright 2010 Google Maps Tools
  http://www.gmaptools.com/
  mapper @ gmaptools.com

*/



var map;
var hotel_marker;
var tt;
window.current_marker = null;

// 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, 'img/marker_purple.png');
icons[1] = new GIcon(G_DEFAULT_ICON, 'img/marker_blue.png');
icons[2] = new GIcon(G_DEFAULT_ICON, 'img/marker_yellow.png');
icons[3] = new GIcon(G_DEFAULT_ICON, 'img/marker_green.png');
icons[4] = new GIcon(G_DEFAULT_ICON, 'img/marker_orange.png');
icons[5] = new GIcon(G_DEFAULT_ICON, 'img/marker_gray.png');

function onMapResize() {
  $('#map').width($(window).width() - 262);
  $('#list').height( $(window).height() );
  map.checkResize();
}

$(document).ready(function() {
  if (GBrowserIsCompatible()) {

    $('#top_sidebar_link').html(window.the_hotel.name);

    // set the sizes of the map and list
    var w = $(window);
    var window_width  = w.width();
    var map_div = $('#map');
    map_div.width(window_width - 262);
    $('#list').height( w.height() );

    // Monitor the window resize event and let the map know when it occurs 
    if (window.attachEvent) {
      window.attachEvent("onresize", onMapResize);
    }
    else {
      window.addEventListener("resize", onMapResize, false);
    }

    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(the_hotel.lat, the_hotel.lng), 13);

    setupGetMarkers(map);
    setupZoomToMarkers(map);
    setupSetTooltip(GMarker);
    setupGetInfoWindowOpener(map); // GMarker by default
  
    tt = new BpTooltip();
    map.addOverlay(tt);

    var hotel_icon = G_DEFAULT_ICON; // new GIcon(G_DEFAULT_ICON, 'img/marker_red.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));
    });


    // this is the id for the current apartment complex, the central location for the map
    var apartment_complex_id = document.location.href.replace(/^.+=(\d+)$/, '$1');
    $.ajax({
      type: 'GET',
      url: 'config/config-' + apartment_complex_id + '.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
          var first_category_id = false;
          $(paca.categories).each(function(i,cat) {
            // add the category to the sidebar
            var p = document.createElement('p');
            p.id = 'category-p-' + this.id;
            if (!first_category_id) {
              first_category_id = this.id;
            }
            p.innerHTML = '<img id="category-image-' + this.id + '" src="img/expand-icon.gif" onclick="sidebar_category_image_clicked(' + this.id + ');" />&nbsp;<a href="javascript:void(0)" id="category-link-' + this.id + '" title="Show all..." onclick="return show_category(' + this.id + ');">' + this.name + '</a>';
            $('#list')[0].appendChild(p);

//            p.category_id = this.id;

            var ul = document.createElement('ul');
            ul.setAttribute('id', 'group_' + (i+1));
            $('#list')[0].appendChild(ul);
            ul.style.display = 'none';
            p.location_list = 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, 10) - parseInt(b.distance_meters, 10);
            }).each(function(){
              var li = document.createElement('li');
              var a = document.createElement('a');
              a.setAttribute('href', 'javascript:show_one_marker(' + this.id + ');');
              if (/\S/.test(this.caption)) {
                a.title = this.caption;
              }
              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);

              var the_location_id = this.id;
              $(a).bind('mouseover',  function(){ onOver(the_location_id);  });
              $(a).bind('mouseout',   function(){ onOut(the_location_id);   });

              // 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();

//          map.setCenter(hotel_marker.getLatLng());
          $('#category-link-' + first_category_id).click();

        }
        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 sidebar_category_image_clicked(id) {
  // collapse all other categories
  $('p[id^=category-p-]').each(function() {
    if (!new RegExp('-' + id + '$').test(this.id)) {
      this.location_list.style.display = 'none';
//      $(this.location_list).slideUp();

      $('#' + this.id.replace(/p/, 'image'))[0].src = 'img/expand-icon.gif';
    }
  })

  // change the icon
  var img = $('#category-image-' + id)[0];
  if (/collapse/.test(img.src)) {
    img.src = 'img/expand-icon.gif';
  }
  else {
    img.src = 'img/collapse-icon.gif';
  }

  // remove all markers from the map, regardless of category
  hide_markers();

  // expand/collapse the category
  var list = $('#category-p-' + id)[0].location_list;
  if (list.style.display == 'none') {
//    list.style.display = '';
    $(list).slideDown();

    // add this category
    $(map.getMarkers()).each(function() {
      if (this._data.category == id) {
        this.show();
      }
    });
    map.zoomToMarkers(.1);
  }
  else {
    list.style.display = 'none';
//    $(list).slideUp();
  }
}

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

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

function show_category(cid) {
  window.current_marker = null;

  // if this is already expanded, collapse it
  var list = $('#category-p-' + cid)[0].location_list;
  if (list.style.display != 'none') {
    sidebar_category_image_clicked(cid);
    return;
  }

  // expand this category, unless it's already expanded
  if ($('#category-p-' + cid)[0].location_list.style.display == 'none') {
    sidebar_category_image_clicked(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 = escape(d.addr1) + ', ' + escape(d.city) + ', ' + escape(d.state) + ' ' + escape(d.zip);

  var links = '<p class="links"><a href="http://maps.google.com/maps?f=d&saddr=' + escape(the_hotel.addr1 + (the_hotel.addr2 ? ' ' + the_hotel.addr2 : '')) + ',+' + escape(the_hotel.city) + ',+' + escape(the_hotel.state) + '+' + escape(the_hotel.zip) + '&daddr=' + addr.replace(/ /g, '+') + '" 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/>' : '') + 
    d.city + ', ' + d.state + ' ' + 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' : '') + 
    d.city + ', ' + d.state + ' ' + d.zip + '\n' +
    d.phone + '\n' +
    d.url;

  return html;
}

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

function hide_markers() {
  window.current_marker = null;

  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;
      }
    });
  }

  // if this is the current marker, then open its infoWindow
  if (current_marker && m._data.id == current_marker._data.id) {
    GEvent.trigger(m, 'click');
    return;
  }

  hide_markers();
  m.show();
  show_polyline(m);

  if (m._data.polyline) {
    map.zoomToMarkers(.1, m._data.polyline.asGLatLngs());
  }
  else {
    map.zoomToMarkers(.1);
  }

  window.current_marker = m;
}


