/**
 * 
 * JS-file for Map- and GUI-functionality.
 * 
 * @author Heikki Ylitalo <heikki.ylitalo@dimenteq.fi>
 * @copyright Dimenteq Oy
 */

//GLOBALS:
var map, mapControls, language = 'fi', selectControl, groute, company, featureInfo, companyName, geoserver, startIndex = 0, toast, companyId, filterArr, colorbox, popup, markers, searchPage = 0, resultsFound = 0, searchActive = false, idList; 
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();

/**
 * 
 * Wait for the DOM to load.
 * 
 */
$(window).load(function() {
	colorbox = $.colorbox;
	singleSelectInputs();
	$("a.local-link").each(function() { 
		$(this).attr("target", "_blank");
	});
	loadMap();
	loadUIFunctionality();
}); // END $(window).load()

/**
 * 
 * Loads the map.
 * 
 */
function loadMap() {
	/*
	 * Map configuration.
	 */
	OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
	var min_zoom = 5;   // min zoom level
	var max_zoom = 18;  // max zoom level
	var options = {
        controls: []
        ,projection: new OpenLayers.Projection("EPSG:900913")
        ,units: "meters"
        ,numZoomLevels: 14
        ,maxZoomLevel: max_zoom
        ,minZoomLevel: min_zoom
        ,maxExtent: new OpenLayers.Bounds(-2.003750834E7,-2.003750834E7,2.003750834E7,2.003750834E7)
		,disableDefaultUI: false
    };
	map = new OpenLayers.Map('map', options);
	geoserver = window.location.host;
	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
    OpenLayers.DOTS_PER_INCH = 91;
    var gmap = new OpenLayers.Layer.Google("Google Streets", {
		sphericalMercator: true
    }); // google map default layer
    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style.fillOpacity = 0.2;
    layer_style.graphicOpacity = 0.5;
    layer_style.strokeWidth = 5;
    layer_style.strokeColor = "#eb1c00";
	groute = new OpenLayers.Layer.Vector("Route",{
    	style: layer_style
    });
	map.addLayers([gmap, groute]);
	map.setCenter(new OpenLayers.LonLat(2913168.0076827, 9048309.7629256), 1);
	$.ajax({url: "/Bisnode/MapAccessLog", dataType: "json", type: "POST"});
    var sketchSymbolizers = {
        "Point": {
            pointRadius: 4,
            graphicName: "circle",
            fillColor: "black",
            fillOpacity: 1,
            strokeWidth: 1,
            strokeOpacity: 1,
            strokeColor: "#eb1c00"
        },
        "Line": {
            strokeWidth: 3,
            strokeOpacity: 1,
            strokeColor: "#eb1c00",
            strokeDashstyle: "dash"
        },
        "Polygon": {
            strokeWidth: 2,
            strokeOpacity: 1,
            strokeColor: "#eb1c00",
            fillColor: "white",
            fillOpacity: 0.3
        }
    };
    var style = new OpenLayers.Style();
    style.addRules([
        new OpenLayers.Rule({symbolizer: sketchSymbolizers})
    ]);
    var styleMap = new OpenLayers.StyleMap({"default": style});
	mapControls = {
		line: new OpenLayers.Control.Measure(
            OpenLayers.Handler.Path, {
                persist: true,
                handlerOptions: {
                    layerOptions: {styleMap: styleMap}
                }
            }
        ),
        polygon: new OpenLayers.Control.Measure(
            OpenLayers.Handler.Polygon, {
                persist: true,
                handlerOptions: {
                    layerOptions: {styleMap: styleMap}
                }
            }
        ),
		zoomin: new OpenLayers.Control.ZoomIn(),
		zoomout: new OpenLayers.Control.ZoomOut(),
		navigation: new OpenLayers.Control.Navigation({
			zoomWheelEnabled: true
			,wheelChange: function(event, deltaZ) { handleMouseWheelZoom(event, deltaZ); }
			,wheelUp: function(event, delta) { handleMouseWheelZoom(event, delta); }
			,wheelDown: function(event, delta) { handleMouseWheelZoom(event, delta); }
			,defaultDblClick: function(event) { handleDoubleClickOnMap(event); }
		}),
		link: new OpenLayers.Control.Permalink(
				'permalink'
			),
		scaleline: new OpenLayers.Control.ScaleLine()
    };
    var control;
    for(var key in mapControls) {
		control = mapControls[key];
		control.events.on({
		    "measure": handleMeasurements
		});
		map.addControl(control);
    }
    map.events.on({'moveend': handleMoveEnd, 'zoomend': handleZoomEnd});
    var winHref = $(location).attr('href').split("/");
	$.each(winHref, function(key, value){
		if( value == "Addresses" ) {
			centerToAddress(winHref[key+1], winHref[key+2], winHref[key+3]);
		}
		if( value == "Companies" ) {
			var id = winHref[winHref.length-2];
			centerToCompany(id);
			showCompanyPoint(id);
		}
		if( value == "a" ) {
			search(winHref[key+2], winHref[key+3]);
		}
		if( value == "b" ) {
			switch(winHref.length) {
				case 8:
					centerTo(winHref[key+2]);
					break;
				case 9:
					centerTo(winHref[key+2] +", "+ winHref[key+3]);		
					break;
				default:
					break;
			}
		}
		if( value == "c" ) {
			var id = winHref[key+2];
			centerToCompany(id);
			showCompanyPoint(id);
		}
	});
}
/**
 * 
 * Hides the default value of all text fields and returns it if nothing was written.
 *
 */
function singleSelectInputs() {
	$(".inputText").each(function(){
		if( this.value == this.defaultValue ) {
			$(this).css({"color": "#888888"});
		}
	});
	$(".routeText").each(function(){
		if( this.value == this.defaultValue ) {
			$(this).css({"color": "#888888"});
		}
	});
	$("input").mouseup(function(e){
        e.preventDefault();
	});
	$(".inputText").focus(function(){
	    this.select();
		clearText(this);
	});
	$(".routeText").focus(function(){
	    this.select();
		clearText(this);
	});
	$(".inputText").focusout(function(){
		defaultText(this);
	});
	$(".routeText").focusout(function(){
		defaultText(this);
	});
}
/**
 * 
 * Show a toast style loading div.
 * 
 */
