/* Copyright © 2002-2004 ESRI Nederland B.V., Grontmij Nederland bv */
var lngTimerID;
var funcOrg__doPostBack;
var noLoadImage=false;
var formTarget;
var resetFormTarget;
var _panelSpace = 0;
var docSubmitted = false;

function printWindow(strHTML)
{
    var w=window.open('','','width=400,height=300,menubar=1,resizable=1,scrollbars=1,toolbar=1')
    //<BASE href="'+window.location.href.replace(/[^\/]*$/,'')+'" />
    w.document.write('<HTML><HEAD><link href="GeoWeb.css" type="text/css" rel="stylesheet"><link href="Custom/Custom.css" type="text/css" rel="stylesheet"><STYLE>.NoPrint {display: none}</STYLE></HEAD><BODY class="PrintWindow">');
    w.document.write(strHTML);
    w.document.write('</BODY></HTML>');
}

function getControl(strID)
{
	return document.getElementById(strID);
}

function ControlIsVisible(ctrl)
{
  if (ctrl)
    return ctrl.style.display != "none";
  else
    return false;
}

function SetControlVisible(ctrl, vis)
{
  if (ctrl)
    ctrl.style.display = vis ? "" : "none";
}

function FocusControl(id)
{
  if (id == null || id.toString() == "")
    return;
  var o = document.getElementById(id);
  if (o)
  {
    if (o.tagName.toLowerCase() == "input" && o.type.toLowerCase() == "text")
      o.select();
    o.focus();
  }
}

function getPageX(control)
{
  var x = 0;
  var p = control;
  while (p)
  {
    x += p.offsetLeft;
    p = p.offsetParent;
  }
  return x;
}
function getPageY(control)
{
  var y = 0;
  var p = control;
  while (p)
  {
    y += p.offsetTop;
    p = p.offsetParent;
  }
  return y;
}

/* Hoogte beschikbaar voor panels */
function GetPanelSpace()
{
  if (_panelSpace == 0) 
  {
    var logo = getControl("divUserLogo");
    var margin = 10; // = body.margin-bottom
    _panelSpace = document.documentElement.offsetHeight - 700 - margin;
  }
    
  return _panelSpace;
}

function docSubmit()
{
  if (docSubmitted)
  {
    ///window.alert("Map.js 91: Already submitted");
    var frm=document.forms[0];
    if(frm.target!="selection_export")
    {
        return false;
    }
  }
  docSubmitted = true;
 	window.clearTimeout(lngTimerID);
	if(!noLoadImage)
		showLoadImage();
	else
		noLoadImage=false;
  if (window.event) 
  {
    var srcElem = getSrcElement(window.event)
	  if ((window.event != null) && (srcElem.nodeName == "SELECT"))
		  CloseDropDown(srcElem);
	}
	SetControlVisible(getControl("divZoekPanel"), false);
	// Update mapsize in hidden input fields before the form is submitted
	setMapSize();
	processScrollPos(saveScrollPos);
	var frm=document.forms[0];
	if(typeof(resetFormTarget)!="undefined"&&resetFormTarget!=null)
	{
		frm.target=resetFormTarget;
		resetFormTarget=null;
	}
	if(typeof(formTarget)!="undefined"&&formTarget!=null)
	{
		resetFormTarget=frm.target;
		frm.target=formTarget;
		formTarget=null;
	}
	
	StorePanelState();
	return true;
}

function doc__doPostBack(eventTarget, eventArgument)
{
	docSubmit();
	funcOrg__doPostBack(eventTarget, eventArgument);
}

function saveScrollPos(ctrl, pos)
{
	var c=getControl(ctrl);
	if(c!=null) getControl(pos).value=c.scrollTop;
	
	
}

function restoreScrollPos(ctrl, pos)
{
	var c=getControl(ctrl);
	if(c!=null) c.scrollTop=getControl(pos).value;

}

function processScrollPos(func)
{
	func('divHoofdgroepen', 'hidScrollHoofdgroep');
	func('divKaartlagen', 'hidScrollKaartlaag');
	func('divPanel', 'hidScrollPanel');
	func('divRedliningLayers', 'ucRedlining_hidScrollRedliningLayers');
}

