/**
* Tiled pannable maps script
*
* @package		klickTel
* @author 		Thomas Frütel <tfruetel@klicktel.de>
* @version 		1.0
* @copyright 	2006 by klickTel GmbH. All Rights Reserved.
*/

// (sk) 26.05.2006
function mapLogSend(message)
{
	//if(Logger != null) Logger.log(message);
}


//A few Globals
tileSize = 256;
meterPerPixel = Array (0.25,0.5,1,2,4,8,16,32,64,128,256,512,1024,2048,4096);
mapObject = "";
clickposX = 0;
clickposY = 0;
buttonstate = false;
offCenterX = tileSize/2;
offCenterY = tileSize/2;

var GeoObject = Class.create ();

GeoObject.prototype = {
	longitude: 0,
	latitude: 0,
	screenX: 0,
	screenY: 0,
	documentID: '',

	initialize: function () {
	},

	draw: function () {
	}
}

var drawablePOI = Class.create ();
Object.extend (drawablePOI, GeoObject);
Object.extend (drawablePOI.prototype,  {
	onclick: "",
	image: "",
	html: ""
});

var Tile = Class.create ();
Object.extend (Tile, GeoObject);
Object.extend (Tile.prototype,  {
	extend:0,
	mainlayer:null,

	initialize: function () {
		this.screenX = 0;
		this.screenY = 0;
	},

	draw: function () {
		node = $(this.documentID);
		this.position();
		node.style.visibility = "visible";
		node.style.margin="0px";
		node.style.padding="0px";
		node.style.width=tileSize+"px";
		node.style.height=tileSize+"px";
		node.border="0";
		node.galleryimg="no";
		node.onselect = function () {
			window.event.returnValue = false;
		};
		node.onscroll = function () {
			return(false);
		}

		if (mapObject.aerial == true) {
			aerial = 1;
			if (mapObject.hybrid == true) {				
				this.mainlayer = 32;
				hybrid=1;
			}
			else {
				this.mainlayer = 8;
				hybrid=0;
			}
		}
		else {			
			aerial = 0;
			hybrid = 0;
			this.mainlayer = 16;
		}
		
		poiappend = "";

		for (i=0; i<mapObject.staticpoi.length; i++) {
			if (i==0) {
				poiappend = mapObject.staticpoi[i];
			}
			else {
				poiappend += "|"+mapObject.staticpoi[i];
			}
		}
		if (mapObject.zoomlevel > 9)
			poiappend = "";


		xcounter = (this.documentID.match("_(.*)_")[1])*1 + 1;
		ycounter = (this.documentID.match("_(.*)_(.*)")[2])*1 +1;
		bitvector = 0;
		
		if (mapObject.weather == true && xcounter == Math.round(mapObject.checkerboard.cols/2)+1 && ycounter == Math.round(mapObject.checkerboard.cols/2)) {
			bitvector = bitvector | 1;
		}
		var traffic = 0;
		if (mapObject.trafficjam == true) {
			bitvector = bitvector | 2;
			traffic = 1;
		}

		//vhost = ((xcounter+ycounter) % 4)+1;
		if (mapObject.roundRobin < mapObject.subdomains) {
			mapObject.roundRobin++;
		} else {
			mapObject.roundRobin = 1;
		}
		
/*
			if (mapObject.route <= 0) { //Map view, include sel_x and sel_y for flag position
				imageLoad (node, "http://ppm"+mapObject.roundRobin+".klicktel.de/"+mapObject.appFolder+"/tileserver_"+this.longitude+";"+this.latitude+";"+this.extend+";"+mapObject.longitudeHome+";"+mapObject.latitudeHome+"_"+mapObject.route+"_"+tileSize+"_"+bitvector+"_1_"+aerial+"_"+hybrid+"_"+poiappend+".png", "");
			} else { //Route
				imageLoad (node, "http://ppm"+mapObject.roundRobin+".klicktel.de/"+mapObject.appFolder+"/tileserver_"+this.longitude+";"+this.latitude+";"+this.extend+"_"+mapObject.route+"_"+tileSize+"_"+bitvector+"_1_"+aerial+"_"+hybrid+"_"+poiappend+".png", "");
			}
*/
/*
			if (mapObject.route <= 0) { //Map view, include sel_x and sel_y for flag position
				imageLoad (node, "http://nmap0"+mapObject.roundRobin+".ppm-ng.de/scripts/image.dll?getxmapdirect&left="+this.longitude+"&top="+this.latitude+"&w="+tileSize+"&h="+tileSize+"&zoom="+meterPerPixel[mapObject.zoomlevel-1]*1000+"&routeid=-1&trafficjam="+traffic+"&layer="+this.mainlayer+"&poicat="+poiappend);
			} else { //Route
				imageLoad (node, "http://nmap0"+mapObject.roundRobin+".ppm-ng.de/scripts/image.dll?getxmapdirect&left="+this.longitude+"&top="+this.latitude+"&w="+tileSize+"&h="+tileSize+"&zoom="+meterPerPixel[mapObject.zoomlevel-1]*1000+"&routeid="+mapObject.route+"&trafficjam="+traffic+"&layer="+this.mainlayer+"&poicat="+poiappend);
			}
*/
			if (location.hostname.search('.release.klickurl.de') != -1) {
				var loc = "api.release.klickurl.de";			
			} else if (location.hostname.search('.local') != -1) {
				var loc = "api.klicktel.local";				
			} else {
				var loc = "api.klicktel.de";
			}
			
			if (mapObject.route <= 0) { //Map view, include sel_x and sel_y for flag position
				imageLoad (node, "http://"+loc+"/kt_map/tileserver_"+this.longitude+";"+this.latitude+";"+meterPerPixel[mapObject.zoomlevel-1]*1000+";"+mapObject.longitudeHome+";"+mapObject.latitudeHome+"_0_"+tileSize+"_"+traffic+"_1_"+this.mainlayer+"_"+hybrid+"_"+poiappend+".png");
			} else { //Route
				imageLoad (node, "http://"+loc+"/kt_map/tileserver_"+this.longitude+";"+this.latitude+";"+meterPerPixel[mapObject.zoomlevel-1]*1000+";"+mapObject.longitudeHome+";"+mapObject.latitudeHome+"_"+mapObject.route+"_"+tileSize+"_"+traffic+"_1_"+this.mainlayer+"_"+hybrid+"_"+poiappend+".png");
			}
			
		node.ondrag = function()
			{
    				window.event.returnValue = false;
			};

	},

	position: function () {
		node = $(this.documentID);
		node.style.position="absolute";
		node.style.left = this.screenX+"px";
		node.style.top =  this.screenY+"px";
	}
});

var ScoutPOI = Class.create ();
Object.extend (ScoutPOI.prototype, GeoObject);
ScoutPOI.prototype = {
	id: "",
	initialize: function (_longitude, _latitude, _id) {
		this.longitude = _longitude;
		this.latitude = _latitude;
		this.id = _id;
	}
};

var PoiBox = Class.create (); //For Klicktel for Outlook
Object.extend (PoiBox.prototype, GeoObject);
PoiBox.prototype = {
	title: "",
	body: "",
	html: "",
	documentID: "scoutPin",
	offsetX: 0,
	offsetY: 0,

	initialize: function () {
		mapObject.scoutPin = this;
	},

	draw: function () {
		if ($(this.documentID) != null) {
			Element.remove (this.documentID);
		}


		this.screenX = (((this.longitude-mapObject.longitude)/mapObject.unitsPerPixel)+mapObject.width/2)+this.offsetX;
		this.screenY = (((mapObject.latitude-this.latitude)/mapObject.unitsPerPixel)+mapObject.height/2)+this.offsetY;

		img = document.createElement ("img");
		div = document.createElement ("div");
		div.id = this.documentID;
		$("container").appendChild (div);
		pars = "title="+this.title+"&body="+this.body;
		url = "/kt_map/poibox.php";
		var myAjax = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: pars,

				onComplete: function (originalRequest) {
					Element.update ($(mapObject.scoutPin.documentID),originalRequest.responseText);
					dimensions = Element.getDimensions ($(mapObject.scoutPin.documentID).firstChild);
					$(mapObject.scoutPin.documentID).style.left = (mapObject.scoutPin.screenX-Math.round(dimensions.width/2))+"px";
					$(mapObject.scoutPin.documentID).style.top = (mapObject.scoutPin.screenY-dimensions.height)+"px";
					$(mapObject.scoutPin.documentID).style.position = "absolute";
					$(mapObject.scoutPin.documentID).style.zIndex = 280;
					//Now the pin that is hidden first, will be displayed when the infobox is closed
					div = document.createElement ("div");
					div.style.cursor = "auto";
					div.style.position = "absolute";
					div.style.bottom = "-3px";
					div.style.left = (Math.round(dimensions.width/2)-10) + "px";
					if (div.style.filter != null) {
						div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/kt_map/images/se_bg.png')";
					} else {
						div.style.backgroundImage= "url(/kt_map/images/se_bg.png)";
						div.style.backgroundRepeat = "no-repeat";
					}
					div.style.width = "40px";
					div.style.height = "29px";
					div.style.zIndex = "281";
					div.style.visibility = "hidden";
					div.id = "poiPin";
					img = document.createElement ("img");
					img.src = "/kt_map/images/spacer.gif";
					if (img.style.filter != null) {
						img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/kt_map/images/se.png')";
					} else {
						img.src = "/kt_map/images/se.png";
					}
					img.onclick = function () {this.parentNode.style.visibility="hidden"; $("poibox").style.visibility="visible"};
					div.appendChild (img);
					if ($(mapObject.scoutPin.documentID) != null) {
						$(mapObject.scoutPin.documentID).appendChild (div);
					}
			 	}
			}
		);
	}
};

