/* This notice must be untouched at all times.

AppForMap v. 0.4a
The latest version is available at
http://sourceforge.net/projects/appformap/

Copyright (c) 2003-2005 Martin Høgh. All rights reserved.
Created 17. 6. 2003 by Martin Høgh <mh@svaj.dk>

JacaScript functions for AppForMap.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See the GNU General Public License
at http://www.gnu.org/copyleft/gpl.html for more details.
*/
var count = 1000;
var divArray = [];
var textArray = [];
var XthePointArray = [];
var YthePointArray = [];
var XYthePointArray = [];
var measureArray = [];
var editArray=[];
var editKey=[];
var editShapeId=[];
var geoType;
var coords;
var startRubberX;
var startRubberY;
var width;
var height;
var jsGeomType;//this holds the geom type for the redline tool - point, line or polygon. Used for regenerating js graphic after zoom/pan
var ie=document.all;
var nn6=document.getElementById&&!document.all;
var isdrag=false;
var x,y;
var dobj;
var ajaxUrl;
var jg_doc_rectangle;
var rubberFlag;
var ajaxFlag;
var pointArrayRegen;
var http;
var pix_coord_array=[];
var coord_array=[];
var ele_array=[];
var time_array=[];
var speed_array=[];
var incline_array=[];
var feature=[];
var showPhoto=[];
var showWpt=[];

function submitGmap() {

	pointsStr = points.join("|");
	if (points.length < 2)
	{
		alert("At least 2 points!");
	}
	else
	{

		document.theForm.gmapPointArray.value = pointsStr;
		if (ajaxFlag)
		{
			ajaxUrl=ajax.serialize(document.getElementById("theForm"));
			sndReq(ajaxUrl,ajaxServer,handler_gmap);
			return false;
		}
		else
		{
			submit();
		}
	}

}
function addContact(contactid,reload)
{
	var callback =
	{
	  success:handler_add_contact,
	  failure:alert,
	  argument:['foo','bar']
	};
	param = "type=json&contactid=" + contactid + "&reload=" + reload;
	//sndReq(param,"servers/http_request_server_contact.phtml",handler_add_contact);
	var request = YAHOO.util.Connect.asyncRequest('POST', "servers/http_request_server_contact.phtml", callback, param);
}
function delContact(contactid)
{
	if (confirm("Are you sure!"))
	{
		param = "type=json&contactid=" + contactid;
		sndReq(param,"servers/http_request_server_delete_contact.phtml",handler_delete_contact);
	}
}