function docLoad()
{
	
	// Intercept ASP.NET __doPostBack method and replace with own
	funcOrg__doPostBack=__doPostBack;
	__doPostBack=doc__doPostBack;
	if(getControl('hidMapW').value=="0")
	{
		checkMapResize();
	}
	UpdateMapCursor();
	var ctrl = null;
	
	ctrl = getControl('cboScale')
	if (ctrl) ctrl.selectedIndex = -1;
	
	ctrl = getControl('btnIdentify');
	if (ctrl) ctrl.onclick=ToolButtonClick_Identify;
	
	ctrl = getControl('btnSelect');
	if (ctrl) ctrl.onclick=ToolButtonClick_Select;
	
	ctrl = getControl('btnMeasure');
	if (ctrl) ctrl.onclick=ToolButtonClick_Measure;
	
	ctrl = getControl('btnRedlining');
	if (ctrl) ctrl.onclick=ToolButtonClick_Redlining;
	
 	ctrl = getControl('btnSketch');
	if (ctrl) ctrl.onclick=ToolButtonClick_Sketch;
            
  // Als RestorePanelState direct wordt aangeroepen is de beschikbare hoogte voor de panels
  // nog niet bekend (indien de browsercache is uitgeschakeld!?)
  setTimeout ("RestorePanelState()", 100);
  setTimeout ("FocusControl(_FocusControl)", 100);
  setTimeout ("processScrollPos(restoreScrollPos)",100);
  setTimeout ("toggleOnLoad()", 100);

}

function setMapSize()
{
	var objMap=getControl('divMap');
	var objMapW=getControl('hidMapW');
	var objMapH=getControl('hidMapH');
  objMapW.value=objMap.offsetWidth;
  objMapH.value=objMap.offsetHeight;
}

function resizeMap()
{
	var objMap=getControl('divMap');
	var objMapW=getControl('hidMapW');
	var objMapH=getControl('hidMapH');
	
	// This test needs to be here because SmartNavigation causes an extra event	
	if(parseInt(objMapW.value)!=objMap.offsetWidth||parseInt(objMapH.value)!=objMap.offsetHeight)
	{
		// Correct size will be set in __doPostBack
		__doPostBack('','');
	}
}

function checkMapResize()
{
	window.clearTimeout(lngTimerID);
	var objMap=getControl('divMap');
	var objMapW=getControl('hidMapW');
	var objMapH=getControl('hidMapH');
	
	if(parseInt(objMapW.value)!=objMap.offsetWidth||parseInt(objMapH.value)!=objMap.offsetHeight)
	{
		lngTimerID=window.setTimeout("resizeMap()",100);
	}
}

function showLoadImage()
{
	var divLoading=getControl("divLoading");
	if(divLoading) divLoading.style.visibility="visible";
}

var blnMouseCapture;
var blnMouseLeftButtonDown;
var strMouseMode;
var ptMouseDown;
var ptMouseCapture;
var objMouseCapture;
var polyPoints;

function point(x,y)
{
	this.x=x;
	this.y=y;
}

function getPagePos(e)
{
	var y=e.offsetTop;
  for(var x=e.offsetLeft; (e=e.offsetParent)!=null; x+=e.offsetLeft)
		y+=e.offsetTop;
  return new point(x,y);
}

function getDocMousePos(e)
{
  if(e.srcElement)
	{
		var pt=getPagePos(e.srcElement);
		pt.x+=e.offsetX;
		pt.y+=e.offsetY;
		return pt;
	}
	return new point(document.body.scrollLeft+e.clientX,document.body.scrollTop+e.clientY);
}

function showMapPos(s)
{
	var divMap=document.getElementById('divMap');
	window.status=s+" map pos="+divMap.offsetLeft+","+divMap.offsetTop+" style="+divMap.style.left+","+divMap.style.top;
}

function panMap(x,y)
{
	var s=document.getElementById('divMap').style;
	s.left=x+"px";
	s.top=y+"px";
}

function setControlPos(n,x,y,w,h)
{
	var s=getControl(n).style;
	s.left=x+"px";
	s.top=y+"px";
	s.width=w+"px";
	s.height=h+"px";
}

function showBox(blnShow)
{
	var strMode=blnShow?"block":"none";
	getControl("divZoomBox").style.display=strMode;	
}

