/*----------------------------------------------------------------------------
 *       JSlint, settings for the javascript code verifier jslint.com
 *
 * Run from the commandline using rhino, or:
 * 1. go to jslint.com
 * 2. click clear all options at the bottom (we define the options below)
 * 3. paste in the code
 *
 *----------------------------------------------------------------------------*/
/*jslint
		adsafe: false,			// if ADsafe.org rules widget pattern should be enforced.
		bitwise: true, 			// if bitwise operators should not be allowed
		browser: true, 			// if the standard browser globals should be predefined
		cap: false,				// if upper case HTML should be allowed
		newcap: false, 			// if Initial Caps must be used with constructor functions
		css: false, 				// if CSS workarounds should be tolerated
		debug: false, 			// if debugger statements should be allowed
		eqeqeq: true, 			// if === should be required
		evil: false, 				// if eval should be allowed
		forin: false, 			// if unfiltered for in statements should be allowed
		fragment: true,			// if HTML fragments should be allowed
		laxbreak: true,			// if statement breaks should not be checked
		nomen: false, 			// if names should be checked for initial underbars
		on: false, 				// if HTML event handlers should be allowed
		onevar: false, 			// if only one var statement per function should be allowed
		passfail: false,			// if the scan should stop on first error
		plusplus: true,			// if ++ and -- should not be allowed
		regexp: true, 			// if . should not be allowed in RegExp literals
		rhino: false, 			// if the Rhino environment globals should be predefined
		safe: false, 				// if the safe subset rules are enforced. These rules are used by ADsafe.
		sidebar: false,			// if the Windows Sidebar Gadgets globals should be predefined
		strict: false, 			// if the ES3.1 "use strict"; pragma is required.
		sub: false, 				// if subscript notation may be used for expressions better expressed in dot notation
		undef: true, 				// if undefined global variables are errors
		white: false, 			// if strict whitespace rules apply
		widget: false			// if the Yahoo Widgets globals should be predefined
*/

// Deprecated but used browser function
/*global unescape, escape*/

// Prototype globals
/*global $, $$, $A, Event, Class, Hash, Ajax, Template, Position*/

// Enimap related:
/*global Wgs84GeoCoord, Rt90GeoCoord*/

// Global variable defined with inline javascript on the HTML page
/*global 
		gEmap,				//
		geoCenter,				//
		defLayer,				//
		symbolLayer,			//
		bullmarker,				//
		bullmarkerShadow,			//
		bullcoord,				//
		place,					//
		placeLayer,				//
		initSymbols,				//
		layerControl,			//
		shadowPin,				//
		mapResult,				//
		subTab,				//
		userContent,			//
		userContentTitle,			//
		country,				//
		countryEXT,			//
		inMapTxt,				//
		zoomInTxt,				//
		zoomOutTxt,			//
		zoomToHere,			//
		viewFromSouth,			//
		viewFromWest,			//
		viewFromNorth,			//
		viewFromEast,			//
		linkToMapTexts, 			//
		skipInMapTxt,			//
		searchForm, 			//
		mapForm,				//
		error_txt,				//
		onLoad				//
*/

//----------------------------------------------------------------------------
// Global variables used by this module:

/*global
		Symbol,				// enimap
		SymbolClickedEventHandler,	// enimap
		eHeight, 				// enimap
		eLeft, 				// enimap
		eTop, 					// enimap
		eWidth, 				// enimap
		Callout, 				// enimap
		Place,					// enimap
		setCookie				// /scripts/global.js
		Dialog,				// /scripts/dialog.js
		DialogHandler,			// /scripts/dialog.js
		TagList, 				// /scripts/result.js
		Hit,					// /scripts/result.js
		CompanyPeopleHit,			// /scripts/result.js
		ResultList,				// /scripts/result.js
		Eniro,					// /scripts/basic.js
*/

/**
 * @author mali01
 * @additions 
 * -	Added the window.loadFirebugConsole to make sure that Firebug 1.2 works on Firefox 2.+
 * -	SymbolClickedEventHandler: Handles remote update of callout when callout is opened.
 * 		Called from MapResult.symbolClicked.
 */
try { 
	/* this is to make sure that console.log works in FF 2.0.+ and Firebug 1.2 */
	window.loadFirebugConsole();
} catch(error) {}
/**
 * Heights
 * calculates the height of <div id="content"> whenever the window is resized
 */
var Heights = {
	init: function() {
		this.calculate();
		Event.observe(window, "resize", Heights.calculate);
	},
	/* calculates the new height of the content div, returns the new height */
	calculate: function() {
		var results = $("results");
		if (!results) {
			return 0;
		}
		var _viewport = document.viewport.getHeight();
		var _offsetHeight = results.cumulativeOffset()[1];
		var height = _viewport - _offsetHeight;
		if (height < 0) {
			height = 'auto';
		} else {
			height += 'px';
		}
		results.setStyle({
			height: height
		});
		return height;
	}
};
Event.observe(document, "dom:loaded",
function() {
	Heights.init();
	Heights.calculate();
});
/*
Resultlist classes and extensions
Extension for the Hit object defined in result.js
*/
var MapHitExtensions = {
	pin: null,
	/* Enimap Symbol object */
	pinShadow: null,
	pinElement: null,
	initialize: function($super, e, type) {
		$super(e, type);
		this.logo = this.e.select('div.logo');
		if (Eniro.Page.lang() === "da" && this.logo.length > 0) {
			this.logo = this.logo[0].getElementsByTagName('img')[0];
			if (this.logo.complete) {
				this.resizeLogo();
			} else {
				Event.observe(this.logo, "load", this.resizeLogo.bind(this), false);
			}
		}
	},
	setPin: function(symbol) {
			var coord = new Wgs84GeoCoord(symbol[1],symbol[2]);
			var layerName = "symbolLayer";
			if (symbol && symbol.layerName){
				layerName = symbol.layerName;
			}
			var options = {layerName: layerName, label: symbol.label, calloutOptions: {title:symbol.calloutTitle, content:symbol.calloutContent}};
			if (symbol[5] && symbol[5] !== ''){
				gEmap.setLayerOptions(layerName, { poiLayout:"ego logo-pin", poiType:'yp-logo', showCalloutOnClick:true});
				options = {layerName: layerName, label: symbol.label, logo: symbol[5], calloutOptions: {title:symbol.calloutTitle, content:symbol.calloutContent}};
			}

			this.pin = gEmap.addPoi(coord, options);
			this.pin.zoomMetaData = symbol.zoomMetaData;
	},
	hoverPin: function() {
		if (this.pin) {
			this.pin.activate();
		}
	},
	unHoverPin: function() {
		if (this.pin) {
			this.pin.deactivate();
		}
	},
	remoteExpand: function() {
		if (!this.expanded) {
			this.expand();
		}
		scroll('results', this.e.offsetTop, this.e.offsetHeight);
	},
	disposeHit: function() { 
		/* detach all symbols ... */
	},
	resizeLogo: function() {}
}; 
/* Type used on map page */
if (typeof CompanyPeopleHit !== 'undefined') {
	var MapHit = Class.create(CompanyPeopleHit, MapHitExtensions);
}
if (typeof Hit !== 'undefined') {
	/**
	 * POI hit type
	 */
	var PoiHit = Class.create(Hit, MapHitExtensions);
	PoiHit.prototype.toggle = function(v) {
		if (!this.expanded) {
			this.expand();
		} else {
			this.hide();
		}
	};
}