function checkTool(el)
{

	//if digitize then don't submit the form
	//alert(document.theForm.tool.value);
	if (document.theForm.tool.value == "postgisquery")
	document.theForm.pointArrayQuery.value = "rectangle";

	if (document.theForm.tool.value == "measure"
	|| (document.theForm.tool.value == "postgisquery" && getQueryTool() != "rectangle")
	|| (document.theForm.tool.value == "digitize" && (document.theForm.operation[0].checked)))
	{
		return false;
	}
	else
	{
		document.theForm.currState.value=currState;
		createFormArray();
		thePointArray = XYthePointArray.join("|");
		document.theForm.pointArrayRegen.value = thePointArray;
		document.theForm.jsGeomType.value = jsGeomType;


		if (ajaxFlag==1)
		{
			ajaxUrl=ajax.serialize(el);
			sndReq(ajaxUrl+"&map.x="+coords.left+"&map.y="+coords.top,ajaxServer,handler_AppForMap);
			return false;
		}
		else return(true);
	}
}
function onClickEvent(evt)
{
	evt = (evt) ? evt : ((window.event) ? event : null);
	var coords = getPositionedEventCoords(evt);
	if (document.theForm.tool.value == "digitize" && document.theForm.operation[1].checked)
	{
		submitEdit();
	}
	if (document.theForm.tool.value == "digitize" && document.theForm.operation[0].checked && !document.theForm.operation[1].checked)
	{
		if (!document.theForm.operation[0].checked)
		{
			alert("Digitize is not selected under PostGIS");
			shieldOff();
		}
		//Which kind of geometry?
		geometryType = document.theForm.theGeometry.value;
		//If no geometry is selected, then
		if (geometryType.length == 0)
		{
			alert("Select geometry.");
			shieldOff()
		}
		else
		{
			if (geometryType == "MULTIPOINT" || geometryType == "POINT" && document.theForm.operation[0].checked)
			{
				createDiv(coords);
				createDraw();
				if (document.theForm.alwaysDraw.checked)
				{
					DrawPoint();
					snapTolerance();
				}
			}
			else if ((geometryType == "MULTILINESTRING" || geometryType == "LINESTRING")
			&& document.theForm.operation[0].checked)
			{
				createDiv(coords);
				createDraw();
				if (document.theForm.alwaysDraw.checked)
				{
					DrawLine();
					snapTolerance();
				}
				calculateLength();
			}
			else if ((geometryType == "MULTIPOLYGON" || geometryType == "POLYGON")
			&& document.theForm.operation[0].checked)
			{
				createDiv(coords);
				createDraw();
				if (document.theForm.alwaysDraw.checked)
				{
					DrawPolygon();
					snapTolerance();
				}
				calculateLength();
			}
		}
	}
	if (document.theForm.tool.value == "measure") //Measure tool is selected
	{
		createDiv(coords);
		createDraw();
		DrawMeasurePolygon();
		calculateLength();
	}
	if (document.theForm.tool.value == "postgisquery" && getQueryTool() != "rectangle")
	{
		geometryType = getQueryTool();
		if (geometryType == "point" || geometryType == "feature")
		{
			removeDiv();
			createDiv(coords);
			createDraw();
			DrawPoint();
			submitPostgisQuery();
		}
		else if (geometryType == "line")
		{
			createDiv(coords);
			createDraw();
			DrawLine();
			calculateLength();
		}
		else if (geometryType == "polygon")
		{
			createDiv(coords);
			createDraw();
			DrawPolygon();
			calculateLength();
		}
	}
}
function submitEdit()
{
	createFormArray();
	numberOfPoints = XYthePointArray.length;
	thePointArray = XYthePointArray.join("|");
	document.theForm.pointArrayEdit.value = "rectangle";
	//submit();
}
function submitDigi()
{
	if (document.theForm.operation[1].checked)
	{
		submit();
		end;
	}
	//Which kind of geometry?
	geometryType = document.theForm.theGeometry.value;
	//If no geometry is selected, then
	if (geometryType.length == 0)
	{
		alert("Select geometry.");
		shieldOff();
	}
	else
	{
		if (geometryType == "MULTIPOINT" || geometryType == "POINT")
		{
			createFormArray();
			numberOfPoints = XYthePointArray.length;
			thePointArray = XYthePointArray.join("|");
			document.theForm.pointArray.value = thePointArray;
			submit();
		}
		else if (geometryType == "MULTILINESTRING" || geometryType == "LINESTRING")
		{
			createFormArray();
			numberOfPoints = XYthePointArray.length;
			thePointArray = XYthePointArray.join("|");
			if (numberOfPoints < 2)
			{
				thePointArray = "";
				alert("At least 2 points have to be entered.");
				shieldOff();
			}
			else
			{
				document.theForm.pointArray.value = thePointArray;
				submit();
			}
		}
		else if (geometryType == "MULTIPOLYGON" || geometryType == "POLYGON")
		{
			createFormArray();
			numberOfPoints = XYthePointArray.length;
			thePointArray = XYthePointArray.join("|");
			if (numberOfPoints < 3)
			{
				thePointArray = "";
				alert("At least 3 points have to be entered.");
				shieldOff();
			}
			else
			{
				document.theForm.pointArray.value = thePointArray;
				submit();
			}
		}
	}
}
function submitPostgisQuery()
{
	if (!ajaxFlag) shieldOn();
	var geometryType = getQueryTool();
	document.theForm.tool.value = "postgisquery";
	if (geometryType == "point")
	{
		createFormArray();
		numberOfPoints = XYthePointArray.length;
		thePointArray = XYthePointArray.join("|");
		document.theForm.pointArrayQuery.value = thePointArray;
		submit();
	}
	else if (geometryType == "feature")
	{
		createFormArray();
		numberOfPoints = XYthePointArray.length;
		thePointArray = XYthePointArray.join("|");
		document.theForm.pointArrayQuery.value = thePointArray;
		document.theForm.featurequery.value = "true";
		submit();
	}
	else if (geometryType == "line")
	{
		createFormArray();
		numberOfPoints = XYthePointArray.length;
		thePointArray = XYthePointArray.join("|");
		if (numberOfPoints < 2)
		{
			thePointArray = "";
			alert("At least 2 points have to be entered.");
			shieldOff();
		}
		else
		{
			document.theForm.pointArrayQuery.value = thePointArray;
			submit();
		}
	}
	else if (geometryType == "polygon")
	{
		createFormArray();
		numberOfPoints = XYthePointArray.length;
		thePointArray = XYthePointArray.join("|");
		if (numberOfPoints < 3)
		{
			thePointArray = "";
			alert("At least 3 points have to be entered.");
			shieldOff();
		}
		else
		{
			document.theForm.pointArrayQuery.value = thePointArray;
			submit();
		}
	}
	else if (geometryType == "rectangle")
	{
		document.theForm.pointArrayQuery.value = "rectangle";
		submit();
	}
}
function redrawQuery()
{
	thePointArray = document.theForm.pointArrayQueryRedraw.value;
	var XYthePointArray = thePointArray.split("|");
	redraw();
}
function DrawPolygon()
{
	jsGeomType="polygon";
	jg_doc.clear();
	jg_doc.setColor("#ff0000"); // red
	jg_doc.setStroke(1);
	jg_doc.drawPolygon(XthePointArray, YthePointArray);
	jg_doc.paint();
}
function DrawLine()
{
	jsGeomType="line";
	jg_doc.clear();
	jg_doc.setColor("#ff0000"); // red
	jg_doc.setStroke(1);
	jg_doc.drawPolyline(XthePointArray, YthePointArray);
	jg_doc.paint();
}
function DrawPoint()
{
	jg_doc.clear();
	jg_doc.paint();
}
function DrawMeasurePolygon()
{
	jsGeomType="measure";
	jg_doc.clear();
	jg_doc.setColor("#000000"); // black
	jg_doc.setStroke(10);
	jg_doc.setStroke(Stroke.DOTTED);
	jg_doc.drawPolygon(XthePointArray, YthePointArray);
	jg_doc.paint();
	jg_doc.setColor("#ff0000"); // red
	jg_doc.setStroke(1);
	jg_doc.drawPolyline(XthePointArray, YthePointArray);
	jg_doc.paint();

}
function popArray()
{
	count = count - 1;
	divArray.pop();
	dd.elements.pop();
	document.getElementById("draw2").removeChild(document.getElementById("draw2").lastChild);
	calculateLength();
	if (document.theForm.alwaysDraw.checked)
	{
		redraw();
	}
}
function spliceArray()
{
	var node = document.theForm.node.value;
	document.getElementById("draw2").removeChild(document.getElementById("draw2").children[node - 1]);
}
function redraw()
{
	createDraw();
	var geometryType = document.theForm.theGeometry.value;
	var geometryType2 = getQueryTool();
	if ((geometryType == "MULTIPOLYGON" || geometryType == "POLYGON") && document.theForm.tool.value == "digitize")
	{
		calculateLength();
		DrawPolygon();
		snapTolerance();
	}
	else if ((geometryType == "MULTILINESTRING" || geometryType == "LINESTRING")
	&& document.theForm.tool.value == "digitize")
	{
		calculateLength();
		DrawLine();
		snapTolerance();
	}
	else if ((geometryType == "MULTIPOINT" || geometryType == "POINT") && document.theForm.tool.value == "digitize")
	{
		jg_doc.clear(); //clear circles
		snapTolerance();
	}
	else if (document.theForm.tool.value == "measure")
	{
		calculateLength();
		DrawMeasurePolygon();
	}
	else if (geometryType2 == "polygon" && document.theForm.tool.value == "postgisquery")
	{
		calculateLength();
		DrawPolygon();
	}
	else if (geometryType2 == "line" && document.theForm.tool.value == "postgisquery")
	{
		calculateLength();
		DrawLine();
	}
	else if (jsGeomType == "polygon")
	{
		calculateLength();
		DrawPolygon();
	}
	else if (jsGeomType == "line")
	{
		calculateLength();
		DrawLine();
	}
	else if (jsGeomType == "measure")
	{
		calculateLength();
		DrawMeasurePolygon();
	}

}
function createDiv(coords)
{
	count = count + 1;
	if (count > 1001);
	YAHOO.example.container.panel2.show();
	//ADD_DHTML("measurebox");


	divArray[count] = document.createElement("div");
	textArray[count] = document.createTextNode(count - 1000);
	divArray[count].style.left = coords.left;
	divArray[count].style.top = coords.top;
	divArray[count].style.padding = "0px";
	divArray[count].style.width = "10px";
	divArray[count].style.height = "10px";
	divArray[count].style.position = "absolute";
	divArray[count].style.border = "solid black 1px";
	divArray[count].style.backgroundColor = "#ffffff";
	divArray[count].style.visibility = "visible";
	divArray[count].style.fontSize = "9px";
	divArray[count].style.textAlign = "center";
	divArray[count].style.verticalAlign = "middle";
	divArray[count].appendChild(textArray[count]);
	divArray[count].onmouseup=redraw;
	divArray[count].ondblclick=rightMouseClick;
	divArray[count].id= ("node" + count);
	document.getElementById("draw2").appendChild(divArray[count]);
	ADD_DHTML("node" + count);
}
function createDraw()
{
	XthePointArray = [];
	YthePointArray = [];
	for (var i = 1001; i <= count; i++)
	{
		var x = dd.elements["node" + i].x;
		var y = dd.elements["node" + i].y;
		var elementPos = getElementPosition("draw");
		x = x - elementPos.left;
		y = y - elementPos.top;
		XthePointArray = XthePointArray.concat(x);
		YthePointArray = YthePointArray.concat(y);
		var geometryType = getQueryTool();
		if (geometryType=="line"){
			if (i>1001) document.getElementById("showPostGISsearch").style.display = "inline";
			else document.getElementById("showPostGISsearch").style.display = "none";
		}
		if (geometryType=="polygon"){
			if (i>1002) document.getElementById("showPostGISsearch").style.display = "inline";
			else document.getElementById("showPostGISsearch").style.display = "none";
		}
	}
}
function createFormArray()
{
	for (var i = 1001; i <= count; i++)
	{
		var newXY = XthePointArray[i - 1001] + "," + YthePointArray[i - 1001];
		XYthePointArray = XYthePointArray.concat(newXY);
	}
}
function snapTolerance()
{
	for (var i = 1001; i <= count; i++)
	{
		var x = dd.elements["node" + i].x;
		var y = dd.elements["node" + i].y;
		var elementPos = getElementPosition("draw");
		x = x - elementPos.left;
		y = y - elementPos.top;
		var width = document.theForm.snapTolerance.value;
		x = x - (width)
		y = y - (width)
		jg_doc.setColor("#101010"); // red
		jg_doc.setStroke(3);
		jg_doc.setStroke(Stroke.DOTTED);
		jg_doc.drawEllipse(x, y, (width * 2), (width * 2));
		jg_doc.paint();
	}
}
function calculateLength()
{
	var text = "</b><table class='postgis' style='color:black' border=0 cellpadding=1><tr><td>"+languageTextNodes+"</td><td>"+languageTextLength+"</td></tr>";
	var totalDistance = 0;
	var distance = [];
	var AreaByCoordinates = 0;
	var x1=0
	var x2=0
	var y1=0
	var y2=0
	for (var i = 1001; i <= count; i++)
	{
		var xStart = pixelToProjX(dd.elements["node1001"].x);
		var yStart = pixelToProjY(dd.elements["node1001"].y);
		x1 = pixelToProjX(dd.elements["node" + i].x);
		y1 = pixelToProjY(dd.elements["node" + i].y);
		if (i > 1001)
		{
			text = text + "<tr><td align='center'>" + (i - 1001) + " - " + (i - 1000) + "</td>";
			x2 = pixelToProjX(dd.elements["node" + (i - 1)].x);
			y2 = pixelToProjY(dd.elements["node" + (i - 1)].y);
			xdiff = x1 - x2;
			ydiff = y1 - y2;
			distance[i] = Math.round(Math.sqrt(Math.pow(xdiff, 2) + Math.pow(ydiff, 2)));
			totalDistance = totalDistance + distance[i];
			text = text + "<td align='center'>" + distance[i] + "</td></tr>";

			/*
			n
			___
			1  \
			= ___  \   (x  -  x ) (y  +  y )
			/     i-1   i    i-1   i
			2  /__

			i = 1
			*/

			AreaByCoordinates = AreaByCoordinates + (x2 - x1) * (y2 + y1)
		}
	}
	AreaByCoordinates = AreaByCoordinates+(x1-xStart)*(y1+yStart);
	AreaByCoordinates= Math.round((AreaByCoordinates/2),2);
	if (AreaByCoordinates<0) AreaByCoordinates=AreaByCoordinates*-1;
	text = text + "<tr><td align='center'>"+languageTextTotal+"</td><td align='center'>" + totalDistance + "</td></tr>";
	text = text + "<tr><td align='center'>"+languageTextArea+"</td><td align='center'>" + AreaByCoordinates + "</td></tr></table>";
	document.getElementById("measurebox").innerHTML = text;
	//document.getElementById("draw1.5").innerHTML = text;

}
function removeDiv()
{
	for (var i = 1001; i <= count; i++)
	{
		divArray.pop();
		document.getElementById("draw2").removeChild(document.getElementById("draw2").lastChild);
	}
	jg_doc.clear();
	dd.elements=[];
	count = 1000;
	calculateLength();
	//document.getElementById("measurebox").innerHTML = "";
	document.getElementById("measurebox").style.visibility = "hidden";
}
function startRubber(evt)
{
	if (document.theForm.tool.value == "zoomin"
	|| (document.theForm.tool.value == "postgisquery" && getQueryTool() == "rectangle")
	|| (document.theForm.tool.value == "digitize" && document.theForm.operation[1].checked))
	{
		rubberFlag=1;
		evt = (evt) ? evt : event;
		var coords = getPositionedEventCoords(evt);
		startRubberX = coords.left;
		startRubberY = coords.top;
		if ((document.theForm.tool.value == "postgisquery" && getQueryTool() == "rectangle"))
		jg_doc_rectangle.setColor("#ff0000")  //red
		if (document.theForm.tool.value == "zoomin")
		jg_doc_rectangle.setColor("#000000"); // black
		jg_doc_rectangle.setStroke(1);
	}
	/*	if (pan= "pdf")
	{

	evt = (evt) ? evt : event;
	var coords = getPositionedEventCoords(evt);
	mouseDownX = coords.left;
	mouseDownY = coords.top;
	document.theForm.downX.value=mouseDownX;
	document.theForm.downY.value=mouseDownY;
	//alert(mouseDownX+","+mouseDownY);
	}*/
}
function moveRubber(evt)
{
	if ((document.theForm.tool.value == "zoomin"
	|| (document.theForm.tool.value == "postgisquery" && getQueryTool() == "rectangle")
	|| (document.theForm.tool.value == "digitize" && document.theForm.operation[1].checked)) && rubberFlag==1)
	{
		evt = (evt) ? evt : event;
		jg_doc_rectangle.clear();
		coords = getPositionedEventCoords(evt);
		x = coords.left - startRubberX;
		y = coords.top - startRubberY;
		if (x > 0 && y > 0)
		{
			jg_doc_rectangle.drawRect(startRubberX, startRubberY, x, y);
		}
		if (x < 0 && y > 0)
		{
			jg_doc_rectangle.drawRect(x + startRubberX, startRubberY, (startRubberX - x) - startRubberX, y);
		}
		if (x > 0 && y < 0)
		{
			jg_doc_rectangle.drawRect(startRubberX, y + startRubberY, x, (startRubberY - y) - startRubberY);
		}
		if (x < 0 && y < 0)
		{
			jg_doc_rectangle.drawRect(x + startRubberX, y + startRubberY, (startRubberX - x) - startRubberX,
			(startRubberY - y) - startRubberY);
		}
		if (1==2)
		{
			d = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
			if (x > 0 && y > 0)
			{
				jg_doc.drawEllipse(startRubberX - (d/2), startRubberY - (d/2), (d), (d));
			}

			if (x < 0 && y > 0)
			{
				jg_doc.drawEllipse(startRubberX - (d/2), startRubberY - (d/2), (d)/1.42, (d)/1.42);
			}

			if (x > 0 && y < 0)
			{
				jg_doc.drawEllipse(startRubberX, x + startRubberY, x, (startRubberY - x) - startRubberY);
			}

			if (x < 0 && y < 0)
			{
				jg_doc.drawEllipse(startRubberX - (d/2), startRubberY - (d/2), (d)/1.42, (d)/1.42);
			}
		}
		//jg_doc.paint();
		jg_doc_rectangle.paint();
		document.theForm.RubberWidth.value = x;
		document.theForm.RubberHeight.value = y;
	}
	/*   if (pan=="pdf")
	{  //alert("");
	evt = (evt) ? evt : event;
	coords = getPositionedEventCoords(evt);
	x = coords.left - mouseDownX;
	y = coords.top - mouseDownY;
	document.getElementById("map").style.left=x;
	document.getElementById("map").style.top=y;

	}*/
}
function stopRubber(evt)
{
	if (document.theForm.tool.value == "zoomin"
	|| (document.theForm.tool.value == "postgisquery" && getQueryTool() == "rectangle")
	|| (document.theForm.tool.value == "digitize" && document.theForm.operation[1].checked))
	{
		evt = (evt) ? evt : ((window.event) ? event : null);
		rubberFlag=null;
	}
}
function abortRubber()
{
	if (document.all && document.theForm.tool.value == "zoomin")
	{
		//jg_doc_rectangle.clear();
	}
}
function mouseover(el)
{
	if (el.className == "button")
	el.className = "raised";
}
function mouseout(el)
{
	if (el.className == "raised")
	el.className = "button";
}
function resetButtons(button)
{
	if (button!="zoomin") document.getElementById("zoomin").className = "button";
	if (button!="zoomout") document.getElementById("zoomout").className = "button";
	if (button!="pan") document.getElementById("pan").className = "button";
	if (button!="info") document.getElementById("info").className = "button";
	if (button!="postgisquery") document.getElementById("postgisquery").className = "button";
	if (button!="measure") document.getElementById("measure").className = "button";
	if (button!="digitize") document.getElementById("digitize").className = "button";
}
function mousedown(el)
{
	if (el.id == "zoomin")
	{
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		zoomin();
	}
	if (el.id == "zoomout")
	{
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		zoomout();
	}
	if (el.id == "pan")
	{
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		pan();
	}
	if (el.id == "postgisquery")
	{
		//if (avancedSearch==true) syn('query',1);
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		postgisquery();
	}
	if (el.id == "info")
	{
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		info();
	}
	if (el.id == "refresh")
	{
		el.className = "pressed";
		document.theForm.updateIsClicked.value=1;
		update();

	}
	if (el.id == "measure")
	{
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		measure();
	}
	if (el.id == "digitize")
	{
		syn('digi',1);
		resetButtons(el.id);
		if (el.className == "raised")
		el.className = "pressed";
		digitize();
	}
	if (el.id == "remove")
	{
		el.className = "pressed";
		removeDiv();
		interuptEdit();
	}
	if (el.id == "printer")
	{
		el.className = "pressed";
	}
	if (el.id == "minimize")
	{
		el.className = "pressed";
	}
	if (el.id == "pdf")
	{
		el.className = "pressed";
	}
	if (el.id == "expandAll")
	{
		el.className = "pressed";
		expandAll();
	}
	if (el.id == "collapseAll")
	{
		el.className = "pressed";
		collapseAll();
	}
	if (el.id == "track")
	{
		el.className = "pressed";
		track();
	}
}
function mouseup(el)
{
	el.className = "raised";
	if (el.id == "minimize")
	{
		switchToolbars();
	}
	if (el.id == "printer")
	{
		printVersion();
	}
	if (el.id == "pdf")
	{
		pdfVersion();
	}
}
function zoomin()
{
	document.theForm.tool.value = "zoomin";
	//True if a feature is selected for editing
	if (editKey!="") confirmInteruptEdit();
}
function zoomout()
{
	document.theForm.tool.value = "zoomout";
	//True if a feature is selected for editing
	if (editKey!="") confirmInteruptEdit();
}
function pan()
{
	document.theForm.tool.value = "pan";
	//True if a feature is selected for editing
	if (editKey!="") confirmInteruptEdit();
}
function info()
{
	removeDiv();
	interuptEdit();
	document.theForm.tool.value = "info";
}
function postgisquery()
{
	//If coming from an other tool with red lining available then remove the js and divs and interupt editing
	if (document.theForm.tool.value == "measure" ||document.theForm.tool.value == "digitize")
	{
		interuptEdit();
		removeDiv();
	}
	document.theForm.tool.value = "postgisquery";
}
function measure()
{
	//If coming from an other tool with red lining available then remove the js and divs and interupt editing
	if (document.theForm.tool.value == "digitize" || document.theForm.tool.value == "postgisquery")
	{
		interuptEdit();
		removeDiv();
	}
	document.theForm.tool.value = "measure";
}
function digitize()
{
	//If coming from an other tool with red lining available then remove the js and divs. Do not interupt editing in the case!
	if (document.theForm.tool.value == "measure" || document.theForm.tool.value == "postgisquery") removeDiv();
	document.theForm.tool.value = "digitize";
	redraw();
}
function spatialsearch()
{
	removeDiv();
	interuptEdit();
	document.theForm.search.value = "true";
	update();
}
function shieldOff()
{
	 YAHOO.example.container.wait.hide();
}
function shieldOn()
{
	YAHOO.example.container.wait.show();
}
function confirmInteruptEdit()
{
	if(confirm(languageTextInterRuptDigi))
	{
		removeDiv();
		interuptEdit();
	}
	else
	{
		this.id = "digitize";
		mousedown(this);
		return(false);
	}
}
function interuptEdit()
{
	editKey=false;
	editShapeId=false;
	document.theForm.shapeId.value="";
	document.theForm.editKey.value="";
	document.getElementById("editInfo").innerHTML = "";
}
function getQueryTool()
{
	if (document.theForm.pg_query_type[0].checked)
	geometryType = "point";
	else if (document.theForm.pg_query_type[1].checked)
	geometryType = "line";
	else if (document.theForm.pg_query_type[2].checked)
	geometryType = "rectangle";
	else if (document.theForm.pg_query_type[3].checked)
	geometryType = "polygon";
	else if (document.theForm.pg_query_type[4].checked)
	geometryType = "feature";
	return (geometryType);
}

