/*
	2008-03-26 | robert `smo´ schmoller | next e-marketing gmbh
*/
var mapdata_url;
var map;
var map_element;
var map_lat;
var map_lng;
var map_zoom;
var map_text;
var map_markers;
var map_language = 'de';
var markers = new Array();
var load_markers = new Array();
var gdirPanel;
var gdir;
var direction_to = '';
var direction_input_element;
var direction_results_element;
var geocoder;


function createMarker($point, $text)  {
	var tm = new GMarker($point);
	markers.push(tm);
	map.addOverlay( tm );
	GEvent.addListener( tm, "click", function(overlay) {
		tm.openInfoWindowHtml($text);
		}
	);
}

function startLoadMarkersByAddress ()
{
	if( load_markers.length > 0 ){
		var m = load_markers.pop()
		loadMarkerByAddress( m.address, m.infodata );
	}
}

function loadMarkerByAddress($address, $text) {
	geocoder.getLatLng( $address, function(point) {
		if (!point) {
			alert($address + " not found");
		} else {
			createMarker( new GLatLng( point.lat(), point.lng() ), $text);
			openFirstMarker();
		}
		startLoadMarkersByAddress();
	} );
}

function getDirection ( $id ) {
	var from = document.getElementById($id).value;
	if( from == '' ){
		if( map_language == 'en' ){
			showDirectionMSG('Please insert a valid address.');
		} else {
			showDirectionMSG('Bitte tragen Sie eine gültige Adresse ein.');
		}
	} else {
		showDirectionMSG('loading data...');
		gdir.load("from: " + from + " to: " + direction_to, {"locale": map_language} );
	}
}

function clearDirection () {
	gdir.clear();
}

function showDirectionInput ( $nr ) {
	var adr = map_markers[$nr].getAttribute("address");
	if( adr.length == '' ){
		adr = parseFloat(map_markers[$nr].getAttribute("lat")) + ',' + parseFloat(map_markers[$nr].getAttribute("lng"));
	} 
	direction_to = adr;
	// first set DIV visible !!!
	document.getElementById(direction_input_element).style.display = 'block';
	// now set focus on element
	document.getElementById('gmapDirectionInputFrom').focus();
}

function handleLoadGDirections () {
	//
	document.getElementById('gmapDirectionsToolBar').style.display = 'block';
	clearDirectionMSG();
}

function handleErrorsGDirections () {
	//
	var t;
	document.getElementById('gmapDirectionsToolBar').style.display = 'none';
	//
	if(gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		if( map_language == 'en' ){
			t = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code;
		} else {
			t = "Die Adresse konnte nicht gefunden werden.<br/>Versuchen Sie es mit einer genauere Angabe oder anderen Schreibweise.<br/>Error code: " + gdir.getStatus().code;
		}
	} else if(gdir.getStatus().code == G_GEO_SERVER_ERROR) {
		if( map_language == 'en' ){
			t = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
		} else {
			t = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
		}
	} else if(gdir.getStatus().code == G_GEO_MISSING_QUERY) {
		if( map_language == 'en' ){
			t = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;
		} else {
			t = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;
		}
// 	else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//		alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	} else if(gdir.getStatus().code == G_GEO_BAD_KEY) {
		if( map_language == 'en' ){
			t = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
		} else {
			t = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
		}
	} else if(gdir.getStatus().code == G_GEO_BAD_REQUEST) {
		if( map_language == 'en' ){
			t = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
		} else {
			t = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
		}
	} else {
		if( map_language == 'en' ){
			t = "An unknown error occurred.<br/>The given address couldn't be found.";
		} else {
			t = 'Ein unbekannter Fehler ist aufgetreten.<br/>Die Adresse konnte nicht gefunden werden.';
		}
	}
	showDirectionMSG(t);
}

function showDirectionMSG ( $text ){
	gdirPanel.innerHTML = '<div id="gmapDirectionMSG">' + $text + '</div>';
}

function clearDirectionMSG ()
{
	gdirPanel.innerHTML = '';
}

function openFirstMarker ()
{
	if( markers.length==1 && map_markers.length==1 ){
		infodata = map_markers[0].firstChild.nodeValue;
		infodata += '<br/><br/><a href="javascript:showDirectionInput(0);">';
		if( map_language == 'en' ){
			infodata += 'Get Directions';
		} else {
			infodata += 'Route berechnen';
		}
		infodata += '</a>';
		markers[0].openInfoWindowHtml( infodata );
	}
}

function load() {
	if (GBrowserIsCompatible()) {
		//
		gdirPanel = document.getElementById(direction_results_element);
		showDirectionMSG('loading GMap');
		//
		map = new GMap2(document.getElementById(map_element));
		geocoder = new GClientGeocoder();
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.setCenter(new GLatLng(map_lat, map_lng), map_zoom);
		//
		gdir = new GDirections(map, gdirPanel);
		GEvent.addListener(gdir, "error", handleErrorsGDirections );
		GEvent.addListener(gdir, "load", handleLoadGDirections );
        //
		GDownloadUrl(mapdata_url, function(data, responseCode) {
			var xml = GXml.parse(data);
			map_markers = xml.documentElement.getElementsByTagName("marker");
			load_markers = new Array();
			for (var i = 0; i < map_markers.length; i++) {
				var lat = map_markers[i].getAttribute("lat");
				var lng = map_markers[i].getAttribute("lng");
				var address = map_markers[i].getAttribute("address");
				var infodata = map_markers[i].firstChild.nodeValue;
				//
				infodata += '<br/><br/><a href="javascript:showDirectionInput(' + i +');">';
				if( map_language == 'en' ){
					infodata += 'Get Directions';
				} else {
					infodata += 'Route berechnen';
				}
				infodata += '</a>';
				//
				if( lat!='' && lng !=''){
					lat = parseFloat(lat);
					lng = parseFloat(lng);
					var point = new GLatLng(lat,lng);
					createMarker(point,infodata);
				} else if( address != '' ){
					load_markers.push( {'address': address, 'infodata': infodata} );
				}
			}
			//
			startLoadMarkersByAddress();
			openFirstMarker();
			clearDirectionMSG();
		});
	}
}

function unload () {
	GUnload();
}