/**
* Retreive the QueryString 
* @param {Object} fobj Form object to retreive all name/values etc.
* @return {String} Returns a string value containing all name/values as a query string. 
*/
function getFormValues(fobj) {
	var elem, name, value, collect;
	var str="";
	var separator="";
	
	var count=fobj.elements.length;
	for (var i=0; i<count; i+=1) {
		elem=fobj.elements[i];
		name=elem.name;
		value=elem.value;
		
		if (name && (value !== '')) {
			collect=false;
			switch (elem.type) {
				case "hidden":
					collect=true;
					break;
				case "radio":
				case "checkbox":
					if (elem.checked === true) {
						collect=true;
					}
					break;
				default:
					collect=true;
					break;
			}
			if (collect) {
				str += separator + encodeURIComponent(name) + "=" + encodeURIComponent(value);
				separator="&";
			}
		}
	} 
	return str;
}

var isWorking = false;
function switchAjaxIndicator(state) {
	var indicator = $('eniroIndicator');
	if (indicator) {
		if (state === 'show') {
			indicator.style.display = "inline";
		} else {
			indicator.style.display = "none";
		}
	}
}

function addSymbols(symArray, id, emap) {
	var callout;
	if (id !== '' && symArray !== '') {
		skipInMapTxt = true;
	}
    emap.clearPois("bullseyeLayer");
    emap.clearPois("symbolLayer");
    emap.clearPlaces();
    emap.closeAllCallouts();

	if (id !== '') {
		if (id === 'B') {
			if (place) {
				place = null;
			}
			if (bullcoord) {
                emap.setLayerOptions("bullseyeLayer", {
                    poiType: 'eye',
                    poiLayout: 'ego',
                    useLabel:false,
                    useShadows:true,
                    hoverPoiOnMouseOver:false
                });
				if (userContent !== "") {
                    emap.addPoi(bullcoord, {
                        layerName:"bullseyeLayer",
                        calloutOptions: {
                            title:userContentTitle,
                            content:userContent
						}
					});
				} else {
                    emap.addPoi(bullcoord, {
                        layerName:"bullseyeLayer"
                    });
				}
			}
		} else {
            emap.clearPois("bullseyeLayer");
			if (!place || place.id !== id) {
			    emap.addPlace(id);
			}
		}
	}

	if (symArray !== '') {
        // need to unescape the string to make sure that
        // swedish characters are not represented as HTML encoded (&oring; for instance)
        // nee to do this as ; is a delimeter for symbols
        symArray = symArray.unescapeHTML();
		var symbols = symArray.split("|");

		if (symbols.length > 10) {
			/* By adding this class we use a larger image containing 25 pin symbols. */
			$('mapWrap').addClassName('hppMax');
		}
		/* used for positioning the map at the end */
		var coord, symbol;

		/* Do it backwards so we get symbol 1 on the top.*/
		for (var i = symbols.length - 1; i > 0; i -= 1) {
			symbol = symbols[i].split(";");
			/* Should we have a callout here? (company & person hits should have)*/
			callout = null;
			if (typeof(symbol[3]) !== "undefined") {
				var hitNumber = symbol[3];

				if (hitNumber) {
					callout = new Callout(hitNumber + ". " + decodeURIComponent(symbol[4]).replace("&apos;", "'"));
					var calloutContent = $('calloutContent_' + hitNumber);
					/* content is fetched from the resultlist*/
					if (calloutContent) {
						var calloutContentTemplate, calloutContentHash;
						if (/^http/.test(calloutContent.innerHTML.strip())) {
							calloutContentTemplate = new Template('#{calloutContent}');
							calloutContentHash = {
								calloutContent: calloutContent.innerHTML.strip()
							};
							callout.zoomMetaData = {
								x: symbol[1],
								y: symbol[2]
							};
						} else {
							calloutContentTemplate = new Template('#{calloutContent}<p><a href="javascript:void(0)" onclick="gEmap.sourceMap.panToGeoCoord(new Wgs84GeoCoord(\'#{x}\',\'#{y}\'),\'7\',true);">#{zoomText}</a></p>');
							calloutContentHash = {
								calloutContent: calloutContent.innerHTML.strip(),
								x: symbol[1],
								y: symbol[2],
								zoomText: zoomToHere
							};
						}
						var calloutContent2 = calloutContentTemplate.evaluate(calloutContentHash);
						callout.setContent(calloutContent2);
						callout.setClassName("callout");
						symbol.calloutContent = calloutContent2;
						symbol.calloutTitle = hitNumber + ". " + decodeURIComponent(symbol[4]).replace("&apos;", "'");
						symbol.label = hitNumber;
						symbol.zoomMetaData = callout.zoomMetaData;
					}
				}
		        emap.setLayerOptions("symbolLayer", {
		            poiLayout:"ego",
		            poiType:mapResult.getPoiType(),
					useShadows:true,
		            showCalloutOnClick:true
		        });
				mapResult.setHitPin(hitNumber, symbol);
			}
		}
		if (mapForm.searchInMap.value !== '1' || mapForm.hits_on_map.value === '1') {
			if (symbols.length > 2) {	
				emap.adjust(["symbolLayer"]);
			} else {
                //get the only pin and zoom on
                emap.jumpTo(mapResult.resultList.hits[0].pin.getGeoCoord(), {
                    zoomLevel:6,
                    tryToSlide:false
                });
			}
		}
	}
}

function handleHttpResponse(content) {
	var resultDiv = $('results'); 
	/* split AJAX data*/
	var result = content.split("!_!"); 
	/* handle HTML and coordinates*/
	if (mapForm.mop.value !== 'nb' || mapForm.searchInMap.value === '2') {
		mapForm.mapstate.value = unescape(result[2]);
		mapForm.mapcomp.value = unescape(result[3]);
		resultDiv.innerHTML = result[7];
		resultDiv.scrollTop = 0;
		result[7].evalScripts();
		Heights.calculate();
		if (result[4] !== '') {
			var zoomLevel = gEmap.sourceMap.getDefaultZoomLevel();
			if (result[6] !== '') {
				if (result[6] > gEmap.sourceMap.getMaxZoomLevel()) {
					zoomLevel = gEmap.sourceMap.getDefaultZoomLevel();
				} else {
					zoomLevel = result[6];
				}
			}
			bullcoord = new Wgs84GeoCoord(result[4], result[5]);
			gEmap.sourceMap.panToGeoCoord(bullcoord, zoomLevel);
			mapForm.mop.value = '';
			if (mapForm.hits_on_map.value === '') {
				mapForm.searchInMap.value = '1';
			}
		}
	} 
	/* handle nearby HTML*/
	var nearbyDiv = $('nearbyCompanies');
	if (nearbyDiv) {
		var puffDiv = $('puff');
		var exampleDiv = $('mapExamples');
		if (puffDiv) {
			puffDiv.style.display = "none";
		}
		if (exampleDiv) {
			exampleDiv.style.display = "none";
		}
		nearbyDiv.innerHTML = result[10];
	}
	if (mapForm.mop.value !== 'nb') {
		mapResult.initialize(); 
		/* handle symbols*/
		addSymbols(result[8], result[9], gEmap);
	} else if (/reportDialog/.test(result[7])) {
		/* This is related to Maps-38 / EGR-1066, and has to do with Eniro.dk / Krak.dk using another contact form for corrections
		 */
		if((Eniro.Page.lang() !== 'da' && Eniro.Page.tab() === 'map') || $('map').hasClassName('maproute') === true) {
			mapResult.reportDialogElement = $("reportDialog");
			mapResult.createReportDialog();
		}
	}
	
	/* escaping all characters entities if there's a where field.*/
	if($('where') !== null) {
		$('where').value = ($('where').value).unescapeHTML();
	}

	/* 
	  * @desc: This is to make sure that nearby search is only for injection of content and not evaluation. 
	  *	       Therefor it shouldn't be inside the statemachine.
	  * @todo: Improve the mop & what in Query Module to avoid this check.
	  */
	if(mapForm.mop.value === "nb"){
		switch (mapForm.what.value){
			case 'map_adr':
				mapForm.mop.value = 'aq';
				break;
			case 'map_wp':
				mapForm.mop.value = 'wp';
				break;
			case 'map':
				mapForm.mop.value = 'yp';
				break;
			default:
		}
	}
		
	isWorking = false;
	switchAjaxIndicator('hide');
}

