// =============================================
// =============================================
// object to manage nearest points on a map
// =====================================================
// CONSTRUCTOR
NearestPointContainer = function(pSize){
	this.points = [];
	this.size = pSize;
	this.furthest = 0;
	this.nearest = 0;
};

NearestPointContainer.prototype.reset = function(){
	this.points = []
	this.furthest = 0;
	this.nearest = 0;
};

NearestPointContainer.prototype.getNearestDist = function(){
	return this.nearest;
};

NearestPointContainer.prototype.test = function(pDist, pData){
	var dataItem = {dist:pDist, data:pData};
	if(this.points.length){
		if((this.points.length == this.size) && (dataItem.dist <= this.furthest)){
			// item needs to be added to our array... but we need to find out where...
			for(var i=0; i<this.points.length; i++){
				if(this.points[i].dist > dataItem.dist){
					this.points.splice(i, 0, dataItem);
					break;
				}
			}
		}else{
			this.points.push(dataItem);
		}
	}else if(!this.points.length){
		// nothing in our array... so we are safe to add this...
		this.points.push(dataItem);
	}
	
	// remove end items if our array is now too large
	while(this.points.length > this.size){
		this.points.splice(this.size, 1);
	}
	
	if(this.points.length){
		this.furthest = this.points[this.points.length-1].dist;
		this.nearest = this.points[0].dist;
	}
	
};

NearestPointContainer.prototype.get = function(){
	return this.points;
};

// =============================================
// =============================================
// map parameters
var map = null; // map reference in a global scope
var geo = null; // Google Maps Client Geocoder
var localSearch = null; // Google Local Search
var localSearch =  null; // search API reference in global scope
var mgr = null; // reference to our marker manager in global scope
var home = {x:52.8691, y:-1.8457}; // long & lat for England
var minZoom = 6;
var maxZoom = 15;
var startZoom = 6; // start point for zoom
var searchZoom = 11; // amount to zoom to after a search
var markerCutOffZoom = 8; // zoom level at which markers are displayed
var DOMContainer = "#map"; // DOM object into which the map gets loaded
var GMarkers = []; // array of markers in use on the map at any moment in time
var data = []; // container for our data to use on the map
var geoStatusCode = []; // status code array
var nearestSearchResults = []; 
var searchResults = [];
var searchForm = null;
var showingSearchResult = false;
var infoWindowMarkerID = 0; // data ID of currently displayed info marker.
var regionalPoints = []; // array of regional markers to be used when the map is zoomed out past the markerCutOffZoom point
var regionalMarker = null;
var officeMarker = null;
var searchMode = "NEAR"; // NEAR | RADIUS
var showImages = true; // flag that turns office images on an off

// object used to manage the nearest points following a geo search
var NearestPoints = new NearestPointContainer(10);


