var shape = {
	type: "distance",
	points:  { x: new Array(), y: new Array() },
	
	clear: function() {
		this.points.x.length = 0;
		this.points.y.length = 0;
		tjg.clear();
		jg.clear();
		document.getElementById("measureInfo").style.display = "none";
	},
	repaint: function(temp) {
		var count = this.points.x.length;
		if (count == 0)
		  return;
		document.getElementById("measureInfo").style.display = "";
		var bArea = this.type == "area";
		if (count > 1) {
			var xa = new Array(this.points.x[count - 2], this.points.x[count - 1]);
			var ya = new Array(this.points.y[count - 2], this.points.y[count - 1]);
			if (temp) {
				if (bArea) {
					xa.push(this.points.x[0]);
					ya.push(this.points.y[0]);
				}
				tjg.clear();
				tjg.setColor("#0000ff");
				tjg.setStroke(2);
				tjg.drawPolyline(xa, ya);
				tjg.paint();
			}
			else { 
				jg.setColor("#0000ff");
				jg.setStroke(2);
				jg.drawPolyline(xa, ya);
				jg.paint();
			}
		}
		
		var pts = { x: new Array(), y: new Array() }
		for (var i = 0; i < count; i++) {
			pts.x[i] = map.getWX(this.points.x[i]);
			pts.y[i] = map.getWY(this.points.y[i]);
		}

		var lastlen = 0;
		var dx, dy;
		if (count > 1) {
			dx = pts.x[count - 2] - pts.x[count - 1];
			dy = pts.y[count - 2] - pts.y[count - 1];
			lastlen = Math.sqrt(dx * dx + dy * dy); 
		}
		
		if (bArea) {
			pts.x.push(pts.x[0]);
			pts.y.push(pts.y[0]);
		}

		var len = 0;
		var area = 0;
		for (var i = 0; i < pts.x.length - 1; i++) {
			var dx = pts.x[i] - pts.x[i + 1];
			var dy = pts.y[i] - pts.y[i + 1];
			len += Math.sqrt(dx * dx + dy * dy);
			area += dx * (pts.y[i] + pts.y[i + 1]) / 2;
		}
		len = Math.round(len * 100) / 100;
		lastlen = Math.round(lastlen * 100) / 100;
		area = Math.round(Math.abs(area) * 100) / 100;
				
		document.getElementById("measureX").innerHTML = "<strong>X:</strong><br />" + Math.round(map.getWX(this.points.x[count - 1]) * 100) / 100;
		document.getElementById("measureY").innerHTML = "<strong>Y:</strong><br />" + Math.round(map.getWY(this.points.y[count - 1]) * 100) / 100;
		if (bArea) { 
			document.getElementById("measureInfo1").innerHTML = "<strong>Plocha:</strong><br />" + area + " m2";
			document.getElementById("measureInfo2").innerHTML = "<strong>Obvod:</strong><br />" + len + " m";
			document.getElementById("measureInfo3").innerHTML = "<strong>Vzdálenost:</strong><br />" + lastlen + " m";
			document.getElementById("measureInfo3").style.display = "";
		}
		else {
			document.getElementById("measureInfo1").innerHTML = "<strong>Celková vzdálenost:</strong><br />" + len + " m";
			document.getElementById("measureInfo2").innerHTML = "<strong>Vzdálenost:</strong><br />" + lastlen + " m";
			document.getElementById("measureInfo3").style.display = "none";
		}				
	}			
};