var mapLegend = {
	createOpener: function() {
		var reportDialog = $('reportDialog');
		var mapLegendOpen = $('map-legend-open');
		if (mapLegendOpen) {
			$('map-legend-open').show();
		}
		else if (reportDialog) {
			reportDialog.up().insert({
				before: this.mapLegendOpenHtml /* Gets set in map.ftl */
			});
		}
		else {
			$('results').insert({
				bottom: this.mapLegendOpenHtml /* Gets set in map.ftl */
			});
		}
	},
	hide: function() {
		$('results').removeClassName('show-legend');
	},
	show: function() {
		$('results').addClassName('show-legend').scrollTop = 0;
	},
	_listenerOpen: function(e) {
		Event.stop(e);
		if ($('map-legend')) {
			mapLegend.show();
		}
		else {
			new Ajax.Request('/query?what=map_nautical_legend&ajax_get_cache=' + encodeURIComponent((new Date()).getTime()), {
				method: 'get',
				encoding: 'ISO-8859-1',
				onSuccess: function(transport) {
					$('results').insert({
						top: transport.responseText
					});
					mapLegend.show();
				}
			});
		}
	},
	_listenerClose: function(e) {
		Event.stop(e);
		mapLegend.hide();
	},
	listenOpen: function() {
		var el = $('map-legend-open');
		if (el) {
			Event.stopObserving(el, 'click', this._listenerOpen);
			Event.observe(el, 'click', this._listenerOpen);
		} 
	},
	listenClose: function() {
		var el = $('map-legend-close');
		if (el) {
			Event.stopObserving(el, 'click', this._listenerClose);
			Event.observe(el, 'click', this._listenerClose);
		}
	}
};
$(document).observe('dom:loaded', function() {
	mapLegend.listenOpen();
	mapLegend.listenClose();
});

Ajax.Responders.register({
	// onSuccess does not get called, so we use onComplete instead and check the status of response
	onComplete: function(request, response) {
		if (request.parameters && request.parameters.mop) {
			var mop = request.parameters.mop;
			if (mop === 'aq' || mop === 'yp') { // Remove legend for nautical chart if a address or company search has been done
				$('results').removeClassName('show-legend');
			}
		}
		if (/2\d\d/.test(response.status)) { // Only Successful status codes (2##)
			if (/map\-legend\-close/.test(response.responseText)) {
				mapLegend.listenClose();
			}
			if (/map\-legend\-open/.test(response.responseText)) {
				mapLegend.listenOpen();
			}
		}
	}
});


/*
 * @important: Please make sure to contact Basim when you update this function!
 * @description: The getData(...) is for the AJAX.Request which uses GET as a method. Do not change this function
 **/
function getData(callback) {
	if (!isWorking) {
		if (mapForm.mop.value !== "nb") {
			mapForm.advert_code.value = "";
		}
		var params = "";
		var what = mapForm.what.value;
		if(mapForm.mop.value === "nb"){
			what = "map";
			params += "what=map&";
		}
		params += getFormValues(mapForm);
		params += "&tpl=map_ajax_" + what; 
		/* the ajax_get_cache is applied to IE7, because of the AJAX request being cached.*/
		params += "&ajax_get_cache=" + encodeURIComponent((new Date()).getTime());
		
		var AjaxOptions = {
			requestHeaders: ['Content-Type', 'application/x-www-form-urlencoded;charset=iso-8859-1'],
			method: 'get',
			parameters: params,
			onComplete: function(transport) { 
				/* transport.status equal 200 indicates it's successful*/
				if (transport.status === 200) {
					handleHttpResponse(transport.responseText);
					if (callback && callback.afterSuccess) {
						callback.afterSuccess.apply();
					}
				}
			},
			onFailure: function() {
				switchAjaxIndicator('hide');
			}
		};
		var AjaxRequest = new Ajax.Request('/query', AjaxOptions);
		isWorking = true;
		switchAjaxIndicator('show');
	}
}
function setMapState(overrideXML) {
    if(overrideXML !== 1) {
        overrideXML = 0;
    }
	var mapstate = gEmap.getMapState();
	mapForm.mapstate.value = mapstate + ";" + overrideXML;
}