function showToast() {
	toast = $().toastmessage('showToast', {
	    text	: t("ajaxLoading"),
	    sticky	: true,
	    type	: "notice",
	    position: "top-right"
	});
}
/**
 * 
 * Hides the toast loading div.
 * 
 */
function hideToast() {
	$().toastmessage('removeToast', toast);
}
/**
 * 
 * Loads the UI functionality.
 * 
 */
function loadUIFunctionality() {
	$("#searchNavi li").click(function(e){
		firebug(e);
	});
	/**
     * Handle route panels waypoint fields' addition.
     */
    $('#btnAdd').click(function() {
		var num		= $('.routeText').length -1;	// how many "duplicatable" input fields we currently have;
		var newNum	= new Number(num+1);		// the numeric ID of the new input field being added
		var newElem = $('#waypoint_' + num).clone().attr('id', 'waypoint_' + newNum).attr('name', 'waypoint_'+newNum);

		newElem.children(':first').attr('id', 'waypoint_' + newNum).attr('name', 'waypoint_' + newNum).attr('class', 'routeText');
		$('#waypoint_' + num).after(newElem);
		$('#waypoint_' + num).after("<div id='br_"+num+"'></div>");
		$( "#btnDel" ).button( "option", "disabled", false );
		if (newNum == 4) {
			$( "#btnAdd" ).button( "option", "disabled", true );
		}
		$("input").mouseup(function(e){
	        e.preventDefault();
		});
		$("input").focus(function(){
		    this.select();
		});
		$(".routeText").autocomplete({
	    	source: function(request, response) {
	    		geocoder.geocode( {'address': request.term }, function(results, status) {
	    			response($.map(results, function(item) {
	    				return {
	    					label:  item.formatted_address,
	    					value: item.formatted_address,
	    					latitude: item.geometry.location.lat(),
	    					longitude: item.geometry.location.lng()
	    				};
	    			}));
	    		});
	    	}
	    });
	});
	$('#btnDel').click(function() {
		var num	= $('.routeText').length -1;	// how many "duplicatable" input fields we currently have
		$('#waypoint_' + num).remove();		// remove the last element
		$("#br_"+num).remove();
		$( "#btnAdd" ).button( "option", "disabled", false );

		// if only one element remains, disable the "remove" button
		if (num-1 == 1) {
			$( "#btnDel" ).button( "option", "disabled", true );
		}
	});
	$("#feedback").colorbox({width:"550px", href: "/Bisnode/feedback.jsp", height:"450px", iframe:true, opacity: 0.5});
	$("#searchTabs").tabs();
	$("input:submit").button(function(){
	});
	$("#btnAdd").button({
		icons: {
			primary: "ui-icon-circle-plus"
    	}
	});
	$("#btnDel").button({
		disabled: true
		,icons: {
			primary: "ui-icon-circle-minus"
    	}
	});
	$(".zoomExplanation").html(t("zoomExplanation"));
	$(".addressExplanation").html(t("addressExplanation"));
	$(".routeExplanation").html(t("routeExplanation")+" "+t("routeExample")+" "+t("routeWaypoints"));
	$("#buttonTable").buttonset();
	$("#left_slide_mini").show();
	$("#left_slide").hide();
	$("#left_panel_content").hide();
	$("#map_left_panel").hide();
	/*$("#searchNavi li").click(function(e){
		e.preventDefault();
		if( e.currentTarget.id == "companySearch" ) {
			showCompanySearch();
			$("#companySearch").addClass("selectedNaviItem");
			$("#addressSearch").removeClass("selectedNaviItem");
			$("#routeSearch").removeClass("selectedNaviItem");
		}
		if( e.currentTarget.id == "addressSearch" ) {
			showAddressSearch();
			$("#addressSearch").addClass("selectedNaviItem");
			$("#companySearch").removeClass("selectedNaviItem");
			$("#routeSearch").removeClass("selectedNaviItem");
		}
		if( e.currentTarget.id == "routeSearch" ) {
			showRouteSearch();
			$("#routeSearch").addClass("selectedNaviItem");
			$("#addressSearch").removeClass("selectedNaviItem");
			$("#companySearch").removeClass("selectedNaviItem");
		}
		return false;
	});
	*/
	$("#tab_collapse_mini").hide();
	$("#tab_collapse_mini").click(function(e){
		e.preventDefault();
		$("#tab_collapse_mini").fadeOut('fast', function() {
			$(".ui-tabs-nav").fadeIn('fast', function() {
				$(".collapsibleTab").animate(
					{
						height: "toggle"
					}
					,function(){
					}
				);
			});
		});
	});
	$(".tab_collapse").click(function(e){
		e.preventDefault();
		$(".collapsibleTab").animate(
			{
				height: "toggle"
			}
			,function(){
				$(".ui-tabs-nav").fadeOut('fast', function() {
					$("#tab_collapse_mini").fadeIn('fast', function() {
					});
				});
			}
		);
	});
	/**
	 * Side panels' toggle functionality.
	 */
	$("#right_slide_mini").hide();
	$("#left_slide_toggle").click(function(e){
		e.preventDefault();
		$("#left_slide").hide();
		$("#left_panel_content").hide("slide", { direction: "left" }, 1000);
		$("#map_left_panel").animate(
			{
				width: "toggle"
			}
			,function() {
				$("#map_left_panel").hide();
				$("#left_slide_mini").show("slide", { direction: "left" }, 1000);
			}
		);
	});
	$("#left_slide_mini").click(function(e){
		e.preventDefault();
		$("#left_slide_mini").hide("slide", function(){
			$("#map_left_panel").animate(
				{
					width: "toggle"
				}
				,function() {
					$("#map_left_panel").show();
					$("#left_panel_content").show("slide", { direction: "left" }, 1000, function(){$("#left_slide").show(/*"slide", { direction: "left" }*/);});
				}
			);
		},{ direction: "left" }, 1000);
	});
	$("#right_slide_toggle").click(function(e){
		e.preventDefault();
		$("#right_slide").hide();
		$("#right_panel_content").hide("slide", { direction: "right" }, 1000);
		$("#map_right_panel").animate(
			{
				width: "toggle"
			}
			,function() {
				$("#map_right_panel").hide();
				$("#right_slide_mini").show("slide", { direction: "right" }, 1000);
			}
		);
	});
	$("#right_slide_mini").click(function(e){
		e.preventDefault();
		$("#right_slide_mini").hide("slide", { direction: "right" }, 1000, function(){
			$("#map_right_panel").animate(
				{
					width: "toggle"
				}
				,function() {
					$("#map_right_panel").show();
					$("#right_panel_content").show("slide", { direction: "right" }, 1000, function(){$("#right_slide").show(/*"slide", { direction: "right" }*/);});
				}
			);
		});
	});
	/**
	 * Bottom toolbar buttons
	 */
	$("#permalink").button({
		icons: {
			primary: "bisnode-permalink"
		}
	}).click(function(e){
		showPermalink(e.currentTarget.href);
		e.preventDefault();
	});
	$("#print").button({
		icons: {
			primary: "bisnode-print"
    	}
	}).click(function(e){
		e.preventDefault();
		window.open('/Bisnode/print.jsp');
	});
	$("#feedback").button({
		icons: {
			primary: "bisnode-feedback"
    	}
	}).click(function(e){
		
	});
	$("#footer_left").buttonset();
	$("#zoomslider").slider({
		min: 0
		,max: map.numZoomLevels
		,value: map.getZoom()
		,animate: true
		,change: function(event, ui) 
			{  
				map.zoomTo(ui.value);
			}
	});
	$("#zoomin").button({
		icons: {
			primary: "bisnode-zoomin"
		},
		text: false
    }).click(function(e){
		e.preventDefault();
		handleZoomIn();
	});
	$("#zoomout").button({
		icons: {
			primary: "bisnode-zoomout"
		},
		text: false
    }).click(function(e){
		e.preventDefault();
		handleZoomOut();
	});
	$("#navigation").button({
		icons: {
			primary: "bisnode-navigation"
		}
	}).mousedown(function(e) {
    	$(this).addClass("toggled");
    	$("#distance").removeClass("toggled");
    	toggleMapControls(this);
    	return false;
    });
	$("#navigation").addClass("toggled");
	$("#distance").button({
		icons: {
			primary: "bisnode-distance"
		}
	}).mousedown(function(e) {
    	$(this).addClass("toggled");
    	$("#navigation").removeClass("toggled");
    	toggleMapControls(this);
    	return false;
    });
	$("#footer_right").buttonset();
	$("a#controlbtn").click(function(e) {
    	e.preventDefault();
        var slidepx=$("div#linkblock").width() + 10;
    	if ( !$("div#maincontent").is(':animated') ) {
			if (parseInt($("div#maincontent").css('marginLeft'), 10) < slidepx) {
 				$(this).removeClass('slide_toggle_close');
 				$(this).addClass('slide_toggle_open');
      			margin = "+=" + slidepx;
    		} else {
     			$(this).removeClass('slide_toggle_open');
     			$(this).removeClass('slide_toggle_close');
      			margin = "-=" + slidepx;
    		}
        	$("div#maincontent").animate({ 
        		marginLeft: margin
      		}, {
                duration: 'slow',
                easing: 'easeOutQuint'
            });
    	}
  	});
	var scale = map.getZoom();
	$("#zoomslider").slider( "value" , scale );
	autoCompletion();
}
/*function showCompanySearch() {
	$("#searchAddressContent").hide();
	$("#searchRouteContent").hide();
	$("#searchCompanyContent").show();
}
function showAddressSearch() {
	$("#searchCompanyContent").hide();
	$("#searchRouteContent").hide();
	$("#searchAddressContent").show();
}
function showRouteSearch() {
	$("#searchCompanyContent").hide();
	$("#searchAddressContent").hide();
	$("#searchRouteContent").show();
}*/
/**
 * 
 * Removes markers-layer if it exists. Variable map must be an OpenLayers map.
 * 
 */