function regenerateGeometry(pointArray)
{
	removeDiv();
	var coords = pointArray.split("|");
	for (var i = 0; i < coords.length; i++)
	{
		oneCoord = coords[i].split(",");
		coords.left = oneCoord[0];
		coords.top = oneCoord[1];
		createDiv(coords);
	}
	redraw();
}
function featureEdit(geometryArray,editKey,editShapeId,tableName,geoType)
{
	var geoType=geoType;
	numShape=geometryArray.length;
	for (i = 0; i <= numShape; i++) {
		if (i != numShape)
		{
			regenerateGeometry(geometryArray[i]);
			if (geoType=="MULTIPOLYGON" || geoType=="POLYGON") popArray();
			var editInfo='Editing:'+tableName+'<br>Gid:'+editKey+'<br>Shape id:'+editShapeId[i];
			document.getElementById("editInfo").innerHTML = editInfo;
			var u=editShapeId[i];
			document.theForm.shapeId.value=u;
			if (confirm('Edit table:'+tableName+' Key:'+editKey+' Shape id:'+u+' Number of shapes: '+numShape)) {document.theForm.operation[0].checked=true;break;}
			else removeDiv();
		}
		else
		{
			u++;
			var editInfo='Editing:'+tableName+'<br>Gid:'+editKey+'<br>Shape id:'+u+' (new)';
			document.theForm.shapeId.value=u;
			document.getElementById("editInfo").innerHTML = editInfo;
			alert(languageTextAddShape);
			document.theForm.operation[0].checked=true;
		}
	}
	document.theForm.editKey.value=editKey;
}
function rightMouseClick(e)
{
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
	targ = targ.parentNode;
	index=targ.id.substr(4,8);
	index=index-1001;
	if (confirm(languageTextDeleteNode))
	{
		dd.elements.splice(index,1);
		recreateDiv();
		redraw();
	}
	else if (confirm(languageTextCloneNode))
	{
		var newDiv;
		dd.elements.splice(index,0,newDiv);
		recreateDiv();
		redraw();
	}
	else return(false);
}
function tableCheck(tableName,el)
{
	var tableName;
	if ((el.checked) || el=="check") document.getElementById(tableName).checked=true;
	else document.getElementById(tableName).checked=false;
}
function deleteFeature()
{
	if (confirm(languageTextDeleteFeature)) {
		document.theForm.deleteobject.value = 1;
		document.theForm.deleteobjectkey.value = editKey;
		update();}
		else return false;
}
function loaded()
{
	document.getElementById("crs_name").innerHTML = document.theForm.crsName.value;
	initExpMenu();
	shieldOff();
	//document.getElementById("frame").style.display="inline";
	
		// disable the feature deletebutton if not a feature is selected for editing
		if (editKey=="") document.theForm.deleteButton.disabled=true;
		else
		{
			document.theForm.deleteButton.disabled=false;
			// Attach event handler
			document.theForm.deleteButton.onclick=deleteFeature;
		}

}
function update()
{
	if (!ajaxFlag) shieldOn();
	removeDiv();
	interuptEdit();
	document.theForm.pointArray.value="";
	document.theForm.pointArrayQuery.value="";
	submit();
}
function submit()
{
	//alert("submit");
	document.theForm.currState.value=currState;
	document.theForm.jsGeomType.value = jsGeomType;
	if (ajaxFlag)
	{
		if (undefined!==window.thePointArray) document.theForm.pointArrayRegen.value = thePointArray;
		ajaxUrl=ajax.serialize(document.getElementById("theForm"));
		sndReq(ajaxUrl,ajaxServer,handler_AppForMap);
	} else
	{

		document.theForm.submit();
	}
}
function submitWithAnotherName()
{
	//alert("submit");
	document.theForm.currState.value=currState;
	document.theForm.jsGeomType.value = jsGeomType;
	if (ajaxFlag)
	{
		//document.theForm.pointArrayRegen.value = thePointArray;
		ajaxUrl=ajax.serialize(document.getElementById("theForm"));
		sndReq(ajaxUrl,ajaxServer,handler_AppForMap);
	} else
	{

		document.theForm.submit();
	}
}
function reload()
{
	document.theForm.currState.value=currState;
	document.theForm.jsGeomType.value = jsGeomType;
	//alert("reload");
	//ajaxFlag=0;
	document.theForm.submit();
}
function URLDecode(psEncodeString)
{
	// Create a regular expression to search all +s in the string
	var lsRegExp = /\+/g;
	// Return the decoded string
	return unescape(String(psEncodeString).replace(lsRegExp, " "));
}
function recreateDiv()
{
	u=dd.elements.length;
	var left=[];
	var top=[];
	for (var i = 0; i < u; i++)
	{
		if (!dd.elements[i])
		{
			left[i]=dd.elements[i+1].x;
			top[i]=dd.elements[i+1].y;
		}
		else
		{
			left[i]=dd.elements[i].x;
			top[i]=dd.elements[i].y;
		}
		var elementPos = getElementPosition("draw");
		left[i] = left[i] - elementPos.left;
		top[i] = top[i] - elementPos.top;
	}
	removeDiv();
	for (var i = 0; i < u; i++)
	{
		coords.left=left[i];
		coords.top=top[i];
		createDiv(coords)
	}
}
function showPositionProj(evt) {
	coords = getPositionedEventCoords(evt);
	x = coords.left;
	y = coords.top;
	document.getElementById("pos").innerHTML = Math.round(pixelToProjX(x)) + " , " + Math.round(pixelToProjY(y));
}
function pixelToProjX(x) {
	if (document.theForm.crsUnit.value=="xy") geowidth = document.theForm.maxx.value - document.theForm.minx.value;
	else geowidth = document.theForm.dmaxx.value - document.theForm.dminx.value;
	pixlength = geowidth / document.theForm.mapWidth.value;
	if (document.theForm.crsUnit.value=="xy") geoCoord = document.theForm.minx.value - x * pixlength;
	else geoCoord = document.theForm.dminx.value - x * pixlength;
	return (geoCoord);
}
function pixelToProjY(y) {
	if (document.theForm.crsUnit.value=="xy")
	geowidth = document.theForm.maxx.value - document.theForm.minx.value;
	else
	geowidth = document.theForm.dmaxx.value - document.theForm.dminx.value;
	pixlength = geowidth / document.theForm.mapWidth.value;
	if (document.theForm.crsUnit.value=="xy")
	geoCoord = document.theForm.maxy.value - y * pixlength;
	else
	geoCoord = document.theForm.dmaxy.value - y * pixlength;
	return (geoCoord);
}
function setSearchFormNyc(gid,table)
{
	document.theForm.search.value = table;
	document.theForm.trkGid.value = gid;
	update();
}
function loadFeatureInGmap(gid,table)
{
	shieldOn();
	if (table=="trk") {
	feature[gid] = new GGeoXml("http://www.toposhare.org/services/routes/kml_single?permalink="+gid, function()
	{
		if (feature[gid].loadedCorrectly())
		{
			feature[gid].gotoDefaultViewport(map);
			shieldOff();
		}
	});
	map.addOverlay(feature[gid]);
	}
	// Only to get 'mode' param
	param = ajax.serialize(document.getElementById("theForm"));
	
	sndReq(param+"&featureInGmap="+table+"&trkGid="+gid,"servers/http_request_server_load_feature_gmap.phtml",handler_gmap);
	e = YAHOO.util.Dom.getElementsByClassName("unload"+gid);
	for(i=0;i<e.length;i++)
	{
		e[i].style.display = "inline";
	}
	e = YAHOO.util.Dom.getElementsByClassName("load"+gid);
	for(i=0;i<e.length;i++)
	{
		e[i].style.display = "none";
	}
					
}
function unLoadFeatureInGmap(gid,table)
{
	if (table=="trk")
	{
		map.removeOverlay(feature[gid]);
		document.getElementById("playerContainer").innerHTML="";
		document.getElementById("wpt_markup").innerHTML="";
		document.getElementById("photo_markup").innerHTML="";
		document.getElementById("tabs").style.display="none";
	}
	e = YAHOO.util.Dom.getElementsByClassName("unload"+gid);
	for(i=0;i<e.length;i++)
	{
		e[i].style.display = "none";
	}
	e = YAHOO.util.Dom.getElementsByClassName("load"+gid);
	for(i=0;i<e.length;i++)
	{
		e[i].style.display = "inline";
	}
}
function shareWptChange(gid)
{
	sndReq("&gid="+gid+"&type=json","servers/http_share_wpt.php",handler_check);
}
function sharePhotoChange(id)
{
	sndReq("&id="+id,"http_share_photo.php",handler_check);
}
function deleteWpt(gid)
{
	if(confirm("Are you sure?"))
	{
		sndReq("&gid="+gid+"&type=json","servers/http_delete_wpt.php",handler_delete_wpt);
	}

}
function deletePhoto(id)
{
	if(confirm("Are you sure?"))
	{
		sndReq("&id="+id+"&type=json","servers/http_delete_photo.php",handler_delete_photo);
	}

}
function zoomToFeatureInMap(gid,table,mode)
{
	str="";
	if (mode=="public") {
		str="&public=true";
		document.getElementById("sharedroutemap").src="http://cal.mapuse.net/client_simple.phtml?search="+table+"&trkGid="+gid+str;
	}
	if (mode=="privat") alert("Soon you will be taken to 'My map' zoomed to the route");
}
function mToMi(meters)
{
	miles=meters*0.0006214;
	return(miles);
}
function round(x)
{
	x = Math.round(x * 100) / 100;
	return(x);
}
function mouseDown(evt)
{
	evt = (evt) ? evt : event;
	var coords = getPositionedEventCoords(evt);
	mouseDownX = coords.left;
	mouseDownY = coords.top;
	document.theForm.downX.value=mouseDownX;
	document.theForm.downY.value=mouseDownY;
}
function dragElement(e)
{
	if (isdrag)
	{
		dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
		dobj.style.top  = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
		return false;
	}
}