function updateMapstate(sw) {
	setMapState();
	if (sw === 1) {
		if (mapForm.search_word.value !== '' && mapForm.searchInMap.value === '2') {
			if (mapForm.what.value === 'map_wp') {
				mapForm.mop.value = 'wp';
			} else {
				mapForm.mop.value = 'yp';
			}
			mapForm.searchInMap.value = '1';
		} else {
			mapForm.mop.value = 'nb';
		}
		
		var mainResultsYP = $("mainResultsYP");
		var mainResultsPerson = $("mainResultsPerson"); 
		
		if (!onLoad && (mainResultsYP === null || mainResultsPerson === null)) {
			getData();
		}
		onLoad = false;
	}
}
/* 
Functions for sending maps
Called from dialog.js
Helps build wap link.
*/
function setSMSMap(e) {
	if (e) {
		var currpos = gEmap.sourceMap.getCurrentLocation();
		e.href = '/query?what=sms_map&step=1&map=%26coordinateX%3D' + currpos.x + '%26coordinateY%3D' + currpos.y; 
		/* Parse mapcomp.*/
		if (mapForm.mapcomp) {
			var mapcompArr = mapForm.mapcomp.value.split(';');
			e.href += '%26streetname%3D' + escape(escape(mapcompArr[3])) + '%26streetnumber%3D' + escape(escape(mapcompArr[4])) + '%26zip%3D' + escape(escape(mapcompArr[6])) + '%26city%3D' + escape(escape(mapcompArr[7]));
		} 
		/*Set tiletype used by mobile application*/
		var tileTypeHash = {
			'hybrid': 'MobileHybrid',
			'aerial': 'MobileAerial',
			'nautical': 'Nautical'
		};
		var mobileTileType = tileTypeHash[gEmap.sourceMap.getTileType()];
		if (mobileTileType) {
			e.href += '%26profile%3D' + escape(mobileTileType);
		}
		/*Set lang (for Finnish site)*/
		if (mapForm.lang) {
			e.href += '&lang=' + escape(mapForm.lang.value);
		}
	}
}
function buildMaplink(form) {
	var maplink = '';
	var f = $(form);
	if (f) { 
		/* Set correct mop*/
		var oldMopValue = f.mop.value;
		f.mop.value = subTab;
		var formValues = escape(getFormValues(f));
		formValues = formValues.replace(/\=/g, '%3D');
		formValues = formValues.replace(/\&/g, '%26');
		maplink = escape('http://' + document.location.host) + '%2Fquery%3F' + formValues + "%26random%3D" + Math.floor(Math.random() * 10000);
		f.mop.value = oldMopValue;
	}
	return maplink;
}  
/* 
Called from dialog.js
Used in i.e. emails
*/
function setMaplink(e) {
	updateMapstate(1);
	if (e) { 
		/* 
		The only param that needs to be sent initially is maplink=
		Ugly fix is to strip the href from it's Query string and append a new one here
		*/
		if (e.href.indexOf('?') !== -1) {
			e.href = e.href.split('?')[0];
		}
		e.href += '?maplink=' + buildMaplink('mapForm');
	}
}
/* 
* This class uses the class ResultList defined in result.js
* A class that handles the different types of resultlist (YP, WP, and poi's) on the map page.
*
*  It ties together the hits in a resultlist with the symbols (pins) on the map.
*/
var MapResult = Class.create({
	initialize: function() {
		this.companyResult = $('mainResultsYP');
		this.peopleResult = $('mainResultsPerson');
		this.poiResult = $('poiResults');
		/* This is related to Maps-38 / EGR-1066, and has to do with Eniro.dk / Krak.dk using another contact form for corrections
		 */
		if((Eniro.Page.lang() !== 'da' && Eniro.Page.tab() === 'map') || $('map').hasClassName('maproute') === true) {
			this.reportDialogElement = $('reportDialog');
			
			/* The reportDialog is not present in the WP Hit list
			 */
			if(this.reportDialogElement) {
				this.reportDialogElement.has_dialog = false;
			}
		}
		
		this.resultList = null; 
		/* What type of result are we suppose to handle?*/
		if (this.companyResult) {
			this.resultList = new ResultList(this.companyResult, {
				obj: MapHit,
				type: 'company'
			}); 
			/* if there are too many tags, a link is added to show/hide the rest of the tags*/
			var func = new TagList();
		} else if (this.peopleResult) {
			this.resultList = new ResultList(this.peopleResult, {
				obj: MapHit,
				type: 'people'
			});
		} else if (this.poiResult) {
			this.resultList = new ResultList(this.poiResult, {
				obj: PoiHit
			});
		}
		this.activeCalloutId = null;
		if (this.resultList) {
			this.resultList.hits.each(function(hit) {
				if (!hit.multi) {
					var self = this; 
					/* Set callbacks*/
					hit.callbacks.after_toggle = function(hit) {
						self.toggleHitPinCallout(hit.id);
					};
					hit.callbacks.after_hover = function(hit) {
						hit.hoverPin();
					};
					hit.callbacks.after_unhover = function(hit) {
						hit.unHoverPin();
					};
				}
			}.bind(this));
		}
		/* This is related to Maps-38 / EGR-1066, and has to do with Eniro.dk / Krak.dk using another contact form for corrections
		 */
		if((Eniro.Page.lang() !== 'da' && Eniro.Page.tab() === 'map') || $('map').hasClassName('maproute') === true) {
			if (this.reportDialogElement) {
				this.createReportDialog();
			}
		} else {
			$("reportDialog").observe("click",function(){
				/**
				 * The param that needs to be sent initially is bookmark=
				 * Strip the href from it's Query string and append a new one here
				 */
				setMapState(1);
				if(this.href.indexOf('?') !== -1) {
					this.href = this.href.split('?')[0];
				} else {
					this.href += '?bookmark=' + buildMaplink('mapForm');
				}
			});
		}
	},
	getPoiType: function() {
		if(this.resultList.opt.type === "people") {
			return "wp";
		}
		return "yp";
	},
	createReportDialog: function() {
		var opt = {};
		if (!this.reportDialogElement) {
			return;
		}
		if (!this.reportDialogElement.has_dialog) {
			opt.e = this.reportDialogElement;
			opt.before_open = function makeLink() {
				setMaplink($('reportDialog'));
			};
			opt.submit_by_ajax = true;
			var dialog = new Dialog(opt);
			this.reportDialogElement.has_dialog = true;
		}
	},
	setHitPin: function(hitId, callout) {
		var hit = this.resultList.getHitById(hitId);
		if (hit) {
			hit.setPin(callout);
		}
	},
	getHitPin: function(hitId) {
		var pinArr = $A(); 
		/* We use an array because a symbol is in fact two different symbols (The shadow image is a handled as a separate symbol tied to another symbol) */
		var hit = this.resultList.getHitById(hitId);
		if (hit) {
			pinArr.push(hit.pin);
			pinArr.push(hit.pinShadow);
		}
		return pinArr;
	},

	poiClickEvent: function(poi) {
		if (!this.resultList){
			return;
		}
		var hit = this.resultList.getHitById(poi.settings.label);
		if (hit){
			var symbol_clicked_event_handler = new SymbolClickedEventHandler(gEmap.sourceMap, poi.getCalloutLayer(), poi);
			symbol_clicked_event_handler.symbolClicked();
                hit.expand();
			scroll('results', hit.e.offsetTop, hit.e.offsetHeight);
		}
	},
		
	poiMouseOverEvent: function(poi) {
		if (!this.resultList){
			return;
		}
		var hit = this.resultList.getHitById(poi.settings.label);
		if (hit){
			hit.hover();
		}
	},

	poiMouseOutEvent: function(poi) {
		if (!this.resultList){
			return;
		}
		var hit = this.resultList.getHitById(poi.settings.label);
		if (hit){
			hit.unHover();
		}		
	},

	toggleHitPinCallout: function(hitId) {
		var hit = this.resultList.getHitById(hitId);
		if (hit.pin) {
			if (hit.expanded || hit.loading) {
				// Bug fix. Anton B. Please tell me about changes in this function.
                var symbol_clicked_event_handler = new SymbolClickedEventHandler(gEmap.sourceMap, hit.pin.getCalloutLayer(), hit.pin);
                symbol_clicked_event_handler.symbolClicked();
                
				this.activeCalloutId = hit.id;
			} else if (this.activeCalloutId === hit.id) {
				hit.pin.getCalloutLayer().close();
			}
		}
		hit = null;
	}
});
function mapCorrection() {
	var maplink = buildMaplink('mapForm');
}
/**
* Script for the showonmap box in the left hand corner of the map
*
**/
var ShowOnMap = Class.create({
	initialize: function() {
		var self = this;
		this.showonmap = $("showonmap");
		this.toggler = this.showonmap.getElementsByTagName("a")[0];
		this.layers = $("layerItems") ? $A($("layerItems").getElementsByTagName("a")) : $A();
		if ($("staticItems")) {
			this.layers = this.layers.concat($A($("staticItems").getElementsByTagName("a")));
		} 
		/* Observe events*/
		this.toggler.onclick = function() {
			return false;
		}; 
		/* This is to stop the click event in early Safari versions. Ugly, but it works*/
		Event.observe(this.toggler, "click", this.toggle.bind(this));
		this.layers.each(function(link) {
			Event.observe(link, "click",
			function(e) {
				Event.stop(e);
				self.toggleLayer(link);
				link.active = link.hasClassName("active");
			});
		}); 
		/* Read visibility info from cookie*/
		if (Eniro.settings().data.showonmap) {
			var som_visibility = Eniro.settings().data.showonmap;
			if (som_visibility === "0") {
				this.showonmap.addClassName("closed");
			} else if (som_visibility === "1") {
				this.showonmap.removeClassName("closed");
			}
		}
		this.hidden = this.showonmap.hasClassName("closed");
	},
	toggle: function(e) {
		if (e) {
			e.stop();
		}
		if (this.hidden) {
			this.show();
		} else {
			this.hide();
		}
	},
	show: function() {
		this.showonmap.removeClassName("closed");
		this.hidden = false;
		Eniro.settings().data.showonmap = "1";
		Eniro.settings().save();
	},
	hide: function() {
		this.showonmap.addClassName("closed");
		this.hidden = true;
		Eniro.settings().data.showonmap = "0";
		Eniro.settings().save();
	},
	toggleLayer: function(el) {
		el = $(el);
		if (el.active) {
			this.deactivateLayer(el);
		} else {
			this.activateLayer(el);
		}
	},
	/* These functions will be called on layer activation/deactivation */
	callbacks: {
		onActivate: {
			"coords": function(el) {
				var gps = $("gps");
				gps.removeClassName("hidden");
				var offset = Position.cumulativeOffset(gEmap.sourceMap.viewport);
				eTop(gps, (gEmap.sourceMap.getViewportHeight() / 2) + offset[1] - eHeight(gps) / 2);
				eLeft(gps, (gEmap.sourceMap.getViewportWidth() / 2) - offset[0] - eWidth(gps) / 2);
			}
		},
		onDeactivate: {
			"coords": function(el) {
				$("gps").addClassName("hidden");
			}
		}
	},
	activateLayer: function(el) {
		el.addClassName("active");
		el.active = true;
		if (this.callbacks.onActivate[el.parentNode.id]) {
			this.callbacks.onActivate[el.parentNode.id](el);
		}
	},
	deactivateLayer: function(el) {
		el.removeClassName("active");
		el.active = false;
		if (this.callbacks.onDeactivate[el.parentNode.id]) {
			this.callbacks.onDeactivate[el.parentNode.id](el);
		}
	}
});
/**
 * Toggler for the different coordinate systems
 */
