/**
 * This is the Main function to draw the map on the page
 *
 * Input: Map element , Marker draggble
 * Output: none
 */
var CurrentMap = null;
var CurrentMapBounds = null;
var CurrentMarker = null;
var CurrentMarkerIsDragabble = true;
var CurrentMarkersBatch = [];

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var BaseIcon = new GIcon();
BaseIcon.shadow = "/images/maps/shadow50.png";
BaseIcon.image = "/images/maps/rentahomemappin.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);

function DrawPropertyMap(mapname, isDragabble) {  
	if (GBrowserIsCompatible()) {
        CurrentMap = new GMap2(document.getElementById(mapname));
        
        // Set the Marker draggble
        CurrentMarkerIsDragabble = isDragabble;
        
        // Add the Property to the Map
		if (!AddPropertyToMap()) 	 {
			return ;
		}
        
		// Add the large Map scale
		CurrentMap.addControl(new GLargeMapControl());
		
		// Add the Sattlite Map toggle
		CurrentMap.addControl(new GMapTypeControl());	
		
		// Add an Overview map
		CurrentMap.addControl(new GOverviewMapControl());
		    
		// Add listiner to the map
		GEvent.addListener(CurrentMap, "moveend", function() {  
				// Update the Map coordinates and marker position
				SetMapMarkerCoords();
			}
		);
		
		// Add listiner to the map
		GEvent.addListener(CurrentMap, "zoomend", function() {  
				// Update the Map coordinates and marker position
				SetMapMarkerCoords();
			}
		);		
    } else {
		alert("Sorry, the Google Maps is not compatible with this browser");
	}
}

// Draw Properties On Map
function DrawPropertiesMap(mapname) {
    if (GBrowserIsCompatible()) {
        if (!document.getElementById(mapname)) {
            return;
        }
        CurrentMap = new GMap2(document.getElementById(mapname));
        CurrentMapBounds = new GLatLngBounds();
        // MUST CENTRE MAP TO USE MARKER MANAGER 
        CurrentMap.setCenter(CurrentMapBounds.getCenter());     

        // Add the large Map scale
        CurrentMap.addControl(new GLargeMapControl());

        // Add the Sattlite Map toggle
        CurrentMap.addControl(new GMapTypeControl());

        // Add an Overview map
        CurrentMap.addControl(new GOverviewMapControl());        

        // Add Properties Markers
        AddPropertiesMarkers();

        // Dimension Map
        CurrentMap.setZoom(CurrentMap.getBoundsZoomLevel(CurrentMapBounds));
        CurrentMap.setCenter(CurrentMapBounds.getCenter());      

        // Add the Map Manager
        window.setTimeout(SetupPropertiesMarkers, 0);
    } else {
        alert("Sorry, the Google Maps is not compatible with this browser");
    }
}

// Create a Marker
function CreateMarker(propLat, propLng, title, html, rank, color) {
    var markerOpts = {};
    var nIcon = new GIcon(cm_baseIcon);

    if (rank > 0 && rank <= 20) {
        nIcon.imageOut = "/images/maps/" +
			"markers/" + color + "/marker" + rank + ".png";
        nIcon.imageOver = "/images/maps/" +
			"markers/" + color + "/marker" + rank + ".png";
        nIcon.image = nIcon.imageOut;
    } else {
        nIcon.imageOut = "/images/maps/" +
			"markers/" + color + "/blank.png";
        nIcon.imageOver = "/images/maps/" +
			"markers/" + color + "/blank.png";
        nIcon.image = nIcon.imageOut;
    }

    // Remove Same Marker Position
//    var existingMarkerHTML = '';
//    for (var i = 0; i < CurrentMarkersBatch.length; i++) {
//        if (CurrentMarkersBatch[i].getPoint().lat() == propLat && CurrentMarkersBatch[i].getPoint().lng() == propLng) {
//            existingMarkerHTML = eval("html" + i);
//            CurrentMarkersBatch.splice(i, 1);
//        }
//    }
    
    markerOpts.icon = nIcon;
    markerOpts.title = title;
    var point = new GLatLng(propLat, propLng);
    var marker = new GMarker(point, markerOpts);

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });

    // Dimension Map for Marker
    CurrentMapBounds.extend(point);

    return marker;
}