function removeMarkers() {
	if( !empty(markers) ) {
		map.removeLayer(markers);
		markers = null;
	}
}
/**
 * 
 * Calls Google Maps JavaScript API geocoder to find out the location of the given address and centers the map to that point.
 * 
 * @param address
 */
function findAddress(address) {
	removeMarkers();
	if( address.value != address.defaultValue && address.value != '' && geocoder ) {
    	geocoder.geocode({"address": address.value}, function(res, status){
    		if (status == google.maps.GeocoderStatus.OK) {
    			var lonlat = new OpenLayers.LonLat(res[0].geometry.location.lng(), res[0].geometry.location.lat())
					.transform(
						new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
						new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
				    );
    			map.setCenter(lonlat, 9);
    			markers = new OpenLayers.Layer.Markers("addressMarkers");
    		    map.addLayer(markers);
    		    var icon = new OpenLayers.Icon("http://"+geoserver+"/Bisnode/lib/img/map-icon-address.png", new OpenLayers.Size(27, 37));
    		    var marker = new OpenLayers.Marker(lonlat, icon);
    		    marker.setOpacity(0.9);
    		    markers.addMarker(marker);
    		    var scale = map.getZoom();
    			$("#zoomslider").slider( "value" , scale );
    		} else {
    			$.colorbox({html: t("addressNotFound")});
    		}
    	});
    }
}
/**
 * 
 * Function which assigns text fields the jQuery UI autocompletion property.
 * 
 */
