//<![CDATA[

// ============================================================================
// Object instantiation
// ============================================================================
// Args:
// strContainerID, the ID of the element into which the map should be placed
// ============================================================================
function sageGoogleMap(strContainerID) {

	// --------------------------------------------------------------------------
	// Determine the ID of the container if passed or use the default "map"
	// --------------------------------------------------------------------------
	if(strContainerID===null){
		this.container = "map";
	}
	else if (typeof(strContainerID)=="undefined"){
		this.container = "map";
	}
	else if(strContainerID === ""){
		this.container = "map";
	}
	else{
		this.container = strContainerID;
	}
	debugit("Creating new map in container("+this.container+")" );

	// --------------------------------------------------------------------------
	// Private variables
	// --------------------------------------------------------------------------
	this.mapObject = null;
	this.geocoder  = null;

	// --------------------------------------------------------------------------
	// Set the default Zoom Level (0-19)
	// --------------------------------------------------------------------------
	this.zoomlevel = 15;

	// --------------------------------------------------------------------------
	// Set the default map type
	// --------------------------------------------------------------------------
	// Set to 1 to display noormal (street) map (G_NORMAL_MAP)
	// Set to 2 to display satellite map        (G_SATELLITE_MAP)
	// Set to 3 to display hybrid map           (G_HYBRID_MAP)
	// --------------------------------------------------------------------------
	this.maptype = 1;

	// --------------------------------------------------------------------------
	// Set to 0 to display no map movement controls
	// Set to 1 to display small map movement controls
	// Set to 2 to display large map movement controls
	// --------------------------------------------------------------------------
	this.MovementControls = 1;

	// Set to 1 to display the controls to change the map type (ie. Map, Satellite, Hybrid)
	this.MapTypeControls = 1;

	// --------------------------------------------------------------------------
	// This is the address to look up
	// --------------------------------------------------------------------------
	//this.address = "#301 1510 Hillside Ave, V8T 2C2 Canada"
	this.address = "";

	// --------------------------------------------------------------------------
	// An array to store any points we add
	// --------------------------------------------------------------------------
	this.points = new Array();

	// --------------------------------------------------------------------------
	// This is the HTML string of text that is displayed in the pop up bubble.
	// --------------------------------------------------------------------------

	// var textstring = "<span class=\"MLSText\">Sage Internet Solutions Ltd.<br>#201-736 Broughton Street<br>Victoria, BC<br>Canada<br>V8W 1E1<br><\/span>";
	//this.textstring = "<span class=\"MLSText\"><strong>MLS&reg; 243717 - $559,900<\/strong><br>" + setaddress + "<\/span>";

}