// Add Properties Top Map
function SetupPropertiesMarkers() {
    // Map Manager
    mapManager = new MarkerManager(CurrentMap);
    mapManager.addMarkers(CurrentMarkersBatch, 2);
    mapManager.refresh();

    return;
    // Put Marker Manual 
//    var bounds = new GLatLngBounds();		
//    for (var i = 0; i < CurrentMarkersBatch.length ; i++) {
//        CurrentMap.setCenter(new GLatLng(CurrentMarkersBatch[i].getPoint().lat(), CurrentMarkersBatch[i].getPoint().lng()), 14);
//        CurrentMap.addOverlay(CurrentMarkersBatch[i]);
//        bounds.extend(CurrentMarkersBatch[i].getPoint());    
//    }
//    
//    CurrentMap.setZoom(CurrentMap.getBoundsZoomLevel(bounds));
//	CurrentMap.setCenter(bounds.getCenter());
}

/**
 * This funcion return the marker to be placed on the map
 *
 * Input: point, html window content
 * Output: Marker
 */
function CreateCurrentMarker(point, html) {  
	var nIcon = new GIcon(BaseIcon);
	var markerOpts = {};
	markerOpts.icon = nIcon;
	markerOpts.title = html;	
	
	if (CurrentMarkerIsDragabble) {
		markerOpts.draggable = true;
		markerOpts.bounceGravity = 1.0;
		markerOpts.bouncy = true;
	} else {
		markerOpts.draggable = false;
	}	
	CurrentMarker = new GMarker(point, markerOpts);  	
	
	// Click - Event add the HTML window
	if (html.length > 0) {
		GEvent.addListener(CurrentMarker, "click", 
			function() {    
				// Center the map aroud the Marker
				CurrentMarker.openInfoWindowHtml(html);
			}
		);  
	}
	
	// Double Click Event
	GEvent.addListener(CurrentMarker, "dblclick", 
		function() {    
			// Center the map aroud the Marker
			CurrentMap.setCenter(CurrentMarker.getPoint(), CurrentMap.getZoom() + 1);
			
			// Update the Map coordinates and marker position
			SetMapMarkerCoords();
		}
	);  
	
	if (CurrentMarkerIsDragabble) {
		// Drag Event - Start
		GEvent.addListener(CurrentMarker, "dragstart", 
			function() {    
				// Do something
			}
		);  
		
		// Drag Event - End
		GEvent.addListener(CurrentMarker, "dragend", 
			function() {    
				// Update the Map coordinates and marker position
				SetMapMarkerCoords();
			}
		);  
	
	}
}

/**
 * This function add the marker to the maps
 *
 * Input: None
 * Output: None
 */
function AddPropertyToMap()		{
	try {
		// Get the  Map from the Page 
		var PropLng = document.getElementById('PropLng').value ;
		var PropLat = document.getElementById('PropLat').value ;
		var MapLng = document.getElementById('MapLng').value ;
		var MapLat = document.getElementById('MapLat').value ;
		var MapZoom = parseInt(document.getElementById('MapZoom').value,10) ;
		
		// Return if no position
		if (PropLng.length == 0 || PropLng == 0) {
			//alert ('There is no map for this propery');
			// set Australia Coords
			//PropLat = -26.994250;
			//PropLng = 135.038450;
			//MapLng = PropLng;
			//MapLat = PropLat;
			//MapZoom = 4;
		    //CurrentMap.setCenter(new GLatLng(MapLat, MapLng), MapZoom);

            // Show area of the map
		    if (MapLat.length != 0 && MapLng != 0) {
		        CurrentMap.setCenter(new GLatLng(MapLat, MapLng), MapZoom);
		        return true;
		    }
		    
		    // No map
		    var container = CurrentMap.getContainer();
		    container.style.visibility = "hidden";
		    container.style.position = "absolute";
			return false ;
		}
		
		// Get the Property Marker Point from the coordinates
		point = new GLatLng(PropLat, PropLng);
		
		// Center the map on map center
		CurrentMap.setCenter(new GLatLng(MapLat, MapLng), MapZoom);
							
		// Create a marker
		CreateCurrentMarker(point,'')

		// Add the marker to map
		CurrentMap.addOverlay(CurrentMarker);
		
		// Update the Map coordinates and marker position
		SetMapMarkerCoords();
		
		return true;
	} catch (e) {
		alert ('There is no map for this propery');
		return false ;
	}
}

/**
 * This function saves the map & marker coords on the page
 *
 * Input: None
 * Output: None
 */
function SetMapMarkerCoords() {
	// Update the Map coordinates and marker position to the calling page
	if (CurrentMarker) {
		document.getElementById('PropLng').value = CurrentMarker.getPoint().lng();
		document.getElementById('PropLat').value = CurrentMarker.getPoint().lat();
		document.getElementById('MapLng').value = CurrentMap.getCenter().lng();
		document.getElementById('MapLat').value = CurrentMap.getCenter().lat();
		document.getElementById('MapZoom').value = CurrentMap.getZoom();
	}
}