var GPSSystemToggler = Class.create({
	systems: {
		sv: ["rt90", "wgs84"]
	},
	initialize: function() {
		this.e = $("gps");
		this.systems = this.systems[Eniro.Page.lang()] || [];
		if (this.systems.length > 1) {
			this.active_system = this.e.hasClassName(this.systems[0]) ? this.systems[0] : this.systems[1];
			$A(this.e.getElementsByTagName("a")).each(function(a) {
				Event.observe(a, "click", this.toggleSystem.bind(this), false);
			}.bind(this));
		}
	},
	toggleSystem: function(v) {
		v.stop();
		Event.element(v).blur();
		this.e.removeClassName(this.active_system);
		this.active_system = this.active_system === this.systems[0] ? this.systems[1] : this.systems[0];
		this.e.addClassName(this.active_system);
	}
});
var som, gps_system;
Event.observe(document, "dom:loaded",
function() {
	if (Eniro.Page.tab() === "map" && $("showonmap")) {
		som = new ShowOnMap();
		if (Eniro.Page.lang() === "sv") {
			gps_system = new GPSSystemToggler();
		}
	}
});

function _innerScroll(sObj) {
	sObj.stepPx = (sObj.scrollToPx - sObj.scrollTop) / 2;
	if (sObj.stepPx > 1 || -1 > sObj.stepPx) {
		sObj.scrollTop = sObj.scrollTop + sObj.stepPx;
        // like jslint says, wrap the call in a function...
        setTimeout(function(){
            _innerScroll(sObj);
        }, 40);
		sObj.moving = true;
	} else {
		sObj.moving = false;
	}
}

function scroll(scrollThisId, hitTop, hitHeight) {
	var sObj = $(scrollThisId);
	sObj.scrollToPx = null; 
	/* If the target is in view don't scroll */
	if (hitTop < sObj.scrollTop) {
		/* scroll up */
		sObj.scrollToPx = hitTop - 2;
	} else if ((hitTop + hitHeight) >= (sObj.scrollTop + sObj.offsetHeight)) {
		/* scroll down */
		sObj.scrollToPx = hitTop + 2;
	}
	if (sObj.scrollToPx && !sObj.moving) {
		_innerScroll(sObj);
	}
}
/**
 * PostCards
 * create special dialog boxes for postcards on maps
 * by Martin Jansson <martin.jansson@netrelations.se> for Eniro
 */
var PostCards = {
	dialogs: new DialogHandler(document.getElementsByTagName("body")[0]),
	/** Creates a new postcard dialog and opens it
	*/
	create: function(options) {
		var dialog_opts = {};
		var content = document.createElement("div");
		var postcard = content.appendChild(document.createElement("img"));
		postcard.src = options.imgsrc || "";
		var info_container = document.createElement("span");
		info_container.className = "more-information-link";
		var info = info_container.appendChild(document.createElement("a"));
		info.href = options.more_info_link;
		info.target = "_blank";
		info.appendChild(document.createTextNode(options.more_info));
		var non = content.appendChild(info_container);
		var creds = content.appendChild(document.createElement("span"));
		creds.appendChild(document.createTextNode(options.photographer));
		creds.className = "photographer";
		var close = content.appendChild(document.createElement("a"));
		close.href = "#";
		close.className = "close-pic";
		close.appendChild(document.createTextNode("St\xe4ng f\xf6nstret"));
		var dialog = PostCards.dialogs.add({
			content: content,
			open_after_create: true,
			title: options.title || "",
			extra_class: "postcard-dialog" + (options.bigger_box ? " postcard-dialog-bigger": "")
		});
		if (dialog.getViewportSize().y < 600) {
			var divstyle = dialog.body.getElementsByTagName("div")[0].style;
			divstyle.height = (dialog.getViewportSize().y - 100) + "px";
			divstyle.overflow = "auto";
		}
		dialog.handler = PostCards.dialogs;
		dialog.moveToTop();
		Event.observe(close, "click", dialog.close.bind(dialog)); 
		/* Close all popups before showing the new postcard */
		for (var i = 0; i < PostCards.dialogs.dialogs.length - 1; i += 1) {
			if (PostCards.dialogs.dialogs[i].opened) {
				PostCards.dialogs.dialogs[i].close();
			}
		}
		return dialog;
	},
	/** Creates a new postcard dialog from a link element
   *  Takes one parameter: an event. So this method should be called via the click event of a link element
   *  The link element's src should be the url to the picture you want to display in the dialog, and the
   *  title attribute of the link should be in the following format: "Title of image|Photographer:Name"
   */
	createFromLink: function(a) {
		if (a.tagName.toLowerCase() === "img") {
			a = a.parentNode;
		}
		var img = a.offsetParent.getElementsByTagName("img")[0];
		var title = a.getAttribute('title') ? a.getAttribute('title').split("|") : [];
		var options = {
			imgsrc: a.getAttribute("href"),
			title: title[0] || "Vykort",
			photographer: title[1] || "Fotograf: ok\xe4nd",
			more_info_link: "http://www.eniro.se/sverigebilder",
			more_info: "Om Sverigebilder",
			bigger_box: img.clientWidth > 150
		};
		var dialog = PostCards.create(options);
	}
};
/**
  * From maps.js
 **/
function insertInMapTxt() {
	searchForm.geo_area.style.color = '#999';
	searchForm.geo_area.value = inMapTxt;
}
function initForm() {
	var form1 = $('map_yp_form');
	var form2 = $('map_wp_form');
	var form3 = $('map_address_form');
	if (form1) {
		searchForm = form1;
		subTab = 'yp';
	} else if (form2) {
		searchForm = form2;
		subTab = 'wp';
	} else if (form3) {
		searchForm = form3;
		subTab = 'aq';
	}
	if (searchForm) {
		if (searchForm.geo_area.value === inMapTxt) {
			insertInMapTxt();
		}
		searchForm.geo_area.onfocus = function() {
			if (this.value === inMapTxt) {
				this.value = '';
			}
			this.style.color = '#000';
		};
	}
}