function selectDragElement(e)
{
	var fobj       = nn6 ? e.target : event.srcElement;
	var topelement = nn6 ? "HTML" : "BODY";

	while (fobj.tagName != topelement && fobj.className != "dragme")
	{
		fobj = nn6 ? fobj.parentNode : fobj.parentElement;
	}

	if (fobj.className=="dragme")
	{
		isdrag = true;
		dobj = fobj;
		tx = parseInt(dobj.style.left+0);
		ty = parseInt(dobj.style.top+0);
		x = nn6 ? e.clientX : event.clientX;
		y = nn6 ? e.clientY : event.clientY;
		document.onmousemove=dragElement;
		return false;
	}
}
function stopDrag()
{
	isdrag=false;
	//alert(dobj.style.left+","+dobj.style.top);
	document.theForm.mapDragX.value=dobj.style.left;
	document.theForm.mapDragY.value=dobj.style.top;
	document.theForm.tool.value="dragpan";
}
function switchToolbars()
{
	if (minimized==0) minimizeToolbar();
	else if (minimized==1) maximizeToolbar();
}
function minimizeToolbar()
{
	document.getElementById("secondary_window").style.display="none";
	document.getElementById("main_window").style.top="0";
	document.getElementById("main_window").style.left="0";
	document.getElementById("secondarytabs").style.display="none";
	document.getElementById("maintabs").style.display="none";
	minimized=1;
	document.theForm.minimized.value=minimized;
}
function maximizeToolbar()
{
	document.getElementById("secondary_window").style.display="inline";
	document.getElementById("main_window").style.top="19";
	document.getElementById("main_window").style.left="300";
	document.getElementById("main_window").style.display="inline";
	document.getElementById("secondarytabs").style.display="inline";
	document.getElementById("maintabs").style.display="inline";
	minimized=0;
	document.theForm.minimized.value=minimized;
}