/*
Google SpreadSheet Code
*/
var cm_map;
var cm_mapMarkers = [];
var cm_mapHTMLS = [];
var bounds = new GLatLngBounds();					

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var cm_baseIcon = new GIcon();
cm_baseIcon.shadow = "/images/maps/shadow50.png";
cm_baseIcon.iconSize = new GSize(20, 34);
cm_baseIcon.shadowSize = new GSize(37, 34);
cm_baseIcon.iconAnchor = new GPoint(9, 34);
cm_baseIcon.infoWindowAnchor = new GPoint(9, 2);
cm_baseIcon.infoShadowAnchor = new GPoint(18, 25);

// Change these parameters to customize map
var param_useSidebar = true;
var param_iconType = "blue";
var param_iconOverType = "green";

// Side bar column parameters
var sidebarTD = document.createElement("td");
sidebarTD.setAttribute("width","150");
sidebarTD.setAttribute("valign","top");
sidebarTD.setAttribute("align","left");
var sidebarDIV = document.createElement("div");
sidebarDIV.id = "cm_sidebarDIV";
sidebarDIV.style.overflow = "auto";
sidebarDIV.style.height = "400px";
sidebarDIV.style.fontSize = "11px";
sidebarDIV.style.color = "#000000";

function cm_load() {  
	if (GBrowserIsCompatible()) {
		// create the map
		cm_map = new GMap2(document.getElementById("cm_map"));
		cm_map.addControl(new GLargeMapControl());
		cm_map.addControl(new GMapTypeControl());	
		cm_map.addControl(new GOverviewMapControl());
		
		cm_AddAllMarkers();
		
		cm_map.setZoom(cm_map.getBoundsZoomLevel(bounds));
		cm_map.setCenter(bounds.getCenter());
	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	} 
}

function cm_AddMarkers(Counter,PropLat,PropLng,html,label, color) {
		
	if(param_useSidebar == true) {
		sidebarTD.appendChild(sidebarDIV);
		document.getElementById("cm_mapTR").appendChild(sidebarTD);
	}

	var point = new GLatLng(PropLat,PropLng); 					
	var marker = cm_createMarker(point,label, html,Counter+1, color);
	cm_map.setCenter(new GLatLng(marker.getPoint().lat(), marker.getPoint().lng()), 14);
	cm_map.addOverlay(marker);
	cm_mapMarkers.push(marker);
	cm_mapHTMLS.push(html);
	bounds.extend(point);
	
	if(param_useSidebar == true) {
		var markerA = document.createElement("a");
		markerA.setAttribute("href","javascript:cm_markerClicked('" + Counter +"')");
		var sidebarText= "";
		sidebarText += "(" + (Counter+1) + ") ";
		sidebarText += label;
		markerA.appendChild(document.createTextNode(sidebarText));
		sidebarDIV.appendChild(markerA);
		sidebarDIV.appendChild(document.createElement("br"));
		sidebarDIV.appendChild(document.createElement("br"));
	} 
}

function cm_createMarker(point, title, html, rank, color) {
	var markerOpts = {};
	var nIcon = new GIcon(cm_baseIcon);

	if(rank > 0 && rank <= 20) {
		nIcon.imageOut = "/images/maps/" +
			"markers/" + color + "/marker" + rank + ".png";
		nIcon.imageOver = "/images/maps/" +
			"markers/" + color + "/marker" + rank + ".png";
		nIcon.image = nIcon.imageOut; 
	} else { 
		nIcon.imageOut = "/images/maps/" +
			"markers/" + color + "/blank.png";
		nIcon.imageOver = "/images/maps/" +
			"markers/" + color + "/blank.png";
		nIcon.image = nIcon.imageOut;
	}
	
	markerOpts.icon = nIcon;
	markerOpts.title = title;		 
	var marker = new GMarker(point, markerOpts);
		
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	GEvent.addListener(marker, "mouseover", function() {
		marker.setImage(marker.getIcon().imageOver);
		cm_markerClicked(rank-1);
	});
	GEvent.addListener(marker, "mouseout", function() {
		marker.setImage(marker.getIcon().imageOut);
	});
	GEvent.addListener(marker, "infowindowopen", function() {
		marker.setImage(marker.getIcon().imageOver);
	});
	GEvent.addListener(marker, "infowindowclose", function() {
		marker.setImage(marker.getIcon().imageOut);
	});
	
	return marker;
}

function cm_markerClicked(markerNum) {
	cm_mapMarkers[markerNum].openInfoWindowHtml(cm_mapHTMLS[markerNum]);
}

/*
Google SpreadSheet Code
*/