function moveBox(x1,y1,x2,y2)
{
	var x=x1<x2?x1:x2;
	var w=Math.abs(x1-x2)+1;
	var y=y1<y2?y1:y2;
	var h=Math.abs(y1-y2)+1;
	x-=ptMouseCapture.x;
	y-=ptMouseCapture.y;
	setControlPos("divZoomBox",x,y,w,h);
}

function moveCircle(x1,y1,x2,y2)
{
	var p=getVMLDraw();
	var oval=document.createElement("v:oval");
	// Calculate box
	var dx=x2-x1;
	var dy=y2-y1;
	var r=Math.sqrt(dx*dx+dy*dy)
	oval.strokecolor="red";
	var fill=document.createElement("v:fill");
	fill.opacity=0.25;
	fill.color="red";
	oval.appendChild(fill);
	oval.style.left=(x1-r)+"px";
	oval.style.top=(y1-r)+"px";
	oval.style.width=(r*2)+"px";
	oval.style.height=(r*2)+"px";
	window.status="straal="+Math.round(r*mapScale)+" meter";
	
	if(p.children!=null && p.children.length>0)
	{
		p.appendChild(oval, p.children[0]);
		while(p.children.length>1) p.removeChild(p.children[0]);
	}
	else
		p.appendChild(oval);
}

function getVMLDraw()
{
	var p=getControl('vmlDraw');
	if(p==null)
	{
		//<v:group id="vmlDraw" style="width: 10000px; height: 10000px" coordsize="10000 10000">
		var p=document.createElement("v:group");
		p.id="vmlDraw";
		p.style.width="10000px";
		p.style.height="10000px";
		p.coordsize="10000 10000";
		var m=getControl('divMapCapture');
		m.insertBefore(p, getControl('divLoading'));
	}
	return p;
}

function removeVMLDraw()
{
	var p=getControl('vmlDraw');
	if(p!=null)
	{
		while(p.children.length>1) p.removeChild(p.children[0]);
	}
}

function updatePoly(shapeType)
{
	var p=getVMLDraw();
    // Kill all children
	if((typeof(polyPoints)!="undefined")&&(polyPoints!=null))
	{
		var poly=document.createElement("v:polyline");
		if(shapeType=="polygon")
		{
			var fill=document.createElement("v:fill");
			fill.opacity=0.25;
			fill.color="red";
			poly.appendChild(fill);
		}
		var stroke=document.createElement("v:stroke");
		stroke.opacity=0.5;
		stroke.weight=1;
		stroke.color="red";
		stroke.joinstyle="round";
		stroke.endcap="round";
		poly.appendChild(stroke);
		// Update polyline coordinates
		var points="";
		for(var i=0;i<polyPoints.length;i++)
		{
			var pt=polyPoints[i];
			if(points!="") points+=" ";
			points+=pt.x+" "+pt.y;
		}
		// Close shape for polygon
		if(shapeType=="polygon") points+=" "+polyPoints[0].x+" "+polyPoints[0].y;
		else poly.filled=false;
	    poly.points=points;
	    if(p.children.length>0)
	    {
			p.replaceChild(poly, p.children[0]);
		    while(p.children.length>1) p.removeChild(p.children[0]);
		}
		else
			p.appendChild(poly);
	}
	else
	{
	    while(p.children.length>0) p.removeChild(p.children[0]);
	}
}

function setActionType(actionType)
{

	var hidActionType=getControl('hidActionType');
	// Deselect current button and select specified button
	var btn=getControl('btn'+hidActionType.value);
	if (btn)
	{
  	btn.className="ImageLinkButton";
	  btn=getControl('btn'+actionType);
	  btn.className="ImageLinkButtonSelected";
	}
	hidActionType.value=actionType;
	// Update mouseMode
	switch(actionType)
	{
	case "Pan":
		setMouseMode("drag");
		break;
	case "ZoomInBox":
	case "ZoomOutBox":
		setMouseMode("box");
		break;
	case "Identify":
	case "Measure":
		setMouseMode("click");
		break;
	case "Select": // Mouse mode depends on choice in combo box
		var cboSelectType=getControl('ucSelect_cboSelectType');
		if(cboSelectType!=null)
		{
			switch(cboSelectType.value)
			{
			case "Query":
				setMouseMode("none");
				break;
			case "Rechthoek":
				setMouseMode("box");
				break;
			case "Cirkel":
				setMouseMode("circle");
				break;
			default:
				setMouseMode("click");
				break;
			}
		}
		break;
	case "Redlining": // Mouse mode depends on choice in combo box
		var cboShapeType=getControl('ucRedlining_cboShapeType');
		if(cboShapeType!=null)
		{
			switch(cboShapeType.value)
			{
			case "point":
			case "label":
				setMouseMode("click");
				break;
			default:
				setMouseMode(cboShapeType.value);
				break;
			}
		}
		else
			setMouseMode("none");
		break;
	case "Sketch":
		var hidMouseMode=getControl('hidSketchMouseMode');
		setMouseMode(hidMouseMode.value);
		break;
	}
	btn.blur();
}

