// setup a namespace and global objects for tracking the map
var bboxMap;
if (!bboxMap) bboxMap = {};
if (!bboxMap.map) bboxMap.map = {};
if (!bboxMap.markers) bboxMap.markers = [];
if (!bboxMap.markerTexts) bboxMap.markerTexts = [];
var bboxMapTimer = 0;
jQuery.fn.bboxGMap2 = function(method, settings) {
	settings = $.extend({
		id: 'map',
		centerLat: 0,
		centerLng:0,
		zoom:16,
		tooltipSel:'#message',
		markerLatLng:[0,0],
		markerIcon:"",
		markerIconSize:[0,0],
		markerIconAnchor:[0,0],
		markerTipText:""
	}, settings || {});
		
	var onMarkerClick = function(marker, index){
		//alert('YOU CLICKED ON THIS MARKER ' + index + ' -- ' + bboxMap.markerTexts[index]);
	}
	
	var onMarkerOver = function(marker, index){
		var markerOffset = bboxMap.map.fromLatLngToContainerPixel(marker.getPoint());
		$(settings.tooltipSel + " .inner").html(bboxMap.markerTexts[index]);
		$(settings.tooltipSel)
			.show()
			.css({ top:markerOffset.y, left:markerOffset.x });
	}
	
	var onMarkerOut = function(marker, index){
	  bboxMapTimer = setTimeout( function(){ $(settings.tooltipSel).hide() }, 500);
	}
		
	if (method == 'init'){
		// create the map
		bboxMap.map = new GMap2(document.getElementById('map'));
		// NOTE - SET THE CENTER BASED ON NUMBERS FROM THE DB
		bboxMap.map.setCenter(new GLatLng(settings.centerLat, settings.centerLng), settings.zoom);
		bboxMap.map.addControl(new GLargeMapControl());
	} else if (method == 'addMarker'){
		var point = new GLatLng(settings.markerLatLng[0], settings.markerLatLng[1]);
		var icon = new GIcon();
		icon.iconSize = new GSize(settings.markerIconSize[0], settings.markerIconSize[1]);
	    icon.iconAnchor = new GPoint(settings.markerIconAnchor[0], settings.markerIconAnchor[1]);
		icon.image = settings.markerIcon;
		var marker = new GMarker(point, icon);
		bboxMap.map.addOverlay(marker);
		var i = bboxMap.markers.length;
		bboxMap.markers[i] = marker;
		bboxMap.markerTexts[i] = settings.markerTipText + '<span class="point"><!-- x --></span>';	// note the span is for the pointer
		// add listeners
		GEvent.addListener(marker, "mouseover", function(){
			onMarkerOver(marker, i);
		});
		GEvent.addListener(marker, "mouseout", function(){
			onMarkerOut(marker, i);
		});
		GEvent.addListener(marker, "click", function(){
			onMarkerClick(marker, i);
		});
	} else if (method == 'showMarker'){
		onMarkerOver(bboxMap.markers[settings.id], settings.id);
	}
	
	return this;
}

$(document).ready(function(){
  $("#message").mouseover(function(){
    clearTimeout(bboxMapTimer);
    $(this).show();
  });
  $("#message").mouseout(function(){
    $(this).hide();
  });
});