function autoCompletion() {
	/*
	 * Address autocompletion.
	 */
	$("#searchPlace .inputText").autocomplete({
    	source: function(request, response) {
    		geocoder.geocode( {'address': request.term+", Suomi" }, function(results, status) {
    			response($.map(results, function(item) {
    				return {
    					label:  item.formatted_address,
    					value: item.formatted_address,
    					latitude: item.geometry.location.lat(),
    					longitude: item.geometry.location.lng()
    				};
    			}));
    		});
    	},
    	select: function(event, ui) {
    		removeMarkers();
    		var lonlat = new OpenLayers.LonLat(ui.item.longitude, ui.item.latitude)
				.transform(
					new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
					new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
			    );
			map.setCenter(lonlat, 9);
			markers = new OpenLayers.Layer.Markers("addressMarkers");
		    map.addLayer(markers);
		    var icon = new OpenLayers.Icon("http://"+geoserver+"/Bisnode/lib/img/map-icon-address.png", new OpenLayers.Size(27, 37));
		    var marker = new OpenLayers.Marker(lonlat, icon);
		    marker.setOpacity(0.9);
		    markers.addMarker(marker);
		    var scale = map.getZoom();
			$("#zoomslider").slider( "value" , scale );
    	}
    });
	/*
	 * Route text autocompletion
	 */
	$(".routeText").autocomplete({
    	source: function(request, response) {
    		geocoder.geocode( {'address': request.term+", Suomi" }, function(results, status) {
    			response($.map(results, function(item) {
    				return {
    					label:  item.formatted_address,
    					value: item.formatted_address,
    					latitude: item.geometry.location.lat(),
    					longitude: item.geometry.location.lng()
    				};
    			}));
    		});
    	}
    });
	/*
	 * Search text autocompletion
	 */
	$("#searchText").autocomplete({
    	source: function(request, response) {
    		$.ajax({
				url: "/Bisnode/SearchAutocomplete"
				,dataType: "json"
				,type: "POST"
				,data: {search: request.term}
				,success: function(data, xhr, status) {
					response($.map(data, function(item) {
						return { label: item.key };
					}));
				}
			});
    	},
    	select: function(event, ui) {
    		searchCompany(ui.item.value);
    	}
    });
}
/**
 * 
 * Draws company's location with a standard WMS-request with the company id as a filter.
 * Also removes the current 'company'-layer from the map.
 * 
 * @param id
 */
function showCompanyPoint(id) {
	removeMarkers();
	if( !empty(company) ) {
		map.removeLayer(company);
	}
	$.ajax({
		url: "/Bisnode/CompanyName"
		,data: {"id": id}
		,type: "POST"
		,success: function(data, textStatus, jqXHR){
			if( !empty(data) ) {
				var lon = data.lon;
				var lat = data.lat;
				companyName = data.name;
				//$("#seoHeaderLeft").html("<h1><strong>"+companyName+" - Yritys</strong></h1>");
				//$("#seoLeftTop").html("<h1><strong>"+companyName+" - Yritys</strong></h1>");
				//$("#seoLeftBottom").html("<h1><strong>"+companyName+" - Yritys</strong></h1>");
				companyId = id;
				var filter = "bisnode_id like \'"+id+"\'";
				company = new OpenLayers.Layer.WMS(
				    "Companies",
				    "http://"+geoserver+"/geoserver/wms",
				    {
				        layers: "company"
				        ,transparent: "true"
				        ,format: "image/png"
				        ,cql_filter: filter
				    },
				    {
				    	isBaseLayer: false
				    	,projection: new OpenLayers.Projection("EPSG:4326")
					    ,singleTile: true
				    	,buffer: 0
				    	,ratio: 1
				    }
				);
				map.addLayer(company);
				var lonlat = new OpenLayers.LonLat(lon, lat).transform(
					      new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
					      new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
					    );
				getCompanyInfo(id, lonlat);
			}
		}
	});
}
/**
 * 
 * Shows a single company information box.
 * 
 * @param id
 */
function getCompanyInfo(id, lonlat) {
	if( popup != null ) {
		map.removePopup(popup);
	}
	var tmp = {"id": "'"+id+"'" };
	$.ajax({
		url: "/Bisnode/SingleCompanyInfo"
		,data: tmp
		,type: "POST"
		,success: function(data, textStatus, jqXHR){
			if( !empty(data) ) {
				var html = data.html;
				popup = popupFactory(html, undefined, lonlat);
				map.addPopup(popup);
				$(".olPopupContent a").attr("target", "_blank");
			}
		}
	});
}
/**
 * 
 * Centers to the given company.
 * 
 * @param id
 */
function centerToCompany(id) {
	showToast();
	$.ajax({
		url: "/Bisnode/CompanyLocation"
		,data: {"id": id}
		,type: "POST"
		,success: function(data, textStatus, jqXHR){
			if( !empty(data) ) {
				map.setCenter(new OpenLayers.LonLat(data.lon, data.lat)
					.transform(
				      new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
				      new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
				    ), 10 // Zoom level
				);
				var scale = map.getZoom();
				$("#zoomslider").slider( "value" , scale );
				hideToast();
			}
		}
	});
}
/**
 * 
 * Centers the map to the given address.
 * 
 * @param address
 */
function centerTo(address) {
	address = prettyWord(address);
	address += ", Suomi";
	geocoder.geocode({"address": address}, function(res, status){
		if (status == google.maps.GeocoderStatus.OK) {
			var lonlat = new OpenLayers.LonLat(res[0].geometry.location.lng(), res[0].geometry.location.lat())
				.transform(
					new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
					new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
			    );
			map.setCenter(lonlat, 9);
			markers = new OpenLayers.Layer.Markers("addressMarkers");
		    map.addLayer(markers);
		    var icon = new OpenLayers.Icon("http://"+geoserver+"/Bisnode/lib/img/map-icon-address.png", new OpenLayers.Size(27, 37));
		    var marker = new OpenLayers.Marker(lonlat, icon);
		    marker.setOpacity(0.9);
		    markers.addMarker(marker);
		    var scale = map.getZoom();
			$("#zoomslider").slider( "value" , scale );
		} else {
			$.colorbox({html: t("addressNotFound")});
		}
	});
	/**/
}
/**
 * 
 * Centers the map to the given address.
 * 
 * @param winHref
 */
