dojo.require("dojox.gfx");

function mapControls() {
	this.mapHeight = 10;
	this.mapWidth = 0;
	this.cursorPosition = {x:0, y:0};
	
	this.container = null;
	this.surface;
	this.g = dojox.gfx.matrix; 
	this.g1 = dojox.gfx.matrix; 
	this.g0 = dojox.gfx.matrix; 
	this.pointsgroup = dojox.gfx.matrix; 
	this.m = dojox.gfx.matrix;
	this.initial_matrix = this.m.normalize([[this.m.rotateg(0), this.m.translate(0, 0)]]);
	this.imageUrl = "";
	this.imageGenerationTime = "";
	this.currentG = 0;
	
	this.init = function() {
		map.resize();
		$("#mapholder").css("cursor", "url(./images/cursors/openhand.cur), default");
	
		$(window).resize(function(){ map.resize(); });
		
		$("a.mapbutton").bind("click", function(){
				if (this.id == "fullext") {
					map.zoomToFullExtent();
				}
				else if (!$(this).hasClass("layers"))  {
					$('#mapholder').imgAreaSelect({disable: true});
					$("#mapholder").draggable('disable');
					$("#mapholder").unbind("click");
					
					$("div.buttons").children("a.selected").not("a.layers").removeClass("selected");
					//$("div.linkholder").children("a.selected").not("a.layers").removeClass("selected");
					$(this).addClass("selected");
					switch (this.id)
					{
						case "pan":
							$("#mapholder").draggable('enable');
							$("#mapholder").css("cursor", "url(./images/cursors/openhand.cur), default");
							break;
						case "zoomin":
							$("#mapholder").css("cursor",  "crosshair");
							$('#mapholder').imgAreaSelect({disable: false}); 
							break;
						case "zoomout" :
							$("#mapholder").bind("click", function(e){ map.onZoomOut(e); });
							$("#mapholder").css("cursor",  "crosshair");
							break;
						case "trash":
							$("#mapholder").bind("click", function(e){ 	trashButtonClick(map.cursorPosition.x, map.cursorPosition.y); });
							$("#mapholder").css("cursor",  "crosshair");
							break;
						case "info":
							$("#mapholder").bind("click", function(e){ infoButtonClick(map.cursorPosition.x, map.cursorPosition.y); });
							$("#mapholder").css("cursor",  "help");
							break;
						case "link":
							$("#mapholder").bind("click", function(e){ map.linkButtonClick() });
							$("#mapholder").css("cursor",  "pointer");
							break;
					}
				}
				else {
					if (!$(this).hasClass("selected")) {
						$(this).parent().children("a.layers").removeClass("selected");
						$(this).addClass("selected");
						var params = {type: this.id}; 
						map.doJSON("/v2/map", params);
					}
				}
				return false;
			});
		
		// mapholder events
		$("#mapholder").mousewheel(function(objEvent, intDelta){ map.MouseScroll(intDelta);	});	
		$("#mapholder").bind("mousemove", function(e){ map.MouseMove(e); });
		$("#mapholder").bind("mousedown", function(e){ if ($.browser.msie)	$("#mapholder").get(0).setCapture(); });
		$("#mapholder").bind("mouseup", function(e){ if ($.browser.msie)	$("#mapholder").get(0).releaseCapture(); });
		$('#mapholder').imgAreaSelect({movable: false, resizable: false, disable: true, onSelectEnd: map.onZoomIn }); 
		$("#mapholder").draggable()
						.draggable('option', 'cursor', "url(./images/cursors/closehand.cur), move")
						.bind('dragstop', function(event, ui) { map.onPan(event, ui) });
	}
	
	this.setMapCursor = function () {
		switch ($("#buttons > a.selected").attr("id"))
		{
			case "pan":
				$("#mapholder").css("cursor", "url(./images/cursors/openhand.cur), default");
				break;
			case "zoomin":
			case "zoomout" :
			case "trash":
				$("#mapholder").css("cursor",  "crosshair");
				$("#mapholder").css("cursor",  "crosshair");
				break;
			case "info":
				$("#mapholder").css("cursor",  "help");
				break;
		}	
	}
	
	this.resize = function() {
		var sizes = this.surfaceSize();
		this.mapHeight = sizes.height;
		this.mapWidth = sizes.width;
		if (this.surface != null) 
			this.surface.setDimensions(this.mapWidth+'px', this.mapHeight+'px');
		$("#main").css('height', this.mapHeight + "px");
		$("#sidebar").css('height', this.mapHeight + "px");
		this.doJSON("/v2/resize", { width: this.mapWidth, height: this.mapHeight });
	}
	this.surfaceSize = function() {
		var sizes = {width: $(window).width(), height: $(window).height()};
		if ($.browser.opera)
			sizes.height = window.innerHeight;
		var heightMargin =  0;
		if ($("div#header").length)
			heightMargin += $("div#header").outerHeight();
		if ($("div#footer").length)
			heightMargin += $("div#footer").outerHeight();
		var widthMargin = 0;
		if ($("div#sidebar").length)
			widthMargin = $("div#sidebar").outerWidth();
		sizes.height = sizes.height-heightMargin;
		sizes.width = sizes.width-widthMargin;
	    return sizes;
	}
	this.refresh = function() {
		map.doJSON("/v2/refresh", "");
	}
	this.doJSON = function (url, params) {			
		this.showLoading(true);
		$.getJSON(url, params, function(data){ map.initGfx(data) });
	}
	this.doUpdate = function (url, params) {			
		this.showLoading(true);
		$.getJSON(url, params, function(data){ map.initGfx(data) });
	}
	this.updatePoints = function (data){
		if (data != "") {
			$.each(data.lastgps, function(i,item){
				$("li#"+item.id).find("td.time").html(item.time);
				$("li#"+item.id).find("td.speed").html(item.speed);
				$("li#"+item.id).find("td.engine").html(item.engine);
			});		
			map.pointsgroup.clear();
			map.makeCircleGrid(data.points);
		}
	}
	this.showLoading = function(value) {
		if (value)
			$("#mapLoading").show();
		else {
			$("#mapLoading").hide();
			$('#mapholder').css("left", "0px").css("top", "0px");
		}
	}
			
	// parseto karti uz full extent
	this.zoomToFullExtent = function() {
		this.doJSON("/v2/fullextent", "");
	}
	
	// scroll functions
	this.zoomFactor = 0;
	this.zoomToFactor = function (zoom, zoomX, zoomY) {
		if (zoom == this.zoomFactor && zoom != 0) {
			var params;
			if ($.browser.opera)
				this.zoomFactor = this.zoomFactor*-1;
			params = { minx: zoomX, miny: zoomY, zoomFactor: this.zoomFactor };
			this.doJSON("/v2/zoom", params);
			this.zoomFactor = 0;
		}
	}
	this.MouseScroll = function (updown) {
		if (updown > 0)
			this.zoomFactor++;
		else  
			this.zoomFactor--;
		if (this.zoomFactor > 0) 
			map.scaleImage((this.zoomFactor + 1) , this.cursorPosition.x , this.cursorPosition.y , 0, 0);
		else
			map.scaleImage((1/(-this.zoomFactor + 1)), this.cursorPosition.x, this.cursorPosition.y, 0, 0);
		//dalay zoom function		
		setTimeout('map.zoomToFactor(' + this.zoomFactor + ', ' + this.cursorPosition.x + ', ' + this.cursorPosition.y + ')', 500);
	}
	this.scaleImage = function (scale, x, y, dx, dy) {
		this.clearAdGraphics();
		this.g.setTransform([this.m.translate(dx, dy), this.m.scaleAt(scale, x, y)]);	
		this.pointsgroup.setTransform([this.m.translate(dx, dy), this.m.scaleAt(scale, x, y)]);	
	}
	
	// move functions 
	this.MouseMove = function (e) {
		this.cursorPosition.x = this.pointerX(e) - $("#mapholder").offset().left;
		this.cursorPosition.y = this.pointerY(e) - $("#mapholder").offset().top;
	}	
	
	// zooming
	this.onZoomIn = function (img, selection) {
		var params;
		params = { minx: selection.x1, miny: selection.y1, maxx: selection.x2 ,maxy: selection.y2 };
		
		var scalex = map.mapWidth/(selection.width);
		var scaley = map.mapHeight/(selection.height);
		var scale, dx, dy, x, y;
		if (selection.width <= 10 || selection.height <= 10) {
			for (i = 0; i < 10; i++ ) {
				params = { minx:  map.cursorPosition.x, miny: map.cursorPosition.y, maxx:  map.cursorPosition.x ,maxy: map.cursorPosition.y };
				setTimeout('map.scaleImage(' + (1 + 1/(10-i)) + ', ' + map.cursorPosition.x + ', ' + map.cursorPosition.y + ', 0, 0)', 30*i);
			}
		}
		else {
			scale = scalex;
			dx = map.mapWidth/2-((selection.width)/2+selection.x1);
			dy = map.mapHeight/2-((selection.height)/2+selection.y1);
			x = selection.x1+(selection.width)/2;
			y = selection.y1+(selection.height)/2;
			for (i = 0; i < 10; i++ ) 
				setTimeout('map.scaleImage(' + (1 + (scale-1)/(10-i)) + ', ' + x + ', ' + y + ', '+dx+', '+dy+')', 30*i);
		}
		
		$('#mapholder').imgAreaSelect({hide: true});
		map.doJSON("/v2/zoomin", params);
	}
	this.onZoomOut = function (e) {
		var params;
		params = { mapx: map.cursorPosition.x, mapy: map.cursorPosition.y };

		for (i = 1; i <= 10; i++)
			setTimeout('map.scaleImage(' + (10/(10+i)) + ', ' + map.cursorPosition.x + ', ' + map.cursorPosition.y + ', 0, 0)', 30*i);

		this.doJSON("/v2/zoomout", params);
	}
	// panning
	this.onPan = function (event, ui) {
		$('#mapholder').css("left", "0px").css("top", "0px");
		this.g.setTransform([this.m.translate(ui.position.left, ui.position.top)]);
		this.pointsgroup.setTransform([this.m.translate(ui.position.left, ui.position.top)]);
		this.clearAdGraphics();
		
		var params;
		var map_point_x = (map.mapWidth/2) - ui.position.left;
		var map_point_y = (map.mapHeight/2) -  ui.position.top;
		params = { mapx: map_point_x, mapy: map_point_y };

		this.doJSON("/v2/pan", params);
	}
		
	//element position 
	//cross browser functions for mouse coords
	this.pointerX = function (evt) {
		if (evt.pageX) return evt.pageX;
		else if (evt.clientX)
		   return evt.clientX + (document.documentElement.scrollLeft ?
		   document.documentElement.scrollLeft :
		   document.body.scrollLeft);
		else return null;
	}
	this.pointerY = function (evt) {
		if (evt.pageY){
			if ($.browser.msie)	
				return evt.pageY;
			else
				return evt.pageY;
		}
		else if (evt.clientY)
		   return evt.clientY + (document.documentElement.scrollTop ?
		   document.documentElement.scrollTop :
		   document.body.scrollTop);
		else return null;
	}
	
	//dojo graphics 
	this.initGfx = function (data){
		this.imageGenerationTime = new Date();
		var localTime = this.imageGenerationTime;
		var sizes = this.surfaceSize();

		this.container = dojo.byId("mapholder");
		if (this.surface != null) {
			this.g = (this.g == this.g0) ? this.g1 : this.g0;
			this.g.clear();
			this.g.setTransform(this.initial_matrix);
			this.g._moveToFront();
		}
		else {
			this.surface = dojox.gfx.createSurface(this.container, this.mapWidth, this.mapHeight);
			this.g0 = this.surface.createGroup().setTransform(this.initial_matrix);
			this.g1 = this.surface.createGroup().setTransform(this.initial_matrix);
			this.pointsgroup = this.surface.createGroup().setTransform(this.initial_matrix);
			this.g = this.g0;

		}
		this.pointsgroup._moveToFront();
		this.pointsgroup.clear();
		this.pointsgroup.setTransform(this.initial_matrix);

		$.each(data.images, function(i,item){
			var img = new Image();
			$(img).attr('src', item.url)
				.load(function(){
					map.showImage(item.x, item.y, item.w, item.h, item.url, localTime);
			});
		});
		this.imageUrl = data.url;
		//alert(data);
		this.makeCircleGrid(data.points);
		this.makeImageList(data.imagepoints);
		this.updateLink(data.x, data.y, data.scale);
		this.showLoading(false);
	}	
	this.showImage = function (x, y, w, h, url, localTime) {
		if (localTime == this.imageGenerationTime) {
			this.g.createImage({x: x, y: y, width: w, height: h, src: url});
			$("image").each(function(){$(this).attr("fill", "transparent")})
		}
	}
	this.pointHint = function(data) {
		var str = "<ul><li>"+data.gpsid+"</li><li>"+data.date+"</li><li>"+data.speed+"</li>";
		if (data.fuel != null)
			str += "<li>Degviela: "+data.fuel+"</li>";
		if (data.engine == "ieslēgts") 
			str += "<li>Motors: "+data.engine+"</li>";
		str += "</ul>";
		$("div#pointhint").html(str);
	}
	this.mouseover = function (ev){
		$("#mapholder").css("cursor", "pointer");
		$("div#pointhint").show();
		$("div#pointhint").css("left", ev.layerX+"px").css("top", ev.layerY+"px");
		$("div#pointhint").html("<img alt='loading' src='/images/loading/loading-circle.gif'/>");
		var attr = this.id.split("_");
		params = { type: attr[0], id: attr[1]};
		$.getJSON("/v2/pointinfo", params, function (data){ map.pointHint(data)});
		if(!($.browser.msie) && this.r)
			this.r.baseVal.value = this.r.baseVal.value+3;
	}
	this.mouseoverImage = function (ev){
		$("#mapholder").css("cursor", "pointer");
		$("div#pointhint").show();
		$("div#pointhint").css("left", (ev.clientX+10)+"px").css("top", ev.clientY+"px");
		$("div#pointhint").html("<h3>"+$(this).attr("name")+"</h3><p>Noklikšķiniet, lai apskatītu.</p>");
	}
	this.mouseout = function (ev){
		map.setMapCursor();
		$("div#pointhint").hide();
		if (this.r)
			this.r.baseVal.value = this.r.baseVal.value - 3;
	}
	this.clickImage = function (ev) {
		if (window.parent == null)
			alert($(this).attr("url"));
		else
			window.parent.location = $(this).attr("url");
	}
	this.makeCircleGrid = function (points){
		if (points) {
			var prevPoint = new Array();
			var pointList = new Object();
			var lastPoint = new Array();
			$.each(points, function(i,item){
				try {
					if(!($.browser.msie && $.browser.version=="6.0"))
					{
						if (((!prevPoint[item.gpsid] ||
								Math.abs(prevPoint[item.gpsid].x-item.x) > 3 || 
								Math.abs(prevPoint[item.gpsid].y-item.y) > 3) && 
								item.x > -1000 && item.y > -1000 &&
								item.x < map.mapWidth+1000 && item.y < map.mapHeight+1000) ||
								item.type == "gpsLast"
								) {
							if (!pointList[item.gpsid]) pointList[item.gpsid] = new Array();
							
							if (!prevPoint[item.gpsid]) {
								if (item.gear == 1 || item.engine == 1) {
									pointList[item.gpsid] = new Array();
									pointList[item.gpsid].push({x: item.x, y: item.y});
								}
								else {
									pointList[item.gpsid] = new Array();
								}
								map.showPoint(item);
								lastPoint[item.gpsid] = item.date;
							}
							else {
								var prev = prevPoint[item.gpsid];
								if (item.gear == 1) {
									if (prev.gear == 1) {
										if (item.date - lastPoint[item.gpsid] > 100) {
											pointList[item.gpsid].push({x: item.x, y: item.y});
											var line = map.pointsgroup.createPolyline({points: pointList[item.gpsid]});
											line.setStroke({color: [255, 0, 0, 0.8], width: 4});
											if (pointList[item.gpsid].length > 2) {
												var direction = (pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x > 0);
												
												var angle = Math.atan2(pointList[item.gpsid][pointList[item.gpsid].length-1].y - pointList[item.gpsid][pointList[item.gpsid].length-2].y, pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x)*180/Math.PI
												map.showPointImage(item, angle);
											}
											else  {
												map.showPoint(item);
											}
											lastPoint[item.gpsid] = item.date;
											pointList[item.gpsid] = new Array();
										}
										pointList[item.gpsid].push({x: item.x, y: item.y});
									}
									else {
										if (prev.engine == 1) {
											pointList[item.gpsid].push({x: item.x, y: item.y});
											var line = map.pointsgroup.createPolyline({points: pointList[item.gpsid]});
											line.setStroke({color: [h2d(item.c.substring(0, 2)), h2d(item.c.substring(2, 4)), h2d(item.c.substring(4, 6)), 0.4], width: 4});
										}
										pointList[item.gpsid] = new Array();
										pointList[item.gpsid].push({x: item.x, y: item.y});
										
										if (pointList[item.gpsid].length > 2) {
												var direction = (pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x > 0);
												
												var angle = Math.atan2(pointList[item.gpsid][pointList[item.gpsid].length-1].y - pointList[item.gpsid][pointList[item.gpsid].length-2].y, pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x)*180/Math.PI
												map.showPointImage(item, angle);
											}
											else  {
												map.showPoint(item);
											}
										lastPoint[item.gpsid] = item.date;
									}
								}
								else if (item.engine == 1) {
									if (prev.engine == 1) {		
										if (item.date - lastPoint[item.gpsid] > 100) {
											pointList[item.gpsid].push({x: item.x, y: item.y});
											var line = map.pointsgroup.createPolyline({points: pointList[item.gpsid]});
											line.setStroke({color: [h2d(item.c.substring(0, 2)), h2d(item.c.substring(2, 4)), h2d(item.c.substring(4, 6)), 0.4], width: 4});
											
											if (pointList[item.gpsid].length > 2) {
												var direction = (pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x > 0);
												
												var angle = Math.atan2(pointList[item.gpsid][pointList[item.gpsid].length-1].y - pointList[item.gpsid][pointList[item.gpsid].length-2].y, pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x)*180/Math.PI
												map.showPointImage(item, angle);
											}
											else  {
												map.showPoint(item);
											}									
											lastPoint[item.gpsid] = item.date;
											pointList[item.gpsid] = new Array();
										}
										pointList[item.gpsid].push({x: item.x, y: item.y});
									}
									else {
										if (prev.gear == 1) {
											var line = map.pointsgroup.createPolyline({points: pointList[item.gpsid]});
											line.setStroke({color: [255, 0, 0, 0.4], width: 4});
										}
										pointList[item.gpsid] = new Array();
										pointList[item.gpsid].push({x: item.x, y: item.y});
										
										if (pointList[item.gpsid].length > 2) {
											var direction = (pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x > 0);
											
											var angle = Math.atan2(pointList[item.gpsid][pointList[item.gpsid].length-1].y - pointList[item.gpsid][pointList[item.gpsid].length-2].y, pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x)*180/Math.PI
											map.showPointImage(item, angle);
										}
										else  {
											map.showPoint(item);
										}
										lastPoint[item.gpsid] = item.date;
									}
								}
								else {
									if (prev.gear == 1) {
										var line = map.pointsgroup.createPolyline({points: pointList[item.gpsid]});
										line.setStroke({color: [255, 0, 0, 0.8], width: 4});
									}
									else if  (prev.engine == 1) {
										var line = map.pointsgroup.createPolyline({points: pointList[item.gpsid]});
										line.setStroke({color: [h2d(prev.c.substring(0, 2)), h2d(prev.c.substring(2, 4)), h2d(prev.c.substring(4, 6)), 0.4], width: 4});
									}
									if (item.type != "gpsLast" && pointList[item.gpsid].length > 2) {
										var direction = (pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x > 0);
										
										var angle = Math.atan2(pointList[item.gpsid][pointList[item.gpsid].length-1].y - pointList[item.gpsid][pointList[item.gpsid].length-2].y, pointList[item.gpsid][pointList[item.gpsid].length-1].x - pointList[item.gpsid][pointList[item.gpsid].length-2].x)*180/Math.PI
										map.showPointImage(item, angle);
									}
									else  {
										map.showPoint(item);
									}
									pointList[item.gpsid] = new Array();
									lastPoint[item.gpsid] = item.date;
								}
							} 
							
							/*if (item.type != "gpsLast" && prevPoint != null && prevPoint[item.gpsid] != null && (item.gear == 1 || item.engine == 1)){
								var line = map.pointsgroup.createLine({x1: item.x, y1: item.y, x2: prevPoint[item.gpsid].x, y2: prevPoint[item.gpsid].y});
								if (item.gear == 1)
									line.setStroke({color: [255, 0, 0, 0.8], width: 4});
								else
									line.setStroke({color: [h2d(item.c.substring(0, 2)), h2d(item.c.substring(2, 4)), h2d(item.c.substring(4, 6)), 0.4], width: 3});
							}*/
							if (item.name != null && item.name != "") {
								var b = map.pointsgroup.createText({x:item.x+13, y: item.y+5, text: item.name, align: "left"});
								b.setFont({family: "Verdana", size: 12, weight: "bold"});
								b.setFill([100, 100, 100, 1]);
								//b.setStroke({color: "white", width: 2});
							}
							prevPoint[item.gpsid] = item;
						}
					}
				} catch (ex){
					//alert(ex.toString())
				}
			});		
			//console.log(pointList["102474"]);
			//var line = map.pointsgroup.createPolyline({points: pointList["102474"]});
			//line.setStroke({color: [0, 0, 255, 0.8], width: 6});
			//console.log(pointList);
		}
	}
	this.showPoint = function (item) {
		var shape = map.pointsgroup.createCircle({cx: item.x, cy: item.y, r: item.r});
		shape.rawNode.id = item.type+"_"+item.id;
		shape.setFill([h2d(item.c.substring(0, 2)), h2d(item.c.substring(2, 4)), h2d(item.c.substring(4, 6)), 0.6]);
		shape.setStroke({color: [100, 100, 100, 1], width: 2});
	
		shape.getEventSource().setAttribute('type', item.type);
		dojo.connect(shape.getEventSource(), "onmouseover", map.mouseover);
		dojo.connect(shape.getEventSource(), "onmouseout", map.mouseout);
	}
	this.showPointImage = function (item, angle) {
		var url = "http://www.kurtuesi.lv/images/icon/";
		angle = (angle-angle%23)/23;
		switch (angle) {
			case 0:
				url += "arrow-000-medium.png";
				break;
			case -1:
			case -2:
				url += "arrow-045-medium.png";
				break;
			case -3:
			case -4:
				url += "arrow-090-medium.png";
				break;
			case -5:
			case -6:
				url += "arrow-135-medium.png";
				break;
			case -7:
			case 7:
				url += "arrow-180-medium.png";
				break;
			case 5:
			case 6:
				url += "arrow-225-medium.png";//
				break;
			case 3:
			case 4:
				url += "arrow-270-medium.png";//
				break;
			case 1:
			case 2:
				url += "arrow-315-medium.png";//
				break;
		} 
		var shape = map.pointsgroup.createImage({x: item.x-8, y: item.y-8, width: 16, height: 16, src: url});
		shape.rawNode.id = item.type+"_"+item.id;
		//shape.setFill([h2d(item.c.substring(0, 2)), h2d(item.c.substring(2, 4)), h2d(item.c.substring(4, 6)), 0.6]);
		//shape.setStroke({color: [100, 100, 100, 1], width: 2});
	
		shape.getEventSource().setAttribute('type', item.type);
		dojo.connect(shape.getEventSource(), "onmouseover", map.mouseover);
		dojo.connect(shape.getEventSource(), "onmouseout", map.mouseout);
	}
	this.makeImageList = function (images){
		if (images) {
			$.each(images, function(i,item){
				var shape = map.pointsgroup.createImage({x: item.x, y: item.y, width: 22, height: 22, src: item.image});
				shape.rawNode.id = item.i;
				shape.getEventSource().setAttribute('name', item.name);
				shape.getEventSource().setAttribute('descr', item.descr);
				shape.getEventSource().setAttribute('url', item.url);
				dojo.connect(shape.getEventSource(), "onmousemove", map.mouseoverImage);
				dojo.connect(shape.getEventSource(), "onclick", map.clickImage);
				dojo.connect(shape.getEventSource(), "onmouseout", map.mouseout);
			});		
		}
	}
	this.clearAdGraphics = function (){
		if (this.g == this.g0)
			this.g1.clear();
		else
			this.g0.clear();
	}
	
	
	this.linkButtonClick = function() {
		var params;
		params = { mapx: this.cursorPosition.x, mapy: this.cursorPosition.y };
		$.getJSON("/v2/link", params, function (data){
			map.updateLink(data.x, data.y, data.scale);											
		});
	}
	this.updateLink = function(x, y, scale) {
		$("#maplink").val(baseUrl+"/v2?x="+x+"&y="+y+"&scale="+scale)
	}
}

var map = new mapControls();
dojo.addOnLoad(map.init);
$(document).ready(function(){ 
	//map.init();
});

function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);} 