/**
 * BrowserVersion
 *
 * @desc Used to retrieve the browser version
 * @todo Move to util directory
 */
(function() {
    var nav       = navigator;
    var userAgent = navigator.userAgent;
	var ua 		  = navigator.userAgent;
    var v         = nav.appVersion;
    var version   = parseFloat(v);

    BrowserVersion = {
        IE      : (Prototype.Browser.IE)    ? parseFloat(v.split("MSIE ")[1]) || 0 : 0,
        Firefox : (Prototype.Browser.Gecko) ? parseFloat(ua.split("Firefox/")[1]) || 0 : 0,
        Camino  : (Prototype.Browser.Gecko) ? parseFloat(ua.split("Camino/")[1]) || 0 : 0,
        Flock   : (Prototype.Browser.Gecko) ? parseFloat(ua.split("Flock/")[1]) || 0 : 0,
        Opera   : (Prototype.Browser.Opera) ? version : 0,
        AIR     : (ua.indexOf("AdobeAIR") >= 0) ? 1 : 0,
        Mozilla : (Prototype.Browser.Gecko || !this.Khtml) ? version : 0,
        Khtml   : (v.indexOf("Konqueror") >= 0 && this.safari) ? version : 0,
        Safari  : (function() {
            var safari = Math.max(v.indexOf("WebKit"), v.indexOf("Safari"), 0);
            return (safari) ? (
                parseFloat(v.split("Version/")[1]) || ( ( parseFloat(v.substr(safari+7)) >= 419.3 ) ? 3 : 2 ) || 2
            ) : 0;
        })()
    };
})();

/**
 * ScreenMode
 *
 * @desc Used to switch the MapApi screen mode
 */
var ScreenMode = Class.create({
	initialize: function(){
		$('show-large-map').observe('click',this.change.bindAsEventListener(this), false);
		$('show-small-map').observe('click',this.change.bindAsEventListener(this), false);
		
		if(BrowserVersion.IE === 6) {
			try {
				document.execCommand('BackgroundImageCache', false, true);
			} catch(e) { }
		}
	},
	change: function(event){
		if (event) {
			event.stop();
		}
		var _map = $('map');
		if(_map.hasClassName('screen-on')) {
			_map.removeClassName('screen-on');
			
			gEmap.fillScreen($("content").getWidth(), $('head').getHeight()-8); // 8 is the top attribute of #mapWrap
			$('mapWrap').insert($('tileTypeWrapper'));
			$('head').removeClassName('ego');
		} else {
			_map.addClassName('screen-on');
			
			gEmap.fillScreen(0, $('head').getHeight()-17); // 17 is the top attribute of #mapWrap
			$('head').insert($('tileTypeWrapper'));
			$('head').addClassName('ego');
		}
		return;
	}
});
/*
Event.observe(document, "dom:loaded", function(){
	//$('map-content') goes for krak.dk
	if(Object.isElement($('content'))) {
		var s = new ScreenMode();
	}
});
*/

