var map;
var gdir; 
var addressMaker;
var ie = jQuery.browser.msie;
var ie6 = ie && parseInt(jQuery.browser.version, 10) == 6;

geocoder = new GClientGeocoder();

var gType = new GMapTypeControl();
var gLarge = new GLargeMapControl();

// Create "venue" marker icon


var destSatNav;
var destLat;
var destLon;
var locationName;
var zoomLevel;
var print = false;

function initialiseMapParameters(name, lat, lng, zoom, icon) {
	locationName = name;
	destLat = lat;
	destLon = lng;
	zoomLevel = zoom;
	
	venueIcon = new GIcon();
	venueIcon.image = icon;
	venueIcon.iconAnchor = new GPoint(18, 44);
	venueIcon.infoWindowAnchor = new GPoint(18, 5);
}

function trim(str, chars) { 
    return ltrim(rtrim(str, chars), chars); 
} 
 
function ltrim(str, chars) { 
    chars = chars || "\\s"; 
    return str.replace(new RegExp("^[" + chars + "]+", "g"), ""); 
} 
 
function rtrim(str, chars) { 
    chars = chars || "\\s"; 
    return str.replace(new RegExp("[" + chars + "]+$", "g"), ""); 
}
	
	
function vGeocoder(from, functn) {
	if(trim(from," \t") == ""){
		alert("The Start Address needs to contain a UK postcode"); 
		return;
	}
	var ajaxURL = contextPath + "/vexed/geocoder?search=" + from;
	$.ajax({
		url: ajaxURL,
		success: function(data) {
			//$('.result').html(data);
			//alert('Load was performed.');
			
			var arry = data.split('|');
			functn(Number(arry[2]),Number(arry[1]));
		},
		error: function() {
			alert('Your location was not recognised or some other error occured.');
			return;
		}
		
	});

}

function load(skipAddressCheck) {
	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("gmaps"));
    
        document.getElementById("directions-text").innerHTML = "";
	    if(document.getElementById("default-directions")){
	    	document.getElementById("default-directions").style.display = "";
	    }
	    document.getElementById("directions-text").style.display = "none";
		gdir = new GDirections(map, document.getElementById("directions-text"));
		GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
		
		if(skipAddressCheck == false){
			GEvent.addListener(gdir, "error", handleErrors);
		}
	
		//destLat = document.getElementById("toSatNavLat").value;
		//destLon = document.getElementById("toSatNavLon").value;
		
		destSatNav = destLat + "," + destLon;
			
	    var center = new GLatLng(destLat, destLon);
		map.setCenter(center, zoomLevel);
		
		if (print) {		
			map.addControl(gType);
			map.addControl(gLarge);
		}
		map.addControl(gLarge);
		map.addControl(gType);
		var marker = new GMarker(center, {draggable: false});
		
		// Set up our GMarkerOptions object literal
		venueMarker = new GMarker(center, { icon: venueIcon });
		
		GEvent.addListener(venueMarker ,"click", function() {     
			var myHtml = "<div class='gmaps-bubble'><h1>Cameron House</h1><br /><p>Cameron House,<br />Loch Lomond,<br />Dunbartonshire,<br />G83 8QZ<br /><br />Telephone: 01389 755 565<br />Fax: 01389 713 281</div>";
			venueMarker.openInfoWindow(myHtml);
		});
	
		map.addOverlay(venueMarker);
		
		
		if (document.getElementById('start-place').value!='') {
			setDirections(document.getElementById('start-place').value);
		}
		
	}
}
var fromAddressSatNav;

function setDirections(fromAddress) {
	if (document.getElementById("directions-text").style.display == "none") {
		document.getElementById("directions-text").style.display = "";
		if (document.getElementById("default-directions")) {
			document.getElementById("default-directions").style.display = "none";
		}
	}

	map.removeOverlay(venueMarker);

	vGeocoder(fromAddress, processSatNav);
	
	
}
function processSatNav(y, x) {
	gdir.load("from: " + y + "," + x + " to: " + destSatNav, {
		"locale" : "en"
	});
	var dest = new GLatLng(destLat, destLon);
	// change the positioning of the marker
	venueIcon.iconAnchor = new GPoint(15, 42);
	var venueMarker2 = new GMarker(dest, {
		icon : venueIcon
	});
	map.addOverlay(venueMarker2);
}

function handleErrors() {
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {

		document.getElementById("directions-text").style.display = "none";
		alert("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.");

	} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {

		document.getElementById("directions-text").style.display = "none";
		alert("A geocoding or directions request could not be successfully processed.");

	} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {

		document.getElementById("directions-text").style.display = "none";
		alert("'Start Address' field had no value. This means that an empty address was specified as input for directions requests");

	} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {

		document.getElementById("directions-text").style.display = "none";
		alert("The given key is either invalid or does not match the domain for which it was given.");

	} else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {

		document.getElementById("directions-text").style.display = "none";
		alert("A directions request could not be successfully processed.");

	} else {

		document.getElementById("directions-text").style.display = "none";
		alert("Directions could not be determined for the specified start address.");
	}

}

function onGDirectionsLoad() {
	// Use this function to access information about the latest load()
	// results.

	// e.g.
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
	gdir.getMarker(1).hide();
	
}