// --------------------------------------------------------------------------
// Create the Render functon
// --------------------------------------------------------------------------
sageGoogleMap.prototype.render = function(){
	debugit("Running: render for ("+this.container+")");

	debugit("Getting element  for ("+this.container+")");
	this.containerObject = document.getElementById(this.container);
	if (!this.containerObject){
		alert("ERROR: The container " + + " has either not been defined on the page or the render function is being called before it exists in the DOM");
		return;
	}


	if (!GBrowserIsCompatible()){
		this.containerObject.innerHTML = "<p class='gmapMessage'>Sorry - A Google map cannot be displayed in this bowser.<\/p>";
		return;
	}

	// This will create a new map in the div layer with the id of strContainerID.
	var o_mapObject = new GMap2(this.containerObject);
	var o_geocoder  = new GClientGeocoder();

	this.mapObject = o_mapObject;
	this.geocoder = o_geocoder;

	//debugit("this.mapObject " + this.mapObject);
	//debugit("this.geocoder " + this.geocoder);


	// --------------------------------------------------------------------------
	// Centre the map initially on (0,0)
	// --------------------------------------------------------------------------
	o_mapObject.setCenter(new GLatLng(0, 0), o_mapObject.zoomlevel);

	// --------------------------------------------------------------------------
	// Set the map type
	// setMapType() can only be called when the map has been centered
	// This is why we centered the map initially on (0,0)
	// G_DEFAULT_MAP_TYPES is an array of map type objects
	// (
	//   G_NORMAL_MAP,
	//   G_SATELLITE_MAP,
	//   G_HYBRID_MAP
	// )
	// --------------------------------------------------------------------------
	o_mapObject.setMapType(G_DEFAULT_MAP_TYPES[this.maptype-1]);


	// --------------------------------------------------------------------------
	// This adds the map zoom and pan controls
	// --------------------------------------------------------------------------
	if(this.MovementControls){

		// ------------------------------------------
		// This adds the small set of map controls
		// this.MovementControls==1
		// ------------------------------------------
		if (this.MovementControls == 1){
			this.mapObject.addControl(new GSmallMapControl());
		}

		// ------------------------------------------
		// This adds the large set of map controls
		// this.MovementControls == 2
		// ------------------------------------------
		else{
			this.mapObject.addControl(new GLargeMapControl());
		}

	}

	// --------------------------------------------------------------------------
	// This adds controls to toggle the type of map being viewed
	// --------------------------------------------------------------------------
	if(this.MapTypeControls){
		this.mapObject.addControl(new GMapTypeControl(true));
	}

	var o_sageGoogleMap = this;

	var i_points = this.points.length;
	debugit("Point count  = " + i_points);


	//for (i_point in this.points){
	var i_point;
	for (i_point=0;i_point<i_points;i_point++){
		var a_point = this.points[i_point];
		debugit("Address="  + this.points[i_point]["address"]);
		debugit("infohtml=" + this.points[i_point]["infohtml"]);
		var point_address  = this.points[i_point]["address"];
		var point_infohtml = this.points[i_point]["infohtml"];
		var point_lng      = this.points[i_point]["lng"];
		var point_lat      = this.points[i_point]["lat"];

		// If we do not have Longitude and Latitude points we are going to look them up from the address
		// If they were provided we just convert our coordinates into a GPoint() and call render_point()
//		debugit("lng=" + this.points[i_point]["lng"]);
//		debugit("lat=" + this.points[i_point]["lat"]);
//		debugit("lat is undefined" + (this.points[i_point]["lat"] == undefined));
//		debugit("lat is undefined" + (this.points[i_point]["lat"] === undefined));
//		debugit("lat is undefined" + (this.points[i_point]["lat"] === 'undefined'));
		if (this.points[i_point]["address"] !== undefined) {
			debugit("Using Address");
			debugit("Address=" + this.points[i_point]["address"]);
			this.geocoder.getLatLng(
				point_address,
				function(oNewPoint){
					render_point(oNewPoint);
					return;
				} // End callback function(oNewPoint)
			); // End geocoder.getLatLng
		}
		else if((this.points[i_point]["lat"] !== undefined) && (this.points[i_point]["lng"] !== undefined)) {
			debugit("Using lng lat");
			var oNewPoint = new GLatLng(this.points[i_point]["lat"], this.points[i_point]["lng"]);
//			debugit("oNewPoint.getX()=" + oNewPoint.getX());
//			debugit("oNewPoint.getY()=" + oNewPoint.getY());
			debugit("oNewPoint.lat()=" + oNewPoint.lat());
			debugit("oNewPoint.lng()=" + oNewPoint.lng());
			render_point(oNewPoint);
		}
		else{
			alert("There is no data on whcih to base the point being added to the map. Perhaps render has been called before correctly adding points with addPointFromGeoLatLng{} or addPointFromAddress{}");
			return;
		}

/*
		this.geocoder.getLatLng(
			point_address,
			function(oNewPoint){
				render_point(oNewPoint);
				return;
				//debugit("o_mapObject " + o_mapObject);
				// --------------------------------------------------------------------
				// If no point is provided it means that the geocoder.getLatLng failed
				// to get a point from the address provided (point_address)
				// FIXME: We are oblitterating the entire map here even if other points
				//        have already been added
				// --------------------------------------------------------------------
				if(!oNewPoint){
					debugit("Sorry - There is no Google map available for the location provided ["+point_address+"]");
					o_sageGoogleMap.containerObject.innerHTML = "<p class='gmapMessage'>Sorry - There is no Google map available for the location provided ["+point_address+"]<\/p>";
					//o_sageGoogleMap.containerObject.style.display="none";
				}
				// --------------------------------------------------------------------
				// Centre the map on the most recently added point
				// Create a new marker on the newly created point which takes its text
				// from the point_infohtml variable
				// --------------------------------------------------------------------
				else {
					debugit("oNewPoint.lat()=" + oNewPoint.lat());
					debugit("oNewPoint.lng()=" + oNewPoint.lng());

					o_mapObject.setCenter(oNewPoint, o_sageGoogleMap.zoomlevel);
					o_mapObject.addOverlay(o_sageGoogleMap.createMarker(oNewPoint, point_infohtml));
				} // End if/Else(!oNewPoint)
			} // End callback function(oNewPoint)
		); // End geocoder.getLatLng
*/
	} // End for (i_point in this.points)


	function render_point(oNewPoint){
			debugit("RENDER POINT");
		//debugit("o_mapObject " + o_mapObject);
		// --------------------------------------------------------------------
		// If no point is provided it means that the geocoder.getLatLng failed
		// to get a point from the address provided (point_address)
		// FIXME: We are oblitterating the entire map here even if other points
		//        have already been added
		// --------------------------------------------------------------------
		if(!oNewPoint){
			debugit("Sorry - There is no Google map available for the location provided ["+point_address+"]");
			o_sageGoogleMap.containerObject.innerHTML = "<p class='gmapMessage'>Sorry - There is no Google map available for the location provided ["+point_address+"]<\/p>";
			//o_sageGoogleMap.containerObject.style.display="none";
		}
		// --------------------------------------------------------------------
		// Centre the map on the most recently added point
		// Create a new marker on the newly created point which takes its text
		// from the point_infohtml variable
		// --------------------------------------------------------------------
		else {
			debugit("oNewPoint.lat()=" + oNewPoint.lat());
			debugit("oNewPoint.lng()=" + oNewPoint.lng());
			o_mapObject.setCenter(oNewPoint, o_sageGoogleMap.zoomlevel);
			o_mapObject.addOverlay(o_sageGoogleMap.createMarker(oNewPoint, point_infohtml));
		} // End if/Else(!oNewPoint)
	} // End render_point(oNewPoint)


	//this.showAddress();
	//o_mapObject.setCenter(this.point, this.zoomlevel);

	return;

}; // End this.render()