function mapObj(id)
{
	this.id = id;
	this.mode = "zoom";
	this.init = init;
	this.setMode = setMode;
	this.detect = detect;
	this.zoom = zoom;
	this.zoomOut = zoomOut;
	this.pan = pan;
	this.center = center;
	this.zoomAll = zoomAll;
	this.zoomSel = zoomSel;
	this.zoomObj = zoomObj;
	this.unselectAll = unselectAll;
	this.lastView = lastView;
	this.resize = resize;
	this.reload = reload;
	this.search = search;
	this.setScale = setScale;
	this.createImage = createImage;
	this.updateImageCursor = updateImageCursor;
	this.getURL = getURL;
	this.viewName = initViewName;
	this.query = "";
	this.getWX = getWX;
	this.getWY = getWY;
	this.getX = getX;
	this.getY = getY;
	this.showScale = true;
	this.flashIcon = flashIcon;
	this.onFlashTimer = onFlashTimer;
	this.flashRepaintIcon = flashRepaintIcon;
					
	function createImage(url)
	{
		var elem = document.getElementById(id);
		if (this.image)
			elem.removeChild(this.image);
		this.image = document.createElement("img");
		this.image.style.position = "relative";
		this.image.zindex = 1;
		this.image.onload = function() {
			var s = readCookie("Map-Extents");
			if (s)
			{
				var ea = s.split(',');
				map.extents = { left: ea[0] * 1, top: ea[1] * 1, right: ea[2] * 1, bottom: ea[3] * 1};
			}
			map.scale = readCookie("Map-Scale") * 1;
			map.globe.style.display = "none";

			var searchItems = document.searchform.searchtype.options;
			var oldIndex = document.searchform.searchtype.selectedIndex;
			if (map.obec) {
				searchItems.length = 6;
				searchItems[2].text = "Číslo budovy"; 
				searchItems[3].text = "Číslo LV"; 
				searchItems[4].text = "Rodné číslo"; 
				searchItems[5].text = "Jméno vlastníka"; 
			}
			else {
				searchItems.length = 2;
			} 
			document.searchform.searchtype.selectedIndex = oldIndex > 0 && oldIndex < searchItems.length ? oldIndex : 0;
			ovmap.updateZoomRect();
		}
		this.image.onerror = function() {
			map.globe.style.display = "none";
		}
		this.image.onabort = function() {
			map.globe.style.display = "none";
		}

		this.image.width = this.width;
		this.image.height = this.height;
 		this.image.oncontextmenu = function() { return false; }
		this.image.src = url;
		elem.appendChild(this.image);
		this.globe.style.display = "";
		this.updateImageCursor();
		this.flashRepaintIcon(false);
	}
	
	function init()
	{
		var elem = document.getElementById(id);
		this.left = getAbsLeft(elem);
		this.top = getAbsTop(elem);
		elem.onmousedown = onMouseDown;
		this.zoomArea = document.createElement("div");
		this.zoomArea.className = "zoomarea";
		this.zoomArea.style.position = "absolute";
		this.zoomArea.style.display = "none";
		elem.appendChild(this.zoomArea);
		this.globe = document.createElement("div");
		this.globe.id = "globe";
		this.globe.style.position = "absolute";
		this.globe.style.display = "none";
		this.globe.style.width = "40px";
		this.globe.style.height = "40px";
		elem.appendChild(this.globe);
		this.repaintIconBackColor = document.getElementById("repaint").style.backgroundColor;
	}
	
	function setMode(mode)
	{
		var elem = document.getElementById(this.mode);
		if (elem)
			elem.className = "tbutton";
		elem = document.getElementById(mode);
		if (elem)
		{
			elem.className = "tbuttond";
			this.mode = mode;	
		}
		switch (mode) {
			case "measure1": 
				shape.type = "distance";
				break;
			case "measure2":
				shape.type = "area";
				break;
		}
		this.updateImageCursor();
		shape.clear();
	}

	function updateImageCursor() {
		var cursor;
		if (!this.image)
		  return;
		switch (this.mode) {
			case "zoom":
				cursor = "url('cursors/zoom.cur'),pointer";
				break;
			case "pan":
				cursor = "url('cursors/pan.cur'),pointer";
				break;
			case "center":
				cursor = "url('cursors/center.cur'),pointer";
				break;
			default:
				cursor = "default";
		}				
		this.image.style.cursor = cursor;
	}
		
	function resize(w, h)
	{
		this.globe.style.left = ((w - parseInt(this.globe.style.width)) / 2) + "px"; 
		this.globe.style.top = ((h - parseInt(this.globe.style.height)) / 2) + "px"; 
		this.width = w;
		this.height = h;
		this.reload();
	}
	
	function zoom(l, t, w, h)
	{
		var cmd = w < 5 || h < 5 ? "ZoomIn;" + l + ";" + t :		   
							"ZoomArea;" + l + ";" + t + ";" + (l + w) + ";" + (t + h);
		this.lastExtents = this.extents;
		this.reload(cmd);
	}

	function zoomOut(x, y)
	{
		var cmd = "ZoomOut;" + x + ";" + y; 
		this.lastExtents = this.extents;
		this.reload(cmd);
	}
	
	function pan(ofsX, ofsY)
	{
		var cmd = "Pan;" + ofsX + ";" + ofsY + ";" + this.scale;
		this.lastExtents = this.extents;
		this.reload(cmd);
	}

	function center(x, y)
	{
		var cmd = "Center;" + x + ";" + y + ";" + this.scale; 
		this.lastExtents = this.extents;
		this.reload(cmd);
	}

	function detect(x, y)
	{
		var elem = document.getElementById("info");
		var s = "<iframe src=\"" + this.getURL("Detect;" + x + ";" + y) + 
			"\" width=100%% height=" + elem.offsetHeight + "px frameborder=0 </iframe>"; 
		elem.innerHTML = s;
	}
	
	function zoomAll()
	{
		this.lastExtents = this.extents;
		this.reload("ZoomAll");
	}
	
	function zoomSel()
	{
		this.lastExtents = this.extents;
		this.reload("ZoomSelObj");
	}

	function zoomObj(eco, mapIdx) {
		this.lastExtents = this.extents;
	  this.reload("ZoomObj;" + eco + ";" + mapIdx);
	}

	function unselectAll() {
		document.getElementById("info").innerHTML = "";
		this.query = "";
		this.reload();
	}
		
	function lastView()
	{
		if (!this.lastExtents || !this.image.complete)
		  return;
		var ex = this.extents;
		this.extents = this.lastExtents;
		this.lastExtents = ex;
		this.reload();
	}
	
	function getURL(cmd, w, h)
	{
		if (!cmd) {
			cmd = this.extents ? "Map" : "ZoomAll";
		}
		var url = mapServerURL + "?User=&VName=" + this.viewName;
		url += "&Cmd=" + cmd;
		url += "&ISize=" + (w ? w : this.width) + ";" + (h ? h : this.height);
		if (this.extents) {
			url += "&Area=" + this.extents.left + ";" + this.extents.top + ";" +
												this.extents.right + ";" + this.extents.bottom;
		}
		if (this.query.length > 0) {
			url += "&SQuery=" + this.query;
		}
		if (this.showScale) {
			url += "&ShowScale=1"; 
		}
		var legURL = legend.getURL();
		if (legURL)
		  url += "&" + legURL;
		url += "&id=" + Math.round((Math.random() * 10000000) + 10000000);
		return url;
	}
	
	function reload(cmd)
	{
		shape.clear();
		this.createImage(this.getURL(cmd));
	}

	function search(type, value, unselect) {
		var filter = null;
		if (value == "") {
			alert("Nebyla zadána hodnota pro výběr.")
			return;
		}
		switch (type) {
			case 0:
				filter = "ATTR='*" + value + "*'";
				break;
			case 1:
				filter = "ATTR='C" + value + "'";
				break;
			case 2:
				filter = ";PopCis=" + value;
				break;
			case 3:
				filter = ";LVCis=" + value;
				break;
			case 4:
				filter = ";RodCis=" + value;
				break;
			case 5:
				filter = ";Jmeno=" + value;
				break;
		}
		if (!filter) 
			return;
		if (unselect) {
			this.query = filter;
		}
		else {
			var q = this.query.split(",");
			var nq = filter.split(",");
	    if (q[0] && q[0].length > 0 && nq[0] && nq[0].length > 0)
	      q[0] += " OR ";
			q[0] += nq[0];
	    if (q[1] && q[1].length > 0 && nq[1] && nq[1].length > 0)
	      q[1] += ";";
			q[1] += nq[1];
			this.query = q[0];
			if (q[1])
				this.query += ";" + q[1];
		}
		this.lastExtents = this.extents;
		this.reload("ZoomSelObj");
		
		var elem = document.getElementById("info");
		var s = "<iframe src=\"" + this.getURL("SelObj") + 
			"\" width=100%% height=" + elem.offsetHeight + "px frameborder=0 </iframe>"; 
		document.getElementById("info").innerHTML = s;
	}
	
	function setScale(value) {
		this.lastExtents = this.extents;
		this.reload("Scale;" + value);
	}
	
	function getX(wx) {
		return Math.round((wx - this.extents.left) * this.width / (this.extents.right - this.extents.left));
	}

	function getY(wy) {
		return Math.round((wy - this.extents.top) * this.height / (this.extents.bottom - this.extents.top));
	}

	function getWX(x) {
		return this.extents.left + x * (this.extents.right - this.extents.left) / this.width;
	}

	function getWY(y) {
		return this.extents.top + y * (this.extents.bottom - this.extents.top) / this.height;
	}
	
	function flashRepaintIcon(value) {
	  if (this.flashTimer) {
	  	if (value)
	  	  return;
	    clearTimeout(this.flashTimer);
	    this.flashTimer = null;
		}
	  if (value) {
	  	this.flash = true;
			this.flashTimer = setTimeout("map.onFlashTimer()", 500);
		} 
		else this.flashIcon(false);
	}

	function onFlashTimer() {
		this.flashIcon(this.flash);
		this.flashTimer = setTimeout("map.onFlashTimer()", 500);
		this.flash = !this.flash;
	}
	
	function flashIcon(value) {
		document.getElementById("repaint").style.backgroundColor = value ? "yellow" : this.repaintIconBackColor;
		
	}
}