var ScoutPin = Class.create ();
Object.extend (ScoutPin.prototype, GeoObject);
ScoutPin.prototype = {
	image: "",
	width: 29,
	height: 54,
	offsetX: 0,
	offsetY: 0,
	documentID: "scoutPin",
	circle: false,
	fixed: false,
	fillFields: false,

	initialize: function (pintype) {
		this.documentID = pintype;
		if (mapObject != null) { //Just to make sure, actually there should allways be a mapObject when the pin is created
			if (pintype == 'startPin') {
				this.fixed=true;
				mapObject.startPin = this;
			} else if (pintype == 'endPin') {
				this.fixed=true;
				mapObject.endPin = this;
			} else if(pintype == 'scoutPin') {
				mapObject.scoutPin = this;
			}			
		}
	},

	draw: function () {
	
		if ($(this.documentID) != null) {
			Element.remove (this.documentID);
		}

		this.screenX = parseInt(((this.longitude-mapObject.longitude)/mapObject.unitsPerPixel)+mapObject.width/2)+this.offsetX;
		this.screenY = parseInt(((mapObject.latitude-this.latitude)/mapObject.unitsPerPixel)+mapObject.height/2)+this.offsetY;

		div = document.createElement ("div");
		div.id = this.documentID;
		div.style.position = "absolute";
		div.style.left = this.screenX+"px";
		div.style.top = this.screenY+"px";
		div.style.zIndex = "40";
		//div.style.border = "1px solid black";

		img = document.createElement ("img");
		img.src = "/kt_map/images/spacer.gif";

		if (this.image == "") {
			backgroundImage = "kt_map/images/flagge_start.png";
			div.style.width = this.width+"px";
			div.style.height = this.height+"px";
		} else {
			backgroundImage = this.image;
			div.style.width = this.width+"px";
			div.style.height = this.height+"px";

		}		
		if (img.style.filter != null) {
			img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+backgroundImage+"')";
		} else {
			div.style.backgroundImage= "url("+backgroundImage+")";
			div.style.backgroundRepeat = "no-repeat";
		}

		div.appendChild (img);

		if (this.circle == true) {
			circle = document.createElement ("div");
			circle.style.zIndex = "-1";
			img = document.createElement ("img");
			img.src = "/kt_map/images/spacer.gif";
			circle.style.width = "36px";
			circle.style.height = "36px";
			circle.style.position = "absolute";
			circle.style.top = ((-1)*this.offsetY - 18)+"px";
			circle.style.left = ((-1)*this.offsetX - 18)+"px";
			circle.id = "circleImage";

			if (img.style.filter != null) {
				img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/redcircle.png')";
			} else {
				circle.style.backgroundImage= "url(/images/redcircle.png)";
			}
			circle.appendChild (img);
			div.appendChild (circle);
		}

		$("container").appendChild (div);

		div.onmousedown = function () {
			if ($("circleImage") != null) {
				$("circleImage").style.visibility = "hidden";
			}
		}

		div.onmouseup = function (){
			if ($("circleImage") != null) {
				$("circleImage").style.visibility= "visible";
			}
			if (mapObject.scoutPin != null) {
				hotSpotX = parseInt($(mapObject.scoutPin.documentID).style.left)-mapObject.scoutPin.offsetX;
				hotSpotY = parseInt($(mapObject.scoutPin.documentID).style.top)-mapObject.scoutPin.offsetY;
				if (mapObject.scoutPin.fixed == false) {
					mapObject.scoutPin.longitude = mapObject.longitude+(hotSpotX-mapObject.width/2)*mapObject.unitsPerPixel;
					mapObject.scoutPin.latitude = mapObject.latitude-(hotSpotY-mapObject.height/2)*mapObject.unitsPerPixel;
				}

				if (mapObject.scoutPin.fillFields) {
					var newCoords = mapObject.getWGS84(mapObject.scoutPin.longitude,mapObject.scoutPin.latitude);
					$("iconX").value = newCoords[1];
					$("iconY").value = newCoords[0];
					$("extend").value = mapObject.getExtend();
					$("longitude").value = mapObject.longitude;
					$("latitude").value = mapObject.latitude;
				}

			}

		};
		if (this.fixed == true) {
			Element.makePositioned(this.documentID);
		} else {
			new Draggable(this.documentID, {revert:false, ghosting:false});
		}
	}
};