function getMouseMode()
{
/*
	switch(getControl('hidActionType').value)
	{
	case "Pan":
		return "drag";
	case "ZoomInBox":
	case "ZoomOutBox":
	case "SelectBox":
		return "box";
	case "Identify":
	case "SelectPoly":
	case "MeasurePoly":
		return "click";
	}
*/
	return getControl('hidMouseMode').value;
}

function setMouseMode(mode)
{
	getControl('hidMouseMode').value=mode;
	UpdateMapCursor();
}

function UpdateMapCursor()
{
	var strCursor="auto";	
	switch(getMouseMode())
	{
	case "none":
		strCursor="default";
		break;
	case "drag":
		strCursor="move";
		break;
	case "box":
	case "circle":
	case "polyline":
	case "polygon":
		strCursor="crosshair";
		break;
	case "click":
		strCursor="pointer";		
		break;
	}

	switch (document.forms[0].hidActionType.value.toLowerCase())
	{
	  case "identify": 
	    strCursor="url(images/identify.cur), " + strCursor;
	    break;
	  case "measure": 
	    strCursor="url(images/measure.cur), " + strCursor;
	    break;
	  case "select":
	    strCursor="url(images/select.cur), " + strCursor;
	    break;
	  case "zoominbox":
	    strCursor="url(images/zoomin.cur), " + strCursor;
	    break;
	  case "zoomoutbox":
	    strCursor="url(images/zoomout.cur), " + strCursor;
	    break;
	}
	
	var objMap=getControl('divMapCapture');
	objMap.style.cursor=strCursor;
}

function CloseDropDown(e)
{
		var v=e.disabled;
		e.disabled=true;
		e.disabled=v;
}

/*
// Code to change mouse cursor, might be needed when radio button is implemented on client side
function mapMouseOver(e)
{
	UpdateMapCursor();
}
*/

function mapMouseDown(e)
{
	if(blnMouseCapture&&e.button&2) return mapCaptureFinish(); // Cancel action on right mouse down
	if(blnMouseLeftButtonDown) return false; // Left button already down, other button is clicked
  var LeftBtn = getLeftButtonDown(e)
  if(!(LeftBtn)) return false;  // Only respond to left button down
	blnMouseLeftButtonDown=true;
	objMouseCapture=document.getElementById('divMapCapture');
	ptMouseCapture=getPagePos(objMouseCapture);
	ptMouseDown=getDocMousePos(e);
	strMouseMode=getMouseMode();
	switch(strMouseMode)
	{
	case "none":
		return false;
	case "drag":
		panMap(0,0);
		break;
	case "box":
		moveBox(ptMouseDown.x,ptMouseDown.y,ptMouseDown.x,ptMouseDown.y);
		showBox(true);
		break;
	case "circle":
		moveCircle(ptMouseDown.x-ptMouseCapture.x, ptMouseDown.y-ptMouseCapture.y, ptMouseDown.x-ptMouseCapture.x, ptMouseDown.y-ptMouseCapture.y);
		break;
	case "polyline":
	case "polygon":
		if(!blnMouseCapture||(typeof(polyPoints)=="undefined")||(polyPoints==null))
		{
			polyPoints=new Array();
			polyPoints[0]=new point(ptMouseDown.x-ptMouseCapture.x, ptMouseDown.y-ptMouseCapture.y);
			polyPoints[1]=new point(ptMouseDown.x-ptMouseCapture.x, ptMouseDown.y-ptMouseCapture.y);
		}
		else
		{
			var pt=new point(ptMouseDown.x-ptMouseCapture.x, ptMouseDown.y-ptMouseCapture.y);
			var ptOld=polyPoints[polyPoints.length-2];
			if(pt.x!=ptOld.x||pt.y!=ptOld.y)
				polyPoints[polyPoints.length]=pt;
		}
		updatePoly(strMouseMode);
		break;
	case "click":
		getControl('hidActionParam').value=(ptMouseDown.x-ptMouseCapture.x)+","+(ptMouseDown.y-ptMouseCapture.y);				
		__doPostBack('','');
		return false;
	default:
		return false;
	}
	if(objMouseCapture.setCapture) objMouseCapture.setCapture();
	blnMouseCapture=true;
	
	return true;
}