// initialise the map
function loadMap(){
	if(GBrowserIsCompatible()){
		searchForm = document.getElementById("mapSearchForm")
		
		// define map in DOM
		map = new GMap2($(DOMContainer).get(0));
		// add controls to the map
		map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());
		// position our map
		map.setCenter(new GLatLng(home.x, home.y), startZoom);
		
		// event listener for when the map has finished moving
		GEvent.addListener(map, "moveend", function() {
			setTimeout("redrawMarkers()", 100);
		});
		
		// event listener for when the info window is closed
		GEvent.addListener(map.getInfoWindow(), "closeclick", function() {
			infoWindowMarkerID = 0; // clear marker reference
		});
		
		
		// set our cleanup onunload handler - we can be sure that this method now exists here
		window.onunload = GUnload;
		
		// define our marker data
		loadMarkerData();
		
		
		// initiate our Geocoder
		geo = new GClientGeocoder();
		localSearch = new GlocalSearch();
		
		// Array for decoding the failure codes ======
		geoStatusCode[G_GEO_SUCCESS]            = "Success";
		geoStatusCode[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
		geoStatusCode[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
		geoStatusCode[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		geoStatusCode[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
		geoStatusCode[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		geoStatusCode[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
		
		
		G_PHYSICAL_MAP.getMinimumResolution = function(){return minZoom};
		G_NORMAL_MAP.getMinimumResolution = function(){return minZoom};
		G_SATELLITE_MAP.getMinimumResolution = function(){return minZoom};
		G_HYBRID_MAP.getMinimumResolution = function(){return minZoom};
		
		G_PHYSICAL_MAP.getMaximumResolution = function(){return maxZoom};
		G_NORMAL_MAP.getMaximumResolution = function(){return maxZoom};
		G_SATELLITE_MAP.getMaximumResolution = function(){return maxZoom};
		G_HYBRID_MAP.getMaximumResolution = function(){return maxZoom}; 
		
		// define our marker icons
		/*regionalIcon = new GIcon(G_DEFAULT_ICON);
		regionalIcon.image = "graphics/localServices/marker_region.png";
		regionalIcon.iconSize = new GSize(23, 32);
		regionalIcon.iconAnchor = new GPoint(11, 32);
		//regionalIcon.infoWindowAnchor = new GPoint(11, 32);
		regionalIcon.shadowSize = new GSize(37, 32);*/
		regionalIcon = new GIcon(G_DEFAULT_ICON);
		regionalIcon.image = "graphics/localServices/marker_region01.png";
		regionalIcon.iconSize = new GSize(34, 45);
		regionalIcon.iconAnchor = new GPoint(17, 32);
		//regionalIcon.infoWindowAnchor = new GPoint(11, 32);
		regionalIcon.shadowSize = new GSize(37, 32);

		officeIcon = new GIcon(G_DEFAULT_ICON);
		officeIcon.image = "graphics/localServices/marker_office.png";
		officeIcon.iconSize = new GSize(19, 26);
		officeIcon.iconAnchor = new GPoint(9, 26);
		officeIcon.infoWindowAnchor = new GPoint(9, 8);
		officeIcon.shadowSize = new GSize(37, 26);

		drawRegionalMarkers();
		
		window.onunload = GUnload;
	}
}

// set onload handler
//window.onload = loadMap;


function addData(pLat, pLong, pTitle, pID, pAddress1, pAddress2, pAddress3, pPostCode, pTelephone, pEmail, pWebsite, pOpeningHours, pProspectus1419, pArea, pDistrict, pImagePath, pImageWidth, pImageHeight){
	// construct address string
	var address = pAddress1;
	if(pAddress2.length) address += "<br \/>" + pAddress2;
	if(pAddress3.length) address += "<br \/>" + pAddress3;
	if(pPostCode.length) address += "<br \/>" + pPostCode;
	// insert breaks into opening hours
	var openingHours = pOpeningHours.replace(new RegExp( "\\n", "g" ), "<br \/>");
	// define data object
	var o = {long:pLong, lat:pLat, title:pTitle, ID:pID, address:address, postCode:pPostCode, telephone:pTelephone, email:pEmail, website:pWebsite, openingHours:openingHours, prospectus1419:pProspectus1419, area:pArea, district:pDistrict, imagePath:pImagePath, imageWidth:pImageWidth, imageHeight:pImageHeight};
	//data.push(o);
	data["ID_" + pID] = o;
}

function getDataByID(pID){
	return data["ID_" + pID];
}


function createMarker(point, html, id) {
	var marker = new GMarker(point, {icon:officeIcon});
	marker.MYid = id;
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
		infoWindowMarkerID = marker.MYid;
		trackOffice();
	});
	return marker;
}

function createRegionalMarker(point, title, id) {
	var marker = new GMarker(point, {title:title, icon:regionalIcon});
	var trueID = id.replace("REGIONAL_", "");
	marker.MYid = id;
	GEvent.addListener(marker, "click", function() {
		//marker.openInfoWindowHtml(html);
		//infoWindowMarkerID = marker.MYid;
		//map.setCenter(marker.getLatLng(), markerCutOffZoom+1);
		toggleRegion(trueID);
		
	});
	return marker;
}


// adds a markers to our marker manager
function loadMarkerData() {	
	
}

// ======================================
// keep track of our markers...
function addMarker(m){
	map.addOverlay(m);
	GMarkers.push(m); // add reference to marker
}

function removeMarker(m){
	// find our marker in our reference array and remove it
	for(var i=0; i<GMarkers.length; i++){
		if(GMarkers[i] == m){
			GMarkers.splice(i, 1);
			break;
		}
	}
	map.removeOverlay(m);
}

function clearMarkers(){
	map.clearOverlays(); // clear all existing markers from the map
	GMarkers = []; // clear our reference array
}

function getMarkerByID(pID){
	// search through our visible markers to look for a given ID 
	for(var i=0; i<GMarkers.length; i++){
		if(GMarkers[i].MYid == pID){
			return GMarkers[i];
		}
	}
	return null;
}
// ======================================

function drawRegionalMarkers(){
	var marker = null;
	
	if((map.getZoom() <= markerCutOffZoom) && !showingSearchResult){
		clearMarkers();
		for(var i=0; i<regionalPoints.length; i++){
			marker = createRegionalMarker(new GLatLng(regionalPoints[i].lat, regionalPoints[i].long), regionalPoints[i].title, "REGIONAL_" + i);
			addMarker(marker);
		}
	}
	
	drawRegionalSidePanel();
}

function drawRegionalSidePanel(){
	var panelHTML = "<div class=\"regionSelect\"><h3>Select your region:<\/h3>";
	for(var i=0; i<regionalPoints.length; i++){
		panelHTML += "<p><a href=\"javascript:void(0);\" onclick=\"toggleRegion(" + i + ")\" class=\"regionTitle\">" + regionalPoints[i].title + "<\/a>";
		if(regionalPoints[i].regionIncludes.length){
			panelHTML += "<br\/><span>Including: " + regionalPoints[i].regionIncludes + "<\/span>";
		}
		panelHTML += "<\/p>";
	}
	panelHTML += "<\/div>";
	$("#mapSide").get(0).scrollTop = 0;
	$("#mapSide").get(0).innerHTML = panelHTML;
}

function getSearchRadius(){
	if($("#searchDist").get(0)){
		return $("#searchDist").get(0).options[$("#searchDist").get(0).selectedIndex].value; // user selected search radius
	}else{
		return 10;
	}
}

// ======================================

// adds a marker to our map
/*function setMarker(){
	var marker = new GMarker(new GLatLng(home.x, home.y));
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml("Marker Test");
	});
	map.addOverlay(marker);
}*/

// ============================================================
// MARKERS
// ============================================================

// search for markers near a given point
function findNearest(point){
	var r = getSearchRadius();

	NearestPoints.reset(); // reset our nearest point object
	
	//map.clearOverlays(); // clear all existing markers from the map
	clearMarkers();
	
	// loop through all our data
	//for(var i=0; i<data.length; i++) {
	var count = 0;
	for(var i in data){
		var m = data[i];
		if(m.ID){ // check for our object as IE include additional properties here...
			count ++;
			var mPoint = new GLatLng(m.lat, m.long);
			var d = point.distanceFrom(mPoint)/1000; // calculate the distance from our given point
			
			//alert("A: " + m);
			NearestPoints.test(d, m); // log this with our nearest point object
			
			// if our dispance is within our search radius, we create a marker
			if((searchMode == "RADIUS") && (d<=r)){
				// create and display a marker
				var marker = createMarker(mPoint, buildMarkerHTML(m), m.ID);
				//map.addOverlay(marker);
				addMarker(marker);
			}
		}
	}

	if(searchMode == "NEAR"){
		showNearestMarkers();
	}
	//drawSidePanel();
	
}

function findNearestPoint(lat, lng){
	var point = new GLatLng(lat, lng);
	map.setCenter(point, searchZoom);
	findNearest(point);
	//$("#mapMsg").get(0).innerHTML = "";
}

// redraws markers visible on current map
// gets called after the map has moved or zoomed and is used to display only those markers that are within the view pane
// if the map is currently showing a search result, this gets skipped as all search results are displayed
function redrawMarkers(){
	var bounds = map.getBounds();
	var r = bounds.getSouthWest().distanceFrom(bounds.getNorthEast())/1000/2;
	var c = map.getCenter();
	
	// clear current search result information
	nearestSearchResults = [];
	searchResults = [];
	
	if(!showingSearchResult){
		
		// clear all markers that do not have an info window open...
		for(var i=0; i<GMarkers.length; i++){
			if(GMarkers[i].MYid != infoWindowMarkerID){
				removeMarker(GMarkers[i]);
				i--; // we have removed a marker from our GMarkers array, so need to correct our index value...
			}
		}
		//map.clearOverlays(); // clear all existing markers from the map
	
		//alert(data.length);
		// loop through our data
		//for(var i=0; i<data.length; i++) {
		// check our zoom level
		if(map.getZoom() > markerCutOffZoom){
			for(var i in data){
				var m = data[i];
				if(m.ID){ // check for our object as IE include additional properties here...
					var mPoint = new GLatLng(m.lat, m.long);
		
					var d = c.distanceFrom(mPoint)/1000; // calculate the distance from the centre of the map in KMs
					
					// are we inside our search radius??
					if(d<=r){
						// make sure that this marker does not already exist
						if(m.ID != infoWindowMarkerID){
							// create and display a marker
							var marker = createMarker(mPoint, buildMarkerHTML(m), m.ID);
							//map.addOverlay(marker);
							addMarker(marker);
						}
					}
				}
			}
		}else{
			drawRegionalMarkers();
		}
	}
	
}

function showNearestMarkers(){
	var aNearest = NearestPoints.get();
	
	for(var i=0; i<aNearest.length; i++){
		var m = aNearest[i].data;
		var mPoint = new GLatLng(m.lat, m.long);
		// create and display a marker
		var marker = createMarker(mPoint, buildMarkerHTML(m), m.ID);
		addMarker(marker);
	}
	
	drawSidePanel(NearestPoints.get(), "10 Nearest Connexions Offices");
}

// populates our side panel with our 'nearest' search results
function drawSidePanel(pData, pTitle){
	//var aNearest = NearestPoints.get();
	var html = "<div class=\"searchResults\"><h3>" + pTitle + "<\/h3>";
	var itemDist = null;
	var itemData = {};
	
	for(var i=0; i<pData.length; i++){
		if(pData[i].dist){
			itemDist = pData[i].dist
		}else{
			itemDist = null;
		}
		if(pData[i].data){
			itemData = pData[i].data;
		}else{
			itemData = pData[i];
		}
		
		html += "<p>";
		html += "<span class=\"distMarker\"><img src=\"graphics\/localServices\/marker_office.gif\" width=\"19\" height=\"26\" alt=\"\" \/><br \/>";
		if(itemDist){
			html += Math.round(itemDist * 10)/10 + "km";
		}
		html += "<\/span>";
		html += "<strong class=\"title\"><a href=\"javascript:void(0);\" onclick=\"toggleOffice(" + itemData.ID + ");\">" + itemData.title + "<\/a><\/strong><br \/>";
		html += "<strong class=\"district\">" + itemData.district + "<\/strong>";
		html += "<span class=\"summary\">" + buildSummaryHTML(itemData) + "<\/span>";
		html += "<\/p>";
	}
	html += "<\/div>";
	$("#mapSide").get(0).scrollTop = 0;
	$("#mapSide").get(0).innerHTML = html;
	// ======================
}

function searchRegion(pIndex){
	var region = regionalPoints[pIndex];
	var aRegionalOffices = [];
	if(region){
		for(var i in data){
			var m = data[i];
			if(m.ID && (m.area == region.title)){ // check for our object as IE include additional properties here...
				aRegionalOffices.push(m);
			}
		}	
	}
	
	if(aRegionalOffices.length){
		//alert(aRegionalOffices.length);
		// sort our array
		
		// build our side panel html
		drawSidePanel(aRegionalOffices, region.title);
	}
}

function toggleRegion(pIndex){
	var region = regionalPoints[pIndex];
	if(region){
		//alert(region.title);
		map.setCenter(new GLatLng(region.lat, region.long), markerCutOffZoom+1);
		searchRegion(pIndex);
		// log with Google Analytics
		analytics("localservices/map/region/" + region.title);
	}
}

function toggleOffice(pID){
	var marker = getMarkerByID(pID);
	var mPoint = null;
	var d = null;
	
	if(!marker){
		// marker not found...
		var d = getDataByID(pID);
		if(d){
			mPoint = new GLatLng(d.lat, d.long);
			// create and display a marker
			marker = createMarker(mPoint, buildMarkerHTML(d), d.ID);					
			//map.addOverlay(marker);
			addMarker(marker);
		}
	}

	if(marker){
		GEvent.trigger(marker, "click");
	}
}

function trackOffice(){
	var logString = "localservices/map/office/";
	var d = getDataByID(infoWindowMarkerID);
	analytics(logString + d.title);
}

// log with Google Analytics
function analytics(logString){
	if(isDefined("pageTracker")){
		pageTracker._trackPageview(logString);
	}else if(isDefined("urchinTracker")){
		urchinTracker(logString);
	}
}

function buildMarkerHTML(pData){
	var html = "<div class=\"markerWrapper\"><div class=\"markerTitle\">";
	html += "<strong class=\"title\">" + pData.title + "<\/strong><br \/>";
	html += "<strong class=\"district\">" + pData.district + "<\/strong><\/div>";
	html += buildSummaryHTML(pData);
	html += "<\/div>";
	return html
}

function buildSummaryHTML(pData){
	var html = "";
	if(showImages){
		if(pData.imagePath.length){html += "<img src=\"" + pData.imagePath + "\" width=\"" + pData.imageWidth + "\" height=\"" + pData.imageHeight + "\" alt=\"\" float=\"right\" class=\"officeImg\"\/>";}
	}
	if(pData.openingHours.length){html += "<strong>Opening Hours:<\/strong><br \/>" + pData.openingHours + "<br \/>";}
	if(pData.address.length){html += "<strong>Address:<\/strong><br \/>" + pData.address + "<br \/>";}
	if(pData.telephone.length){html += "<strong>Telephone:<\/strong> " + pData.telephone + "<br \/>";}
	if(pData.email.length){html += "<strong>Email:<\/strong> <a href=\"mailto:" + pData.email + "\">" + pData.email + "<\/a><br \/>";}
	if(pData.website.length){html += "<strong>Website:<\/strong> <a href=\"http:\/\/" + pData.website + "\" target=\"_blank\" title=\"" + pData.website + " - opens in a new window\">" + pData.website + "<\/a><br \/>";}
	if(pData.prospectus1419.length){html += "<strong>14-19 Prospectus:<\/strong> <a href=\"http:\/\/" + pData.prospectus1419 + "\" target=\"_blank\" title=\"" + pData.prospectus1419 + " - opens in a new window\">" + pData.prospectus1419 + "<\/a><br \/>";}
	
	//if(pData.dropInHours.length){html += "<strong>Drop In Hours:<\/strong><br \/>" + pData.dropInHours + "<br \/>";}
	return html
}

// ============================================================
// GEO CODING
// ============================================================


function searchMap(){
	var didYouMeanHTML = "";
	
	if(searchForm){
	
		// ==================================================
		// Search using Google Maps GeoCache Object
		// NOTE: searches include 'UK' by default to force results to the UK
		//alert(searchForm.address.value);
		geo.getLocations(searchForm.address.value + ", England, UK", function(result){
			if(result.Status.code == G_GEO_SUCCESS){
				showingSearchResult = true;
				if(result.Placemark.length > 1){
					// multiple results - ask user to select an address
					//document.getElementById("mapMsg").innerHTML = "Did you mean:";
					didYouMeanHTML = "<p><strong>Did you mean:</strong></p>";
					didYouMeanHTML += "<div id=\"locationOptions\">";
					didYouMeanHTML += "<ol>";
					// Loop through the results
					for(var i=0; i<result.Placemark.length; i++){
						var p = result.Placemark[i].Point.coordinates;
						didYouMeanHTML += "<li><a href='javascript:findNearestPoint(" +p[1]+","+p[0]+");$.modal.close();'>"+ result.Placemark[i].address+"<\/a><\/li>";
					}
					didYouMeanHTML += "<\/ol>";
					didYouMeanHTML += "<\/div>";
					didYouMeanHTML += "<div style=\"text-align: center\"><button onclick=\"$.modal.close();\">Cancel</button></div>";
					$.modal(didYouMeanHTML, {
						onOpen: function (dialog){
							dialog.overlay.fadeIn("fast", function () {
								dialog.container.slideDown("fast", function () {
									dialog.data.fadeIn("fast");
								});
							});
						},
						onClose: function (dialog) {
							dialog.data.fadeOut("fast", function () {
								dialog.container.slideUp("fast", function () {
									dialog.overlay.fadeOut("fast", function () {
										$.modal.close(); // must call this!
									});
								});
							});
						}
					});
					//Modalbox.show(didYouMeanHTML, {title:"Did you mean:", width:300});
				}else{
					// single result - go straight to it
					//document.getElementById("mapMsg").innerHTML = "";
					//$("#mapMsg").get(0).innerHTML = "";
					var p = result.Placemark[0].Point.coordinates;
					findNearestPoint(p[1],p[0]);
				}
			}else{
				// error with search - inform user
				var reason = "Code " + result.Status.code;
				if (geoStatusCode[result.Status.code]) {
					reason = geoStatusCode[result.Status.code]
				} 
				//alert("Could not find '" + searchForm.address.value + "'\r\n" + reason);
				
				// ==================================================
				// Search using LocalSearch Object
				localSearch.setSearchCompleteCallback(null, function() {
					if(localSearch.results.length >= 1){
						if(localSearch.results.length > 1){
							// multiple results - ask user to select an address
							didYouMeanHTML = "<p><strong>Did you mean:</strong></p>";
							didYouMeanHTML += "<div id=\"locationOptions\">";
							didYouMeanHTML += "<ol>";
							// Loop through the results
							for(var i=0; i<localSearch.results.length; i++){
								//var p = localSearch.results[i].Point.coordinates;
								didYouMeanHTML += "<li><a href='javascript:findNearestPoint(" +localSearch.results[i].lat +","+localSearch.results[i].lng +");$.modal.close();'>"+ localSearch.results[i].streetAddress +"<\/a><\/li>";
							}
							didYouMeanHTML += "<\/ol>";
							didYouMeanHTML += "<\/div>";
							didYouMeanHTML += "<div style=\"text-align: center\"><button onclick=\"$.modal.close();\">Cancel</button></div>";
							$.modal(didYouMeanHTML, {
								onOpen: function (dialog){
									dialog.overlay.fadeIn("fast", function () {
										dialog.container.slideDown("fast", function () {
											dialog.data.fadeIn("fast");
										});
									});
								},
								onClose: function (dialog) {
									dialog.data.fadeOut("fast", function () {
										dialog.container.slideUp("fast", function () {
											dialog.overlay.fadeOut("fast", function () {
												$.modal.close(); // must call this!
											});
										});
									});
								}
							});
						}else{
							//var p = result.Placemark[0].Point.coordinates;
							findNearestPoint(localSearch.results[0].lat, localSearch.results[0].lng);
						}
					}else{
						// no results found - inform the user
						alert("Could not find '" + searchForm.address.value + "'\r\nPlease ammend your search.");
					}
					/*alert(localSearch.results.length);
					if(localSearch.results[0]){
						for(var d in localSearch.results[0]){
							alert(d + " - " + localSearch.results[0][d]);
						}						
					}*/
				});
				localSearch.execute(searchForm.address.value + ", England, UK");
				//alert("secondary search");
			}
		});
		
	}
}


// clear our current search
function clearSearch(){
	nearestSearchResults = [];
	searchResults = [];
	searchForm.address.value = "";
	//$("#mapMsg").get(0).innerHTML = "";
	//$("#mapSide").get(0).scrollTop = 0;
	//$("#mapSide").get(0).innerHTML = "";
	showingSearchResult = false;
	redrawMarkers();
	drawRegionalSidePanel();
	// reset our map
	map.returnToSavedPosition()
}


// test for return being used to submit the search form
function checkSubmit(myfield, e){
	var keycode = "";
	
	if(window.event){
		keycode = window.event.keyCode;
	}else if(e){
		keycode = e.which;
	}else{
		return true;
	}

	if(keycode == 13){
		//myfield.form.submit();
		searchMap();
		return false;
	}else{
		return true;
	}
}

function isDefined(variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function clearSearchField(pElement, pDefaultValue){
	if(pElement.value == pDefaultValue){
		pElement.value = "";
	}
	pElement.style.color = "black";
	
}