var Map = Class.create ();
Object.extend (Map.prototype, GeoObject);
Map.prototype = {
	//Properties

	documentID: '',
	width: 0,
	height: 0,
	zoomlevel: 0,
	checkerboard: null,
	showpoi: false,
	unitsPerPixel: 0,
	aerial: false,
	hybrid: false,
	offsetX: 0,
	offsetY: 0,
	moveTargetX:0,
	moveTargetY:0,
	rightCol:0,
	leftCol:0,
	topRow:0,
	bottomRow:0,
	longitudeHome:0,
	latitudeHome:0,
	zoomlevelHome:0,
	extendHome: 0,
	staticpoi: Array (),
	initTime: 0,
	timings:0,
	POIUpdatesInProgress:0,
	openPOI: '',
	xPos: 0,
	yPos:0,
	route: -1,
	poiUpdateTimeout:0,
	POIIframe: 0,
	appFolder: 'kt_map',
	exclusiveEvent: false,
	slider: null,
	dynamicZoomStart: -1,
	dynPOICats: Array (),
	sliderMutex: false,
	drawablePOIs: Array (),
	scoutPin: null,
	startPin: null,
	endPin: null,
	scoutCustomer: null,
	scoutList: Array (),
	poiInfoLatency: false,
	poiInfoLatencyTimeout: null,
	scoutRouteStart: '',
	resizeLatency: false,
	resizeLatencyTimeout: null,
	weather: false,
	trafficjam:false,
	noMove: false,
	subdomains: 4,
	roundRobin: 0,
	ieEntryId: 0,
	noPin: false,


	//Constructor
	initialize: function (_documentID, _width, _height, _longitude, _latitude, _zoomlevel, _timings, _anchorNode) {

//		window.onerror=function(){return true};

		this.timings = _timings;
		now = new Date();
		this.initTime = now.getTime();
		if (this.timings > 0) {
			mapLogSend ("Map.initialize called at "+this.getLifeTime());
		}
		//Create a global reference to this object
		mapObject = this;
		mapObject = this;
		x = Math.floor(_width/tileSize)+2;
		y = Math.floor(_height/tileSize)+2;
		this.zoomlevel = _zoomlevel;
		this.checkerboard = new Checkerboard (x,y);
		this.longitude = parseInt(_longitude);
		this.latitude = parseInt (_latitude);
		this.longitudeHome = parseInt(_longitude);
		this.latitudeHome = parseInt(_latitude);
		this.width = _width;
		this.height = _height;
		this.extend = meterPerPixel[this.zoomlevel-1] * tileSize*5;
		this.unitsPerPixel = this.extend/(tileSize/2);
		this.documentID = _documentID;

		preload = new Image();
		preload.src= this.appFolder+"/images/loading.gif";
		for (x=0; x<this.checkerboard.cols; x++) {
			for (y=0; y<this.checkerboard.rows; y++) {
				tile = new Tile ();
				offsetX = (x-Math.floor(this.checkerboard.cols/2))*this.extend*2-this.extend;
				offsetY = (y-Math.floor(this.checkerboard.rows/2))*this.extend*2+this.extend;
				tile.longitude = this.longitude+offsetX;
				tile.latitude = this.latitude+offsetY;
				this.checkerboard.putTile(x,y,tile);
			}
		}

		container = document.createElement ("div");
		container.id = "container";
		container.style.width = this.width+"px";
		container.style.height = this.height+"px";
		container.style.position = "absolute";
		container.style.overflow = "hidden";
		container.style.backgroundColor = "#dcdccd";
		container.style.cursor = "url(/kt_map/images/hand.cur), auto";
		container.style.cursor = "url(/kt_map/images/hand.cur), wait";
		Element.makePositioned($(_anchorNode));
		$(_anchorNode).appendChild (container);

		// Layer 1: Map Tiles
		// Layer 2: Dynamic POIs
		// Layer 3: Temporary Layer for updating dynamic POI data

		layers = new Array ();
		for (i=1; i<=3; i++) {
			layers[i] = document.createElement ("div");
			layers[i].style.width = this.width+"px";
			layers[i].style.height = this.height+"px";
			layers[i].style.zIndex = i+1;
			layers[i].style.position="absolute";
			layers[i].style.top = "0px";
			layers[i].style.left = "0px";
			layers[i].xPos = 0; //Variables to easily keep track of screen position
			layers[i].yPos = 0; //Variables to easily keep track of screen position
			layers[i].id = "map_layer_"+i;

			$("container").appendChild(layers[i]);
		}
		$("map_layer_3").style.display = "none";

		poiInfo = document.createElement ("div");
		poiInfo.style.position = "absolute";
		poiInfo.style.left = "0px";
		poiInfo.style.top = "0px";

		poiInfo.style.zIndex = 6;
		poiInfo.id = "poiInfo";
		poiInfo.style.display = "none";
		$("container").appendChild (poiInfo);

		this.POIIframe = document.createElement("iframe");
		this.POIIframe.style.height = "0px";
		this.POIIframe.style.width = "0px";

		$("container").appendChild(this.POIIframe);


		this.POIIframe.style.visibility = "hidden";
		this.activateEvents ();

		//Create Navigation Widgets

		this.getWidget("zoomslider15");
		this.getWidget("mapmodebuttons");
		       //this.getWidget("contextmenu");
		this.getWidget("kompass");
		this.getWidget("copyright");
		this.getWidget("scale");

		if (this.timings > 0) {
			mapLogSend("Map.initialize finished at: "+this.getLifeTime());
		}
		this.staticpoi = Array (7383, 7360, 7310, 7352, 7366, 7321, 7369, 7313, 7326, 7322, 7380, 7311);
		return true;
	},

	resize: function (_width, _height) {

		if (mapObject.exclusiveEvent == true) {
			return true;
		}
		if (_width == mapObject.width && _height == mapObject.height) {
			return (false);
		}

		if (mapObject.resizeLatency == true) {
			return (false);
		}
		mapObject.resizeLatency = true;
		mapObject.resizeLatencyTimeout = window.setTimeout (function() {mapObject.resizeLatency = false;}, 500);

		mapObject.exclusiveEvent = true;

		anchorNode = $("container").parentNode;
//		window.onerror = function() {return true};
		Element.remove ($("container"));

		mapObject.width = _width;
		mapObject.height = _height;
		x = Math.floor(_width/tileSize)+2;
		y = Math.floor(_height/tileSize)+2;
		mapObject.checkerboard = new Checkerboard (x,y);
		for (x=0; x<mapObject.checkerboard.cols; x++) {
			for (y=0; y<mapObject.checkerboard.rows; y++) {
				tile = new Tile ();
				offsetX = (x-Math.floor(mapObject.checkerboard.cols/2))*mapObject.extend*2-this.extend;
				offsetY = (y-Math.floor(mapObject.checkerboard.rows/2))*mapObject.extend*2+this.extend;
				tile.longitude = mapObject.longitude+offsetX;
				tile.latitude = mapObject.latitude+offsetY;
				mapObject.checkerboard.putTile(x,y,tile);
			}
		}


		container = document.createElement ("div");
		container.id = "container";
		container.style.width = mapObject.width+"px";
		container.style.height = mapObject.height+"px";
		container.style.position = "absolute";
		container.style.overflow = "hidden";
		container.style.backgroundColor = "#dcdccd";

		//$(anchorNode).appendChild (container);

		anchorNode.appendChild (container);

		layers = new Array ();
		for (i=1; i<=3; i++) {
			layers[i] = document.createElement ("div");
			layers[i].style.width = mapObject.width+"px";
			layers[i].style.height = mapObject.height+"px";
			layers[i].style.zIndex = i+1;
			layers[i].style.position="absolute";
			layers[i].style.top = "0px";
			layers[i].style.left = "0px";
			layers[i].xPos = 0; //Variables to easily keep track of screen position
			layers[i].yPos = 0; //Variables to easily keep track of screen position
			layers[i].id = "map_layer_"+i;

			$("container").appendChild(layers[i]);
		}
		$("map_layer_3").style.display = "none";

		poiInfo = document.createElement ("div");
		poiInfo.style.position = "absolute";
		poiInfo.style.left = "0px";
		poiInfo.style.top = "0px";
		poiInfo.style.zIndex = 6;
		poiInfo.id = "poiInfo";
		poiInfo.style.display = "none";
		$("container").appendChild (poiInfo);

		mapObject.POIIframe = document.createElement("iframe");
		mapObject.POIIframe.style.height = "0px";
		mapObject.POIIframe.style.width = "0px";

		$("container").appendChild(mapObject.POIIframe);

		mapObject.POIIframe.style.visibility = "hidden";
		mapObject.activateEvents ();

		mapObject.getWidget("zoomslider15");
		mapObject.getWidget("mapmodebuttons");
		mapObject.getWidget("kompass");
		mapObject.getWidget("copyright");
		mapObject.exclusiveEvent = false;
	},

	getLifeTime: function () {
		now = new Date();
		return  now.getTime() - this.initTime;
	},

	goHome: function () {
		mapObject.longitude = mapObject.longitudeHome;
		mapObject.latitude = mapObject.latitudeHome;
		if (mapObject.route != (-1)) {
			mapObject.setZoomLevel (mapObject.zoomlevelHome);
		}
		mapObject.draw ();
	},

	killStaticPOI: function () {
		mapObject.staticpoi = Array ();
	},

	draw: function () {
		if (this.timings > 0) {
			mapLogSend ("Map.draw called at "+this.getLifeTime());
		}
		mapLogSend ("Map.draw()");
		window.clearTimeout(mapObject.poiUpdateTimeout);
		if (mapObject.longitudeHome == 0) {
			mapObject.longitudeHome = mapObject.longitude;
		}

		if (mapObject.latitudeHome == 0) {
			mapObject.latitudeHome = mapObject.latitude;
		}

		if (mapObject.zoomlevelHome == 0) {
			mapObject.zoomlevelHome = mapObject.zoomlevel;
		}

		if ($("tempLayer") != null) {
			Element.remove ($("tempLayer"));
		}

		$("map_layer_1").id = "tempLayer";
		$("tempLayer").style.zIndex = 1;

		baselayer = document.createElement ("div");
		baselayer.style.width = mapObject.width+"px";
		baselayer.style.height = mapObject.height+"px";
		baselayer.style.zIndex = 2;
		baselayer.style.position="absolute";
		baselayer.style.top = "0px";
		baselayer.style.left = "0px";
		baselayer.xPos = 0; //Variables to easily keep track of screen position
		baselayer.yPos = 0; //Variables to easily keep track of screen position
		baselayer.id = "map_layer_1";

		$("container").appendChild(baselayer);
		for (x=0; x<mapObject.checkerboard.cols; x++) {
			for (y=0; y<mapObject.checkerboard.rows; y++) {
				tile = $("tile_"+x+"_"+y);
				if (tile != null) {
					tile.id = "tempTile"+x+"_"+y;
				}
			}
		}

		for (i=1; i<3; i++) {
			$("map_layer_"+i).style.top = "0px";
			$("map_layer_"+i).style.left = "0px";
			$("map_layer_"+i).xPos = 0; //Variables to easily keep track of screen position
			$("map_layer_"+i).yPos = 0; //Variables to easily keep track of screen position
		}

		var now = new Date();
		var year = now.getFullYear();

		if (mapObject.aerial == true) {
			$("copyright").style.height="26px";
			Element.update ("copyright", "&copy "+year+" telegate MEDIA AG / Tele Atlas<br>Luftbilder &copy; GeoContent");
		} else {
			$("copyright").style.height="12px";
			Element.update ("copyright", "&copy "+year+" telegate MEDIA AG / Tele Atlas");
		}

		offCenterX = tileSize/2;
		offCenterY = tileSize/2;
		this.leftCol = 0;
		this.rightCol = this.checkerboard.cols-1;
		this.topRow = 0;
		this.bottomRow = this.checkerboard.rows-1;

		if (this.checkerboard.rows % 2 == 0) {
			offsetbottom = 1;
			offsettop = 1;
		} else {
			offsetbottom = 0;
			offsettop = 2;
		}

		if (this.checkerboard.cols % 2 == 0) {
			offsetright = 1;
			offsetleft = 1;
		}
		else {
			offsetright = 0;
			offsetleft = 2;
		}
		
		//Screen Offset is needed when the map size is not a multitude of tileSize
		screenOffsetX = Math.round((this.width % tileSize) / 2);
		screenOffsetY = Math.round((this.height % tileSize) / 2);
		for (x=0; x<Math.ceil(this.checkerboard.cols/2); x++) {
			rightcol = Math.floor(this.checkerboard.cols/2)+x;
			leftcol = Math.floor(this.checkerboard.cols/2)-x-1;
			//Right column
			for (y=0; y<Math.ceil(this.checkerboard.rows/2); y++) {
				bottomrow = Math.floor(this.checkerboard.rows/2)+y;
				toprow = Math.floor(this.checkerboard.rows/2)-y-1;
				//Bottom Row

				tile = this.checkerboard.getTile(rightcol, bottomrow);
				tile.screenX = rightcol*tileSize-tileSize+screenOffsetX;
				tile.screenY = bottomrow*tileSize-tileSize+screenOffsetY;
				tile.longitude = this.longitude+(x*2*this.extend)+offsetright*this.extend-this.extend;
				tile.latitude = this.latitude-(y*2*this.extend)-offsetbottom*this.extend+this.extend;
				tile.extend = this.extend;

				if ($("tile_"+rightcol+"_"+bottomrow) == null) {
					img = document.createElement("img");
				} else {
					img = $("tile_"+rightcol+"_"+bottomrow);
				}
				img.id = "tile_"+rightcol+"_"+bottomrow;
				$("map_layer_1").appendChild(img);
				tile.documentID = "tile_"+rightcol+"_"+bottomrow;
				tile.draw();

				//Top Row
				if (toprow >= 0) {

					tile = this.checkerboard.getTile(rightcol, toprow);
					tile.screenX = rightcol*tileSize-tileSize+screenOffsetX;
					tile.screenY = toprow*tileSize-tileSize+screenOffsetY;
					tile.longitude = this.longitude+(x*2*this.extend)+offsetright*this.extend-this.extend;
					tile.latitude = this.latitude+(y*2*this.extend)+offsettop*this.extend+this.extend;
					tile.extend = this.extend;
	
					if ($("tile_"+rightcol+"_"+toprow) == null) {
						img = document.createElement("img");
					} else {
						img = $("tile_"+rightcol+"_"+toprow);
					}
					img.id = "tile_"+rightcol+"_"+toprow;
					$("map_layer_1").appendChild(img);
					tile.documentID = "tile_"+rightcol+"_"+toprow;
					tile.draw();
				}
			}

			//Left column
			if (leftcol >=0) {
				for (y=0; y<Math.ceil(this.checkerboard.rows/2); y++) {
					bottomrow = Math.floor(this.checkerboard.rows/2)+y;
					toprow = Math.floor(this.checkerboard.rows/2)-y-1;
					//Bottom Row

					tile = this.checkerboard.getTile(leftcol, bottomrow);
					tile.screenX = leftcol*tileSize-tileSize+screenOffsetX;
					tile.screenY = bottomrow*tileSize-tileSize+screenOffsetY;
					tile.longitude = this.longitude-(x*2*this.extend)-offsetleft*this.extend-this.extend;
					tile.latitude = this.latitude-(y*2*this.extend)-offsetbottom*this.extend+this.extend
					tile.extend = this.extend;

					if ($("tile_"+leftcol+"_"+bottomrow) == null) {
						img = document.createElement("img");
					} else {
						img = $("tile_"+leftcol+"_"+bottomrow);
					}
					img.id = "tile_"+leftcol+"_"+bottomrow;
					$("map_layer_1").appendChild(img);
					tile.documentID = "tile_"+leftcol+"_"+bottomrow;
					tile.draw();


					//Right column
					if (toprow >= 0) {

						tile = this.checkerboard.getTile(leftcol, toprow);
						tile.screenX = leftcol*tileSize-tileSize+screenOffsetX;
						tile.screenY = toprow*tileSize-tileSize+screenOffsetY;
						tile.longitude = this.longitude-(x*2*this.extend)-offsetleft*this.extend-this.extend;
						tile.latitude = this.latitude+(y*2*this.extend)+offsettop*this.extend+this.extend;
						tile.extend = this.extend;

						if ($("tile_"+leftcol+"_"+toprow) == null) {
							img = document.createElement("img");
						} else {
							img = $("tile_"+leftcol+"_"+toprow);
						}
						img.id = "tile_"+leftcol+"_"+toprow;
						$("map_layer_1").appendChild(img);
						tile.documentID = "tile_"+leftcol+"_"+toprow;
						tile.draw();
					}
				}
			}
		}
	
		if (this.showpoi == true) {
			this.getPOI ();
		}
		if ($("rightclickmenu") != null) {
			$("rightclickmenu").style.visibility="hidden";
		}

		$("map_layer_1").ondblclick = this.doubleclick;
		$("map_layer_2").ondblclick = this.doubleclick;

		mapObject.dynamicZoomStart = -1;

		if (this.route < 0 && this.noPin == false) {
			scoutPin = new ScoutPin ('startPin');
			scoutPin.width=59;
			scoutPin.height=54;
			scoutPin.offsetX=-3;
			scoutPin.offsetY=-58;
			scoutPin.longitude = this.longitudeHome;
			scoutPin.latitude =  this.latitudeHome;			
			scoutPin.fixed = true;
		}
	
		if (mapObject.scoutPin != null) {
			mapObject.scoutPin.draw();
		}
		if (mapObject.startPin != null) {
			mapObject.startPin.draw();
		}
		if (mapObject.endPin != null) {
			mapObject.endPin.draw();
		}

		var scaletimeout = window.setTimeout (function(){
				if ($("scaleimage") != null) {
					$("scaleimage").style.visibility = "visible";$("scaleimage").src="/kt_map/scale.php?mpp="+meterPerPixel[mapObject.zoomlevel-1];
				}
			}, 200);


		if (this.timings > 0) {
			mapLogSend ("Map.draw finished at "+this.getLifeTime());
		}
	},

	setMapScoutCustomer: function (customer) {
		mapObject.scoutCustomer = customer;
		mapObject.showpoi = true;
	},

	setPOIZoomLevel: function () {
		if (mapObject.zoomlevel > 4) {
			mapObject.setZoomLevel (4);
			mapObject.draw();
		}
	},

	setMapMode: function (aerial, hybrid) {

		if (aerial == false && hybrid == false) {
			if ($("mapbutton_link") != null) {
				$("mapbutton_link").style.backgroundColor = '#ffcc66';
			}
			if ($("aerialbutton_link") != null) {
				$("aerialbutton_link").style.backgroundColor = '#f1f1f1';
			}
			if ($("hybridbutton_link") != null) {
				$("hybridbutton_link").style.backgroundColor = '#f1f1f1';
			}
			if ($("mapmode_klickbar_route") != null) {
				$("mapmode_klickbar_route").value ="map";
			}
			if ($("mapmode_klickbar_map") != null) {
				$("mapmode_klickbar_map").value ="map";
			}
			if ($("mapmode_options") != null) {
				$("mapmode_options").value ="map";
			}
			if ($("mapmode_miniform") != null) {
				$("mapmode_miniform").value ="map";
			}

			//Context Menu changes
			if ($("haken_map") != null) {
				$("haken_map").style.visibility = "visible";
			}
			if ($("haken_aerial") != null) {
				$("haken_aerial").style.visibility = "hidden";
			}
			if ($("haken_hybrid") != null) {
				$("haken_hybrid").style.visibility = "hidden";
			}
		}

		if (aerial == true && hybrid == false) {
			if ($("mapbutton_link") != null) {
				$("mapbutton_link").style.backgroundColor = '#f1f1f1';
			}
			if ($("aerialbutton_link") != null) {
				$("aerialbutton_link").style.backgroundColor = '#ffcc66';
			}
			if ($("hybridbutton_link") != null) {
				$("hybridbutton_link").style.backgroundColor = '#f1f1f1';
			}
			if ($("mapmode_klickbar_route") != null) {
				$("mapmode_klickbar_route").value ="aerial";
			}
			if ($("mapmode_klickbar_map") != null) {
				$("mapmode_klickbar_map").value ="aerial";
			}
			if ($("mapmode_options") != null) {
				$("mapmode_options").value ="aerial";
			}
			if ($("mapmode_miniform") != null) {
				$("mapmode_miniform").value ="aerial";
			}

			//Context Menu changes
			if ($("haken_map") != null) {
				$("haken_map").style.visibility = "hidden";
			}
			if ($("haken_aerial") != null) {
				$("haken_aerial").style.visibility = "visible";
			}
			if ($("haken_hybrid") != null) {
				$("haken_hybrid").style.visibility = "hidden";
			}
		}

		if (aerial == true && hybrid == true) {
			if ($("mapbutton_link") != null) {
				$("mapbutton_link").style.backgroundColor = '#f1f1f1';
			}
			if ($("aerialbutton_link") != null) {
				$("aerialbutton_link").style.backgroundColor = '#f1f1f1';
			}
			if ($("hybridbutton_link") != null) {
				$("hybridbutton_link").style.backgroundColor = '#ffcc66';
			}
			if ($("mapmode_klickbar_route") != null) {
				$("mapmode_klickbar_route").value ="hybrid";
			}
			if ($("mapmode_klickbar_map") != null) {
				$("mapmode_klickbar_map").value ="hybrid";
			}
			if ($("mapmode_options") != null) {
				$("mapmode_options").value ="hybrid";
			}
			if ($("mapmode_miniform") != null) {
				$("mapmode_miniform").value ="hybrid";
			}

			//Context Menu changes
			if ($("haken_map") != null) {
				$("haken_map").style.visibility = "hidden";
			}
			if ($("haken_aerial") != null) {
				$("haken_aerial").style.visibility = "hidden";
			}
			if ($("haken_hybrid") != null) {
				$("haken_hybrid").style.visibility = "visible";
			}

		}

		mapObject.aerial = aerial;
		mapObject.hybrid = hybrid;
		mapObject.draw ();
	},

	moveTo: function (longitude, latitude) {
		mapObject.longitude = longitude;
		mapObject.latitude = latitude;
		mapObject.draw();
	},

	switchWeather: function () {
		if (mapObject.weather == false) {
			mapObject.weather = true;
			if ($('weather_haken') != null) {
				$('weather_haken').style.visibility = "visible";
			}

		} else {
			mapObject.weather = false;
			if ($('weather_haken') != null) {
				$('weather_haken').style.visibility = "hidden";
			}
		}
		mapObject.draw();
	},

	switchTrafficjam: function () {
		if (mapObject.trafficjam == false) {
			mapObject.trafficjam = true;
			if ($('trafficjam_haken') != null) {
				$('trafficjam_haken').style.visibility = "visible";
			}

		} else {
			mapObject.trafficjam = false;
			if ($('trafficjam_haken') != null) {
				$('trafficjam_haken').style.visibility = "hidden";
			}
		}
		mapObject.draw();
	},


	getPOI: function () {
		if (mapObject.zoomlevel > 4 && mapObject.scoutCustomer == null && mapObject.scoutList.length == 0 && mapObject.ieEntryId == 0) {
		$("map_layer_2").style.display = "none";
			return true;
		}

		if (mapObject.showpoi == false && mapObject.ieEntryId == 0) {
			$("map_layer_2").style.visibility = "hidden";
			return true;
		}

		$("map_layer_3").style.visibility = "hidden";
		$("map_layer_3").style.display = "block";

		$("map_layer_3").style.top = "0px";
		$("map_layer_3").style.left = "0px";
		$("map_layer_3").xPos = 0;
		$("map_layer_3").yPos = 0;

		if (mapObject.showpoi == true || mapObject.ieEntryId != 0) {//Get POIs from Server

			pars = "centerX="+this.longitude+"&centerY="+this.latitude+"&upp="+this.unitsPerPixel+"&width="+this.width+"&height="+this.height+"&random="+Math.random();
			mapObject.POIUpdatesInProgress++;

			if (mapObject.scoutList.length > 0) {
				extendHeight = (mapObject.height/2)*mapObject.unitsPerPixel;
				extendWidth = (mapObject.width/2)*mapObject.unitsPerPixel;
				mapTop = mapObject.latitude + extendHeight;
				mapBottom = mapObject.latitude - extendHeight;
				mapLeft = mapObject.longitude - extendWidth;
				mapRight = mapObject.longitude + extendWidth;
				html = "";
				for (i=0; i<mapObject.scoutList.length; i++) {
					scout = mapObject.scoutList[i];
					if (scout.longitude > mapLeft && scout.longitude < mapRight && scout.latitude > mapBottom & scout.latitude < mapTop) {
						fromTop = Math.round((mapTop-scout.latitude)/mapObject.unitsPerPixel)-4;
						fromLeft = Math.round((scout.longitude - mapLeft)/mapObject.unitsPerPixel)-4;
						html += ("<img onclick=\"mapObject.showPOIInfo('scout_"+scout.id+"');\" id=\"scout_"+scout.id+"\" src=\"/images/0"+(i+1)+".png\" style=\"position:absolute;left:"+fromLeft+"px;top:"+fromTop+"px\">");
					}
				}
				mapObject.fillPOI (html);
				return (true);
			}

			if (mapObject.scoutCustomer != null) {
				pars = "customer="+mapObject.scoutCustomer+"&centerX="+this.longitude+"&centerY="+this.latitude+"&upp="+this.unitsPerPixel+"&width="+this.width+"&height="+this.height+"&random="+Math.random();
				mapObject.POIUpdatesInProgress++;
				mapObject.POIIframe.src = mapObject.appFolder+"/scoutupdater.php?"+pars;
				return true;
			}


			if (mapObject.ieEntryId != 0) {
				pars = "entry_id="+mapObject.ieEntryId+"&centerX="+this.longitude+"&centerY="+this.latitude+"&upp="+this.unitsPerPixel+"&width="+this.width+"&height="+this.height+"&random="+Math.random();
				mapObject.POIUpdatesInProgress++;
				mapObject.POIIframe.src = "/"+mapObject.appFolder+"/ieentryupdater.php?"+pars;
				return true;
			}

			if (mapObject.openPOI != '') {
				pars+="&openPOI="+mapObject.openPOI;
			}

			if (mapObject.dynPOICats.length > 0) {
				braids = "&braids=";
				for (i=0; i<mapObject.dynPOICats.length;i++) {
					braids += mapObject.dynPOICats[i];
				}
				mapObject.POIIframe.src = mapObject.appFolder+"/poi_se_updater.php?"+pars+braids;
				return true;
			}
			mapObject.POIIframe.src = mapObject.appFolder+"/poiupdater.php?"+pars;
		}
		if (mapObject.drawablePOIs.length > 0) {
			extendHeight = (mapObject.height/2)*mapObject.unitsPerPixel;
			extendWidth = (mapObject.widtht/2)*mapObject.unitsPerPixel;
			mapTop = mapObject.latitude + extendHeight;
			mapBottom = mapObject.latitude - extendHeight;
			mapLeft = mapObject.longitude - extendWidth;
			mapRight = mapObject.longitude + extendWidth;
			for (i=0; i<mapObject.drawablePOIs.length; i++) {
				poi = mapObject.drawablePOIs[i];
				if (poi.longitude > mapLeft && poi.longitude < mapRight && poi.latitude > mapBottom & poi.latitude < mapTop) {
					mapLogSend ("POI "+i+" found to be on map!");
				}
			}
		}
	},

	fillPOI: function (html) {

		Element.update ("map_layer_3", html);

		$("map_layer_3").style.left = $("map_layer_3").xPos+"px";
		$("map_layer_3").style.top = $("map_layer_3").yPos+"px";
		$("map_layer_3").style.visibility = "visible";
		$("map_layer_2").style.display = "none";

		$("map_layer_2").id = "old_poi_layer";
		$("map_layer_3").id = "map_layer_2";
		$("old_poi_layer").id = "map_layer_3";

		Element.update ($("map_layer_3"), ""); //Clear Layer
		$("map_layer_2").style.zIndex = 3;
		$("map_layer_3").style.zIndex = 4;
		mapObject.POIUpdatesInProgress = 0;
	},

	getWidget: function (id) {

		if (this.timings > 0) {
		mapLogSend("Map.getWidget called with id: "+id+" at "+this.getLifeTime());
		}
		if (document.getElementById(id) != null) {//Destroy existing widget
			Element.remove($(id));
		}
		widget = document.createElement("div");
		widget.id = id;
		widget.oncontextmenu = function () {return(false)};
		widget.style.zIndex = 50;
		widget.style.cursor = "auto";
		widget.style.cursor = "auto";
		$("container").appendChild(widget);
		//Math.random is used on the next line to keep internet explorer from caching the Ajax Request
		url = mapObject.appFolder+"/widgets/"+id+".php";
		new Ajax.Updater(id, url, {evalScripts: true, method: 'get', parameters: 'r='+Math.random(), onFailure:function(){
			mapLogSend("Failed loading widget: "+id)
		}});

		if (id == 'kompass' && (mapObject.width < 300 || mapObject.height < 300)) {
			$(id).style.visibility="hidden";
		}
		if (id == 'mapmodebuttons' && (mapObject.width < 280 || mapObject.height < 280)) {
			$(id).style.visibility="hidden";
		}

		if (this.timings >= 0) {
			mapLogSend("Map.getWidget finished with id: "+id+" at "+this.getLifeTime());
		}
	},

	zoomIn: function (degree) {
		if (this.timings > 0) {
			mapLogSend("Map.zoomIn called with degree: "+degree+" at "+this.getLifeTime());
		}

		if (this.zoomlevel > 1){
			/*
			if ($("scaleimage") != null) {
				$("scaleimage").src = "/kt_map/images/spacer.gif";
				$("scaleimage").style.visibility = "hidden";
			}
			$("map_layer_2").style.visibility = "hidden";
			if (mapObject.scoutPin != null) {
				$(mapObject.scoutPin.documentID).style.visibility = "hidden";
			}
			redraw = false;
			newlevel = this.zoomlevel-1;

			zoomfactor = meterPerPixel[this.zoomlevel-1]/meterPerPixel[newlevel-1];
			mapPosX = parseInt($("map_layer_1").style.left);
			mapPosY = parseInt($("map_layer_1").style.top);
			mapCenterX = Math.round(this.width/2);
			mapCenterY = Math.round(this.height/2);
			for (x=0; x<this.checkerboard.cols; x++) {
				for (y=0; y<this.checkerboard.rows; y++) {
					tile = this.checkerboard.getTile(x, y);
					tileCenterX = parseInt ($(tile.documentID).style.left)+ mapPosX;
					tileCenterY = parseInt ($(tile.documentID).style.top) + mapPosY;
					offsetFromCenterX = tileCenterX-mapCenterX+tileSize/2;
					offsetFromCenterY = tileCenterY-mapCenterY+tileSize/2;
					moveByX = (zoomfactor-1)*(offsetFromCenterX-tileSize/2);
					moveByY = (zoomfactor-1)*(offsetFromCenterY-tileSize/2);

					new Effect.Parallel(
						[new Effect.Scale(tile.documentID, 100*zoomfactor),
						new Effect.MoveBy(tile.documentID, moveByY, moveByX)

						],
						{
							duration: 0.5,
							afterFinish: function(effect)
        						{
        							if (redraw == false) {
        								redraw = true;
        								mapObject.setZoomLevel(newlevel);
        								window.clearTimeout(mapObject.poiUpdateTimeout);
        								//mapObject.noMove = true;
        								//mapObject.poiUpdateTimeout = window.setTimeout(function(){mapObject.draw();mapObject.noMove = false;}, 1000);
										mapObject.draw();
									}
        						}
						}
					)
				}
			}
			*/
			newlevel = this.zoomlevel-1;
			mapObject.setZoomLevel(newlevel);
        	window.clearTimeout(mapObject.poiUpdateTimeout);
        	mapObject.draw();

		}
		if (this.timings > 0) {
			mapLogSend("Map.zoomIn finished with degree: "+degree+" at "+this.getLifeTime());
		}
	},

	zoomOut: function (degree) {
		if (this.timings > 0) {
			mapLogSend("Map.zoomOut called with degree: "+degree+" at "+this.getLifeTime());
		}
		if (this.zoomlevel < meterPerPixel.length) {
			/*
			if ($("scaleimage") != null) {
				$("scaleimage").src = "/kt_map/images/spacer.gif";
				$("scaleimage").style.visibility = "hidden";
			}
			$("map_layer_2").style.visibility = "hidden";
			if (mapObject.scoutPin != null) {
				$(mapObject.scoutPin.documentID).style.visibility = "hidden";
			}
			redraw = false;
			newlevel = this.zoomlevel+1;
			zoomfactor = meterPerPixel[this.zoomlevel-1]/meterPerPixel[newlevel-1];
			//Do a few calculations to avoid them slowing down the loop
				checkerboard = this.checkerboard;
			mapPosX = parseInt($("map_layer_1").style.left);
			mapPosY = parseInt($("map_layer_1").style.top);
			mapCenterX = Math.floor(this.width/2);
			mapCenterY = Math.floor(this.height/2);
			for (x=0; x<this.checkerboard.cols; x++) {
				for (y=0; y<checkerboard.rows; y++) {
					tile = checkerboard.getTile(x, y);
					tileCenterX = parseInt ($(tile.documentID).style.left)+ mapPosX;
					tileCenterY = parseInt ($(tile.documentID).style.top) + mapPosY;
					offsetFromCenterX = tileCenterX-mapCenterX+tileSize/2;
					offsetFromCenterY = tileCenterY-mapCenterY+tileSize/2;
					tile.moveByX = (zoomfactor-1)*(offsetFromCenterX-tileSize/2);
					tile.moveByY = (zoomfactor-1)*(offsetFromCenterY-tileSize/2);

					checkerboard.putTile (x,y,tile);
				}
			}
			for (x=0; x<this.checkerboard.cols; x++) {
				for (y=0; y<this.checkerboard.rows; y++) {
					tile = checkerboard.getTile(x, y);

					new Effect.Parallel(
						[
						new Effect.MoveBy(tile.documentID, tile.moveByY, tile.moveByX, {sync:true}),
						new Effect.Scale(tile.documentID, 100*zoomfactor, {sync:true})
						],
						{
							duration: 0.5,
							afterFinish: function(effect)
        						{
        								if (redraw == false) {
        								redraw = true;
        								mapObject.setZoomLevel(newlevel);

										mapObject.draw();
									}
        						}
						}
					)
				}
			}*/
			newlevel = this.zoomlevel+1;
			mapObject.setZoomLevel(newlevel);
			mapObject.draw();

		}
		if (this.timings > 0) {
			mapLogSend("Map.zoomOut finished with degree: "+degree+" at "+this.getLifeTime());
		}
	},

	setExtend: function (extend) {
		targetUnitsPerPixel = 2*extend/(Math.min (mapObject.width, mapObject.height));
		i=0;
		while (i<14 && meterPerPixel[i] < targetUnitsPerPixel/10) {
			i++;
		}
		mapObject.setZoomLevel (i+1);
	},

	getExtend: function () {
		minExtend = Math.min (mapObject.width, mapObject.height)/2;
		return minExtend * mapObject.unitsPerPixel;
	},

	setZoomLevel: function (level) {
		if (this.timings > 0) {
			mapLogSend("Map.setZoomLevel called at "+this.getLifeTime());
		}
		this.zoomlevel = level;
		pixelcorrection = 0;
		if (level > 6) {
			pixelcorrection += 0.005;
		}
		this.extend = meterPerPixel[this.zoomlevel-1] * tileSize*5;
		this.unitsPerPixel = this.extend/(tileSize/2);

		if (mapObject.slider != null) {
			mapObject.slider = new Control.Slider('handle1','track1',{axis:'vertical', sliderValue:(level-1)/14});
			//mapObject.slider.setValue ((level-1)/11+pixelcorrection);
		}
		for (x=0; x<this.checkerboard.cols; x++) {
			for (y=0; y<this.checkerboard.rows; y++) {
				tile = new Tile ();
				offsetX = (x-Math.floor(this.checkerboard.cols/2))*this.extend*2;//-this.extend;
				offsetY = (y-Math.floor(this.checkerboard.rows/2))*this.extend*2;//+this.extend;
				tile.longitude = this.longitude+offsetX;
				tile.latitude = this.latitude+offsetY;
				this.checkerboard.putTile(x,y,tile);
			}
		}
		mapObject.hidePOIInfo ();
		if (this.timings > 0) {
			mapLogSend("Map.setZoomLevel finished at "+this.getLifeTime());
		}
	},

	getGeoCenter: function () {
		if (this.timings > 0) {
			mapLogSend("Map.getGeoCenter called at "+this.getLifeTime());
		}
		geoCenter = new Array (this.longitude, this.latitude);
		if (this.timings > 0) {
			mapLogSend("Map.getGeoCenter finished at "+this.getLifeTime());
		}
		return geoCenter;
	},

	checkTiles: function () {
		return(false);
	},

	move: function (pixelX, pixelY) {

		if (this.timings > 0) {
			mapLogSend("Map.move called at "+this.getLifeTime());
		}


		if (mapObject.exclusiveEvent == true) {
			return (false);
		}

		if ($("tempLayer") != null) {
			Element.remove ($("tempLayer"));
		}

		mapObject.exclusiveEvent = true;

		mapObject.deactivateEvents ();

		mapObject.moveTargetX = Math.round(pixelX);
		mapObject.moveTargetY = Math.round(pixelY);
		effects = [
			new Effect.MoveBy ($("map_layer_1"), Math.round(pixelY), Math.round(pixelX))
			, new Effect.MoveBy ($("map_layer_2"), Math.round(pixelY), Math.round(pixelX))
			, new Effect.MoveBy ($("map_layer_3"), Math.round(pixelY), Math.round(pixelX))
			, new Effect.MoveBy ($("poiInfo"), Math.round(pixelY), Math.round(pixelX))

			];
		if (mapObject.scoutPin != null) {
			effects.push (new Effect.MoveBy ($(mapObject.scoutPin.documentID), Math.round(pixelY), Math.round(pixelX)));
		}
		if (mapObject.startPin != null) {
			effects.push (new Effect.MoveBy ($(mapObject.startPin.documentID), Math.round(pixelY), Math.round(pixelX)));
		}		
		if (mapObject.endPin != null) {
			effects.push (new Effect.MoveBy ($(mapObject.endPin.documentID), Math.round(pixelY), Math.round(pixelX)));
		}
		new Effect.Parallel (effects,
			{duration:0.5, afterFinish: function(effect) {

					mapObject.longitude -= mapObject.unitsPerPixel * Math.round(pixelX);
					mapObject.latitude += mapObject.unitsPerPixel * Math.round(pixelY);
					offCenterX += Math.round(pixelX);
					offCenterY += Math.round(pixelY);

					$("map_layer_1").xPos += pixelX;
					$("map_layer_1").yPos += pixelY;
					$("map_layer_2").xPos += pixelX;
					$("map_layer_2").yPos += pixelY;
					$("map_layer_3").xPos += pixelX;
					$("map_layer_3").yPos += pixelY;

					mapObject.getPOI();

					while (offCenterX > tileSize) {
						mapObject.shiftRight();
						offCenterX -= tileSize;
					}

					while (offCenterX < 0) {
						mapObject.shiftLeft();
						offCenterX += tileSize;
					}

					while (offCenterY > tileSize) {
						mapObject.shiftUp();
						offCenterY -= tileSize;
					}

					while (offCenterY < 0) {
						mapObject.shiftDown();
						offCenterY += tileSize;
					}

					mapObject.activateEvents ();
					mapObject.exclusiveEvent = false;
			}});

		if (this.timings > 0) {
			mapLogSend("Map.move finished at "+this.getLifeTime());
		}

	},

	activateEvents: function () {

		$("container").onmousedown = this.mousedown;
		$("container").onmouseup = this.mouseup;
		$("container").oncontextmenu = function() {return(false)};
		$("map_layer_1").onlick = this.doubleclick;
		$("map_layer_2").ondblclick = this.doubleclick;
		$("container").onscroll = function () {
			return false;
		}

		if(window.addEventListener&&navigator.product&&navigator.product=="Gecko") //Browser switch for setting the right event for the mousewheel
         		$("container").addEventListener('DOMMouseScroll', this.scroll, false)
      		else
         		$("container").onmousewheel = this.scroll;
	},

	doubleclick: function (e) {
		if (!e) var e = window.event;
		if (mapObject.poiInfoLatency == true) {
			return (false);
		}
		element = Event.element(e).id;
		mapLogSend("Element: "+Event.element(e).id);
		clickXPos = Event.pointerX(e);
		clickYPos = Event.pointerY(e);
		containerPosition = Position.cumulativeOffset($("container"));
		mapXPosFromCenter = clickXPos-containerPosition[0]-mapObject.width/2;
		mapYPosFromCenter = clickYPos-containerPosition[1]-mapObject.height/2;
		mapObject.longitude = mapObject.longitude+mapXPosFromCenter*mapObject.unitsPerPixel;
		mapObject.latitude = mapObject.latitude-mapYPosFromCenter*mapObject.unitsPerPixel;
		mapObject.zoomIn(1);

		//mapObject.draw();
		return (false);
	},

	scroll: function (e) {
		return true;
		if (!e) var e = window.event;
			if (e.wheelDelta)
		    	wheelDelta=e.wheelDelta;
		  	else if (e.detail)
		    	wheelDelta=e.detail*-1;
			if (wheelDelta > 0) {
				mapObject.zoomIn();
			}
			else {
				mapObject.zoomOut();
			}
			if (e.cancelable) // may as well check.
				e.preventDefault();
			return(false);
	},

	deactivateEvents: function () {
		$("container").onmousedown = function() {return(false)};
		$("container").onmouseup = function() {return(false)};
		$("container").oncontextmenu = function() {return(false)};
		$("container").onscroll = function () {
			return false;
		}
	},

	mousedown: function (e) {
		if (!e) var e = window.event;


		if (Event.isLeftClick(e)) {
			container.style.cursor = "url(/kt_map/images/hand_closed.cur), auto";
			container.style.cursor = "url(/kt_map/images/hand_closed.cur), wait";
			//if (mapObject.clickOnPOI(e)) {
			//} else {
				t = window.setTimeout(function(){mapObject.hideContextMenu()}, 200);
				clickposX = e.screenX;
				clickposY = e.screenY;
				buttonstate = true;
				document.onmousemove = mapObject.mousemove;
			//}
		} else {
			clickposX = Event.pointerX(e);
			clickposY = Event.pointerY(e);
			containerOffset = Position.cumulativeOffset($("container"));
			//$("contextmenu").style.left = (clickposX-containerOffset[0])+"px";
			//$("contextmenu").style.top = (clickposY-containerOffset[1])+"px";
			mapLogSend(containerOffset[1]);
			//new Effect.Appear("contextmenu2", {to:0.8});

		}

		element = Event.element(e);
		return(false);
	},

	hideContextMenu: function () {
		/*
		$("contextmenu").style.left = "-50px";
		$("contextmenu").style.top =  "-50px";
		$("contextmenu2").style.display="none";
		*/
	},

	mouseup: function (e) {
		if (!e) var e = window.event;
		buttonstate = false;
		container.style.cursor = "url(/kt_map/images/hand.cur), auto";
		container.style.cursor = "url(/kt_map/images/hand.cur), wait";
		element = Event.element(e);
		document.onmousemove = function (){return(false)};

		mapObject.longitude += mapObject.offsetX*mapObject.unitsPerPixel;
		mapObject.latitude -= mapObject.offsetY*mapObject.unitsPerPixel;
		if (Math.abs(mapObject.offsetX) > 5 || Math.abs(mapObject.offsetY) > 5) { //Map has been moved
			if (mapObject.showpoi == true) {
				mapObject.getPOI();
			}
		}
		mapObject.offsetX = 0;
		mapObject.offsetY = 0;
		return(false);
	},

	mousemove: function (e) {
		if (!e) var e = window.event;
		if (!buttonstate)
			return (false);
		document.onmouseup = function () {return false};

		if (mapObject.noMove == true) {
			return false;
		}

		if (Event.element(e).name == 'reiter') {
			return false;
		}

		if ($("tempLayer") != null) {
			Element.remove ($("tempLayer"));
		}

		mapObject.hidePOIInfo ();
		positionX = e.screenX;
		positionY = e.screenY;
		mouseOffsetX = Math.round(positionX-clickposX);
		mouseOffsetY = Math.round(positionY-clickposY);
		checkerboard = mapObject.checkerboard;
		cols = checkerboard.cols;
		rows = checkerboard.rows;

		for (i=1; i<=3; i++) {
			if ($("map_layer_"+i) != null) {
				$("map_layer_"+i).xPos+= mouseOffsetX;
				$("map_layer_"+i).yPos+= mouseOffsetY;
				$("map_layer_"+i).style.left = $("map_layer_"+i).xPos + "px";
				$("map_layer_"+i).style.top = $("map_layer_"+i).yPos + "px";
			}
		}
		$("poiInfo").style.left = parseInt ($("poiInfo").style.left)+mouseOffsetX+"px";
		$("poiInfo").style.top = parseInt ($("poiInfo").style.top)+mouseOffsetY+"px";

		mapObject.offsetX -= mouseOffsetX;
		mapObject.offsetY -= mouseOffsetY;

		offCenterX += mouseOffsetX;
		offCenterY += mouseOffsetY;

		if (offCenterX > tileSize || offCenterY > tileSize || offCenterX < 0 || offCenterY < 0) {
			while (offCenterX > tileSize) {
				mapObject.shiftRight();
				offCenterX -= tileSize;
			}

			while (offCenterX < 0) {
				mapObject.shiftLeft();
				offCenterX += tileSize;
			}

			while (offCenterY > tileSize) {
				mapObject.shiftUp();
				offCenterY -= tileSize;
			}

			while (offCenterY < 0) {
				mapObject.shiftDown();
				offCenterY += tileSize;
			}
		}
		if (mapObject.scoutPin != null) {
			pin = $(mapObject.scoutPin.documentID);
			pin.style.left = (parseInt(pin.style.left)+mouseOffsetX)+"px";
			pin.style.top = (parseInt(pin.style.top)+mouseOffsetY)+"px";
		}
		if (mapObject.startPin != null) {
			pin = $(mapObject.startPin.documentID);
			pin.style.left = (parseInt(pin.style.left)+mouseOffsetX)+"px";
			pin.style.top = (parseInt(pin.style.top)+mouseOffsetY)+"px";
		}
		if (mapObject.endPin != null) {
			pin = $(mapObject.endPin.documentID);
			pin.style.left = (parseInt(pin.style.left)+mouseOffsetX)+"px";
			pin.style.top = (parseInt(pin.style.top)+mouseOffsetY)+"px";
		}

		clickposX = positionX;
		clickposY = positionY;
		document.onmouseup = mapObject.mouseup;

		return(false);
	},

	inGermany: function () {
		xExtend = (mapObject.width * mapObject.unitsPerPixel) / 2;
		yExtend = (mapObject.height * mapObject.unitsPerPixel) / 2;

		if (mapObject.longitude - xExtend > 56241821)
			return false;
		if (mapObject.longitude + xExtend < 49907506)
			return false;
		if (mapObject.latitude - yExtend > 61086046)
			return false;
		if (mapObject.latitude + yExtend < 50941052)
			return false;

		return true;
	},

	showPOIInfo: function (elementID, layer) {
		if (layer == null) {
			var layer = 2;
		}

		if (mapObject.POIUpdatesInProgress > 0) {
			return (false);
		}
 		if (mapObject.poiInfoLatency == true) {
			return (false);
		}

		mapObject.poiInfoLatency = true;
		mapObject.poiInfoLatencyTimeout = window.setTimeout(function(){mapObject.poiInfoLatency = false}, 250);

		pars = "id="+elementID;
		if (elementID.substr(0,5) == "scout") {
			pars += "&routeParams="+mapObject.scoutRouteStart;
		}

		$("poiInfo").style.display = "block"
		$("poiInfo").style.visibility = "hidden"; //The switching of the visibility is done to avoid jumping
		updater = new Ajax.Updater ("poiInfo",
			"/kt_map/poiinfo.php",
			{
				method: 'get',
				parameters: pars,
				onComplete: function () {a=window.setTimout(mapObject.positionPOIInfo(elementID), 10)},
				onFailure: function () {alert('Fehler beim Ajax Update!')},
				evalScripts: true
			});
		mapObject.openPOI = elementID;
	},

	showMultiPOIInfo: function (elementIDs) {
		if (layer == null) {
			var layer = 2;
		}

		if (mapObject.POIUpdatesInProgress > 0) {
			return (false);
		}

		mapObject.poiInfoLatency = true;
		mapObject.poiInfoLatencyTimeout = window.setTimeout(function(){mapObject.poiInfoLatency = false}, 250);

		pars = "id="+elementIDs;
		if (mapObject.dynPOICats.length > 0) {
			pars += "&braids="
			for (i=0; i<mapObject.dynPOICats.length;i++) {
				pars += mapObject.dynPOICats[i];
				if (i<mapObject.dynPOICats.length-1)
					pars += ";";
			}
		}
		$("poiInfo").style.display = "block"
		$("poiInfo").style.visibility = "hidden"; //The switching of the visibility is done to avoid jumping
		updater = new Ajax.Updater ("poiInfo",
			"/kt_map/multipoiinfo.php",
			{
				method: 'get',
				parameters: pars,
				onComplete: function () {a=window.setTimout(mapObject.positionPOIInfo(elementIDs), 10)},
				onFailure: function () {alert('Fehler beim Ajax Update!')},
				evalScripts: true
			});
		mapObject.openPOI = elementIDs;
	},

	positionPOIInfo: function (elementID) {

		moveX = 0;
		moveY = 0;

		pinTop = parseInt ($(elementID).parentNode.style.top);
		pinLeft = parseInt ($(elementID).parentNode.style.left);

		//$(elementID).parentNode.style.visibility = "hidden";
		//$(elementID).parentNode.style.backgroundImage = "";
		Element.removeClassName($(elementID).parentNode, "iesh");
		$(elementID).parentNode.style.filter="";

		layerHeight = Element.getHeight("poiInfo");
		dimensions = Element.getDimensions("poiInfo");
		console.log("LAYERHEIGHT: %s", layerHeight);
		console.log("PINTOP: %s", pinTop);
		layerWidth = dimensions.width;
		if (elementID.substr(0,4) == "mvie") { //Multi Entry
			console.log("MVIE");
			$("poiInfo").style.left = (pinLeft+156-layerWidth)+"px";
			$("poiInfo").style.top = (pinTop+26-layerHeight)+"px";

			if (pinLeft-300 < 95) {
				moveX = 95 - (pinLeft-300);
			}

			if (pinLeft + 85 > mapObject.width) {
				moveX = mapObject.width - (pinLeft + 85);
			}

			if (pinTop+2-layerHeight < 60) {
				moveY = 60 - (pinTop+2-layerHeight);
			}

			if (moveX != 0 || moveY != 0) {
				mapObject.move (moveX, moveY);
			}
			$("poiInfo").style.display = "block";
			$("poiInfo").style.visibility = "visible";
			return (true);
		}

		if (elementID.substr(0,2) == "ie") {
			console.log("IE");
			$("poiInfo").style.left = (pinLeft-312)+"px";
			$("poiInfo").style.top = (pinTop+27-layerHeight)+"px";

			if (pinLeft-300 < 85) {
				moveX = 85 - (pinLeft-300);
			}

			if (pinLeft + 85 > mapObject.width) {
				moveX = mapObject.width - (pinLeft + 85);
			}

			if (pinTop+2-layerHeight < 60) {
				moveY = 75 - (pinTop+2-layerHeight);
			}

			if (moveX != 0 || moveY != 0) {
				mapObject.move (moveX, moveY);
			}
			$("poiInfo").style.display = "block";
			$("poiInfo").style.visibility = "visible";
			return (true);
		}

		if (elementID.substr(0,5) == "scout") {
			console.log("SCOUT");
			pinTop = parseInt ($(elementID).style.top);
			pinLeft = parseInt ($(elementID).style.left);
			$("poiInfo").style.position = "absolute";
			$("poiInfo").style.left = (pinLeft-layerWidth/2+4)+"px";
			$("poiInfo").style.top = (pinTop-layerHeight)+"px";

			if (pinLeft-200 < 55) {
				moveX = 55 - (pinLeft-200);
			}

			if (pinLeft + 85 > mapObject.width) {
				moveX = mapObject.width - (pinLeft + 85);
			}

			if (pinTop+2-layerHeight < 60) {
				moveY = 60 - (pinTop+2-layerHeight);
			}

			if (moveX != 0 || moveY != 0) {
				mapObject.move (moveX, moveY);
			}
			$("poiInfo").style.display = "block";
			$("poiInfo").style.visibility = "visible";
			return (true);
		}
		console.log("ELSE");
		$("poiInfo").style.position = "absolute";
		$("poiInfo").style.left = (pinLeft+153-layerWidth)+"px";
		$("poiInfo").style.top = (pinTop+2-layerHeight)+"px";

		if (pinLeft-200 < 75) {
			moveX = 75 - (pinLeft-200);
		}

		if (pinLeft + 85 > mapObject.width) {
			moveX = mapObject.width - (pinLeft + 85);
		}

		if (pinTop+2-layerHeight < 60) {
			moveY = 60 - (pinTop+2-layerHeight);
		}

		if (moveX != 0 || moveY != 0) {
			mapObject.move (moveX, moveY);
		}

		$("poiInfo").style.display = "block";
		$("poiInfo").style.visibility = "visible";
		return (true);
	},

	hidePOIInfo: function () {
			$("poiInfo").style.display = "none"
			if ($(mapObject.openPOI) != null && mapObject.openPOI != "") {
				mapLogSend("Showing "+mapObject.openPOI);
				//$(mapObject.openPOI).style.visibility = "visible";
				Element.addClassName($(mapObject.openPOI).parentNode, "iesh");
				$(mapObject.openPOI).parentNode.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/kt_map/images/ie_bg.png',sizingMethod='scale')";
			}
			if ($("rightclickmenu") != null) {
				$("rightclickmenu").style.visibility="hidden";
			}

			mapObject.openPOI = "";
	},

	shiftRight: function () {
		if (this.timings > 0) {
			mapLogSend("Map.shiftRight called at "+this.getLifeTime());
		}
		if (mapObject.rightCol < 0) {
			mapObject.rightCol = mapObject.checkerboard.cols-1;
		}
		mapObject.leftCol = mapObject.rightCol;

		for (y=0; y<mapObject.checkerboard.rows; y++) {
			tile = mapObject.checkerboard.getTile(mapObject.rightCol,y);
			tile.screenX -= tileSize*(this.checkerboard.cols);
			tile.longitude -= mapObject.extend*2*(this.checkerboard.cols);
			tile.draw ();
		}
		mapObject.rightCol--;
		if (this.timings > 0) {
			mapLogSend("Map.shiftRight finished at "+this.getLifeTime());
		}
	},

	shiftLeft: function () {
		if (this.timings > 0) {
			mapLogSend("Map.shiftLeft called at "+this.getLifeTime());
		}
		if (mapObject.leftCol > mapObject.checkerboard.cols-1) {
			mapObject.leftCol = 0;
		}
		mapObject.rightCol = mapObject.leftCol;

		for (y=0; y<mapObject.checkerboard.rows; y++) {
			tile = mapObject.checkerboard.getTile(mapObject.leftCol,y);
			tile.screenX += tileSize*(this.checkerboard.cols);
			tile.longitude += mapObject.extend*2*(this.checkerboard.cols);
			tile.draw ();
		}
		mapObject.leftCol++;
		if (this.timings > 0) {
			mapLogSend("Map.shiftLeft finished at "+this.getLifeTime());
		}
	},

	shiftUp: function () {
		if (this.timings > 0) {
			mapLogSend("Map.shiftUp called at "+this.getLifeTime());
		}
		if (mapObject.bottomRow < 0) {
			mapObject.bottomRow = mapObject.checkerboard.rows-1;
		}
		mapObject.topRow = mapObject.bottomRow;

		for (x=0; x<mapObject.checkerboard.cols; x++) {
			tile = mapObject.checkerboard.getTile(x, mapObject.topRow);
			tile.screenY -= tileSize*(this.checkerboard.rows);
			tile.latitude += mapObject.extend*2*(this.checkerboard.rows);
			tile.draw ();
		}
		mapObject.bottomRow--;
		if (this.timings > 0) {
			mapLogSend("Map.shiftUp finished at "+this.getLifeTime());
		}
	},

	shiftDown: function () {
		if (this.timings > 0) {
			mapLogSend("Map.shiftDown called at "+this.getLifeTime());
		}
		if (mapObject.topRow > mapObject.checkerboard.rows-1) {
			mapObject.topRow = 0;
		}


		mapObject.bottomRow = mapObject.topRow;

		for (x=0; x<mapObject.checkerboard.cols; x++) {
			tile = mapObject.checkerboard.getTile(x, mapObject.bottomRow);
			tile.screenY += tileSize*(this.checkerboard.rows);
			tile.latitude -= mapObject.extend*2*(this.checkerboard.rows);
			tile.draw ();
		}
		mapObject.topRow++;
		if (this.timings > 0) {
			mapLogSend("Map.shiftDown finished at "+this.getLifeTime());
		}

	},

	switchStaticPoi: function (poitype) {
		if (this.staticpoi.indexOf(poitype) ==  -1) {
			this.staticpoi.push(poitype);
			}
		else {
			this.staticpoi = this.staticpoi.without(poitype);
		}

	},

	slideIn: function (elementID) {
			if ($(elementID).slidestatus == 1) {
				new Effect.Parallel (
					[
						new Effect.Fade(elementID, { sync: true, to: 0, from: 0.8 })
					]
				)
				$(elementID).slidestatus = 0
			}
			else {
				//$(elementID).style.visibility = "visible";
				new Effect.Parallel (
					[
						new Effect.Appear(elementID, { sync: true, to: 0.8, from: 0.0 }),
					]
				)
				$(elementID).slidestatus = 1;
			}
	},

	//Konvertierung Geokoordinaten
	getKlickTel: function (longitude, latitude) {
            var a      = 6378137;     // earth radius
            var e      = 0.081819191; // eccentricity
            var p0     = 46.5;        // centre of projection
            var p1     = 40;          // first parallel in degrees
            var p2     = 55;          // second parallel in degrees
            var l      = 6;           // centre meridian in degrees

            var phi0 = ( p0 * Math.PI ) / 180;
            var phi1 = ( p1 * Math.PI ) / 180;
            var phi2 = ( p2 * Math.PI ) / 180;
            var lambda0 = ( l * Math.PI ) / 180;

            // Temporary variables
            var n = Math.log( Math.cos(phi1 ) / Math.cos(phi2 ) ) / Math.log( Math.tan( ( Math.PI / 4 ) + ( phi2 / 2 ) ) / Math.tan( ( Math.PI / 4 ) + ( phi1 / 2 ) ) );

            var f = ( Math.cos( phi1 ) * Math.pow( Math.tan( ( Math.PI / 4 ) + ( phi1 / 2 ) ), n ) ) / n;

            var rho0 = ( a * f ) / Math.pow( Math.tan( ( Math.PI / 4 ) + ( phi0 / 2 ) ), n );

            // Transform 84 to klickTel internal
            var phi = ( longitude * Math.PI ) / 180;
            var lambda = ( latitude * Math.PI ) / 180;
            var rho = ( a * f ) / Math.pow( Math.tan( ( Math.PI / 4 ) + ( phi / 2 ) ), n );
            var ny = n * ( lambda - lambda0 );

            var x = 50000000 + Math.round( ( 10 * rho * Math.sin( ny ) ));
            var y = 50000000 + Math.round( ( 10 * ( rho0 - ( rho * Math.cos( ny ) ) ) ));
            return [x, y];
	},


	getWGS84: function (longitude, latitude) {
	   		var a      = 6378137;     // earth radius
            var e      = 0.081819191; // eccentricity
            var p0     = 46.5;        // centre of projection
            var p1     = 40;          // first parallel in degrees
            var p2     = 55;          // second parallel in degrees
            var l      = 6;           // centre meridian in degrees

            var phi0 = ( p0 * Math.PI ) / 180;
            var phi1 = ( p1 * Math.PI ) / 180;
            var phi2 = ( p2 * Math.PI ) / 180;
            var lambda0 = ( l * Math.PI ) / 180;

            // Temporary variables
            var n = Math.log( Math.cos(phi1 ) / Math.cos(phi2 ) ) / Math.log( Math.tan( ( Math.PI / 4 ) + ( phi2 / 2 ) ) / Math.tan( ( Math.PI / 4 ) + ( phi1 / 2 ) ) );

            var f = ( Math.cos( phi1 ) * Math.pow( Math.tan( ( Math.PI / 4 ) + ( phi1 / 2 ) ), n ) ) / n;

            var rho0 = ( a * f ) / Math.pow( Math.tan( ( Math.PI / 4 ) + ( phi0 / 2 ) ), n );

            var x = (longitude - 50000000)/10;
            var y = (latitude - 50000000)/10;
            var my = Math.atan(x / (rho0 - y));
            var lambda = my/n + lambda0;
            var rho = Math.sqrt(Math.pow(x,2) + Math.pow((rho0 - y),2));
            if (n < 0) {
                    rho = -rho;
            }

            var phi = 2*Math.atan(Math.pow((a*f/rho),(1/n))) - Math.PI/2;
            var LongitudeWGS84 = (phi*180/Math.PI);
            var LatitudeWGS84 = (lambda*180/Math.PI);
            return [LongitudeWGS84, LatitudeWGS84];
	}

}