function mapMouseMove(e)
{
	var ptMouse=getDocMousePos(e);
	var ptRef=getPagePos(document.getElementById('divMapCapture'));
  window.status='x='+Math.round(mapX+mapScale*(ptMouse.x-ptRef.x))+' y='+Math.round(mapY-mapScale*(ptMouse.y-ptRef.y))
	if(!blnMouseCapture) return;
	switch(strMouseMode)
	{
	case "drag":
		panMap(ptMouse.x-ptMouseDown.x,ptMouse.y-ptMouseDown.y);
		break;
	case "box":
		moveBox(ptMouseDown.x,ptMouseDown.y,ptMouse.x,ptMouse.y);
		break;
	case "circle":
		moveCircle(ptMouseDown.x-ptMouseCapture.x, ptMouseDown.y-ptMouseCapture.y, ptMouse.x-ptMouseCapture.x, ptMouse.y-ptMouseCapture.y);
		break;
	case "polyline":
	case "polygon":
		// update last point
		polyPoints[polyPoints.length-1]=new point(ptMouse.x-ptMouseCapture.x, ptMouse.y-ptMouseCapture.y);
		updatePoly(strMouseMode);
		break;
	}
}

function mapMouseOut(e)
{
  window.status='';
}

function mapLoseCapture(e)
{
	if(!blnMouseCapture) return;
	blnMouseCapture=false;
	switch(strMouseMode)
	{
	case "drag":
		panMap(0,0);
		break;
	case "box":
		showBox(false);
		break;
	case "circle":
		removeVMLDraw();
	case "polyline":
	case "polygon":
		polyPoints=null;
		updatePoly(strMouseMode);
		break;
	}
}

function mapMouseUp(e)
{
  var LeftBtn = getLeftButtonDown(e)  
  if(!(LeftBtn)) return false;  // Only respond to left button down
	blnMouseLeftButtonDown=false; // Left button released, update state
	if(!blnMouseCapture) return false;
	// Ignore mouse up when drawing polyline or polygon and stay in mouse capture mode
	if(strMouseMode=="polyline"||strMouseMode=="polygon") return false;
	
	var ptMouse=getDocMousePos(e);
	blnMouseCapture=false; // Set to false so mapLoseCapture won't cancel action
	mapCaptureFinish();
	switch(strMouseMode)
	{
	case "drag":
		getControl('hidActionParam').value=(ptMouse.x-ptMouseDown.x)+","+(ptMouse.y-ptMouseDown.y);
		__doPostBack('','');
		break;
	case "box":
	case "circle":
		getControl('hidActionParam').value=(ptMouseDown.x-ptMouseCapture.x)+","+(ptMouseDown.y-ptMouseCapture.y)+","+(ptMouse.x-ptMouseCapture.x)+","+(ptMouse.y-ptMouseCapture.y);
		__doPostBack('','');
		break;
	}
	
	return true;
}

function mapDoubleClick(e)
{
	//if(!(e.button&1)) return; // Only handle left button
	if(!blnMouseCapture) return;
	if(strMouseMode=="polyline"||strMouseMode=="polygon")
	{
		blnMouseCapture=false; // Set to false so mapLoseCapture won't cancel action
		mapCaptureFinish();
		// Delete last point
		polyPoints.length--;
		// Create string with coordinates
		var s="";
		for(var i=0;i<polyPoints.length;i++)
		{
			var pt=polyPoints[i];
			if(s!="") s+=",";
			s+=pt.x+","+pt.y;
		}
		// Post coordinates to server
		getControl('hidActionParam').value=s;
		__doPostBack('','');
	}
}

