/*
 * Google Maps Location Finder v1.0.0
 *
 * Copyright (c) 2008 Anthony James McCreath
 *
 * http://www.mccreath.org.uk/Article/Google-Maps-Location-Finder_42.aspx
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
 
 /* Initial settings */
 
var GmlLat = -34.92441;
var GmlLng = 138.622352;
var GmlLevel = 14;
var GmlAddress = "24 Wakefield St, Kent Town";

/**********************/

var GmlMap;
var GmlEditorMarker;
var GmlLatInput;
var GmlLngInput;
var GmlAddressInput;

var GmlClientGeocoder;

google.load("maps", "2");

function GetGoogleMapUrl(key)
{
    return "http://maps.google.com/?ll="+GmlEditorMarker.getLatLng().toUrlValue()+"&z="+GmlMap.getZoom();
}

function GetStaticMapUrl(key)
{
    var mapType = "roadmap";
    
    switch(GmlMap.getCurrentMapType().getName())
    {
        case "Hybrid":
            mapType = "hybrid";
            break;
        case "Satellite":
            mapType = "satellite";
            break;
    }
    
    if (key == undefined) {
        key = "ABQIAAAAkw6gVxNz7EV2QRCVbg9kIRRZC_nn5wZYQ5ZEUmVWg3R7X6ji8hTo_1ddrKgSxMeo1_Im5er0ryHGkQ";
    }
    
    return "http://maps.google.com/staticmap?center="+GmlMap.getCenter().toUrlValue()+"&zoom="+GmlMap.getZoom()+"&size="+GmlMap.getSize().width+"x"+GmlMap.getSize().height+"&maptype="+mapType+"&markers="+GmlEditorMarker.getLatLng().toUrlValue()+",reda&key="+key+"&sensor=false";
}

function GetStaticMapHtml(key)
{
    return "<a href='"+GetGoogleMapUrl(key)+"' title='View in Google Maps'><img src='"+GetStaticMapUrl(key)+"' alt='A map marking my location' /></a>"; 
}

function SetStaticMapHtml()
{
    var e = document.getElementById("GmlTextBoxStaticMap");
    
    if (e !== null) {
        e.value = GetStaticMapHtml('YOUR_KEY_HERE'); 
	}
}
    
function GmlCentreMarker(overlay,point)
{
    var newLatLng = point;
    GmlEditorMarker.setLatLng(newLatLng);
    GmlLatInput.value = GmlEditorMarker.getLatLng().lat(); 
    GmlLngInput.value = GmlEditorMarker.getLatLng().lng();
    GmlMap.savePosition();  
    SetStaticMapHtml();
}

function GmlUpdateInputsFromMarker()
{
    GmlLatInput.value = GmlEditorMarker.getLatLng().lat(); 
    GmlLngInput.value = GmlEditorMarker.getLatLng().lng();
    GmlMap.savePosition();  
    SetStaticMapHtml();
}

function GmlMoveEditorMarkerLatLng() {
    var newLatLng = new google.maps.LatLng(GmlLatInput.value, GmlLngInput.value);
    GmlEditorMarker.setLatLng(newLatLng); 
    GmlMap.setCenter(newLatLng);
    GmlMap.savePosition();
    SetStaticMapHtml();
}

function GmlMoveEditorMarkerAddressResponse(response) {
    if (!response || response.Status.code != 200) {
        alert("Sorry, I could not find that address, please try again.");
    //    alert("Sorry, we were unable to geocode that address (status code "+ response.Status.code+")");
    } else {
		var accuracy = -1;
		var place = null;
		for(var i = 0; i< response.Placemark.length; i++)
		{
			var placemark = response.Placemark[i];
			
			if (placemark.AddressDetails.Accuracy > accuracy)
			{
				place = placemark;
				accuracy = placemark.AddressDetails.Accuracy;
			}
		}
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
        GmlEditorMarker.setLatLng(point);
        GmlMap.setCenter(point);
        GmlUpdateInputsFromMarker();
    }
    SetStaticMapHtml();
}

function GmlMoveEditorMarkerAddress() { 
    GmlClientGeocoder.getLocations(GmlAddressInput.value,  GmlMoveEditorMarkerAddressResponse);
}

// usage is onkeypress="if (GmlIsEnter(event)) {...}"
function GmlIsEnter(e)
{
return false; // is causing .Net post issues
    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    } else if (e) {
        keycode = e.which;  
    } else {
        return false;
    }

    return keycode == 13;
}

function GmlAddEditorMarker(latitude, longitude, latInputId, lngInputId, addressInputId) {
    var position = new google.maps.LatLng(latitude, longitude);

    GmlEditorMarker = new google.maps.Marker(position, { title: "Drag to your favourite location", draggable: true, bouncy: true });
    
    GmlEditorMarker.enableDragging();
   
    GmlMap.addOverlay(GmlEditorMarker);
    
    GmlMap.enableScrollWheelZoom();
    
    GmlLatInput = document.getElementById(latInputId);
    GmlLngInput = document.getElementById(lngInputId);
    GmlAddressInput = document.getElementById(addressInputId);
      
    GEvent.addListener(GmlEditorMarker, "dragend", function() {  GmlUpdateInputsFromMarker();  });
    
    GEvent.addListener(GmlMap, "click", function(overlay,point) {  GmlCentreMarker(overlay,point);  });   
}

function GmlLoader() {
    if (window.addEventListener) {
	    window.addEventListener("unload",google.maps.Unload,false);
    } else if (window.attachEvent) {
	    window.attachEvent("onunload",google.maps.Unload);
    } else {
	    window.onunload = function() {google.maps.Unload();};
    }

    if (google.maps.BrowserIsCompatible() && document.getElementById("GmlMap") !== null) { 
    
        if (google.loader.ClientLocation)
        {
            GmlLat = google.loader.ClientLocation.latitude;
            GmlLng = google.loader.ClientLocation.longitude;
            GmlAddress = google.loader.ClientLocation.address.city + ", "+google.loader.ClientLocation.address.country;    
        }

        GmlClientGeocoder = new google.maps.ClientGeocoder();
        GmlMap = new google.maps.Map2(document.getElementById("GmlMap"));
        GmlMap.setCenter(new google.maps.LatLng(GmlLat, GmlLng), GmlLevel); 
        GmlAddEditorMarker(GmlLat, GmlLng,'GmlTextBoxLat','GmlTextBoxLng','GmlTextBoxAddress'); 
        GmlUpdateInputsFromMarker(); 
        GmlAddressInput.value = GmlAddress; 
        GmlMap.addControl(new google.maps.LargeMapControl()); 
        GmlMap.addControl(new google.maps.MapTypeControl()); 
        SetStaticMapHtml();
    }
}

if (window.addEventListener) {
        window.addEventListener('load',GmlLoader,false);
    } else if (window.attachEvent) {
        window.attachEvent('onload',GmlLoader);
    } else {
        window.onload = function() {GmlLoader();};
}