var Checkerboard = Class.create ();
Checkerboard.prototype = {
	//Properties
	matrix: [],
	rows: 0,
	cols: 0,

	//Constructor
	initialize: function (_x, _y) {
		if (mapObject.timings > 0) {
			mapLogSend("Checkerboard.initialize called at "+mapObject.getLifeTime());
		}
		this.cols = _x;
		this.rows = _y;
		this.matrix = new Array(_y);
		for (row=1; row<=_x; row++){
			this.matrix[row] = new Array(_y);
		}
		if (mapObject.timings > 0) {
			mapLogSend("Checkerboard.initialize finished at "+mapObject.getLifeTime());
		}
	},

	//Methods
	getTile: function (_x, _y) {
		return (this.matrix[_x+1][_y+1]);
	},

	putTile: function (_x, _y, _tile) {
		this.matrix[_x+1][_y+1] = _tile;
	},

	dump: function () {

	}
}

function imageLoad (domNode, url, pars) { //Asynchronous image loading with xmlHTTPRequest
	// As there seems to be no way to parallelize browser requests, it is pointless to use Ajax here. Falling back to plain old
	// src parameter setting
	if (mapObject.timings > 0) {
		mapLogSend("Function imageLoad called at "+mapObject.getLifeTime());
	}
	domNode.src = mapObject.appFolder+"/images/loading.gif";
	imageAssign (domNode, url, pars);

	if (mapObject.timings > 0) {
		mapLogSend("Function imageLoad finished at "+mapObject.getLifeTime());
	}
}

function imageAssign (domNode, url, pars) {
		domNode.onerror = function() { //Try to retrieve the image again after 10 Seconds
			window.setTimeout ('document.getElementById("'+domNode.id+'").src="'+url+'"', 10000);
		}
		domNode.src = url;
}

function getLeft(refObj)
   {
   xPos = refObj.offsetLeft;
   parentObj=refObj.offsetParent;
   while(parentObj != null) {xPos+=parentObj.offsetLeft;parentObj=parentObj.offsetParent}
   return xPos;
   }

function getTop(refObj)
   {
   yPos = refObj.offsetTop;
   parentObj=refObj.offsetParent;
   while(parentObj != null) {yPos+=parentObj.offsetTop;parentObj=parentObj.offsetParent}
   return yPos;
}

function getPDF(routeID,longitude,latitude,extend)
{
    location.href='pdf.php?routeID='+routeID+'&longitude='+longitude+'&latitude='+latitude+'&extend='+extend;

    return false;
}