function afterInsert(gid)
{
	//alert(gid);
	window.open(baseUrl+"/gotoroute.php?gid="+gid,"gotoroute","menubar=0,resizable=0,width=350,height=250");
}

function WMSCreateMap(name, copyright, baseUrl, layer, format, transparent, minResolution, maxResolution, extraTileLayers, urlArg)
{
	var tileLayer = new GTileLayer(new GCopyrightCollection(copyright), minResolution, maxResolution);
	tileLayer.baseUrl = baseUrl;
	tileLayer.layer = layer;
	tileLayer.format = format;
	tileLayer.transparent = transparent;
	tileLayer.getTileUrl = WMSGetTileUrl;
	tileLayer.getCopyright = function(){
		return {prefix:'', copyrightTexts:[copyright]};
	};
	var tileLayers=[];
	for(var i in extraTileLayers) tileLayers.push(extraTileLayers[i]);
	tileLayers.push(tileLayer);
	return new GMapType(tileLayers, G_SATELLITE_MAP.getProjection(), name, {errorMessage:"",urlArg:'o'});
}
function WMSGetTileUrl(tile, zoom)
{
	var southWestPixel = new GPoint(tile.x * 256, (tile.y+1) * 256);
	var northEastPixel = new GPoint((tile.x+1) * 256, tile.y*256);
	var southWestCoords = G_NORMAL_MAP.getProjection().fromPixelToLatLng(southWestPixel,zoom);
	var northEastCoords = G_NORMAL_MAP.getProjection().fromPixelToLatLng(northEastPixel,zoom);
	var bbox = southWestCoords.lng() + ',' + southWestCoords.lat() + ',' + northEastCoords.lng() + ',' + northEastCoords.lat();
	var transparency = this.transparent?'&TRANSPARENT=TRUE':'';
	return this.baseUrl+'?VERSION=1.1.1&REQUEST=GetMap&LAYERS='+this.layer+'&STYLES=&SRS=EPSG:4326&BBOX='+bbox+'&WIDTH=256&HEIGHT=256&FORMAT='+this.format+'&BGCOLOR=0xCCCCCC&EXCEPTIONS=INIMAGE'+transparency;
}
// Functions for filter select
function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
				return;
			} else {
				//alert(point.x+" "+point.y)
				disableForm([document.filter1.statefilter,document.filter1.provfilter,document.filter1.placefilter]);
				document.filter1.coord.value=point.x+" "+point.y;
				document.filter1.submit();
			}
		}
		);
	}
}
function showPlace(place)
{
	alert('Place search coming soon');
}

