// Used by Google Maps
var mymap = null;
var geocoder = null;
var baseicon = null;
var searchStringSaved = null;
var active_markers = [];
var marker = null;

// Used by Google Directions
var gdir;
var addressMarker;
		
	
$.fn.loadMap = function(settings) {
	
    var params = jQuery.extend({latitude: 38.6, longitude: 75.36, zoom: 2, addMarker: false, editListing: false}, settings);
    if (GBrowserIsCompatible()) {
        // Create map
        mymap = new GMap2($("#map")[0]);
        
        // Add Controls
		mymap.addControl(new GSmallMapControl());
		mymap.addControl(new GMapTypeControl());
		// Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
        baseIcon = new GIcon();
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        baseIcon.infoShadowAnchor = new GPoint(18, 25);
		//GEvent.addListener(mymap, "moveend", function() {
		//  if (searchStringSaved != null) {
		//  	$().getMarkers();
		//  }
        //});
        
        /*
        Display lat, long, and zoom level for debugging
        GEvent.addListener(mymap, "moveend", function() {
			var center = mymap.getCenter();
			$("#message").html(center.toString() + " / " + mymap.getZoom());
		});
		*/        
			        
		geocoder = new GClientGeocoder();

		center = new GLatLng(params.latitude, params.longitude);
	  	mymap.setCenter(center, params.zoom);
		if (params.addMarker) {
			$().addMarker(params.editListing);
		} else {
			// Get Markers
			$().getMarkers();	  	
		}		
	}
}


$.fn.getMarkers = function() {
	var bounds = mymap.getBounds();
  	var southWest = bounds.getSouthWest();
  	var northEast = bounds.getNorthEast();
	var min_latitude = southWest.lat();
	var min_longitude = southWest.lng();
	var max_latitude = northEast.lat();
	var max_longitude = northEast.lng();
	
	if (searchStringSaved != '') {
	
        $.getJSON('/rentals/ajax', {min_latitude: min_latitude, min_longitude: min_longitude, max_latitude: max_latitude, max_longitude: max_longitude},
            function(data) {
            	$.each(data, function(i, item) {
            		if ($.inArray(item.id, active_markers) < 0) {
						active_markers.push(item.id);
						mymap.addOverlay($().createMarker(new GLatLng(item.latitude,item.longitude), i, item.key, item.id, item.title, item.subtitle, item.city, item.state, item.postal_code, item.desc, item.image));
					}
            	});
            }
        );
        
	}
}

$.fn.createMarker = function(point, index, key, id, title, subtitle, city, state, postal_code, desc, imageId) {
	// Create a lettered icon for this point using our icon class
	//var letter = String.fromCharCode("A".charCodeAt(0) + index);
	//var letteredIcon = new GIcon(baseIcon);
	//letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
	
	if (imageId) {
		var imgUrl = '/images/rentals/listings/' + imageId + '-tn.jpg';
	} else {
		var imgUrl = '/images/rentals/no_image_sm.jpg';
	}
	
	// Set up our GMarkerOptions object
	//markerOptions = { icon:letteredIcon };
	//var marker = new GMarker(point, markerOptions);
	var marker = new GMarker(point);
	var markerText = "<div style=\"width: 75px; padding: 0 4px 0 0; float: left;\"><img src=\"" + imgUrl + "\" width=\"75\" height=\"50\"/></div><div class=\"infoBoxInfo\" style=\"width: 200px; float: left; font-size: 11px;\">";
	markerText += "<div><b>" + title + "</b></div>";
	markerText += "<div>" + city + ", " + state + " " + postal_code + "</div>";
	markerText += '<div><a href="/rentals/' + key + '">More Information</a></div></div>';
	
	GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(markerText, {maxWidth: 400});
	});
	return marker;
}
	
$.fn.showAddress = function(address, addMarker) {
  if (address) {
	  if (geocoder) {
		geocoder.getLatLng(
		  address,
		  function(point) {
		  	mymap.clearOverlays();
			if (!point) {
			  alert('Address not found on map.');
			  return false;
			} else {
			  mymap.setCenter(point, 13);
			  if (addMarker) {
				  var marker = new GMarker(point);
				  mymap.addOverlay(marker);
			  }
			}
		  }
		);
	  }
  } else {
  	center = new GLatLng(38.607522374855736, -75.3641942024231);
	mymap.setCenter(center, 10);
  }
}

$.fn.mPT = function(lat, lon, zoom) {

	mymap.setCenter(new GLatLng(parseFloat(lat), parseFloat(lon)), parseInt(zoom));

}

$.fn.zoomToPoints = function(min_lat, min_long, max_lat, max_long) {

	var bounds = new GLatLngBounds();
	
	bounds.extend(new GLatLng(min_lat, min_long));
	bounds.extend(new GLatLng(max_lat, max_long));
	
	mymap.setZoom(mymap.getBoundsZoomLevel(bounds) - 1);
	mymap.setCenter(bounds.getCenter());

}
	
$.fn.zoomToRegion = function(region) {
	var bounds = new GLatLngBounds();
	
	bounds.extend(new GLatLng(min_lat, min_long));
	bounds.extend(new GLatLng(max_lat, max_long));
	
	mymap.setZoom(mymap.getBoundsZoomLevel(bounds) - 1);
	mymap.setCenter(bounds.getCenter());
}

$.fn.returnCoords = function() {
    var coords = center.toString().replace("(", "").replace(")", "").split(", ");
    window.opener.$('#latitude').val(coords[0]);
    window.opener.$('#longitude').val(coords[1]);
    window.opener.$('#latlngstatus').html('Set');
    window.close();
}
	
$.fn.addMarker = function(draggable) {
    if (marker) {
        mymap.removeOverlay(marker);
    }
    center = mymap.getCenter();
    marker = new GMarker(center, {draggable: draggable})
    GEvent.addListener(marker, "dragend", function() {
        center = marker.getLatLng();
    });
    mymap.addOverlay(marker);
}

$(document).ready(function() {
    $().loadMap(mapParams);
});

$(document).unload(function() {
    GUnload();
});

