// Locimeutils
var map; var geocoder; var omap; var lqs; var address; var addressAccuracy;
var icon; var markerListener; var marker; var dorevgeocode;

function setFocusHere( tagid ) {
	document.getElementById(tagid).focus();
}

function createMarker(point,html) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function createAndDisplayWatchedMarker(lat,lon) {
	var point = new GLatLng(lat,lon);
	marker = new GMarker(point, {draggable:true, icon:icon, title:"Drag it to desired position"});
	
	map.clearOverlays();
	marker.clickable = false;
	map.addOverlay(marker);
	// alert('lat:'+lat+":"+lon)
	if (map.getZoom() == 1 && lat != 0 && lon != 0 ) {
		map.setZoom(13);
	}
	map.panTo(marker.getLatLng());
	
	if (markerListener) {
		GEvent.removeListener(markerListener);
		updatePageDataLoc(marker.getLatLng().toUrlValue());
	}
	// updatePageDataLoc(marker.getLatLng().toUrlValue())
	
	if (markerListener) {
		GEvent.removeListener(markerListener);
	}
	markerListener = GEvent.addListener(marker, "dragend", function() {
		map.panTo(marker.getLatLng());
		updatePageDataLoc(marker.getLatLng().toUrlValue());
		doReverseGeocoding(marker.getLatLng());
	});
	return marker;
}

function updatePageDataLoc(loc) {
	// document.getElementById("place_lqs").value = loc;
	document.getElementById("place_coords").value = loc;
	// document.getElementById("place_address").value = loc;
	document.getElementById("geo_coords").innerHTML = loc;
}


function positionOverview() {
    var omapel=document.getElementById("map_overview");
	var x = 150; var y= 120;

    // == restyling ==
	omapel.firstChild.style.background = "#808080";
	omapel.firstChild.style.border = "0";
	omapel.firstChild.firstChild.style.border="0";
	omapel.firstChild.firstChild.style.left="4px";
	omapel.firstChild.firstChild.style.top="4px";
	omapel.firstChild.firstChild.style.width = x-4+"px";
	omapel.firstChild.firstChild.style.height = y-4+"px";
	omap.hide();
	omapel.style.visibility="visible"
}

function mapInitialize() {
	if (GBrowserIsCompatible()) { 
				
	  	map = new GMap2(document.getElementById("map"));
		map.setUIToDefault();
		geocoder = new GClientGeocoder();
		
		var iconOptions = {};
		iconOptions.width = 26;
		iconOptions.height = 26;
		iconOptions.primaryColor = "#FF8A00FF";
		iconOptions.cornerColor = "#FF8A00FF";
		iconOptions.strokeColor = "#333333FF";
		icon = MapIconMaker.createMarkerIcon(iconOptions);
		
	} else {
		alert("Sorry, the dynamic map functions are not compatible with this browser, you see the static map with less functions.");
	}
}

function loadDynamicGMap(lat, lon, zoom, maptype) {
	mapInitialize();
	if (map) { 

		var maptypes_s2l = {};
		maptypes_s2l.m = G_NORMAL_MAP;
		maptypes_s2l.k = G_SATELLITE_MAP;
		maptypes_s2l.h = G_HYBRID_MAP;
		maptypes_s2l.p = G_PHYSICAL_MAP;

		map.setMapType(maptypes_s2l[maptype]);
		map.setCenter(new GLatLng(lat,lon),zoom);
				
		createAndDisplayWatchedMarker(lat,lon)

		//  ======== Add a map overview ===========
		omap = new GOverviewMapControl(new GSize(150,120));
		map.addControl(omap);

		//  ======== Cause the overview to be positioned AFTER IE sets its initial position ======== 
		setTimeout("positionOverview()",3500);
		
		//  ======== Add Listeners ======== 
		GEvent.addListener(map, "zoomend", function(prev, next) {
			// alert("You zoomed from: " + prev + " to: " + next + " zoom level");
			document.getElementById("place_zoom").value = next;
			map.panTo(marker.getLatLng());
		});
		GEvent.addListener(map, "maptypechanged", function() {
			// alert("You changed the maptype to:" + map.getCurrentMapType().getUrlArg());
			document.getElementById("place_maptype").value = map.getCurrentMapType().getUrlArg();
		});

	}
}

function updateParamsFromGeocoder(response) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		map.clearOverlays();
  		place = response.Placemark[0];
		createAndDisplayWatchedMarker(place.Point.coordinates[1], place.Point.coordinates[0]);
		// doReverseGeocoding(marker.getLatLng());	
		setDoRevGeoAndDeleteLink();
		// dorevgeocode=1;
		updatePageWithAddress(place);
	}
}

function updateParamsFromReverseGeocoder(response) {
	if (response && response.Status.code == 200) {
		// alert('mam response');
		place = response.Placemark[0];
		document.getElementById("address_info").innerHTML = place.address + ' <span style="white-space: nowrap;">(with accuracy: ' + getGeoAddressAccuracy(place.AddressDetails.Accuracy) + ')</span>';
	}
}

function updatePageWithAddress(place) {
	if (dorevgeocode) {
		document.getElementById("address_info").innerHTML = place.address + ' <span style="white-space: nowrap;">(with accuracy: ' + getGeoAddressAccuracy(place.AddressDetails.Accuracy) + ')</span>';
	}
}

function setDoRevGeoAndDeleteLink() {
	dorevgeocode=1;
	document.getElementById("do_reverse_geocoding_div").innerHTML = ' '
}

// queryLocation() is called when you click on the Try map button
// in the form.  It geocodes the address entered into the form
function queryLocation() {
	if (map) {
		var address = document.getElementById("place_lqs").value;
		geocoder.getLocations(address, updateParamsFromGeocoder);
	}
}

function doReverseGeocoding(latlon) {
	// dorevgeocode = 1;
	if (dorevgeocode && map && latlon != null) {
		geocoder.getLocations(latlon, updateParamsFromReverseGeocoder);
	}
}


function toggleExtForm( what ) {
	var switcher = new Object();
	switcher.moreless = ['/images/but_more.png', '/images/but_more_less.png'];
	switcher.mapmap = ["/images/but_map.png", "/images/but_map_less.png"];
	var elem;
	var link;

	if( document.getElementById ) {
		elem = document.getElementById( "extendedformpart" );
		link = document.getElementById( what );
	} else if ( document.all ) {
	  elem = eval( "document.all.extendedformpart" );
	  link = eval( "document.all." + what );
	} else
		return false;

	if( elem.style.display == "block" ) {
		elem.style.display = "none";
		link.setAttribute( "src", switcher[what][0] );
	} else {
		elem.style.display = "block";
		link.setAttribute( "src", switcher[what][1] );
	}
	// setQFocus();
}


function addMyCodeToFunction(func,code){
    if(func == undefined)
	return code;
    else{
	return function(){
	    func();
	    code();
	}
    }
}

function enterDoesGeocoding(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	if(keycode == 13) {
		queryLocation();
		return false;
	}
	return true;
}

function getGeoAddressAccuracy(n) {
	var acc = {};
	acc[0] = "unknown";
	acc[1] = "country";
	acc[2] = "region";
	acc[3] = "sub-region";
	acc[4] = "town";
	acc[5] = "post/zip code";
	acc[6] = "street";
	acc[7] = "intersection";
	acc[8] = "address";
	acc[9] = "premise";
	return acc[n];
}


// updateDataAfterMapEvents();