function disableForm(e)
{
	for(i=0;i<e.length;i++)
	{
		e[i].disabled = true;
	}
}


function enableForm(e)
{
	for(i=0;i<e.length;i++)
	{
		e[i].disabled = false;
	}
}

function closeToUserSwitch(e)
{
	if (e.checked==true)
	{
		disableForm([document.filter1.adressefilter,document.filter1.statefilter,document.filter1.provfilter,document.filter1.adressebutton]);
	}
	else
	{
		enableForm([document.filter1.adressefilter,document.filter1.statefilter,document.filter1.provfilter,document.filter1.adressebutton]);
	}
}

function checkForSize(e)
{
	var counter = 0;
	for(i=0;i<e.options.length;i++)
	{
		if(e.options[i].selected) counter++;
	}
	return counter;
}
function getProvs()
{
	action=ajax.serialize(document.getElementById("filter1"));
	sndReq(action,"servers/http_request_server_filter.phtml",handler_filter);
}

function $(e){if(typeof e=='string')e=document.getElementById(e);return e};
function collect(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n};

ajax={};
ajax.serialize=function(f){var g=function(n){return f.getElementsByTagName(n)};var nv=function(e){if(e.name)return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);else return ''};var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');};


function createRequestObject() {
	var ro;
	// Mozilla, Safari,...
	if (window.XMLHttpRequest) {
		ro = new XMLHttpRequest();
		if (ro.overrideMimeType) {
			ro.overrideMimeType('text/xml');
			// See note below about this line
		}
		// IE
	} else if (window.ActiveXObject) {
		try {
			ro = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				ro = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!ro) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	return ro;
}
function sndReq(param,server,handler) {
	//location.href = server+"?"+action; //uncomment if you need for debugging
	http = createRequestObject();
	http.open('POST', server, true);
	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	http.onreadystatechange = handler;
	http.send(param);
}

function updateisclicked() {
	document.theForm.updateIsClicked.value=1;
}
handler_AppForMap=function() {
	if (http.readyState == 1) {
		document.getElementById("loadStatus").style.display="inline";
	}
	if(http.readyState == 4){
		document.getElementById("loadStatus").style.display="none";
		if (http.status == 200) {
			var response = http.responseXML.documentElement;

			mapimageUrl=response.getElementsByTagName('mapimageUrl')[0].firstChild.data;

			overlayMapimageUrl=response.getElementsByTagName('overlayMapimageUrl')[0].firstChild.data;

			document.theForm.pointArray.value = "";
			thePointArray = "";

			maxx=response.getElementsByTagName('maxx')[0].firstChild.data;
			minx=response.getElementsByTagName('minx')[0].firstChild.data;
			maxy=response.getElementsByTagName('maxy')[0].firstChild.data;
			miny=response.getElementsByTagName('miny')[0].firstChild.data;

			dmaxx=response.getElementsByTagName('dmaxx')[0].firstChild.data;
			dminx=response.getElementsByTagName('dminx')[0].firstChild.data;
			dmaxy=response.getElementsByTagName('dmaxy')[0].firstChild.data;
			dminy=response.getElementsByTagName('dminy')[0].firstChild.data;

			document.theForm.maxx.value=maxx;
			document.theForm.minx.value=minx;
			document.theForm.maxy.value=maxy;
			document.theForm.miny.value=miny;

			document.theForm.dmaxx.value=dmaxx;
			document.theForm.dminx.value=dminx;
			document.theForm.dmaxy.value=dmaxy;
			document.theForm.dminy.value=dminy;

			units=response.getElementsByTagName('units')[0].firstChild.data;
			document.theForm.crsUnit.value=units;

			map_x=response.getElementsByTagName('map_x')[0].firstChild.data;
			document.theForm.clickX.value=map_x;


			map_y=response.getElementsByTagName('map_y')[0].firstChild.data;
			document.theForm.clickY.value=map_y;

			rubberwidth=response.getElementsByTagName('rubberwidth')[0].firstChild.data;
			if (rubberwidth!="none")
			{
				document.theForm.RubberWidthCache.value=rubberwidth;
			}
			else document.theForm.RubberWidthCache.value="";

			rubberheight=response.getElementsByTagName('rubberheight')[0].firstChild.data;
			if (rubberheight!="none")
			{
				document.theForm.RubberHeightCache.value=rubberheight;
			}

			centerx=response.getElementsByTagName('centerx')[0].firstChild.data;
			document.theForm.centerX.value=centerx;

			centery=response.getElementsByTagName('centery')[0].firstChild.data;
			document.theForm.centerY.value=centery;

			scale=response.getElementsByTagName('scale')[0].firstChild.data;
			document.theForm.scale.value=scale;

			proj=response.getElementsByTagName('proj')[0].firstChild.data;
			document.theForm.proj.value=proj;

			if (mapimageUrl!="none")
			{
				document.getElementById("draw0").innerHTML="<img name src='"+mapimageUrl+"'>";
			}
			document.getElementById("overlay_mapimage").innerHTML="<img name src='"+overlayMapimageUrl+"'>";

			refmapimageUrl=response.getElementsByTagName('refmapimageUrl')[0].firstChild.data;
			if (refmapimageUrl!="none")
			{
				document.getElementById("refmap").innerHTML="<img name src='"+refmapimageUrl+"'>";
			}

			legendUrl=response.getElementsByTagName('legendUrl')[0].firstChild.data;
			if (legendUrl!="none")
			{
				document.getElementById("legendImage").innerHTML="<img name src='"+legendUrl+"'>";
			}

			pointArrayRegen=response.getElementsByTagName('pointArrayRegen')[0].firstChild.data;

			digiGeom=response.getElementsByTagName('digiGeom')[0].firstChild.data;

			dump=response.getElementsByTagName('dump')[0].firstChild.data;

			removegraphic=response.getElementsByTagName('removegraphic')[0].firstChild.data;

			crs=response.getElementsByTagName('crs')[0].firstChild.data;
			document.getElementById("crs_name").innerHTML=crs;
			document.theForm.crsName.value=crs;

			crsDialog=response.getElementsByTagName('crsDialog')[0].firstChild.data;
			document.getElementById("crs_dialog").innerHTML=crsDialog;

			exportDialog=response.getElementsByTagName('exportDialog')[0].firstChild.data;
			//document.getElementById("export_dialog").innerHTML=exportDialog;

			editArray=response.getElementsByTagName('editArray')[0].firstChild.data;
			gid=response.getElementsByTagName('gid')[0].firstChild.data;
			key=response.getElementsByTagName('key')[0].firstChild.data;

			searchDialog=response.getElementsByTagName('searchDialog')[0].firstChild.data;

			jg_doc_rectangle.clear();

			removeDiv();
			XthePointArray = [];
			YthePointArray = [];
			XYthePointArray = [];

			document.theForm.RubberWidth.value = "";
			document.theForm.RubberHeight.value = "";

			if (pointArrayRegen!="none")
			{
				//alert(pointArrayRegen);
				regenerateGeometry(pointArrayRegen);
			}
			if (digiGeom!="none")
			{
				//alert(digiGeom);
				document.theForm.theGeometry.value=digiGeom;
			}
			if (dump!="none")
			{
				document.getElementById("info_window").innerHTML=URLDecode(dump);
				YAHOO.example.container.panel1.show();
			}
			if (removegraphic!="false")
			{
				removeDiv();
				interuptEdit();
			}
			if (searchDialog!="none")
			{
				document.getElementById("search_dialog").innerHTML=URLDecode(searchDialog);
				if (document.theForm.search.value=="true") document.getElementById("searchbutton").innerHTML = searchButtonActive;
			}
			var php = new PHP_Serializer();
			//alert(php.unserialize(editArray));
			if (php.unserialize(editArray)!="none")
			{
				//alert(unser+","+gid+","+php.unserialize(key)+","+digiGeom);
				featureEdit(php.unserialize(editArray),gid,php.unserialize(key),'twprgpy3',digiGeom);
			}
			//			wfsUrl=response.getElementsByTagName('wfsUrl')[0].firstChild.data;
			//			document.getElementById("wfsUrl").innerHTML=URLDecode(wfsUrl);
			//reset search form
			document.theForm.search.value="";
			document.theForm.updateIsClicked.value="";

			routeInserted=response.getElementsByTagName('routeInserted')[0].firstChild.data;
			if (routeInserted!="none") afterInsert(routeInserted);


		}
		else
		{
			alert('There was a problem with the request.');
		}
	}
}
handler_gmap = function() {
	// Create our "tiny" marker icon
	var iconWpt = new GIcon();
	iconWpt.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	iconWpt.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	iconWpt.iconSize = new GSize(12, 20);
	iconWpt.shadowSize = new GSize(22, 20);
	iconWpt.iconAnchor = new GPoint(6, 20);
	iconWpt.infoWindowAnchor = new GPoint(5, 1);
	
	var iconPhoto = new GIcon();
	iconPhoto.image = "images/silk/icons/camera.png";
	iconPhoto.iconSize = new GSize(16, 16);
	iconPhoto.shadowSize = new GSize(16, 16);
	iconPhoto.iconAnchor = new GPoint(8, 8);
	iconPhoto.infoWindowAnchor = new GPoint(16, 1);

	if(http.readyState == 4){
		shieldOff();
		if (http.status == 200) {

			var response = http.responseXML.documentElement;
			try {mode=response.getElementsByTagName('mode')[0].firstChild.data;} catch(e){}
			featureForGmap=response.getElementsByTagName('featureForGmap')[0].firstChild.data;
			featureDesc=response.getElementsByTagName('featureDesc')[0].firstChild.data;
			trkGid=response.getElementsByTagName('trkGid')[0].firstChild.data;
			try {featureExtent=eval(response.getElementsByTagName('featureExtent')[0].firstChild.data);} catch(e){}
			try {featureCenter=response.getElementsByTagName('featureCenter')[0].firstChild.data;} catch(e){}
			try {weatherHTML=response.getElementsByTagName('weather')[0].firstChild.data;} catch(e){}

		
				// Load photo table and icons
				photoTableHTML=response.getElementsByTagName('photoTable')[0].firstChild.data;
				document.getElementById("photo_markup").innerHTML=photoTableHTML;
				photoJS=response.getElementsByTagName('photoJavaScript')[0].firstChild.data;
				photoJSArray = eval('(' + photoJS + ')');// JSON
				for (var i = 0; i < photoJSArray.length; i++) {
					eval(photoJSArray[i]);
				}
				// Load wpts table and icons
				wptTableHTML=response.getElementsByTagName('wptTable')[0].firstChild.data;
				document.getElementById("wpt_markup").innerHTML=wptTableHTML;
				wptJS=response.getElementsByTagName('wptJavaScript')[0].firstChild.data;
				wptJSArray = eval('(' + wptJS + ')');// JSON
				for (var i = 0; i < wptJSArray.length; i++) {
			
					wptJSArray[i] = wptJSArray[i].replace(/[\r\n]+/g, "<br/>");
					
					eval(wptJSArray[i]);
				}
				// Inline the tabs element
				document.getElementById("tabs").style.display="inline";

			if(response.getElementsByTagName('isWpt')[0].firstChild.data == "true")
			{
				this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("wpt_table"));
				this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;

				if (mode=="public")
				{
					var wptColumnDefs = [{key:"Name",label:"Name",sortable:true},{key:"Symbol",label:"Symbol",sortable:true},{key:"Show",label:"Show"},{key:"GPX",label:"GPX"}];
			     	this.myDataSource.responseSchema = {fields: [{key:"Name"},{key:"Symbol"},{key:"Show"},{key:"GPX"}]};
			      	}
			      	else if (mode=="privat")
			      	{
					var wptColumnDefs = [{key:"Name",label:"Name",sortable:true},{key:"Symbol",label:"Symbol",sortable:true},{key:"Shared",label:"Public"},{key:"Delete",label:"Delete"},{key:"Show",label:"Show"},{key:"GPX",label:"GPX"}];
			     	this.myDataSource.responseSchema = {fields: [{key:"Name"},{key:"Symbol"},{key:"Shared"},{key:"Delete"},{key:"Show"},{key:"GPX"}]};

			      
			      	}
				this.myDataTable = new YAHOO.widget.DataTable("wpt_markup", wptColumnDefs, this.myDataSource,{sortedBy:{key:"Name", dir:"asc"}});
				}
			if(response.getElementsByTagName('isPhoto')[0].firstChild.data == "true")
			{
				// Skin photo table
				this.photoDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("photo_table"));
				this.photoDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;

				if (mode=="public")
				{
					var photoColumnDefs = [{key:"Title",label:"Title",sortable:true},{key:"Show",label:"Show"}];
			     	this.photoDataSource.responseSchema = {fields: [{key:"Title"},{key:"Show"}]};
			      	}
			    else if (mode=="privat")
			    {
					var photoColumnDefs = [{key:"Title",label:"Title",sortable:true},{key:"Delete",label:"Unlink"},{key:"Show",label:"Show"}];
			     	this.photoDataSource.responseSchema = {fields: [{key:"Title"},{key:"Delete"},{key:"Show"}]};
			     }
				this.photoDataTable = new YAHOO.widget.DataTable("photo_markup", photoColumnDefs, this.photoDataSource,{sortedBy:{key:"Title", dir:"asc"}});
			}

			
			    
				var newDiv = document.createElement("div");
				newDiv.id=("toposhare"+trkGid);
				document.getElementById("playerContainer").innerHTML="";
				document.getElementById("playerContainer").appendChild(newDiv);

				profileimageUrl=response.getElementsByTagName('profileimageUrl')[0].firstChild.data;
				mapimageUrl=response.getElementsByTagName('routemapimageUrl')[0].firstChild.data;
				trkTopText=response.getElementsByTagName('trkTopText')[0].firstChild.data;
				document.getElementById("trkNameId").innerHTML=trkTopText;
                
                eval("playerObj"+trkGid+" = new player('"+trkGid+"');");
				eval("playerObj"+trkGid+".percent_array=response.getElementsByTagName('js_str')[0].firstChild.data.split('|')");
				eval("playerObj"+trkGid+".pix_coord_array=response.getElementsByTagName('pix_coord_str')[0].firstChild.data.split('|')");
				eval("playerObj"+trkGid+".coord_array=response.getElementsByTagName('coord_str')[0].firstChild.data.split(',')");
				eval("playerObj"+trkGid+".ele_array=response.getElementsByTagName('ele_str')[0].firstChild.data.split('|')");
				eval("playerObj"+trkGid+".time_array=response.getElementsByTagName('time_str')[0].firstChild.data.split('|')");
				eval("playerObj"+trkGid+".speed_array=response.getElementsByTagName('speed_str')[0].firstChild.data.split('|')");
				eval("playerObj"+trkGid+".incline_array=response.getElementsByTagName('incline_str')[0].firstChild.data.split('|')");
				eval("playerObj"+trkGid+".weatherHTML=weatherHTML");
				eval("playerObj"+trkGid+".addHTML()");
				eval("playerObj"+trkGid+".addWeather()");
				eval("playerObj"+trkGid+".addMapImage(mapimageUrl)");
				eval("playerObj"+trkGid+".addProfileImage(profileimageUrl)");
				eval("playerObj"+trkGid+".reset()");
				eval("playerObj"+trkGid+".pause()");
				eval("playerObj"+trkGid+".interval=100000000000");

				trkTopTextForPlayer=response.getElementsByTagName('trkTopTextForPlayer')[0].firstChild.data;
				document.getElementById("trkNameIdPlayer").innerHTML=trkTopTextForPlayer;
				
				YAHOO.example.container.panelwidget = new YAHOO.widget.Panel("panelwidget", {visible:true, draggable:false, close:false } );
				YAHOO.example.container.panelwidget.render();
				YAHOO.example.container.panelwidget.show();

			
			
		}
		else
		{
			alert('There was a problem with the request.');
		}
	}

}
handler_filter = function()
{
	if(http.readyState == 4){
		if (http.status == 200)
		{
			var response = http.responseXML.documentElement;
			provForm=response.getElementsByTagName('provform')[0].firstChild.data;
			document.getElementById("provFilterEle").innerHTML=provForm;
			if (checkForSize(document.filter1.statefilter)>1)
			{
				provForm="<select style='width:100%' name='provfilter' size=5 MULTIPLE><option value=0 SELECTED>All</option></select>";
				document.getElementById("provFilterEle").innerHTML=provForm}
		}
		else
		{
			alert('There was a problem with the request.');
		}
	}
}
handler_add_contact = function(http)
{
	if(http.status == 200)
	{
		if (http.status == 200)
		{
			var response = eval('(' + http.responseText + ')');// JSON
			alert(response.message);
			if (response.reload==1) 
			{
				window.location.reload();
			}
		}
		else
		{
			alert('There was a problem with the request.');
		}
	}
}
handler_delete_contact = function()
{
	if(http.readyState == 4)
	{
		if (http.status == 200)
		{
			var response = eval('(' + http.responseText + ')');// JSON
			document.getElementById("contact_list").innerHTML = response.list;
		}
		else
		{
			alert('There was a problem with the request.');
		}
	}
}
handler_delete_wpt = function()
{
	if(http.readyState == 4)
	{
		if (http.status == 200)
		{
			var response = eval('(' + http.responseText + ')');// JSON
			document.getElementById("wpt_" + response.gid).style.textDecoration = "line-through";
		}
		else
		{
			alert('There was a problem with the request.');
		}
	}
}
handler_delete_photo = function()
{
	if(http.readyState == 4)
	{
		if (http.status == 200)
		{
			var response = eval('(' + http.responseText + ')');// JSON
			document.getElementById("photo_" + response.id).style.textDecoration = "line-through";
		}
		else
		{
			alert('There was a problem with the request.');
		}
	}
}