function refreshMap() {
	gEmap.sourceMap.show();
}
function softPan(direction) {
	gEmap.sourceMap.softPanToDirection(direction);
}
function panMouseover(obj, divID) {
	obj.style.backgroundColor = "#FF5C5B";
	if (divID) {
		$(divID).style.backgroundColor = "#FF5C5B";
	}
}
function panMouseout(obj, divID) {
	obj.style.backgroundColor = "#C72727";
	if (divID) {
		$(divID).style.backgroundColor = "#C72727";
	}
}
function showAddrList(sw) {
	var samsg = $('showAddrMsg');
	var hamsg = $('hideAddrMsg');
	var alist = $('addressList');
	var ylist = $('mainResultsYP');
	var wlist = $('mainResultsPerson');
	var nearby = $("nearbyCompanies");
	if (sw) {
		samsg.style.display = "none";
		if (nearby) {
			nearby.style.display = "none";
		}
		if (ylist) {
			ylist.style.display = "none";
		}
		if (wlist) {
			wlist.style.display = "none";
		}
		hamsg.style.display = "block";
		alist.style.display = "block";
	} else {
		samsg.style.display = "block";
		if (nearby) {
			nearby.style.display = "block";
		}
		if (ylist) {
			ylist.style.display = "block";
		}
		if (wlist) {
			wlist.style.display = "block";
		}
		hamsg.style.display = "none";
		alist.style.display = "none";
	}
} 
/* Start Tools functions ---------------------------------------*/
function oldStyleLinkToMap(id, extraParms) { 
	mapForm.mop.value = 'aq'; 
	/* Remove mapstate if ps_id or advert_code exist.*/
	if (mapForm.ps_id.value !== "" || mapForm.advert_code.value !== "") {
		mapForm.mapstate.value = "";
	}
	setMapState();
	var qstr = getFormValues($(id));
	var url = 'http://' + document.location.host + '/query?' + qstr;
	if (extraParms) {
		url = url + "&" + extraParms;
	}
	return url;
}
function oldestStyleLinkToMap(id, extraParms) { 
	/*  set correct mop */
	mapForm.mop.value = subTab;
	/* Remove mapstate if ps_id or advert_code exist.*/
	if (mapForm.ps_id.value !== "" || mapForm.advert_code.value !== "") {
		mapForm.mapstate.value = "";
	}
	setMapState(1);
	var qstr = getFormValues($(id));
	var url = 'http://' + document.location.host + '/query?' + qstr;
	if (extraParms) {
		url = url + "&" + extraParms;
	}
	return url;
}
function submitForm(id, extraParms) { 
	/*Used when changing tab*/
	window.location = oldStyleLinkToMap(id, extraParms);
}
function getLinkToMap() {
	var extraParms;
	if (getLinkToMap.beforeFn) {
		extraParms = getLinkToMap.beforeFn();
	}
	return oldestStyleLinkToMap('mapForm', extraParms);
}
function setGetLinkToMapHook(beforeFn) {
	getLinkToMap.beforeFn = beforeFn;
}
function printMap(extraParams) {
	//var oldwhat = mapForm.what.value;
	//if(oldwhat != 'map_wp') mapForm.what.value = 'map';
	mapForm.mop.value = 'mp';
	mapForm.searchInMap.value = '1';
	mapForm.tpl.value = 'map_print';
	var qStr = getFormValues(mapForm);
	if (extraParams) {
		qStr += extraParams;
	}
	if(Eniro.Page.lang() === "fi" && $("map_address_form")) {
		window.open("/query?" + qStr, 'print', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=768,height=' + Math.max(window.outerHeight ? window.outerHeight - 100 : document.viewport.getHeight(), 600) + ',top=0,left=0');
	} else {
		window.open("/query?" + qStr, 'print', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=670,height=' + Math.max(window.outerHeight ? window.outerHeight - 100 : document.viewport.getHeight(), 600) + ',top=0,left=0');
	}
	mapForm.tpl.value = '';
	//mapForm.what.value = oldwhat;
}
function toggleCoords() {
	var gps = $("gps");
	if (gps.hasClassName("hidden")) {
		gps.removeClassName("hidden");
	} else {
		gps.addClassName("hidden");
	}
} 
/* End Tools functions -----------------------------------------*/
function clearForm() {
	try {
		mapForm.search_word.value = '';
		mapForm.geo_area.value = '';
		mapForm.header_code.value = '';
		mapForm.header_code_exact.value = '';
		mapForm.selected_header_code.value = '';
		mapForm.heading_exact.value = '';
		mapForm.layers.value = '';
		mapForm.ns.value = '';
		mapForm.stq.value = '0';
		mapForm.filter.value = '';
		mapForm.pis.value = '0';
		mapForm.hits_on_map.value = '';
		mapForm.proximity.value = '';
		mapForm.tpl.value = '';
		mapForm.link_id.value = '';
		mapForm.ps_id.value = ''; 
		/* Additional YP adv. params.*/
		mapForm.advanced.value = '';
		mapForm.adv_search_word.value = '';
		mapForm.adv_search_word_type.value = '';
		mapForm.company_name.value.value = '';
		mapForm.company_name_type.value = '';
		mapForm.phone_number.value = '';
		mapForm.street.value = '';
		mapForm.street_type.value = '';
		mapForm.zip_code.value = '';
		mapForm.post_area.value = '';
		mapForm.district_codes.value = '';
	} catch(e) {}
} 
/* Start AJAX functions -----------------------------------------------------------------*/
function nearbySearch(hdata, hdata2) {
	clearForm();
	mapForm.what.value = 'map';
	mapForm.mop.value = 'yp';
	mapForm.heading.value = '';
	mapForm.searchInMap.value = '1';
	mapForm.disable_multi_company_merge.value = '1';
	if (hdata2) { 
		/* nearby search*/
		mapForm.header_code.value = hdata;
		mapForm.search_word.value = hdata2;
		if ($('map_yp_form')) {
			/* Only insert value into search_word field if YP subtab.*/
			searchForm.search_word.value = hdata2; 
		}
	} else { 
		/* nearby (company) link*/
		mapForm.link_id.value = hdata;
	}
	getData();
}
function selectAddress(zl, x, y, comp, where, atype) { 
	/* Prevents EniMap from freezing when swiched coordinates are submited*/
	if (x > 45 && y < 45) {
		var tmp = x;
		x = y;
		y = tmp;
		zl = 2;
	}
	bullcoord = new Wgs84GeoCoord(x, y);
	addSymbols('', atype,gEmap);
	mapForm.mapcomp.value = unescape(comp); 
	/* searchForm.geo_area.value = unescape(where); */
	mapForm.stq.value = '0';
	mapForm.searchInMap.value = '2';
	skipInMapTxt = true; 
	/* eniMap.setZoomLevel(zl); */
	gEmap.sourceMap.panToGeoCoord(bullcoord, zl);
}
function listPaging(hitnr, mop) {
	mapForm.stq.value = hitnr;
	mapForm.mop.value = mop;
	mapForm.searchInMap.value = '1';
	getData();
}
/* End AJAX functions -------------------------------------------------------------------*/
function updateXYMapcomp(x, y) {
	var oldMapcomp = mapForm.mapcomp.value.split(';');
	var mapcomp = '';
	for (var i = 0; i < oldMapcomp.length - 1; i += 1) {
		if (i === 12) {
			mapcomp += x;
		} else if (i === 13) { 
			mapcomp += y;
		} else {
			mapcomp += oldMapcomp[i];
		}
		mapcomp += ';';
	}
}
function updateAddressHash() { 
	/* Set correct mop*/
	var oldMopValue = mapForm.mop.value;
	mapForm.mop.value = subTab; 
	/* Remove mapstate if ps_id or advert_code exist.*/
	if (mapForm.ps_id.value !== "" || mapForm.advert_code.value !== "") {
		mapForm.mapstate.value = "";
	}
	var qstr = getFormValues($("mapForm"));
	window.location.hash = qstr;
	mapForm.mop.value = oldMopValue;
	updateMapstate();
} 

/**
 * Should be called when the symbolClicked event is fired
 * <pre>
 * 	<code>var och = new SymbolClickedEventHandler(eniMap, layer, symbol);</code>
 *  <code>och.updateContent();</code>
 * </pre>
 * @param eniMap
 * @param layer
 * @param symbol
 * @return
 */
function SymbolClickedEventHandler(eniMap, layer, symbol) {
	this.eniMap = eniMap;
	this.layer = layer;
	this.symbol = symbol;
	this.callout = null;
	this.ajaxWentWell = false;
	this.resultListContainer = $("calloutContent_" + symbol.settings.label);
	if (this.symbol.calloutLayer === null && this.layer !== null) {
		this.symbol.calloutLayer = this.layer;
	} else if (this.symbol.calloutLayer === null && this.layer === null) {
		this.symbol.calloutLayer = this.eniMap.getDefaultCalloutLayer();
	}
}
SymbolClickedEventHandler.prototype = {
	symbolClicked: function() {
		this.callout = this.symbol.getCallout();
		var calloutContent = this.symbol.callout.content;
		if (/^http/.test(calloutContent)) {
			this._updateCalloutContent(calloutContent);
		} else {
			this._openCallout();
			this._updateZoomHereLink();
			this._attachDialogToDialogLinks();
			this._findImagesInCallout();
		}
		calloutContent = null;
	},
	_getContentFromResultList: function() {
		return $(this.resultListContainer).innerHTML.strip();
	},
	_openCallout: function() {
        if (this.eniMap.isFarDestination(this.symbol.getGeoCoord())) {
            this.eniMap.panToGeoCoord(this.symbol.getGeoCoord());
        }
		this.layer.initCallout(this.callout);
		this.layer.showCallout(this.callout); 
		/* this.eniMap.panToGeoCoord(this.symbol.getGeoCoord(), eniMap.getZoomLevel(), true); */
	},
	_findAllDialogLinks: function() {
		return $$(".callout a.dialog");
	},
	_findZoomHereLink: function() {
		return $$(".callout a.zoom_here").first();
	},
	_updateZoomHereLink: function() {
		var _zoomHereLink = this._findZoomHereLink();
		if (_zoomHereLink && this.symbol.zoomMetaData) {
			var x = this.symbol.zoomMetaData.x;
			var y = this.symbol.zoomMetaData.y;
            _zoomHereLink.onclick = function() {
                gEmap.sourceMap.panToGeoCoord(new Wgs84GeoCoord(x,y),7,true);
            };
		}
		_zoomHereLink = null;
	},
	_findImagesInCallout: function() {
		$(this.layer.contentDiv).select("img").each(function(img) {
			var self = this;
			img.onload = function() {};
		}.bind(this));
	},
	_attachDialogToDialogLinks: function() {
		var client;
		if (!this.dialogs) {
			this.dialogs = new DialogHandler();
		}
		var _dialogLinks = this._findAllDialogLinks();
		_dialogLinks.each(function(_dialogLink) {
			if (!_dialogLink.has_dialog) {
				var dialog_opt = {
					e: _dialogLink,
					submit_by_ajax: _dialogLink.hasClassName('ajax')
				};
				if ($(_dialogLink.parentNode).hasClassName("clickcall")) {
					dialog_opt.before_submit = function() {
						client = $("client");
						if (client !== null) {
							Eniro.settings().data.c2c_phone_no = client.value;
							Eniro.settings().save();
						}
					};
					dialog_opt.extra_class = "phone-us-dialogue";
				}
				if ($(_dialogLink.parentNode).hasClassName("clickcall") || $(_dialogLink.parentNode).hasClassName("sms")) {
					dialog_opt.after_content = function(dialogue) {
						client = $("client");
						if (client !== null) {
							client.value = Eniro.settings().data.c2c_phone_no || "";
						}
						var info = dialogue.box.select("div.infobox");
						if (info[0]) {
							info = info[0];
							info.hide();
							dialogue.box.select("a.toggle_info").each(function(e) {
								e.observe("click",
								function(v) {
									Event.stop(v);
									dialogue.box.select("div.infobox")[0].toggle();
								});
							}.bind(dialogue));
						}
					};
				}
				if ($(_dialogLink.parentNode).hasClassName("contact")) {
					dialog_opt.after_content = function(dialogue) {
						var cookies_error = dialogue.box.select("#cookies_error")[0];
						var contact_form = dialogue.box.select("#contact_form")[0];
						if (!Eniro.Page.check_cookies_enabled()) {
							if (cookies_error) {
								cookies_error.setStyle({
									display: 'block'
								});
								if (contact_form) {
									contact_form.hide();
								}
							}
						}
						var warning_message = dialogue.box.select("#warning_message")[0];
						if (warning_message) {
							if (!warning_message.hasClassName('first')) {
								warning_message.hide();
							}
							var rand_no = Math.floor((3) * Math.random());
							if (rand_no === 0) {
								warning_message.show();
							}
						}
					};
				}
				var dialogue = this.dialogs.add(dialog_opt);
				dialogue.handler = this.dialogs;
				_dialogLink.has_dialog = true;
			}
		}.bind(this));
	},
	_updateCalloutContent: function(url) { 
		/* at first we need to reset the content of the callout or we get a flash of the URL*/
		/* that is used to get the extended content.*/
		this.callout.setContent('<div class="loading">&nbsp;</div>');
		this.eniMap.getDefaultCalloutLayer().initCallout(this.callout);
		url = url + "/ajax_get_cache/" + encodeURIComponent((new Date()).getTime());
		var AjaxRequest = new Ajax.Request(url, {
			method: "get",
			encoding: "ISO-8859-1",
			onCreate: function(transport) {
				this.ajaxWentWell = false;
				switchAjaxIndicator('show');
			}.bind(this),
			onSuccess: function(transport) {
				this.ajaxWentWell = true;
				switchAjaxIndicator('hide');
			}.bind(this),
			onComplete: function(transport) {
				if (this.ajaxWentWell && transport.status === 200) {
					this.resultListContainer.update(transport.responseText.strip());
					this.callout.setContent(transport.responseText.strip());
					this._openCallout();
					this._updateZoomHereLink();
					this._attachDialogToDialogLinks();
					this._findImagesInCallout();
				}
			}.bind(this),
			onFailure: function(transport) {
				switchAjaxIndicator('hide');
			}
		});
	}
};
function saveStartLocation(s_zl, s_sname, s_snr, s_box, s_zip, s_city, s_cx, s_cy, s_area, s_munic) {
	/* I don't want to change tab when saving startlocation */
	var what;
	if ($('map_wp_form')) {
		what = 'map_wp';
	} else if ($('map_yp_form')) {
		what = 'map';
	} else {
		what = 'map_adr';
	}
	var startLink = 'http://' + document.location.host + '/query?mapstate=' + s_zl + '&mapcomp=;;;' + s_sname + ';' + s_snr + ';' + s_box + ';' + s_zip + ';' + s_city + ';;;;;' + s_cx + ';' + s_cy + ';;;' + s_area + ';' + s_munic + '&startMap=1';
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000 * 24 * 1000);
	setCookie('egoStartMap', startLink + '&what=map_adrendStartMap', expire, '/', -1, '');
	if (what) {
		startLink = startLink + '&what=' + what;
	}
	window.location = startLink;
}
function delStartLocation() {
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000 * 24 * 1000);
	setCookie('egoStartMap', '', expire, '/', -1, '');
	window.location = 'http://' + document.location.host;
}
/**
 * Info-box (puff) on map front page
 * Creates info-box
 * @author Natasha Banegas
 */