function mapCaptureFinish()
{
	if(objMouseCapture&&objMouseCapture.releaseCapture) objMouseCapture.releaseCapture();
}

function mapKeyPress(e)
{
	if(e.keyCode==27)
		mapCaptureFinish();
}

function ScaleChange(cbo)
{
	CloseDropDown(cbo);
    getControl('txtScale').value=cbo.options[cbo.selectedIndex].text;
    getControl('btnSetScale').click();
}

function clickLayer(e)
{
 	window.clearTimeout(lngTimerID);
  var ctl=getControl('hidUpdateLayers');
  
  if(e.shiftKey)
  { // All on or off, execute action immediately
    var srcElem = getSrcElement(e);
    ctl.value = srcElem.checked?'on':'off';
    __doPostBack('','');
  }
  else if(e.ctrlKey)
  {
    //if ctrlKey was pressed while clicking, more clicks kan be done
    //postback happens later when ctrlKey was released (keyUp)
    ctl.value='update';
    document.onkeyup = CheckForControlKeyUp;
  }
  else
  {
    ctl.value='update';
    lngTimerID=window.setTimeout("__doPostBack('','')",500);
  }
}

/*Function CheckForControlKeyUp
* eventhandler for onkeyup when checking checkboxes of layers
* if the ctrlKey has gone up then do the postback
* MHU 20070111
*/
function CheckForControlKeyUp(e)
{
    //if not e (then it's undefined so not a valid event)
    if(!e)
    {
        //get window.event (probably not needed, just in case)
        e = window.event;
    }
    //if the event comes from the ctrlKey
    if(e.keyCode==17)
    {
        //remove onkeyup to prevent multiple postback as result of typing or something
        document.onkeyup=null;
        
        //do the postback 
        __doPostBack('','');
    }
}

function setRedliningShapeType(t)
{
	if(getControl('hidActionType').value!='Redlining') return;
	switch(t)
	{
	case "point":
	case "label":
		setMouseMode("click");
		break;
	default:
		setMouseMode(t);
	}
}

function ToolButtonClick(actionType)
{
	if(getControl('hidActionType').value==actionType)
	{
	    
	    return true;
	}
	
	setActionType(actionType);
	
	//action changed so panel could be opened, but at least we should not force to close it 
	var txtPanelState = getControl(txtPanelStateId);
    txtPanelState.value='';
    
	return false;
}

function ToolButtonClick_Identify()
{
	return ToolButtonClick('Identify');
}

function ToolButtonClick_Select()
{
	// If panel not visible, let click through to server to activate it
	if(getControl('ucSelect_cboSelectType')==null) return true;
	return ToolButtonClick('Select');
}

function ToolButtonClick_Measure()
{
	return ToolButtonClick('Measure');
}

function ToolButtonClick_Redlining()
{
	// If panel not visible, let click through to server to activate it
	if(getControl('ucRedlining_txtLayerName')==null) return true;
	return ToolButtonClick('Redlining');
}

function ToolButtonClick_Sketch()
{
	// If panel not visible, let click through to server to activate it
	if(getControl('hidSketchMouseMode')==null) return true;
	return ToolButtonClick('Sketch');
}

function OpenExportMapWindow()
{
	var objMap=getControl('divMap');
	var w=objMap.offsetWidth+20;
	var h=objMap.offsetHeight+30;
    window.open('','ExportMap','width='+w+',height='+h+',menubar=0,resizable=0,scrollbars=0,toolbar=0');
  return false;
}

function CopyMap()
{
	if (document.body.createControlRange) 
	{
    var map=getControl('imgMap');
    var controlRange=document.body.createControlRange();
    controlRange.addElement(map);
    controlRange.execCommand('Copy');
	}
	else
	  window.alert ("Kopi\u00EBren naar het clipboard wordt niet ondersteund door deze browser.");
}


function debug(str)
{
  str = str.toString();
  getControl("debug").innerHTML = str.replace (/&/g, "&amp;").replace (/</g, "&lt;").replace (/\n/g, "<br>");
}
