var map = null;
var map_types = null;
var s_icon = null;
var mgr = null;
var geocoder = null;
var to_geocode = null;
var bounds = null;

// Call this function when the page has been loaded
function initialize() {
  map_types = {
    'map': {
      'ypos': '0',
      'g_type': G_NORMAL_MAP
    },
    'sat': {
      'ypos': '-22px',
      'g_type': G_SATELLITE_MAP
    },
    'hybrid': {
      'ypos': '-44px',
      'g_type': G_HYBRID_MAP
    }
  };
  s_icon = create_icon();

  map = new GMap2(document.getElementById("search_map"));
  GEvent.addListener(map, 'load', function() {
      map.enableContinuousZoom();
      set_map_type($('a#maptype_map'));
      mgr = new ClusterMarker(map, {
        clusterMarkerIcon: s_icon, 
        clusterMarkerTitle: "Click to zoom in and see %count properties"
      });
      if (markers_to_add != null) add_markers(markers_to_add);
  }); 
  map.setCenter(new GLatLng(35.42039, -80.89782), 8);
}

function set_map_zoom(e) {
  if (e.attr('id') == 'map_zoom_in') {
    map.zoomIn();
  } else {
    map.zoomOut();
  }
}
function set_map_type(e) {
  $('#map_type_control a').removeClass('active');
  e.addClass('active');
  m_type = map_types[e.attr('id').replace('maptype_','')];
  $('#map_type_control').css('background-position', '0px ' + m_type.ypos);
  map.setMapType(m_type.g_type);
}
function create_marker(data) {
  var p = new GLatLng(data.lat, data.lng);
  bounds.extend(p);
  var m = new GMarker(p, s_icon);
  GEvent.addListener(m, 'click', function() {
      $.post("/search-properties", { 'i': data.id }, function(html, textStatus) {
        m.openInfoWindowHtml(html);
        });
      });
  return m;
}
function add_markers(data) {
  mgr.removeMarkers();
  var markers = new Array();
  var m = null;
  bounds = new GLatLngBounds();
  for (i=0; i<data.length; i++) {
    if (data[i].lat == null || data[i].lat == '') {
      geocode(data[i].id, data[i].address);
    } else {
      m = create_marker(data[i]);
      markers.push(m);
    }
  }
  if (markers.length > 0) {
    mgr.addMarkers(markers);
    refresh_map();
  }
  if (markers.length == 1) {
    GEvent.trigger(m, 'click');
  }
}
function refresh_map() {
  var z = map.getBoundsZoomLevel(bounds) - 1;
  if (z > 8) {
    map.setCenter(bounds.getCenter(), z);
  } else {
    map.setCenter(new GLatLng(35.42039, -80.89782), 8);
  }
  if (to_geocode == null || to_geocode.length < 1) {
    $('#search_ind').addClass('hidden');
    $('#search_ind').hide();
  }
}
function geocode(id, address) {
  if (geocoder == null) {
    geocoder = new GClientGeocoder();
    to_geocode = new Array();
  }
  to_geocode.push({ id: id, address: address });
  do_geocode();
}
function do_geocode() {
  if (geocoder.IG_busy == true) return;
  if (to_geocode.length < 1) {
    refresh_map();
    return;
  }

  var next = to_geocode.shift();
  geocoder.IG_busy = true;
  geocoder.getLatLng(next.address, function(point) {
    if (point != null) {
      $.post("/search-properties", { 'i': next.id, 'lat': point.lat(), 'lng': point.lng() });
      var to_add = new Array();
      to_add.push(create_marker({ 'id': next.id, 'lat': point.lat(), 'lng': point.lng() }));
      mgr.addMarkers(to_add);
    }
    geocoder.IG_busy = false;
    do_geocode();
  });
}

$(document).ready(function() {
 initialize();

 $('ul.tab_header a').click(function() {
   old_tab_id = $('ul.tab_header li.active').attr('id').replace('select_','tab_');
   $('#'+old_tab_id).hide();
   $('ul.tab_header li').removeClass('active');
   $(this).parent().addClass('active');
   $('#'+$(this).parent().attr('id').replace('select_','tab_')).show();
   if ($(this).parent().attr('id') == 'select_map' && old_tab_id != 'tab_map') { 
     map.checkResize(); 
     refresh_map();
   }
 });
 $('#map_zoom_control a').click(function() { set_map_zoom($(this)); });
 $('#map_type_control a').click(function() { set_map_type($(this)); });

 $('#search_ind').hide();
 $('a#map_button_submit').click(function() {
     if ($('#search_ind').hasClass('hidden')) {
       $('#search_ind').removeClass('hidden');
       $('#search_ind').show();
       $.post("/search-properties", $('#live_search').serialize(), function(t, s) {
         try {
           eval(t);
         } catch(e) {
           $('#search_ind').addClass('hidden');
           $('#search_ind').hide();
         }
       });
     }
     return false;
 });
 $('a#map_button_clear').click(function() {
     $('#live_search').each(function() {
       this.reset();
       });
     mgr.removeMarkers();
     refresh_map();
     return false;
   });
});