Event.observe(document, "dom:loaded",
function() {
	var puff = document.getElementById("puff");
	var inner_puff = document.getElementById("inner_puff");
	if (puff && inner_puff) {
		if (inner_puff.childNodes.length > 1) {
			puff.className = "show";
		}
	}
});
/**
 * Redirect to a search_word page without reloading.
 * @param {string} search_word The search word to seach for and
 * redirect to.
 */
function submitSearchWord(search_word) {
	var def_coords = '1;16;59;0;-15;73;47;46';
	var width = gEmap.sourceMap.getViewportWidth();
	var height = gEmap.sourceMap.getViewportHeight();
	document.mapForm.geo_area.value = search_word;
	document.mapForm.searchInMap.value = '';
	document.mapForm.mapcomp.value = '';
	document.mapForm.mapstate.value = def_coords + ';' + width + ';' + height;
	document.mapForm.mop.value = "aq";
	document.mapForm.what.value = "map_adr";
	skipInMapTxt = true;
	var callback = {
		afterSuccess: function() {
			gEmap.sourceMap.switchToObliqueMap();
		}
	};
	getData(callback); 
	if ($('where')) {
		$('where').value = search_word;
	}
	return false;
}
/**
* Remembers the state of the overviewmap in a cookie
*/
var OverviewmapRememberer = Class.create({
	initialize: function(overviewmap) {
		var self = this;
		this.overviewmap = overviewmap;
		this._read_cookie();
		Event.observe($("close-overviewmap"), "click",
		function() {
			self.close_map();
			self._write_cookie();
		});
		Event.observe($("open-overviewmap"), "click",
		function() {
			self.open_map();
			self._write_cookie();
		});
	},
	/**
	* Open the map
	*/
	open_map: function() {
		this.overviewmap.openOverView();
		gEmap.sourceMap.overviewmap.panToGeoCoord(gEmap.sourceMap.getCurrentLocation());
		this.visible = true;
	},
	/**
	* Close the map
	*/
	close_map: function() {
		this.overviewmap.closeOverView();
		this.visible = false;
	},
	/**
	* Read visibility info from cookie
	*/
	_read_cookie: function() {
		var visibility = Eniro.settings().data.overviewmap;
		if (visibility !== null) {
			if (visibility === "0") {
				this.close_map();
			} else {
				this.open_map();
			}
		}
	},
	_write_cookie: function() {
		Eniro.settings().data.overviewmap = this.visible ? "1": "0";
		Eniro.settings().save();
	}
});

/* Used by DWD to hide SMS link when activating DWD features */
function toggleSendSMSLink(state) {
	var sendsmslink = $('maptools').down('li.sms');
	try {
		if (typeof state != 'undefined' && (state == 'show' || state == 'hide')) {
			sendsmslink[state]();
		}
		else {
			sendsmslink.toggle();
		}
	} 
	catch (e) {}
}

/**
 * This is a temporary solution for the DSB link, which will be removed in WCM in october 2009.
 * There's a duplicate of this script when the page is evaluated in the Ajax.response. 
 */
document.observe("dom:loaded", function() {
	if(Eniro.Page.tab() === "map" && $("map_address_form") !== null) {
		var dsb = $('dsb');
		if(dsb !== null){
			var timeout;
			dsb.observe("mouseout", function(e){
				timeout = setTimeout(function() {
					dsb.removeClassName('hover');
				}, 20);
			});
			dsb.observe("mouseover", function(e){
				if (timeout) {
					clearTimeout(timeout);
				}
				dsb.addClassName('hover');
			});
		}

		var dsb_link = $('dsb-link');
		if (dsb_link !== null) {
			dsb_link.observe("click",function(e){
				/**
				 * The param that needs to be sent initially is /bin/query.exe/mn?S=ADDRESS_GOES_HERE&SADR=1
				 * Strip the href from it's Query string and append a new one here
				 */
				if(this.href.indexOf('?') !== -1) {
					this.href = this.href.split('/bin/query.exe/mn?')[0];
				}
				this.href += '/bin/query.exe/mn?S=' + encodeURIComponent($('where').value) + '&SADR=1';
				return false;
			});
			
		}
	}
});