handler_ip_location = function()
{
	if(http.readyState == 4)
	{
		if (http.status == 200)
		{
			var response = http.responseXML.documentElement;
			try 
			{
				var coord = response.getElementsByTagName('gmlcoordinates')[0].firstChild.data;
				var coordArray = coord.split(",");
				marker = new GMarker(new GPoint(coordArray[0],coordArray[1]));
			    map.addOverlay(marker);
				document.signup.coord.value=coordArray[0]+" "+coordArray[1];
				document.getElementById("coordText").innerHTML=(Math.round(coordArray[0]*1000000)/1000000)+" "+(Math.round(coordArray[0]*1000000)/1000000);
				var name = response.getElementsByTagName('gmlname')[1].firstChild.data;
				document.getElementById("info_text").innerHTML = "We guess you are located in "+name+"<br />You can click in the map to set another home location.";
	
			}
			catch (e)
			{
				document.getElementById("info_text").innerHTML="Could not locate you!<br />You can click in the map to set home location.";
			}
			//document.getElementById("info_box").style.display = "inline";

		} 
		else
		{
			alert('There was a problem with the request.');
		}
	}
}

function openMapWin(page,search,trkGid,minimized)
{
	var iLangID = iLangID;
	var iWidth 					= 800;
	var iHeight 				= 600;
	var strWinName = "MapServer";
	var strURL = "/"+page+"?search="+search+"&trkGid="+trkGid+"&minimized="+minimized;
	var popleft = (screen.width - iWidth) / 2;
	var poptop = (screen.height - iHeight) / 2;
	
	var strParameters 	= "width=" + iWidth + ",height=" + iHeight + 
						",resizable=0,scrollbars=0,status=1,left="+
						popleft+",top="+poptop+",screenX="+popleft+
						",screenY="+poptop+",toolbar=0";

	if (MapappWin == null) openWin = true;
	else if (MapappWin.closed) openWin = true;
	else openWin = false;
	
	if (openWin) {
		hid = trkGid;
		MapappWin 	= window.open(strURL, strWinName, strParameters);
		MapappWin.focus();
	} else {
		if (!MapappWin.closed) {
			if(hid != trkGid)
			{
				hid = trkGid;
				MapappWin.location = strURL;
			}
			MapappWin.focus();
		}
	}
}
function getFlickrData(){
      //postData = YAHOO.util.Connect.setForm(document.getElementById("flickr"));
      shieldOn();
            postData = ajax.serialize(document.getElementById("flickr"));
	             var request =  sndReq(postData, "../servers/flickr.php?type=json", handler_flickr);


}
function geotagFlickrData(){
      //postData = YAHOO.util.Connect.setForm(document.getElementById("flickr2"));
      shieldOn();
      postData = ajax.serialize(document.getElementById("flickr2"));
	  var request =  sndReq(postData, "../servers/flickr.php?type=json&geocode=true", handler_flickr);
}

function nextPageFlickrData(page)
{
	shieldOn();
     var request =  sndReq(postData, "../servers/flickr.php?type=json&page="+page, handler_flickr);	
}

handler_flickr  = function()
{
	if (http.readyState == 4)
        {
	shieldOff();
	     if (http.status == 200)
	     {
		var response = eval('(' + http.responseText + ')');// JSON
		document.getElementById("setList").innerHTML =  response['setHTML'];
		document.getElementById("photoList").innerHTML =  response['photoHTML'];
		if (response['geocoded'] == "false") alert('No photos was geotagged!');
		}
	}
}
handler_check = function()
{
	
}