function centerToAddress(country, city, street) {
	country = country.replace(/_/g, "+");
	city = city.replace(/_/g, "+");
	street = street.replace(/_/g, "+");
	var address = country+","+city+","+street;
	geocoder.geocode({"address": address}, function(res, status){
		if (status == google.maps.GeocoderStatus.OK) {
			var lonlat = new OpenLayers.LonLat(res[0].geometry.location.lng(), res[0].geometry.location.lat())
				.transform(
					new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
					new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
			    );
			map.setCenter(lonlat, 9);
			markers = new OpenLayers.Layer.Markers("addressMarkers");
		    map.addLayer(markers);
		    var icon = new OpenLayers.Icon("http://"+geoserver+"/Bisnode/lib/img/map-icon-address.png", new OpenLayers.Size(27, 37));
		    var marker = new OpenLayers.Marker(lonlat, icon);
		    marker.setOpacity(0.9);
		    markers.addMarker(marker);
		    var scale = map.getZoom();
			$("#zoomslider").slider( "value" , scale );
		} else {
			$.colorbox({html: t("addressNotFound")});
		}
	});
	/**/
}
/**
 * 
 * Calls Google Maps API direction service and draws a route on the map and guidance information on the left panel.
 * 
 * @returns {Boolean}
 */
function showRoute(input) {
	showToast();
	var inputs = $('#route :input');
    var values = new Array();
    var i = 0;
    inputs.each(function() {
    	if( $(this).val() != "Hae" ) {
			values.push( $(this).val() );
    	}
    });
    var start = values.splice(0,1);
    var end = values.pop();
    var wps = [];
    for( var i = 0; i < values.length; ++i) {
    	wps[i] = { location: values[i], stopover:false };
    }
    var origin = start[0];
    var destination = end;
	var request = {
		origin: origin,
		destination: destination,
		waypoints: wps,
		optimizeWaypoints: true,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(result, status) {
		hideToast();
		if (status == google.maps.DirectionsStatus.OK) {
			var pointArr = [];
			$("#left_panel_result_text").html("");
			var html = "<ul>";
			$.each(result.routes[0].legs, function(){
				$.each(this.steps, function(){
					html += "<li>"+this.instructions+"</li>";
				});
			});
			html += "</ul>";
			if( $("#map_left_panel").css("display") == "none" ) {
				$("#left_slide_mini").hide("slide", function(){
					$("#map_left_panel").animate(
						{
							width: "toggle"
						}
						,function() {
							$("#map_left_panel").show();
							$("#left_panel_content").show("slide", { direction: "left" }, 1000, function(){$("#left_slide").show();});
						}
					);
				},{ direction: "left" }, 1000);
			}
			$("#left_panel_result_text").html( html );
			$.each(result.routes[0].overview_path, function(){
				var point = new OpenLayers.Geometry.Point(this.lng(), this.lat()).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
				pointArr.push(point);
			});
			var curve = new OpenLayers.Geometry.LineString(pointArr);
			groute.removeAllFeatures();
			groute.addFeatures( [new OpenLayers.Feature.Vector(curve)] );
			var bounds = result.routes[0].bounds;
			var tr = bounds.getNorthEast();
			var bl = bounds.getSouthWest();
			extent = new OpenLayers.Bounds();
			extent.extend(new OpenLayers.LonLat(tr.lng(),tr.lat()).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913")));
			extent.extend(new OpenLayers.LonLat(bl.lng(),bl.lat()).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913")));
			map.zoomToExtent(extent);
			var scale = map.getZoom();
			$("#zoomslider").slider( "value" , scale );
		} else {
			$.colorbox({html: t("zeroResults")+"<br />"+t("routeExplanation")});
		}
	});
	/**/
}
/**
 * 
 * Geocode an address and then perform a search to that extent.
 * 
 * @param address
 * @param value
 */
function search(address, value) {
	address = prettyWord(address);
	geocoder.geocode({"address": address}, function(res, status){
		if (status == google.maps.GeocoderStatus.OK) {
			var lonlat = new OpenLayers.LonLat(res[0].geometry.location.lng(), res[0].geometry.location.lat())
				.transform(
					new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
					new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
			    );
			map.setCenter(lonlat, 8);
			searchActive = true;
			showToast();
			search = prettyWord(value).toLowerCase();
			search = safeEncode(search);
			searchPage = 0;
			var extents = map.getExtent().toGeometry().getVertices();
			var tmp = new Object();
			var index = 0;
			for( var i in extents ){
				var name = "";
				switch(index) {
					case 0:
						name = "bottom-left";
						break;
					case 1:
						name = "bottom-right";
						break;
					case 2:
						name = "top-right";
						break;
					case 3:
						name = "top-left";
						break;
					default:
						break;
				}
				tmp[name] = new OpenLayers.LonLat(extents[i].x, extents[i].y).transform(
						new OpenLayers.Projection("EPSG:900913"),
						new OpenLayers.Projection("EPSG:4326")
					);
				++index;
			}
			var jsonExtents = JSON.stringify(tmp);
			$.getJSON("/Bisnode/Search"
				,{
					search: search
					,extents: jsonExtents
					,limit: 25
					,offset: 0
				}
				,function(data) {
					if( data != '' ) {
						showSearchResults(data, jsonExtents);
					} else {
						hideToast();
						$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
					}
				}
			);
		} else {
			$.colorbox({html: t("addressNotFound")});
		}
	});
	/**/
}
/**
 * 
 * Searches for a company.
 * 
 * @param search
 */
function searchCompany(search) {
	companyName = search;
	searchActive = true;
	showToast();
	search = search.toLowerCase();
	search = safeEncode(search);
	searchPage = 0;
	var extents = map.getExtent().toGeometry().getVertices();
	var tmp = new Object();
	var index = 0;
	for( var i in extents ){
		var name = "";
		switch(index) {
			case 0:
				name = "bottom-left";
				break;
			case 1:
				name = "bottom-right";
				break;
			case 2:
				name = "top-right";
				break;
			case 3:
				name = "top-left";
				break;
			default:
				break;
		}
		tmp[name] = new OpenLayers.LonLat(extents[i].x, extents[i].y).transform(
				new OpenLayers.Projection("EPSG:900913"),
				new OpenLayers.Projection("EPSG:4326")
			);
		++index;
	}
	var jsonExtents = JSON.stringify(tmp);
	$.getJSON("/Bisnode/Search"
		,{
			search: search
			,extents: jsonExtents
			,limit: 25
			,offset: 0
		}
		,function(data) {
			if( data != '' ) {
				showSearchResults(data, jsonExtents);
			} else {
				hideToast();
				$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
			}
		}
	);
}
/**
 * 
 * Searches the database for the given value and returns companies that match the search parameter.
 * Also removes any prior 'company'-layers from the map.
 * 
 */
function doSearch(input) {
	var search = input.value;
	companyName = search;
	if( search != input.defaultValue && search != '' ) {
		searchActive = true;
		showToast();
		search = search.toLowerCase();
		search = safeEncode(search);
		searchPage = 0;
		var extents = map.getExtent().toGeometry().getVertices();
		var tmp = new Object();
		var index = 0;
		for( var i in extents ){
			var name = "";
			switch(index) {
				case 0:
					name = "bottom-left";
					break;
				case 1:
					name = "bottom-right";
					break;
				case 2:
					name = "top-right";
					break;
				case 3:
					name = "top-left";
					break;
				default:
					break;
			}
			tmp[name] = new OpenLayers.LonLat(extents[i].x, extents[i].y).transform(
					new OpenLayers.Projection("EPSG:900913"),
					new OpenLayers.Projection("EPSG:4326")
				);
			++index;
		}
		var jsonExtents = JSON.stringify(tmp);
		$.getJSON("/Bisnode/Search"
			,{
				search: search
				,extents: jsonExtents
				,limit: 25
				,offset: 0
			}
			,function(data) {
				if( data != '' ) {
					showSearchResults(data, jsonExtents);
				} else {
					hideToast();
					$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
				}
			}
		);
	}
	/**/
}
/**
 * 
 * Handles the rendering of the doSearch()-function
 * 
 * @param data
 */
function showSearchResults(data, jsonExtents) {
	removeMarkers();
	if( !empty(company) ) {
		map.removeLayer(company);
	}
	var html = 
			"<div id='showPoints'>" +
				"<button id='startResults' title="+t('tooltip_startResults')+"></button>" +
				"<button id='previousResults' title="+t('tooltip_previousResults')+"></button>" +
				"<button id='moreResults' title="+t('tooltip_moreResults')+"></button>" +
				"<button id='endResults' title="+t('tooltip_endResults')+"></button>" +
			"</div>";
	var totalHtml = "<div id='resultsFound'>";
	html += "<ol>";
	var filter = "";
	var i = 0;
	//var k = 0;
	filterArr = new Array();
	idList = new Array();
	$.each(data, function(key, value) {
		if(value.id == -1) {
			resultsFound = value.nimi;
			var totalPages = resultsFound / 25;
			var ceil = Math.ceil(totalPages);
			totalHtml += t("resultsFound")+ "1 / " + ceil +"</div>";
		} else {
			var nimi = value.nimi;
			if( nimi.length > 25 ) {
				nimi = nimi.substring(0, 25);
				nimi += " ...";
			} 
			html += '<li> <a id='+value.id+' href="#" class="companyLink">' + nimi + '</a> </li>';
			if( i == 0 ) {
				filter += "bisnode_id LIKE \'"+value.id+"\'";
			} else {
				filter += " OR bisnode_id LIKE \'"+value.id+"\'";
			}
			++i;
			idList.push(value.id);
		}
	});
	filterArr.push(filter);
	html += "</ol>";
	if( $("#map_left_panel").css("display") == "none" ) {
		$("#left_slide_mini").hide("slide", function(){
			$("#map_left_panel").animate(
				{
					width: "toggle"
				}
				,function() {
					$("#map_left_panel").show();
					$("#left_panel_content").show("slide", { direction: "left" }, 1000, function(){$("#left_slide").show();});
				}
			);
		},{ direction: "left" }, 1000);
	}
	$("#left_panel_result_text").html( totalHtml + html );
	$("#previousResults").attr('disabled', 'disabled');
	if( resultsFound < 26 ) {
		$("#moreResults").attr('disabled', 'disabled');
	}
	$("#startResults").button({
		icons: {
			primary: "ui-icon-seek-first"
    	}
	}).click(function(e){
		e.preventDefault();
		getResultPage("start", jsonExtents);
	});
	$("#endResults").button({
		icons: {
			primary: "ui-icon-seek-end"
    	}
	}).click(function(e){
		e.preventDefault();
		getResultPage("end", jsonExtents);
	});
	$("#moreResults").button({
		icons: {
			primary: "ui-icon-seek-next"
    	}
	}).click(function(e){
		e.preventDefault();
		getResultPage("next", jsonExtents);
	});
	$("#previousResults").button({
		icons: {
			primary: "ui-icon-seek-prev"
    	}
	}).click(function(e){
		e.preventDefault();
		getResultPage("previous", jsonExtents);
	});
	$("#showPoints").buttonset();
	company = new OpenLayers.Layer.WMS(
	    "Companies",
	    "http://"+geoserver+"/geoserver/wms",
	    {
	        layers: 'company'
	        ,transparent: "true"
	        ,format: "image/png"
	        ,cql_filter: filterArr[0]
	    },
	    {
	    	isBaseLayer: false
	    	,projection: new OpenLayers.Projection("EPSG:4326")
	    	,singleTile: true
	    	,buffer: 0
	    	,ratio: 1
	    }
	);
	map.addLayer(company);
	featureInfo = new OpenLayers.Control.WMSGetFeatureInfo({
        url: "http://"+geoserver+"/geoserver/wms", 
        title: t("featureInfo"),
        layers: [company],
        queryVisible: true
    });
	featureInfo.events.register("getfeatureinfo", this, getFeatureInfo);
	map.addControl(featureInfo);
	featureInfo.activate();
	$(".companyLink").click(function(event){
		var id = $(this).attr("id");
		listFeatureInfo(event);
	});
	mapControls.link.updateLink();
	hideToast();
}
/**
 * 
 * Fetches start/end/next/previous result page.
 * 
 */
function getResultPage(direction, extents) {
	var search = $("#searchText").val();
	companyName = search;
	if( search != $("#searchText")[0].defaultValue && search != '' ) {
		showToast();
		search = search.toLowerCase();
		search = safeEncode(search);
		var tmp = new Object();
		var index = 0;
		switch( direction ) {
			case "start":
				var totalPages = resultsFound / 25;
				searchPage = 0;
				if( Math.floor(totalPages) >= 1 ) {
					$("#moreResults").button("enable");
				} else {
					$("#moreResults").button("disable");
				}
				$("#previousResults").button("disable");
				$.getJSON("/Bisnode/Search"
					,{
						search: search
						,extents: extents
						,limit: 25
						,offset: 0
					}
					,function(data) {
						if( data != '' ) {
							updateSearchResults(data);
						} else {
							hideToast();
							$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
						}
					}
				);
				var spText = searchPage + 1;
				$("#resultsFound").html(t("resultsFound")+ spText +" / " +Math.ceil(totalPages));
				break;
			case "end":
				var totalPages = resultsFound / 25;
				if( Math.floor(totalPages) == 0 ) {
					searchPage = 0;
					$("#previousResults").button("disable");
					$("#moreResults").button("disable");
				} else {
					searchPage = Math.floor(totalPages);
					$("#previousResults").button("enable");
					$("#moreResults").button("disable");
				}
				$.getJSON("/Bisnode/Search"
					,{
						search: search
						,extents: extents
						,limit: 25
						,offset: searchPage
					}
					,function(data) {
						if( data != '' ) {
							updateSearchResults(data);
						} else {
							hideToast();
							$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
						}
					}
				);
				var spText = searchPage + 1;
				$("#resultsFound").html(t("resultsFound")+ spText +" / " +Math.ceil(totalPages));
				break;
			case "next":
				var totalPages = resultsFound / 25;
				if( searchPage <= totalPages ) {
					++searchPage;
					if( searchPage < Math.floor(totalPages) ) {
						$("#moreResults").button("enable");
					} else {
						$("#moreResults").button("disable");
					}
					$("#previousResults").button("enable");
					$.getJSON("/Bisnode/Search"
						,{
							search: search
							,extents: extents
							,limit: 25
							,offset: searchPage
						}
						,function(data) {
							if( data != '' ) {
								updateSearchResults(data);
							} else {
								hideToast();
								$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
							}
						}
					);
					var spText = searchPage + 1;
					$("#resultsFound").html(t("resultsFound")+ spText +" / " +Math.ceil(totalPages));
				}
				break;
			case "previous":
				if( searchPage > 0 ) {
					var totalPages = resultsFound / 25;
					--searchPage;
					$("#moreResults").button("enable");
					if( searchPage == 0) {
						$("#previousResults").button("disable");
					} else {
						$("#previousResults").button("enable");
					}
					$.getJSON("/Bisnode/Search"
						,{
							search: search
							,extents: extents
							,limit: 25
							,offset: searchPage
						}
						,function(data) {
							if( data != '' ) {
								updateSearchResults(data);
							} else {
								hideToast();
								$.colorbox({html: "<p>"+t("zeroResults")+" "+t("zoomExplanation")+"</p>"});
							}
						}
					);
					var spText = searchPage + 1;
					$("#resultsFound").html(t("resultsFound")+ spText +" / " +Math.ceil(totalPages));
				}
				break;
			default:
				break;
		}
	}
}
/**
 * 
 * Updates search results
 * 
 * @param data
 */
function updateSearchResults(data) {
	if( !empty(company) ) {
		map.removeLayer(company);
	}
	var html = "";
	var sortedArr = objectKeys(data);
	var filter = "";
	var i = 0;
	var k = 0;
	filterArr = new Array();
	var bbox = map.getExtent().transform(
			new OpenLayers.Projection("EPSG:900913"),
			new OpenLayers.Projection("EPSG:4326")
		).toBBOX();
	$.each(data, function(key, value) {
		if(value.id == -1) {
			resultsFound = value.nimi;
		} else {
			var nimi = value.nimi;
			if( nimi.length > 25 ) {
				nimi = nimi.substring(0, 25);
				nimi += " ...";
			} 
			html += '<li> <a id='+value.id+' href="#" class="companyLink">' + nimi + '</a> </li>';
			if( i == 0 ) {
				filter += "bisnode_id LIKE \'"+value.id+"\'";
			} else {
				filter += " OR bisnode_id LIKE \'"+value.id+"\'";
			}
			++i;
		}
	});
	filterArr.push(filter);
	if( $("#map_left_panel").css("display") == "none" ) {
		$("#left_slide_mini").hide("slide", function(){
			$("#map_left_panel").animate(
				{
					width: "toggle"
				}
				,function() {
					$("#map_left_panel").show();
					$("#left_panel_content").show("slide", { direction: "left" }, 1000, function(){$("#left_slide").show();});
				}
			);
		},{ direction: "left" }, 1000);
	}
	$("#left_panel_result_text ol").html( html );
	company = new OpenLayers.Layer.WMS(
	    "Companies",
	    "http://"+geoserver+"/geoserver/wms",
	    {
	        layers: 'company'
	        ,transparent: "true"
	        ,format: "image/png"
	        ,cql_filter: filterArr[0]
	    },
	    {
	    	isBaseLayer: false
	    	,projection: new OpenLayers.Projection("EPSG:4326")
	    	,singleTile: true
	    	,buffer: 0
	    	,ratio: 1
	    }
	);
	map.addLayer(company);
	$(".companyLink").click(function(event){
		var id = $(this).attr("id");
		listFeatureInfo(event);
	});
	mapControls.link.updateLink();
	/**/
	hideToast();
}
/**
 * 
 * When a search list item is clicked show a popup on top the company
 * 
 * @param event
 */
function listFeatureInfo(event) {
	if( popup != null ) {
		map.removePopup(popup);
	}
	var id = event.currentTarget.id;
	var tmp = {"id": "'"+id+"'"};
	$.ajax({
		url: "/Bisnode/CompanyLocation?id="+id
		,type: "POST"
		,success: function(data, textStatus, jqXHR){
			if( !empty(data) ) {
				var lonlat = new OpenLayers.LonLat(data.lon, data.lat).transform(
						new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
						new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
			    );
				var size = new OpenLayers.Size(500,300);
				$.ajax({
					url: "/Bisnode/SingleCompanyInfo"
					,data: tmp
					,type: "POST"
					,success: function(data1, textStatus1, jqXHR1){
						if( !empty(data1) ) {
							var html = data1.html;
							popup = popupFactory(html, undefined, lonlat);
							map.addPopup(popup);
							$(".olPopupContent a").attr("target", "_blank");
						}
					}
				});
			}
		}
	});
	/**/
}
/**
 * 
 * Gets feature info from a cluster of companies.
 * 
 * @param event
 */
function getFeatureInfo(event) {
	if( popup != null ) {
		map.removePopup(popup);
	}
	//showToast();
	var ids = "";
	var i = 0;
	$(idList).each(function(key, value){
		if( key == 0 ) {
			ids += "'"+value+"'";
		} else {
			ids += ", '"+value+"'";
		}
		++i;
	});
	var search = companyName;
	var lonlat = map.getLonLatFromPixel(event.xy);
	var zoom = map.getZoom();
	var data = {"lon": lonlat.lon, "lat": lonlat.lat, "ids": ids, "zoom": zoom};
	$.ajax({
		url: "/Bisnode/CompanyList"
		,data: data
		,type: "POST"
		,success: function(data, textStatus, jqXHR){
			if( !empty(data) ) {
				var length = 0;
				$.each(data, function(){
					++length;
				});
				if( length < 2 ) {
					var html = "";
					$.each(data, function(){
						html += this.html;
					});
					html = html.split("id=");
					html = html[1].split(" class=");
					html = html[0].split("_");
					getCompanyInfo(html[1], lonlat);
				} else {
					var html = "<div id='companyClusterExplanation'>" +t("companyClusterExplanation")+"</div>";
					html += "<ul>";
					$.each(data, function(){
						html += "<li>" + this.html + "</li>";
					});
					html += "</ul>";
					var size = new OpenLayers.Size(500,300);
					popup = popupFactory(html, undefined, lonlat);
					map.addPopup(popup);
					$(".popupLink").click(function(e){
						var idParts = e.currentTarget.id.split("_");
						getCompanyInfo(idParts[1], lonlat);
					});
				}
			}
		}
	});
	//hideToast();
	Event.stop(event);
}
/**
 * 
 * Handles all measurements done on the map.
 * 
 * @param event
 */
function handleMeasurements(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var km = measure/1.609344;
    var out = "";
    if(order == 1) {
		out += t("distance")+": "+ km.toFixed(2) + " " + units;
    } else {
		out += t("area")+": "+ km.toFixed(2) + " " + units + "<sup>2</sup>";
    }
    var popupPos = event.geometry.components[event.geometry.components.length-1];
    popup = new OpenLayers.Popup(t("distance"),
            new OpenLayers.LonLat(popupPos.x,popupPos.y),
            new OpenLayers.Size(100,25),
            out,
            true);
    map.addPopup(popup);
}
/**
 * 
 * Handles the activation of zoom functionality.
 * 
 * @param event
 */
function handleActivate(event) {
	if( event.object.displayClass == "olControlZoomIn" ) {
		handleZoomIn();
	} else if( event.object.displayClass == "olControlZoomOut" ) {
		handleZoomOut();
	} else {
		// NOP
	}
}
/**
 * 
 * Shows a permalink window of the current map viewport.
 * 
 */
function showPermalink(href) {
	var html = '<p>'+t("plinkExplanation")+'</p><span style=""><input id="pLink" class="inputText" type="text" name="pLink" value="'+href+'"/></span>';
	$.colorbox({
		html: html,
		opacity: 0.5,
		width: 700,
		onComplete: function(){
			$("#pLink").mouseup(function(e){
		        e.preventDefault();
			});
			$("#pLink").focus(function(){
			    this.select();
			});
		}
	});
}
/**
 * 
 * Handles zoom in functionality
 * 
 */
function handleZoomIn() {
	//Check if search is active and that we are not already showing a notice.
	if( searchActive && !$(".toast-item-wrapper").length ) {
		$().toastmessage('showNoticeToast', t("searchExtentChange"));
	}
	map.zoomIn();
	var scale = map.getZoom();
	$("#zoomslider").slider( "value" , scale );
}
/**
 * 
 * Handles zoom out functionality.
 * 
 */
function handleZoomOut() {
	//Check if search is active and that we are not already showing a notice.
	if( searchActive && !$(".toast-item-wrapper").length ) {
		$().toastmessage('showNoticeToast', t("searchExtentChange"));
	}
	map.zoomOut();
	var scale = map.getZoom();
	$("#zoomslider").slider( "value" , scale );
}
/**
 * 
 * Handles move end event.
 * 
 * @param event
 */
function handleMoveEnd(event) {
	//Check if search is active and that we are not already showing a notice.
	if( searchActive && !$(".toast-item-wrapper").length ) {
		$().toastmessage('showNoticeToast', t("searchExtentChange"));
	}
}
/**
 * 
 * Handle zoom end event.
 * 
 * @param event
 */
function handleZoomEnd(event) {
	
}
/**
 * 
 * Activates/deactivates map control.
 * 
 * @param element
 */
function toggleMapControls(element) {
	if( featureInfo != null ) {
		featureInfo.deactivate();
		map.removeControl(featureInfo);
	}
	for(key in mapControls) {
		var control = mapControls[key];
		if(element.name == key && $(element).is('.toggled')) {
		    control.activate();
		} else {
		    control.deactivate();
		}
    }
	if( element.id == "navigation" ) {
		if( featureInfo != null ) {
			map.addControl(featureInfo);
			featureInfo.activate();
		}
	}
}
/**
 * 
 * Activates navigation tool.
 * 
 */
function handleNavigateTool() {
	if( mapControls['navigation'].active() ) {
		
	} else {
		mapControls['navigation'].activate();
	}
}
/**
 * 
 * Handles double click on the map.
 * 
 */
function handleDoubleClickOnMap() {
	handleZoomIn();
}
/**
 * 
 * Handles the use of mouse wheel.
 * 
 * @param event
 * @param delta
 */
function handleMouseWheelZoom(event, delta) {
	if( delta < 0 ) {
		handleZoomOut();
	} else {
		handleZoomIn();
	}
}
/**
 * 
 * Activates/deactivates the given element.
 * 
 * @param element
 */
function toggleControl(element) {
    for(key in mapControls) {
		var control = mapControls[key];
		if(element.name == key && $(element).is('.ui-state-active')) {
		    control.activate();
		} else {
		    control.deactivate();
		}
    }
}