function onMouseDown(e)
{
	if (!map.image || !map.image.complete)
	  return false;
	if (!e) var e = window.event;
	map.focusPos = getCursorPos(e);
	map.focusPos.x -= map.left;
	map.focusPos.y -= map.top;

	document.onmouseup = onMouseUp;
	if (getMouseButton(e) == "LEFT") {
		document.onmousemove = onMouseMove;
		switch (map.mode)
		{
			case "measure1":
			case "measure2":
				shape.points.x.push(map.focusPos.x);
				shape.points.y.push(map.focusPos.y);
				shape.repaint(true);
				break;
		}
	}
	setZoomRect(map.zoomArea, map.focusPos.x, map.focusPos.y, 0, 0);
	map.zoomArea.style.cursor = map.image.style.cursor;
	return false;	
}

function onMouseMove(e)
{
	if (!e) var e = window.event;

	var pos = getCursorPos(e);
	pos.x = Math.min(Math.max(0, pos.x - map.left), map.image.width - 1);
	pos.y = Math.min(Math.max(0, pos.y - map.top), map.image.height - 1);
	switch (map.mode)
	{
		case "zoom": 
			var w = Math.abs(pos.x - map.focusPos.x);
			var h = Math.abs(pos.y - map.focusPos.y);
			setZoomRect(map.zoomArea, pos.x < map.focusPos.x ? pos.x : map.focusPos.x,
									pos.y < map.focusPos.y ? pos.y : map.focusPos.y, w, h); 
			map.zoomArea.style.display = "";
			break;
		case "pan":
			map.image.style.left = pos.x - map.focusPos.x + "px"; 
			map.image.style.top = pos.y - map.focusPos.y + "px";
			break;
		case "center":
		case "detect":
			map.focusPos = pos;		
			break;
		case "measure1":
		case "measure2":
			shape.points.x[shape.points.x.length - 1] = pos.x;
			shape.points.y[shape.points.y.length - 1] = pos.y;
			shape.repaint(true);
			break;
	}
	return false;	
}

