/*
 * Core Map Bootloader (right, a JS bootloader...)
 *
 * An odd mix of Google-required proto-OOP and jQuery
 */


//google.load('maps', '3');

if (typeof(jQuery) != 'undefined') {

  jQuery(function() {
    if (jQuery.browser.msie && eval(jQuery.browser.version) < 7) {
      jQuery('#map-ie6-info').show();
    } else {
      if (google.maps.BrowserIsCompatible()) {
        jQuery.getScript('/site_media/javascript/map.listing.js', function() {
          buildMap();
        });
      } else {
        jQuery('#browser-is-compatible').show();
      }
    }

    jQuery('body').unload(function() {
      google.maps.Unload();
    });

  });
}

var shift = new GSize(0,-100)

GMap2.prototype.panShifted = function (latlon,z,sh) {
        var proj = this.getCurrentMapType().getProjection();
        var px = proj.fromLatLngToPixel(latlon,z);
        var sePx = new GPoint(px.x + sh.width, px.y + sh.height);
        var seLatLng = proj.fromPixelToLatLng(sePx,z);
        this.panTo(seLatLng,z);
}

function buildMap() {

  /* THIS WILL BE XHR'D IN
  var listing_data = [
    {'lat': 37.441, 'lng': -122.2,  'city': 'Traverse City', 'state': 'MI', 'price': '123,000', 'beds': 2, 'baths': 3, 'thumb': 'images/home1.jpg'},
    {'lat': 37.441, 'lng': -122.18, 'city': 'Elk Rapids', 'state': 'MI', 'price': '777,000', 'beds': 2, 'baths': 3, 'thumb': 'images/home2.jpg'},
    {'lat': 37.439, 'lng': -122.16, 'city': 'Alden', 'state': 'MI', 'price': '666,000,', 'beds': 2, 'baths': 3, 'thumb': 'images/home3.jpg'}
  ];
  THIS WILL BE XHR'D IN */

  var map_id = 'map';
  var bounds = new google.maps.LatLngBounds();

  jQuery.getJSON('/json/listing/', function(listing_data) {
    var map_div = jQuery('#' + map_id).get(0);

    if (!map_div) {
      jQuery.log.error('Unable to locate map div. This won\'t be pretty...');
    } else if (!listing_data) {
      jQuery('#error-loading-map-data').show();
    } else {
      var map     = new google.maps.Map(map_div);
          map.addControl(new google.maps.LargeMapControl());
          map.setCenter(new google.maps.LatLng(Number(44), Number(-84.6173)), 8);
      var mgr     = new google.maps.MarkerManager(map);
      var markers = new Array();
      var last_marker_shown;
     var houseIcon = new GIcon();
     houseIcon.image = "http://realestate.mynorth.com/site_media/images/house_icon.png";
     houseIcon.shadow = "http://realestate.mynorth.com/site_media/images/house_icon_shadow.png";
     //houseIcon.iconSize = new GSize(30, 45);
     houseIcon.iconAnchor = new GPoint(13, 23);
     //var style = new MarkerStyle();
     //style.iconStyle.align = Align.fromString("middle-center");
     // Set up our GMarkerOptions object literal
     markerOptions = { icon:houseIcon };

      jQuery.each(listing_data, function() {
        var marker = new google.maps.Marker(new google.maps.LatLng(this.latitude, this.longitude), markerOptions);
        //marker.setStyle(style);
        var mdata  = this;
        //console.log(marker);
        google.maps.Event.addListener(marker, 'click', function() {
          map.addOverlay(new MapListing(mdata, map_id, this.getLatLng()));
          //map.panTo(this.getLatLng());
          map.panShifted(this.getLatLng(), map.getZoom(), shift);
        });
        bounds.extend(marker.getLatLng());
        mgr.addMarker(marker, 0);
        markers.push(marker);
      });

      map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)+1);
      function mapLoadCheck() {
        if (map.isLoaded()) {
          // This is so fragile, it's scary
          var map_ctl = jQuery('#map div.gmnoprint img[src$="mapcontrols2.png"]');

          if (map_ctl.get(0)) {
            clearInterval(mapLoadCheckInt);
            map_ctl.attr('src', '/site_media/images/mapcontrols2_custom.png');
            jQuery('#map_overlay').fadeOut(2500);
          }
        }
      };

      var randomMarker = {
        is_playing: false,
        interval: undefined,
        timeout: undefined,
        current: undefined,
        resume_time: 10000,
        play_time: 5000
      };

      (function(m) {
        m.show = function() {
          if (m.current >= markers.length || m.current == undefined) {
            m.current = 0;
          } else {
            //markers[m.current].remove();
          }
          //var cLatLng = markers[m.current].getLatLng();
          //var newcenter = new google.maps.LatLng(cLatLng.lat()+.5, cLatLng.lng())
          //var currentZoom = map.getZoom();
          //jQuery.log.log(newcenter);
          google.maps.Event.trigger(markers[m.current], 'click');
          //map.panTo(newcenter);
          m.current++;
        };

        m.play = function() {
          if (!m.is_playing) {
            m.is_playing = true;
            m.interval   = setInterval(m.show, m.play_time);
          }
        };

        m.stop = function() {
          if (m.is_playing) {
            //jQuery.log.log('Random markers stopped.');
            clearInterval(m.interval);
            m.is_playing = false;
          }
          // If this line is left in, then after 10 seconds, the random markers start up again.
          // m.resume();
        };

        m.resume = function() {
          clearTimeout(m.timeout);
          m.timeout = setTimeout(m.play, m.resume_time);
          //jQuery.log.log('Resume timer reset.');
        };

      })(randomMarker);


      google.maps.Event.addListener(map, 'mousemove', function() {
        randomMarker.stop();
      });

      var mapLoadCheckInt = setInterval(mapLoadCheck, 50);
      randomMarker.play();

    }

  });

};