// ============================================================================
// FUNCTION showAddress()
// ============================================================================
sageGoogleMap.prototype.showAddress = function (){

	// --------------------------------------------------------------------------
	// Our object is being assigned to o_sageGoogleMap so that the callback
	// function for geocoder.getLatLng can see it within its scope
	// --------------------------------------------------------------------------
	// FIXME - make the callback function this.callback(point) ?
	var o_sageGoogleMap = this;
	var o_mapObject = this.mapObject;


	this.geocoder.getLatLng(
		this.address,
		function(point){
			//debugit("o_mapObject " + o_mapObject);
			if(!point){
				o_sageGoogleMap.containerObject.innerHTML = "<p style='text-align:center;vertical-align:middle;font-weight:bold;'><br><br><br>Sorry - There is no Google map available for the location provided or there is not enough geographical information from which to generate a map.<\/p>";
			}
			else {
				o_mapObject.setCenter(point, o_sageGoogleMap.zoomlevel);
			} // End if(!point)
		} // End callback function(point)
	); // End geocoder.getLatLng
}; // End function showAddress(address)

// This adds the map marker onto a point of the map
//						map.addOverlay(createMarker(point, textstring));
//sageGoogleMap.prototype.createMarker = function (point, text){
//};

// ============================================================================
// FUNCTION addPointFromAddress()
// ============================================================================
sageGoogleMap.prototype.addPointFromAddress = function (strAddress, strInfoHtml){
	var a_point = new Array();
	a_point["address"]  = strAddress;
	a_point["infohtml"] = strInfoHtml;
	this.points.push(a_point);
	//alert(this.points[0]["address"]);
};

// ============================================================================
// FUNCTION addPointFromGeoLatLng()
// ============================================================================
sageGoogleMap.prototype.addPointFromGeoLatLng = function (dblLat, dblLng, strInfoHtml){
	var a_point         = new Array();
	a_point["lat"]      = dblLat;
	a_point["lng"]      = dblLng;
	a_point["infohtml"] = strInfoHtml;
	this.points.push(a_point);
	//alert(this.points[0]["address"]);
};

// ============================================================================
// FUNCTION createMarker()
// ============================================================================
// This function will setup a marker that when you click on it will display
// HTML content in it.
// ============================================================================
sageGoogleMap.prototype.createMarker = function (point, text){
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function(){
		marker.openInfoWindowHtml(text);
	});
	return marker;
};



var debugit = function (s_text){
	var o_debug_map = document.getElementById("debug_map");
	if(o_debug_map){
		try{
			// ----------------------------------------------------------------------
			// causes an error if the element is not visible so we use that factor
			// by employing a "try...catch statement
			// ----------------------------------------------------------------------
			if(o_debug_map.visibility=="visible"){
				o_debug_map.innerHTML = o_debug_map.innerHTML + '<br />' + s_text;
			}
		}
		catch(e){
			// ----------------------------------------------------------------------
			// what you want to do on error (nothing)
			// ----------------------------------------------------------------------
		}

	}

};




//]]>