function onMouseUp(e)
{
	if (!e) var e = window.event;
	var button = getMouseButton(e);
	document.onmousemove = null;
	document.onmouseup = null;
	switch (map.mode)
	{
		case "openmapp":
			if (button == "LEFT")
	  	{
				map.openp(map.focusPos.x, map.focusPos.y);
			}	
			break;
		case "detect":
			if (button == "LEFT")
	  	{
				map.detect(map.focusPos.x, map.focusPos.y);
			}	
			break;
	  case "zoom":
			if (button == "RIGHT")
				map.zoomOut(map.focusPos.x, map.focusPos.y);
			else if (button == "LEFT") {
				var zoomRect = getZoomRect(map.zoomArea);		  
				map.zoom(zoomRect.left, zoomRect.top, zoomRect.width, zoomRect.height);
			}
			break;  
	  case "pan":
			if (button == "LEFT")
	  	{
				map.pan(parseInt(map.image.style.left),	parseInt(map.image.style.top));
			}
	  	break;
	  case "center":
			if (button == "LEFT")
	  	{
				map.center(map.focusPos.x, map.focusPos.y);
			}	
			break;
		case "measure1":
		case "measure2":
			shape.repaint();
			if (button == "RIGHT")
				shape.clear();
			break;
		case "parinfo":
			if (button == "LEFT")	{
				window.open(map.getURL("ParInfoXY;" + map.focusPos.x + ";" + map.focusPos.y), 
					"ParInfo").focus();
			}	
			break;
	
	}
	map.zoomArea.style.display = "none";
	return false;	
}
