
///////////////////////////////////////////////////////////////////////////////////////////
// helpers tied to map tools
///////////////////////////////////////////////////////////////////////////////////////////
function __doPanZoom(zoomBarVar, mapID, cmd, arg)
{
    var zoomBar = null;
    try{ zoomBar = eval(zoomBarVar); }catch(ex){}
    if (zoomBar == null) return;

	var map = __getMapTools(mapID);
	if (map == null) return;
	
	var zoom = map.GetZoom();
    
    switch (cmd)
    {
        case "ZoomFull": zoomBar.updateThumb(0);  break;
        case "ZoomIn":  zoomBar.updateThumb(zoom+1);  break;
        case "ZoomOut":  zoomBar.updateThumb(zoom-1); break;
        case "SetZoom": zoomBar.updateThumb(arg); break;
    }   
    
    map[cmd](arg);
}

function __UpdateAnimationLayer(response, mapID)
{
    __amUpdateEventValidation();

	if (!__amIsAspAjaxCall)
    {
        try
        {
	        var parts = response.split('``');
		    if (parts[0] == 'LAYER') 
		    {   
		        var animDiv = __$(mapID+"_animdiv"); 
		        __clearDiv(animDiv);
		    
    			animDiv.innerHTML = parts[2];
	    		__$(mapID+"_animarg").value = parts[1];
		    }
		    else
		    {
		        var mapDiv = __$(mapID); 
		        __clearDiv(mapDiv);
		   
		        mapDiv.innerHTML = parts[1]; 

                // update background GM/VE layer
        	    var map = __getMapTools(mapID);
	            if (map) map.UpdateBackLayer();
		    }
	    }
	    catch(e){}
	}

	var map = __getMapTools(mapID);
	if (!map) return;
	
	if (map.GetEnableAnimation()) 
	    map.RunAnimationTimer();
}

function __UpdateAnimationLayerError(response, mapID)
{
    __amUpdateEventValidation();
    
	var map = __getMapTools(mapID);
	if (!map) return;
	
	if (map.GetEnableAnimation()) 
	    map.RunAnimationTimer();
}

///////////////////////////////////////////////////////////////////////////////////////////
// AspMap Internal Tools
///////////////////////////////////////////////////////////////////////////////////////////
function __AspMapTools()
{
this.ZOOMFULL = 100;
this.PIXELPAN = 101;
this.ZOOMIN = 102;
this.ZOOMOUT = 103;
this.SETZOOM = 104;
this.CENTERAT = 105;
this.SETSCALE = 106;
this.CENTERANDZOOM = 107;
this.CENTERANDSCALE = 108;
this.RESIZETO = 109;

this.mouseMoveHandler = null;
this.panToolHandler = null;
this.pointToolHandler = null;
this.infoToolHandler = null;
this.markerClickHandler = null;
this.apiVar = null;
///////////////////////////////////////////////////////////////////////////////////////////
// public
///////////////////////////////////////////////////////////////////////////////////////////

// events

this.Add_MouseMove = function(callback)
{
    this.mouseMoveHandler = callback;
}

this.Remove_MouseMove = function(callback)
{
    this.mouseMoveHandler = null;
}

this.Add_PanToolClick = function(callback)
{
    this.panToolHandler = callback;
}

this.Remove_PanToolClick = function(callback)
{
    this.panToolHandler = null;
}

this.Add_PointTool = function(callback)
{
    this.pointToolHandler = callback;
}

this.Remove_PointTool = function(callback)
{
    this.pointToolHandler = null;
}

this.Add_InfoTool = function(callback)
{
    this.infoToolHandler = callback;
}

this.Remove_InfoTool = function(callback)
{
    this.infoToolHandler = null;
}

this.Add_MarkerClick = function(callback)
{
    this.markerClickHandler = callback;
}

this.Remove_MarkerClick = function(callback)
{
    this.markerClickHandler = null;
}


// methods

this.PanLeft = function(percentage)
{
    this.Pan( - this.MapWidth() * percentage / 100, 0);
}

this.PanTop = function(percentage)
{
    this.Pan(0, - this.MapHeight() * percentage / 100);
}

this.PanRight = function(percentage)
{
    this.Pan(this.MapWidth() * percentage / 100, 0);
}

this.PanBottom = function(percentage)
{
    this.Pan(0, this.MapHeight() * percentage / 100);
}

this.ZoomFull = function()
{
    this.ApiCall(this.ZOOMFULL);
}

this.ZoomIn = function()
{
    this.ApiCall(this.ZOOMIN);
}

this.ZoomOut = function()
{
    this.ApiCall(this.ZOOMOUT);
}

this.Pan = function(dx, dy)
{
    this.ApiCallXY(this.PIXELPAN, "", dx, dy);
}

this.Refresh = function()
{
    this.Pan(0,0);
}

this.CenterAt = function(x,y)
{
    this.ApiCallXY(this.CENTERAT, "", x, y);
}

this.CenterAndZoom = function(x,y, zoom)
{
    this.ApiCallXY(this.CENTERANDZOOM, zoom, x, y);
}

this.CenterAndScale = function(x,y, scale)
{
    this.ApiCallXY(this.CENTERANDSCALE, scale, x, y);
}

this.ResizeTo = function(width, height)
{
    if (this.MapWidth() != width || this.MapHeight() != height)
        this.ApiCallXY(this.RESIZETO, "", width, height);
}

this.Resize = function()
{
    var d = __$(this.MapID);
    if (d.parentNode)
        this.ResizeTo(__getDivW(d.parentNode), __getDivH(d.parentNode));        
}

// properties

this.SetZoom = function(zoom)
{
    if (this.GetZoom() != zoom)
        this.ApiCall(this.SETZOOM, zoom);
}

this.GetZoom = function()
{
    return this.GetInt("zoom");
}

this.GetZoomLevelCount = function()
{
    return this.GetInt("zlct");
}

this.GetMapScale = function()
{
    return this.GetDbl("scl");
}

this.SetMapScale = function(scale)
{
    this.ApiCall(this.SETSCALE, scale);
}

// internal API calls
this.ApiCall = function(cmd, arg)
{
    this.ApiCallXY(cmd, arg, "", "");
}

this.ApiCallXY = function(cmd, arg, x, y)
{
    if (typeof(arg) == "undefined")
        arg = "";
    this.SetApiCall();   
    this.SubmitTool(cmd, x, y, arg);
}

///////////////////////////////////////////////////////////////////////////////////////////
// animation
this.ttimer = null;

this.OnLoad = function()
{
    if (this.ttimer == null && this.GetEnableAnimation()) 
    {
        this.RunAnimationTimer();
    }
}

this.RunAnimationTimer = function()
{    
    if (this.GetAnimationInterval() > 0)
    {
        clearTimeout(this.ttimer);
        this.ttimer = null;
        this.ttimer=setTimeout(__getMapToolsName(this.MapID)+".DoAnimation()", this.GetAnimationInterval());
    }
}

this.DoAnimation = function()
{
    if (!__amIsAspAjaxCall)
        map_callback(this.UniqueID, __UpdateAnimationLayer, 'ANIM', this.MapID, __UpdateAnimationLayerError);
    else
        this.RunAnimationTimer();
}

this.RefreshAnimationLayer = function()
{
    if (!this.GetEnableAnimation())
    {
        this.DoAnimation();
    } 
   
    return false;
}

this.SetAnimationInterval = function(value)
{ 
    this.SetInt("animint", value);
}

this.GetAnimationInterval = function()
{ 
    return this.GetInt("animint");
}

this.GetEnableAnimation = function()
{
    return this.GetBool("at");
}

this.SetEnableAnimation = function(enable)
{
    if (enable != this.GetEnableAnimation())
    {
        this.SetBool("at", enable);
        
		if (enable)
		{
			this.DoAnimation();
		}
		else
		{
			clearTimeout(this.ttimer);
			this.ttimer = null;
		}
	}
      	
    return false;    
}


///////////////////////////////////////////////////////////////////////////////////////////
// private
this.hspc = 0;		// horizontal image offset
this.vspc = 0;		// vertical image offset
this.MapCanvas = null;
this.MapID = "";
this.UniqueID = "";
this.ZoomBarVar = null;
this.GetZoomBar = function() { try{ return eval(this.ZoomBarVar); }catch(ex){} return null; }

this.TOOL_ZOOMIN = 1;
this.TOOL_ZOOMOUT = 2;
this.TOOL_CENTER = 3;
this.TOOL_PAN = 4;
this.TOOL_INFO = 5;
this.TOOL_DISTANCE = 6;
this.TOOL_QINFO = 7;
	
this.TOOL_POINT = 8;
this.TOOL_LINE = 9;
this.TOOL_POLYLINE = 10;
this.TOOL_RECT = 11;
this.TOOL_CIRCLE = 12;
this.TOOL_POLYGON = 13;

this.isDragging = false;

this.x1=0;
this.y1=0;
this.x2=0;
this.y2=0;
this.prevPanX = 0;
this.prevPanY = 0;

this.Xpts = null;
this.Ypts = null; 

this.rleft=0;
this.rright=0;
this.rtop=0;
this.rbottom=0;

this.isOnMoveInited = false;

this.qInfoX = 0;
this.qInfoY = 0;

this.SetTool = function (tool)
{
	this.CancelTool();	
	this.SetMapTool(tool);
	this.UpdateCursor();	
}

this.SetArgument = function (arg)
{
    this.SetToolArgument(arg);
}

this.GetArgument = function ()
{
    return this.GetToolArgument();
}

this.GetTool = function() {	return this.GetMapTool(); }

this.UpdateCursor = function()
{
    this.SetCursor( this.GetCursor() );
}

/****************************************************************************************
internal functions
****************************************************************************************/
this.StartTool = function(x,y)
{
	this.MapCanvas.setStroke(this.LineWidth());
	this.MapCanvas.setColor(this.LineColor());	

	switch (this.GetTool())
	{
		case this.TOOL_POINT:	
			this.StartPoint(x,y);
			break;
		case this.TOOL_ZOOMIN:			
		case this.TOOL_RECT:
			this.StartRect(x,y);			
			break;
		case this.TOOL_LINE:
			this.StartLine(x,y);			
			break;
		case this.TOOL_PAN:
			this.StartPan(x,y);			
			break;			
		case this.TOOL_CIRCLE:
		    this.StartPolyline(x,y);
			this.StartCircle(x,y);						
			break;
		case this.TOOL_DISTANCE:			
		case this.TOOL_POLYLINE:
			this.StartPolyline(x,y);
			break;			
		case this.TOOL_POLYGON:
			this.StartPolygon(x,y);
			break;								
		case this.TOOL_ZOOMOUT:
			this.StartZoomOut(x,y);
			break;		
		case this.TOOL_CENTER:
			this.StartCenter(x,y);
			break;		
		case this.TOOL_INFO:
			this.StartInfo(x,y);
			break;					
		case this.TOOL_QINFO:
			this.StartQuickInfo(x,y);
			break;								
	}
}

this.DragTool = function(x,y)
{
	switch (this.GetTool())
	{
		case this.TOOL_RECT:
		case this.TOOL_ZOOMIN:
			this.DrawRect(x,y);
			break;
		case this.TOOL_LINE:
			this.DrawLine(x,y);
			break;
		case this.TOOL_PAN:
			this.DrawPan(x,y);
			break;			
		case this.TOOL_CIRCLE:		
		    this.DrawDistance(x,y, false);
			this.DrawCircle(x,y, false);			
			break;
		case this.TOOL_POLYLINE:
			this.DrawPolyline(x,y);
			break;						
		case this.TOOL_DISTANCE:
			this.DrawDistance(x,y, true);
			break;									
		case this.TOOL_POLYGON:
			this.DrawPolygon(x,y);
			break;
		case this.TOOL_INFO:
			this.DrawInfo(x,y);
			break;								
		case this.TOOL_QINFO:
			this.DrawInfo(x,y);
			break;											
	}		
}

this.StopTool = function(x,y)
{
	switch (this.GetTool())
	{
		case this.TOOL_RECT:		
			this.StopRect();
			break;
		case this.TOOL_LINE:
			this.StopLine();
			break;
		case this.TOOL_PAN:
			this.StopPan();
			break;			
		case this.TOOL_CIRCLE:
			this.StopCircle();
			this.StopDistance();
			break;
		case this.TOOL_ZOOMIN:
			this.StopZoomIn();
			break;			
		case this.TOOL_INFO:
			this.StopInfo();
			break;								
		case this.TOOL_QINFO:
			this.StopQuickInfo();
			break;											
	}
}

this.CancelTool = function()
{
	this.StopDrag();
	this.MapCanvas.clear();	
}

this.StopCompTool = function()
{
	switch (this.GetTool())
	{
		case this.TOOL_POLYLINE:
			this.StopPolyline();
			break;						
		case this.TOOL_DISTANCE:
			this.StopDistance();
			break;									
		case this.TOOL_POLYGON:
			this.StopPolygon();
			break;
	}	
}

/********** POINT ****************************************************************/
this.StartPoint = function(x,y)
{
	this.MapCanvas.clear();
    this.OnPointTool(x,y);
}

this.StartZoomOut = function(x,y)
{
	this.MapCanvas.clear();
	this.OnZoomOutTool(x,y);	
}

this.StartCenter = function(x,y)
{
	this.MapCanvas.clear();
	this.OnCenterTool(x,y);	
}

/********** INFO ****************************************************************/
this.StartInfo = function(x,y)
{
	this.MapCanvas.clear();
	
	if (this.EnablePan())
	    this.StartPan(x, y);
	else
	    this.OnInfoTool(x,y);
}

this.StartQuickInfo = function(x,y)
{
    this.HideInfoWindow();
	this.MapCanvas.clear();
	
	if (this.EnablePan())
	    this.StartPan(x, y);
	else
	    this.OnQuickInfoTool(x,y);
}

this.DrawInfo = function(x,y)
{
	this.UpdateDrag(x,y);
	if (Math.abs(this.x1 - this.x2) > 1 || Math.abs(this.y1 - this.y2) > 1)
	{
	    this.DrawPan(x,y);
    }
}  

this.StopInfo = function()
{	
    this.StopDrag();
	if (Math.abs(this.x1 - this.x2) > 1 || Math.abs(this.y1 - this.y2) > 1)
	{
	    this.SetOverrideTool(this.TOOL_PAN);
		this.StopPan();
	}
	else
        this.OnInfoTool(this.x1,this.y1);
}

this.StopQuickInfo = function()
{	
    this.StopDrag();
	if (Math.abs(this.x1 - this.x2) > 1 || Math.abs(this.y1 - this.y2) > 1)
	{
	    this.SetOverrideTool(this.TOOL_PAN);
		this.StopPan();
	}
	else
        this.OnQuickInfoTool(this.x1,this.y1);
}

/********** ZOOMIN ****************************************************************/
this.StopZoomIn = function()
{
	this.StopDrag();
	this.MapCanvas.clear();
	this.UpdateRect();
	if (this.rright - this.rleft > 1)
		this.OnZoomInRectTool(this.rleft, this.rtop, this.rright, this.rbottom);
	else
		this.OnZoomInTool(this.x1, this.y1);
}


/********** RECT ****************************************************************/
this.StartRect = function(x,y)
{
	this.StartDrag(x,y);
	this.UpdateRect();	
}

this.DrawRect = function(x,y)
{	
	this.MapCanvas.clear();
	this.UpdateDrag(x,y);
	this.UpdateRect();
	this.MapCanvas.drawRect(this.rleft, this.rtop, this.rright-this.rleft, this.rbottom-this.rtop); 
	this.MapCanvas.paint();
}

this.StopRect = function()
{
	this.StopDrag();
	this.MapCanvas.clear();
	this.UpdateRect();
	if (this.rright - this.rleft > 1)
		this.OnRectTool(this.rleft, this.rtop, this.rright, this.rbottom);			
}

this.UpdateRect = function()
{
	var tempX=this.x1;
	var tempY=this.y1;
	if (this.x1>this.x2) 
	{
		this.rright=this.x1;
		this.rleft=this.x2;
	} 
	else 
	{
		this.rleft=this.x1;
		this.rright=this.x2;
	}
	
	if (this.y1>this.y2) 
	{
		this.rbottom=this.y1;
		this.rtop=this.y2;
	} 
	else 
	{
		this.rtop=this.y1;
		this.rbottom=this.y2;
	}
}

/********** LINE ****************************************************************/
this.StartLine = function(x,y)
{
	this.StartDrag(x,y);
}

this.DrawLine = function(x,y)
{
	this.MapCanvas.clear();
	this.UpdateDrag(x,y);
	this.MapCanvas.drawLine(this.x1, this.y1, this.x2, this.y2); 
	this.MapCanvas.paint();
}

this.StopLine = function()
{
	this.StopDrag();
	this.MapCanvas.clear();
	if (Math.abs(this.x1 - this.x2) > 1 || Math.abs(this.y1 - this.y2) > 1)
		this.OnLineTool(this.x1, this.y1, this.x2, this.y2);			
}

/********** PAN ****************************************************************/
this.StartPan = function(x,y)
{   
    if (__amIsAspAjaxCall) return;
 
    this.HideInfoWindow();
	this.StartDrag(x,y);
	this.prevPanX = x;
	this.prevPanY = y;
}

this.DrawPan = function(x,y)
{  
    if (!this.isDragging) return;

	this.SetPanCursorForInfo();
	this.UpdateDrag(x,y);

try
{
	var img = __$(this.MapID + "_Image");
	var left = (this.x2 - this.x1) + 'px';
	var top = (this.y2 - this.y1) + 'px';
	
	img.style.left =  left;
    img.style.top = top;
    
    // wms layers
    var index = 0;
    while (true)
    {
        img = __$(this.MapID + "wms" + index);
        if (!img) break;
        
    	img.style.left =  left;
        img.style.top = top;
        
        index++;
    }

	left = (this.x2 - this.x1);
	top = (this.y2 - this.y1);
    
    // tile layers
    this.PanImage(this.MapID + "tile", left, top);
    
    // google or VE layers
    this.PanBackLayer(x - this.prevPanX, y - this.prevPanY);
    
    // markers
    this.PanImage(this.MapID + "m", left, top);
}
catch(e){ }
    
   	this.prevPanX = x;
	this.prevPanY = y;
}

this.PanImage = function(id, left, top)
{
    var index = 0;
    while (true)
    {        
        img = __$(id + index);
        if (!img){ break; }
        
        var itop = img.offsetTop;
        var ileft = img.offsetLeft;
        
        if (!img.getAttribute("itop"))
        {
            img.setAttribute("itop", img.offsetTop);
            img.setAttribute("ileft", img.offsetLeft);
        }
        else
        {
            itop = parseInt(img.getAttribute("itop"));
            ileft = parseInt(img.getAttribute("ileft"));            
        }    
        
    	img.style.left = (ileft + left) + "px";
        img.style.top = (itop + top) + "px";
        
        index++;
    }        
}

this.StopPan = function()
{
    if (!this.isDragging) return;

    this.UpdateCursor();
	this.StopDrag();
	if (Math.abs(this.x1 - this.x2) > 1 || Math.abs(this.y1 - this.y2) > 1)
		this.OnLineTool(this.x1, this.y1, this.x2, this.y2);
	else
	{
	    if (this.panToolHandler)
	    try
	    {
	        this.panToolHandler(this.apiVar, this.GetMouseEventArgs(true));
	    }
	    catch(e){}
	}
}

/********** CIRCLE ****************************************************************/
this.StartCircle = function(x,y)
{
	this.StartDrag(x,y);
}

this.DrawCircle = function(x,y, clearCanvas)
{
	if (clearCanvas) this.MapCanvas.clear();
	this.UpdateDrag(x,y);
	var d = this.dist(this.x1, this.y1, this.x2, this.y2);
	this.MapCanvas.drawEllipse(this.x1-d, this.y1-d, d*2, d*2); 
	this.MapCanvas.paint();
}

this.StopCircle = function()
{
	this.StopDrag();
	this.MapCanvas.clear();
	if (Math.abs(this.x1 - this.x2) > 1)
	{
		var d = this.dist(this.x1, this.y1, this.x2, this.y2);	
		this.OnCircleTool(this.x1, this.y1, d);
	}
}

this.dist = function(x1, y1, x2, y2)
{
	return Math.round(Math.abs(this.hypot(x1-x2, y1-y2)));
}

this.hypot = function(a, b)
{
   return Math.sqrt((a * a) + (b * b))
}

/********** POLYLINE ****************************************************************/
this.StartPolyline = function(x,y)
{
	if (!this.isDragging)
	{
		this.Xpts = new Array();
		this.Ypts = new Array(); 
	}

	this.StartDrag(x,y);
	this.Xpts[this.Xpts.length] = x;
	this.Ypts[this.Ypts.length] = y;									
}

this.DrawPolyline = function(x,y)
{
	this.MapCanvas.clear();
	this.UpdateDrag(x,y);
	this.MapCanvas.drawPolyline(this.Xpts, this.Ypts);
	this.MapCanvas.drawLine(this.x1, this.y1, this.x2, this.y2);
	this.MapCanvas.paint();
}

this.StopPolyline = function()
{	
	this.StopDrag();
	this.MapCanvas.clear();
	if (this.Xpts.length > 1 && this.dist(this.Xpts[0], this.Ypts[0], this.Xpts[1], this.Ypts[1]) > 1)
		this.OnPolylineTool(this.Xpts, this.Ypts);			
}

this.DrawDistance = function(x,y, paintCanvas)
{
    var fcolor = "#000000";
	var bcolor = "#FFFFFF";

    this.MapCanvas.clear();	    
	this.UpdateDrag(x,y);
	this.MapCanvas.drawPolyline(this.Xpts, this.Ypts);
	this.MapCanvas.drawLine(this.x1, this.y1, this.x2, this.y2);
	
	var distance = 0;
	for (var i = 0; i < this.Xpts.length-1; i++)
	    distance += this.dist(this.Xpts[i], this.Ypts[i], this.Xpts[i+1], this.Ypts[i+1]);    
	distance += this.dist(this.x1, this.y1, this.x2, this.y2);
		
	distance *= this.mpp();
	
	var top = this.MapHeight() - 28;
	
	if ((distance/1609.34) > 1)
	{
	    var units = Math.round(1000 * distance / 1609.34) / 1000;
	    this.MapCanvas.drawString(units + " " + this.miles(), 1, top, fcolor, bcolor);
	}
    else
    {
        units = Math.round(distance / 0.3048);
	    this.MapCanvas.drawString(units + " " + this.feet(), 1, top, fcolor, bcolor);    
    }	
	    
	if ((distance/1000) > 1)
	{
	    units = Math.round(1000 * distance / 1000) / 1000;
	    this.MapCanvas.drawString(units + " " + this.km(), 1, top+14, fcolor, bcolor);
	}
	else
	{	    
	    this.MapCanvas.drawString((Math.round(10 * distance)/10) + " " + this.meters(), 1, top+14, fcolor, bcolor);	    
	}
	
	if (paintCanvas)	
	    this.MapCanvas.paint();
}

this.StopDistance = function()
{	
	this.StopDrag();
	this.MapCanvas.clear();
}

/********** POLYGON ****************************************************************/
this.StartPolygon = function(x,y)
{
	if (!this.isDragging)
	{
		this.Xpts = new Array();
		this.Ypts = new Array(); 
	}
	
	this.StartDrag(x,y);
	this.Xpts[this.Xpts.length] = x;
	this.Ypts[this.Ypts.length] = y;									
}

this.DrawPolygon = function(x,y)
{
	this.MapCanvas.clear();
	this.UpdateDrag(x,y);
	var tx = new Array().concat(this.Xpts);
	var ty = new Array().concat(this.Ypts);
	tx[tx.length] = this.x2;
	ty[ty.length] = this.y2;
	this.MapCanvas.drawPolygon(tx, ty);
	this.MapCanvas.paint();
}

this.StopPolygon = function()
{
	this.StopDrag();
	this.MapCanvas.clear();
	if (this.Xpts.length > 2  && this.dist(this.Xpts[0], this.Ypts[0], this.Xpts[1], this.Ypts[1]) > 1)
	{
		this.Xpts[this.Xpts.length] = this.Xpts[0];
		this.Ypts[this.Ypts.length] = this.Ypts[0];									
		this.OnPolygonTool(this.Xpts, this.Ypts);			
	}
}

/***************************************************************************/
this.StartDrag = function(x,y) 
{
	this.x1=x;
	this.y1=y
	this.x2=this.x1+1;
	this.y2=this.y1+1;
	this.isDragging=true;
}

this.UpdateDrag = function(x,y) 
{
	this.x2=x;
	this.y2=y;
}

this.StopDrag = function() 
{
	this.isDragging=false;
	return true;
}

/****************************************************************************************
Mouse/key event handlers
****************************************************************************************/
this.mouseX=0;
this.mouseY=0;

this.IsLeftDown = function(e)
{
	var button;
    if (e.which == null)
       button= (e.button < 2) ? 1 : ((e.button == 4) ? 2 : 3);
    else
       button= (e.which < 2) ? 1 : ((e.which == 2) ? 2 : 3);	
	
	return (button == 1);
}

this.OnMouseDown = function(e)
{
	if(!this.IsLeftDown(e))  
	{	
		this.CancelTool();
		return;	
	}

	// adjust left-top
	this.OnResize();

	this.GetImageXY(e);
	
	if ( this.mouseX>=0 &&
		 this.mouseX<this.MapWidth() && this.mouseY>=0 && this.mouseY<this.MapHeight()) 
	{
		this.StartTool(this.mouseX, this.mouseY);
		return false;
	} 	

	return false;
}

this.CallOnMouseMove = function() 
{	
	var t = thisToolsObj;
	var W = t.MapWidth();
	var H = t.MapHeight();

	if (t.mouseX>W)
		t.mouseX = W - 1;
	if (t.mouseY>H)
		t.mouseY = H - 1;
	if (t.mouseX<=0)
		t.mouseX = 1;
	if (t.mouseY<=0)
		t.mouseY = 1;

	if (t.isDragging)
	{	
		t.DragTool(t.mouseX, t.mouseY);
	}

	return false;
}

var tools_gt;
var tools_gfunc;
var tools_gCount=0;
var thisToolsObj = null;

this.OnMouseMove = function(e)
{
	thisToolsObj = this;

	if (!this.isDragging)
	{
	    this.RefreshCursor();	
    	this.OnResize();
	}
	
	this.GetImageXY(e);

	/*if (this.isDragging)
	{		
		clearTimeout(tools_gt);
		tools_gCount++;	
	
		tools_gfunc=function() 
		{ 
			CallOnMouseMove();
		};
	
		if (tools_gCount <= 3) 
		{
	  		tools_gt=setTimeout(tools_gfunc,80);
		} 
		else 
		{
	  	tools_gfunc();
	  	tools_gCount=0;
		}
	}*/
	
	this.CallOnMouseMove();

	//this.ShowLatLong(true);	

	//this.HideToolTips();
		
	return false;
}

this.RefreshCursor = function()
{
    var refreshFlag = __$(this.MapID + "_rf");
    if (refreshFlag == null) return;
    if (refreshFlag.value == "1")
    {
        this.UpdateCursor();
        refreshFlag.value = "0";
    }
}

this.OnMouseLeave = function(e) 
{
    if (this.isDragging && this.GetMapTool() == this.TOOL_PAN)
    {
        this.StopTool();
    }
        
	this.ShowLatLong(false);
	
	return false;
}

this.GetCenterLatLong = function()
{
    return new AspMap.Point(this.GetDbl("_xd"), this.GetDbl("_yd"));
}

this.GetCenterInMapUnits = function()
{
    return new AspMap.Point(this.GetDbl("_xu"), this.GetDbl("_yu"));
}

this.GetMouseEventArgs = function(insideMap)
{
    var dpp = this.GetDbl("_dpp");
    var upp = this.GetDbl("_upp");

    var center = this.GetCenterLatLong();		
	var lng = center.x + (this.mouseX-Math.round(this.MapWidth()/2)) * dpp;
	var lat = center.y - (this.mouseY-Math.round(this.MapHeight()/2)) * dpp;
	
	center = this.GetCenterInMapUnits();		
	var x = center.x + (this.mouseX-Math.round(this.MapWidth()/2)) * upp;
	var y = center.y - (this.mouseY-Math.round(this.MapHeight()/2)) * upp;	

    var args = new AspMap.MouseEventArgs();
    args.x = this.mouseX;
    args.y = this.mouseY;
    args.isInside = insideMap;
    args.longitude = lng;
    args.latitude = lat;
    args.mapPoint = new AspMap.Point(x,y);
    
    return args;            
}

this.ShowLatLong = function(show)
{		
	try
	{
	    if (this.mouseMoveHandler)
	    {	        
	        this.mouseMoveHandler(this.apiVar, this.GetMouseEventArgs(show));
	    }
	}
	catch(ex){}
}

this.OnMouseOver = function(e) 
{
	this.RefreshCursor();
	return false;
}

this.OnMouseUp = function(e) 
{
	if (this.isDragging/* || this.GetTool()==this.TOOL_INFO*/)
	{	
	    this.GetImageXY(e);
		this.StopTool(this.mouseX, this.mouseY);
	}

	return false;
}

this.OnDoubleClick = function(e)
{
    var tool = this.GetTool();

	if (this.isDragging)
	{			
		this.StopCompTool();
	}
	else if (tool == this.TOOL_PAN || tool == this.TOOL_INFO || tool == this.TOOL_QINFO)
	{
	    if (!this.IsLeftDown(e)) return;

    	this.OnResize();
    	this.GetImageXY(e);
        
        this.SetOverrideTool(this.TOOL_ZOOMIN);
        this.OnZoomInTool(this.mouseX, this.mouseY);
	}
	
	return false;	
}

this.OnKeyDown = function(e)
{
   if (e.keyCode == 27)
	  this.CancelTool(); 
}

this.OnMouseWheel = function(e)
{
   if (this.isDragging || !this.EnableMouseWheel()) return;
   
    this.OnResize();
	this.GetImageXY(e);
	  
    e = e ? e : window.event;
    var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40; 
   
   var res = __cancelEvent(e);
   
    this.OnWheel(wheelData > 0, this.mouseX, this.mouseY); // zoom in if wheelData is positive
   
   return res;
}

// get cursor location
this.GetImageXY = function (event) 
{
	if (event.pageX) 
	{
		this.mouseX=event.pageX;
		this.mouseY=event.pageY;	
	} 
	else 
	{
	    // if IE in standards mode - http://www.quirksmode.org/js/doctypes.html
		if (document.documentElement && document.documentElement.scrollTop) 
		{
   			this.mouseX=event.clientX + document.documentElement.scrollLeft-2;  
		   	this.mouseY=event.clientY + document.documentElement.scrollTop-2;
		} 
		else 
		{
			this.mouseX=event.clientX + document.body.scrollLeft-2;  
   			this.mouseY=event.clientY + document.body.scrollTop-2;
  		}  		
	}	
	
	this.mouseX = this.mouseX-this.hspc;
	this.mouseY = this.mouseY-this.vspc;			
}

///////////////////////////////////////////////////////////////////////////////////////////////
// constructor
///////////////////////////////////////////////////////////////////////////////////////////////
this.Init = function (MapID, UniqueID, ZoomBarVar)
{	
	var MapCanvasID = MapID + "_Canvas";
	
	this.MapID = MapID; 
	this.UniqueID = UniqueID; 
	this.ZoomBarVar = ZoomBarVar;
	this.MapCanvas = new jsGraphicsEx(MapCanvasID);
	this.MapCanvas.setStroke(1);
	this.MapCanvas.setColor("#FF0000");
	this.MapCanvas.setFont("verdana,geneva,helvetica,sans-serif", "12px", "font-weight:bold;");

	this.UpdateCursor();
}

this.MapWidth = function()
{
	return parseInt(this.GetMapCanvas().style.width);
}
this.MapHeight = function()
{
	return parseInt(this.GetMapCanvas().style.height);
}

this.OnResize = function ()
{
try
{
	this.vspc = 0;
	this.hspc = 0;
	var element = this.GetMapCanvas();

	do
	{
		this.hspc += element.offsetLeft;
		this.vspc += element.offsetTop;
	}
	while( (element = element.offsetParent))
}
catch(ex){}
}

this.GetMapCanvas = function ()
{
	return __$(this.MapID+ "_Canvas");
}

this.GetMapImg = function ()
{
	return __$(this.MapID+ "_Image");
}

this.Show = function()
{
  var div = __$(this.MapID);
  if (div) div.style.visibility = "visible";  
  
  if (this.GetZoomBar()) this.GetZoomBar().show();  

  this.UpdateBackLayerVisibility();  
}

this.Hide = function()
{ 
  var div = __$(this.MapID);
  if (div) div.style.visibility = "hidden";
  
  if (this.GetZoomBar()) this.GetZoomBar().hide();
  
  this.UpdateBackLayerVisibility();
}

this.UpdateMapVisibility = function()
{
    if (this.IsVisible())
        this.Show();
    else
        this.Hide();
}

////////////////////////////////////////////////////////////////
// Server-side tool events
////////////////////////////////////////////////////////////////
this.OnPointTool = function(x,y)
{
    var processed = false;	
	if (this.pointToolHandler)
    try
    {
        processed = this.pointToolHandler(this.apiVar, this.GetMouseEventArgs(true));
    }
    catch(e){}
	    
	if (!processed)
	    this.Submit(x, y, "");
}

this.OnRectTool = function(x1, y1, x2, y2)
{
	this.Submit(this.pack(x1,x2), this.pack(y1,y2), "");
}

this.OnLineTool = function(x1, y1, x2, y2)
{
	this.OnRectTool(x1, y1, x2, y2);
}

this.OnCircleTool = function(x, y, radius)
{
	this.Submit(x, y, radius);
}

this.OnPolylineTool = function(pointsX, pointsY)
{
	this.Submit(pointsX.join(";"), pointsY.join(";"), "");
}

this.OnPolygonTool = function(pointsX, pointsY)
{
	this.Submit(pointsX.join(";"), pointsY.join(";"), "");
}

this.OnZoomInTool = function(x, y)
{
	this.Submit(x, y, "");
}

this.OnZoomInRectTool = function(x1, y1, x2, y2)
{
	this.OnRectTool(x1, y1, x2, y2);
}

this.OnZoomOutTool = function(x, y)
{
	this.Submit(x, y, "");
}

this.OnCenterTool = function(x, y)
{
	this.Submit(x, y, "");
}

this.OnInfoTool = function(x, y)
{
    var processed = false;	
	if (this.infoToolHandler)
    try
    {
        processed = this.infoToolHandler(this.apiVar, this.GetMouseEventArgs(true));
    }
    catch(e){}
	    
    if (!processed)
	    this.Submit(x, y, "");
}

this.OnWheel = function(zoomin, x, y)
{
    if (zoomin)
    {
        var cx = Math.round(this.MapWidth()/2 + (x - this.MapWidth()/2) / 2);
        var cy = Math.round(this.MapHeight()/2 + (y - this.MapHeight()/2) / 2);
        
        this.AnimateZoom(x,y,zoomin);
        
        this.SubmitTool(this.TOOL_ZOOMIN, cx, cy, "");
    }
    else
    {
        var xy = this.Rotate(this.MapWidth()/2, this.MapHeight()/2, x - this.MapWidth()/2, y - this.MapHeight()/2, 180);
        
        this.AnimateZoom(x,y,zoomin);
        
        this.SubmitTool(this.TOOL_ZOOMOUT, xy.x, xy.y, "");
    }
}

this.AnimateZoom = function(x,y,isZoomIn)
{
    var imgID = "";
    if (isZoomIn)
        imgID = "aspmap_whzi";
    else
        imgID = "aspmap_whzo";    
            
    var img = __$(imgID);
    if (img)
    {
         var ext = __getDivExt(this.MapID);
            
         img.style.left = (ext.left + x - 29) + "px";
         img.style.top = (ext.top + y - 29) + "px";
         img.src = img.src;
         img.style.display = "block";
         setTimeout("try{__$('" + imgID + "').style.display = 'none';}catch(e){}", 320);           
     }
}

this.Rotate = function(centerX, centerY, x, y, angle)
{
	angle = (angle)*Math.PI/180.0;
		
	var px = Math.round(x*Math.cos(angle) - y*Math.sin(angle) + centerX);
	var	py = Math.round(x*Math.sin(angle) + y*Math.cos(angle) + centerY);		
    
    return {x:px, y:py};
}

this.OnQuickInfoTool = function(x, y)
{   
    this.SetCmdParams(this.GetTool(), this.GetArgument(), x, y, "");
    this.qInfoX = x;
    this.qInfoY = y;        
    map_callback(this.UniqueID, __showQuickInfo, 'QINFO', this);	
    
    // clear x/y hiddens
    this.SetCmdParams(this.GetTool(), this.GetArgument(), "", "", "");
}

this.HotspotInfoClick = function(argument, xy)
{       
    var coords = xy.split(",");
    this.qInfoX = parseInt(coords[0]);
    this.qInfoY = parseInt(coords[1]);        
    map_callback(this.UniqueID, __showQuickInfo, 'HINFO'+argument, this);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////
// markers
///////////////////////////////////////////////////////////////////////////////////////////////////////
this.MarkerClick = function(argument, index, postbackFunc)
{
    var processed = false;	
	if (this.markerClickHandler)
    try    
    {
        var args = new AspMap.MarkerClickEventArgs(); 
        args.argument = argument;
        args.content = "";
        
        var contentDiv = __$(this.MapID + "c" + index);
        if (contentDiv) args.content = contentDiv.innerHTML;
    
        processed = this.markerClickHandler(this.apiVar, args);
    }
    catch(e){}
	    
    if (!processed && postbackFunc.length > 0)   
        eval(postbackFunc);
}

this.MarkerInfo = function(index, x, y)
{
    this.qInfoX = parseInt(x);
    this.qInfoY = parseInt(y);
    
    var contentDiv = __$(this.MapID + "c" + index);
    if (contentDiv)
    {
        this.ShowInfo(contentDiv.innerHTML);
    }
}


///////////////////////////////////////////////////////////////////////////////////////////////////////
// Info window
///////////////////////////////////////////////////////////////////////////////////////////////////////
this.HideInfoWindow = function()
{   
    __hideQuickInfo(this.MapID);
}

this.ShowInfo = function(html)
{   
    if (html.length == 0) return;
    
    var infoWin = __$(this.MapID+"_infodiv");
    if (!infoWin) return;

    var infoCt = __$(this.MapID+"_infoct");
    if (!infoCt) return;    
    
    var infoContentDiv = __$(this.MapID+"_infodivc");
    if (!infoContentDiv) return;          

    var infoContentUI = __$("iwui$");
    if (!infoContentUI) return;          

    __hideQuickInfo(this.MapID); 

    infoContentDiv.innerHTML =  infoContentUI.innerHTML.replace("iwctnt", html);
       
    var x = this.qInfoX; 
    var y = this.qInfoY;
    var divW = __getDivW(infoWin);
    var divH = __getDivH(infoWin);
    var screenW = this.MapWidth();
    var screenH = this.MapHeight();
    
    var padding = 12;
    var calloutW = 20;
    var indentY = 20;
    var divX = 0;
    var divY = 0;

    if (divW <= screenW)
    {
	    divX = x - divW / 2 - calloutW / 2;
 	    if (divX+divW > screenW)
	    {
            var d = divX+divW - screenW + 1;
	        if (screenW - x <= padding)
		        d -= padding - (screenW - x) + 1;
  	        divX -= d;
	    }
	    if (divX <= 0)
	    {
	        var d = Math.abs(divX);
	        if (x <= calloutW + padding)
		        d -= calloutW + padding - x;
	        else
	            d += 1;
	        divX += d;
	    }
    }
    else
    {	
	    divX = x - divW / 2 - calloutW / 2;
	    if (divX <= 0)
	    {
	        var d = Math.abs(divX);
	        if (x < calloutW + padding)
		        d -= calloutW + padding - x;
	        else
	            d += 1;
	        divX += d;
	    }
	    else
	        divX = 1;
    }

    x -= calloutW;
		
    if (((y + divH + indentY >= screenH) || (y - divH - indentY > 0)) 
		&& (y - divH - indentY) >= 0)
    {
        divY = y - divH - indentY;
	    y -= 22;	
    }
    else
    {        
	    divY = y + indentY;	
    }

    if (divY > y)
    {
    	infoCt.src = __$("rtct$").src;
    }
    else
    {
	    infoCt.src = __$("rbct$").src;
    }
    
    infoWin.style.left = divX + "px";
    infoWin.style.top = divY + "px";    
	
    infoCt.style.left = x + "px";
    infoCt.style.top = y + "px";    
    
    infoCt.style.visibility="visible";   
    infoWin.style.visibility="visible";
}

///////////////////////////////////////////////////////////////////////////////////////////////////////
// server-side communications
///////////////////////////////////////////////////////////////////////////////////////////////////////

// submits current tool
this.Submit = function(x,y,arg)
{
    this.HideInfoWindow();
	this.SetCmdParams(this.GetTool(), this.GetArgument(), x, y, arg);
	__submitMapToolCmd();
}

// submits arbitrary tool
this.SubmitTool = function(tool, x, y, arg)
{
    this.HideInfoWindow();
	this.SetCmdParams(this.GetTool(), this.GetArgument(), x, y, arg);
	this.SetOverrideTool(tool);
	__submitMapToolCmd();
}

this.SetCmdParams = function(tool, targ, x, y, arg)
{
	__$(this.MapID + '_arg').value = arg; 
	__$(this.MapID + '_targ').value = targ;
	__$(this.MapID + '_tool').value = tool;
	__$(this.MapID + '_x').value = x;     
	__$(this.MapID + '_y').value = y;     
}

///////////////////////////////////////////////////////////////////////////////////////////////////////
// cursors
///////////////////////////////////////////////////////////////////////////////////////////////////////
this.SetInfoCursor = function()
{
	this.GetMapCanvas().style.cursor = "help";
}

this.SetCrossCursor = function()
{
	this.GetMapCanvas().style.cursor = "crosshair";
}

this.SetPanCursor = function()
{
	this.GetMapCanvas().style.cursor = "move";
}

this.SetPanCursorForInfo = function()
{
    var c = this.GetStr("_curspan");
    if (c.length > 0)
	    this.GetMapCanvas().style.cursor = c;
}

this.SetDefCursor = function()
{
	this.GetMapCanvas().style.cursor = "default";
}

this.GetCursor = function()
{
	return __$(this.MapID + "_curs").value;
}

this.SetCursor = function(c)
{
    if (c == null) return;
    
    __$(this.MapID + "_curs").value = c;
	
	if (c.length > 0)    
	{
	    this.GetMapCanvas().style.cursor = c;
	    return;
	}		
	
	var tool = this.GetTool();
	
	// set default cursors
	if (tool == this.TOOL_CENTER)
		this.SetCrossCursor();
	else if (tool == this.TOOL_PAN)
		this.SetPanCursor();
	else if (tool == this.TOOL_INFO || tool == this.TOOL_QINFO)
		this.SetInfoCursor();	
	else
		this.SetDefCursor();
}

this.HideToolTips = function()
{
    // hides tooltips leaved on screen by tracking mouseovers    
    __TT.hideToolpipsFromTracking();
}


///////////////////////////////////////////////////////////////////////////////////////////////////////
// map properties stored in hidden fields
///////////////////////////////////////////////////////////////////////////////////////////////////////
this.GetMapTool = function()
{
	return parseInt(__$(this.MapID + "_tool").value);
}

this.SetMapTool = function(tool)
{
	__$(this.MapID + "_tool").value = tool;
}

this.SetOverrideTool = function(tool)
{
	__$(this.MapID + "_otool").value = tool;
}

this.SetApiCall = function()
{
	__$(this.MapID + "_api").value = "1";
}

this.SetToolArgument = function (arg)
{
    __$(this.MapID + "_targ").value = arg;
}

this.GetToolArgument = function ()
{
    return __$(this.MapID + "_targ").value;
}

this.mpp = function()
{
	return parseFloat(__$(this.MapID + "_mpp").value);
}
this.miles = function()
{
	return __$(this.MapID + "_mis").value;
}
this.feet = function()
{
	return __$(this.MapID + "_fts").value;
}
this.km = function()
{
	return __$(this.MapID + "_kms").value;
}
this.meters = function()
{
	return __$(this.MapID + "_mts").value;
}

this.LineWidth = function()
{
	return parseInt(__$(this.MapID + "_tlw").value);
}

this.LineColor = function()
{
	return __$(this.MapID + "_tlc").value;
}

this.EnablePan = function()
{
	return __$(this.MapID + "_enpan").value == "1";
}

this.EnableMouseWheel = function()
{
	return __$(this.MapID + "_emw").value == "1";
}

this.BackLayerService = function()
{
    var s = __$(this.MapID + "blservice");
    if (s)
        return s.value;
    
    return null;
}

this.BackLayerType = function()
{
    var s = __$(this.MapID + "bltype");
    if (s)
        return parseInt(s.value);
    
    return 0;
}

this.BackLayerVisible = function()
{
    var s = __$(this.MapID + "blvisible");
    if (s)
        return s.value == "1";
    
    return false;
}

this.IsVisible = function()
{
    return this.GetBool("_vis");
}

this.SetVisible = function(value)
{
    this.SetBool("_vis", value);
    this.UpdateMapVisibility();
}

///////////////////////////////////////////////////////////////////////////////////////////
// hidden properties set/get
///////////////////////////////////////////////////////////////////////////////////////////
this.GetDbl = function(param)
{
    return parseFloat(this.GetStr(param));
}

this.SetDbl = function(param, value)
{
    this.SetStr(param, value);
}

this.GetBool = function(param)
{
    return this.GetStr(param) == "1";
}

this.SetBool = function(param, value)
{
    this.SetStr(param, value?"1":"0");
}

this.GetInt = function(param)
{
    return parseInt(this.GetStr(param));
}

this.SetInt = function(param, value)
{
    this.SetStr(param, Math.round(value));
}

this.GetStr = function(param)
{
    return __$(this.MapID + param).value;
}

this.SetStr = function(param, value)
{
    __$(this.MapID + param).value = value;
}

// mix
this.pack = function(a,b)
{
	return (a + ";" + b);
}

////////////////////////////////////////////////////////////////////////////////////////////////
// printing
////////////////////////////////////////////////////////////////////////////////////////////////
this.Print = function()
{

var framediv = null;

try
{
    var html = __$(this.MapID).innerHTML;
    
    var onregex = /[o]n[a-zA-Z0-9]+="[^"]*"/g;
    html = html.replace(onregex, "");
    
    var frame = frames["amprnfr"];
    framediv = frame.document.getElementById("content");
    framediv.style.position = "relative";
    framediv.style.width = this.MapWidth() + "px";
    framediv.style.height = this.MapHeight() + "px";
    framediv.innerHTML = html;
        
    var canvasDiv = frame.document.getElementById(this.MapID + "_Canvas");   
    canvasDiv.style.backgroundImage = ""; // fix firefox transp. gif printing issue

    var bgLayer = __$(this.MapID+"bglayer").cloneNode(true);
    bgLayer.style.left="0px";
    bgLayer.style.top="0px";    
    bgLayer.style.zIndex = 0;
    framediv.appendChild(bgLayer);

    frame.document.body.style.visibility = "visible";
    
    frame.focus();
    frame.prn();
}
catch (e){  }

}


////////////////////////////////////////////////////////////////////////////////////////////////
// background layer
////////////////////////////////////////////////////////////////////////////////////////////////
this.backLayerDiv = null;
this.backLayer = null;

this.InitBackLayerDiv  = function()
{
	var backLayerDiv = document.createElement("div");
	backLayerDiv.style.position = "absolute";	
	backLayerDiv.id = this.MapID + "bglayer";	
	this.InitBackLayerSize(backLayerDiv);	
	backLayerDiv.style.zIndex = "180";
	backLayerDiv.style.visibility='hidden';
	
    document.body.appendChild(backLayerDiv);
  	    
	this.backLayerDiv = backLayerDiv;
	
	var service = this.BackLayerService();
	if (service)
	{
	    if (service == "google")
	    {
	        this.backLayer = new AspMapGM(this.backLayerDiv, this.BackLayerType())
	    }
	    else if (service == "ve")
	    {
	        this.backLayer = new AspMapVE(this.backLayerDiv, this.BackLayerType())	        
	    }
	    
	    if (this.backLayer.IsValid())
	    {
	        this.backLayer.CenterAndZoom(this.GetCenterLatLong(), this.GetZoom());
	        
	        if (this.BackLayerVisible() && this.IsVisible())
	            backLayerDiv.style.visibility="visible";
	    }
	    else
	         this.backLayer = null;
	}
}

this.UpdateBackLayer  = function()
{
    if (this.backLayer)
	{
	    this.UpdateBackLayerVisibility();
	        
	    this.backLayer.SetMapType(this.BackLayerType());
	        
	    this.backLayer.CenterAndZoom(this.GetCenterLatLong(), this.GetZoom());
	}
}

this.UpdateBackLayerVisibility  = function()
{
    if (this.backLayer)
	{
	    if (this.BackLayerVisible() && this.IsVisible())
	        this.backLayerDiv.style.visibility="visible";
	    else
	        this.backLayerDiv.style.visibility="hidden";
	}
}


this.PanBackLayer  = function(dx, dy)
{
    if (this.backLayer)
	{
      this.backLayer.Pan(dx, dy);
    }  
}

this.ResizeBackLayer  = function()
{
    if (this.backLayerDiv) 
    {
        this.InitBackLayerSize(this.backLayerDiv);
        
        if (this.backLayer)  this.backLayer.Resize(this.MapWidth(), this.MapHeight());
    }
}

this.InitBackLayerSize = function(div)
{
    var ext = __getDivExt(this.MapID);
    if (ext == null) return;
	div.style.left = ext.left + "px";
	div.style.top = ext.top + "px";
	div.style.width = this.MapWidth() + "px";
	div.style.height = this.MapHeight() + "px";
}

/////////////////////////////////////////////////////////////////////////////////////////////////

this.load = function()
{
    this.RegisterAspAjaxHandlers();
    this.InitBackLayerDiv();
    this.UpdateMapVisibility();    
}

this.pageLoaded = function(sender, args)
{
    this.UpdateMapVisibility();
    this.ResizeBackLayer();
    this.UpdateBackLayer();  
}

this.resize = function(e)
{
    this.ResizeBackLayer();
}

__addHandlerCtx(window, "load", this);
__addHandlerCtx(window, "resize", this);

// ASP.NET AJAX support
this.RegisterAspAjaxHandlers = function()
{
    try
    {
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(__getAjaxEventCtx(this, "pageLoaded"));
    }
    catch(ex){}
}

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// AJAX call indicators
//////////////////////////////////////////////////////////////////////////////////////////////////////////
__addHandler(window, "load", __amAspAjaxInit);

var __amIsAspAjaxCall = false;
var __amEventValidation = null;

function __amAspAjaxInit()
{
    try
    {
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(__amAspAjaxBeginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(__amAspAjaxEndRequest);        
    }
    catch(ex){}    
}
function __amAspAjaxBeginRequest(sender, args)
{
    __amIsAspAjaxCall = true;
    
    try{ __TT.H(); } catch(e) {}
}
function __amAspAjaxEndRequest(sender, args)
{
    __amIsAspAjaxCall = false;
    
    try
    {    
        var ev = __$("__EVENTVALIDATION");
        if (ev)
           __amEventValidation = ev.value;
    }
    catch(ex){}
}

function __amUpdateEventValidation()
{
    try
    {            
        if (__amEventValidation)
        {
            var ev = __$("__EVENTVALIDATION");
            if (ev)
                ev.value = __amEventValidation;
        }
    }
    catch(ex){}    
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// google maps service
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AspMapGM(div, mapType)
{
this.mapObj = null;
this.dragObj = null;
       
this.IsValid = function()
{
    return (this.mapObj != null);
}

this.CenterAndZoom = function(center, zoom)
{
    if (!this.IsValid()) return;
    
    try{ this.mapObj.setCenter(new GLatLng(center.y, center.x), zoom);  }catch (e){}
}

this.Pan = function(dx, dy)
{
    if (!this.IsValid()) return;
    
    try{    
    
    this.dragObj.moveBy(new GSize(dx, dy)); 
    
    } catch (e)   {}
}

this.SetMapType = function(type)
{
    if (!this.IsValid()) return;

try{    
    switch (type)
    {
        case 0: this.mapObj.setMapType(G_NORMAL_MAP); break;
        case 1: this.mapObj.setMapType(G_SATELLITE_MAP); break;
        case 2: this.mapObj.setMapType(G_HYBRID_MAP); break;
        case 3: this.mapObj.setMapType(G_PHYSICAL_MAP); break;
    }    
}catch (e){}    
}

this.Resize = function(width, height)
{
    if (!this.IsValid()) return;

    try{    this.mapObj.checkResize();  }catch (e){}
}

// init 
try 
{
   // create GMap, hide nav controls
   this.mapObj = new GMap2( div );
                
   this.SetMapType(mapType);
            
   //since v 2.93 getDragObject is now available.
   if(typeof this.mapObj.getDragObject == "function") 
   {
       this.dragObj = this.mapObj.getDragObject();
   } 
} 
catch (e) 
{
   this.mapObj  = null;
}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// VE service
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AspMapVE(div, mapType)
{
this.mapObj = null;
this.dragObj = null;
       
this.IsValid = function()
{
    return (this.mapObj != null);
}

this.CenterAndZoom = function(center, zoom)
{
    if (!this.IsValid()) return;
    
    try{ this.mapObj.SetCenterAndZoom(new VELatLong(center.y, center.x), zoom+1);  }catch (e){}
}

this.Pan = function(dx, dy)
{
    if (!this.IsValid()) return;
    
   try{    
    
    this.mapObj.vemapcontrol.PanMap(-dx, -dy); 
    
   } catch (e)   {}
}

this.SetMapType = function(type)
{
    if (!this.IsValid()) return;

try{    
    switch (type)
    {
        case 0: this.mapObj.SetMapStyle(VEMapStyle.Road); break;
        case 1: this.mapObj.SetMapStyle(VEMapStyle.Aerial); break;
        case 2: this.mapObj.SetMapStyle(VEMapStyle.Hybrid); break;
    }    
}catch (e){}    
}

this.Resize = function(width, height)
{
    if (!this.IsValid()) return;

    try{    this.mapObj.Resize(width, height);  }catch (e){}
}


        try 
        {       
            this.mapObj = new VEMap(div.id);
                       
            if (this.mapObj != null) 
            {
                try {
                   this.mapObj.LoadMap(null, null, null, true);
                   this.mapObj.AttachEvent("onmousedown", function() {return true; });
                } catch (e) { }
            
              this.SetMapType(mapType);            
              this.mapObj.HideDashboard();   
            }            
        } 
        catch (e) 
        {
          this.mapObj  = null;
        }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// ZoomBar
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AspMapZoomBar(clientID, mapID, levelCount, levelH, showBar, pos)
{

// init
this.mapID = mapID;
this.clientID = clientID;
this.showBar = showBar;
this.levelCount = levelCount;
this.levelH = levelH;
this.drag = false;
this.pos = pos; // 0-outside, 1-left, 2-right

// methods
this.mousedown = function(e)
{
  if (!this.showBar) return true;
  
  if(e.preventDefault) // prevents firefox image drag
    e.preventDefault();
  
  this.drag = true;
  return false;
}

this.mousemove = function(e)
{
  if (!this.drag || !this.showBar) return true;

  this.moveThumb(e);

  return false;
}

this.mouseup = function(e)
{
  if (!this.drag || !this.showBar) return true;
  this.drag = false;

  var newLevel = this.moveThumb(e);

  if (newLevel >= 0)
  {
    var map = __getMapTools(this.mapID);
    if (!map) return false;
    map.SetZoom(newLevel);
  }
  
  return false;
}

this.resize = function(e)
{
  if (this.drag) return true;
  if (this.pos == 0)return true;

  var ext = __getDivExt(this.mapID);
  if (!ext) return true;

  var div = __$(this.clientID);
  div.style.top = ext.top + 4 + "px";
  
  if (this.pos == 1)
    div.style.left = ext.left + 4 + "px";
  else
    div.style.left = ext.right - __getDivW(div) - 4 + "px";
  
  var map = __getMapTools(this.mapID);
  if (map && map.IsVisible())    
    this.show();
    
  return true;
}

this.show = function()
{
  var div = __$(this.clientID);
  if (div) div.style.visibility = "visible";  
}

this.hide = function()
{
  var div = __$(this.clientID);
  if (div) div.style.visibility = "hidden";  
}


this.load = function(e)
{
  this.resize();
  return true;
}


this.moveThumb = function(e)
{
  e = e || window.event; 

  var mouseY = this.getMouseY(this.barID(), e);
  var barH = __getDivH(__$(this.barID()));

  var level = 0;
  
  if (mouseY <= 0)
    level = this.levelCount - 1;
  else if (mouseY >= barH) 
    level = 0;
  else 
    level = this.mouseToLevel(mouseY);
  
  if (level < 0 || level >= this.levelCount) return -1; 

  this.updateThumb(level);

  return level;
}

this.updateThumb = function(level)
{
  if (level < 0 || level >= this.levelCount) return; 

  var thumb = __$(this.thumbID());
  if (!thumb) return;

  var thumbH = __getDivH(thumb);

  thumb.style.top = (this.levelCount - level - 1) * this.levelH -
                    Math.round((thumbH - this.levelH ) / 2)  + "px";
}

this.mouseToLevel = function(mouseY)
{
  return this.levelCount - Math.floor(mouseY / this.levelH) - 1;
}

this.getMouseY = function(targetID, ev)
{
  var target = __$(targetID);
  if (!target) return 0;

  var top  = 0, y = 0;
 
  while (target.offsetParent)
  {
	top  += target.offsetTop;
    target  = target.offsetParent;
  }

  top  += target.offsetTop;
  
  var zoomBar = __$(this.clientID);
  top += Math.round((zoomBar.offsetHeight - zoomBar.clientHeight)/2);

  ev = ev || window.event;

  if (ev.pageY)
      y = ev.pageY;
  else
  {
        if (document.documentElement && document.documentElement.scrollTop) 
		{
		   	y=ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop;
		} 
		else 
		{
   			y=ev.clientY + document.body.scrollTop - document.body.clientTop;
  		}  		
  }		

  return y - top;
}

this.thumbID = function() { return this.clientID + "_th"; }
this.barID = function() { return this.clientID + "_bar"; }

this.pageLoaded = function(sender, args) 
{
   	var tools = __getMapTools(this.mapID);
	if (tools == null) return;
	
	this.resize();
	this.updateThumb(tools.GetZoom());
}

// constructor
if (this.showBar)
{
  __addHandlerCtx(document.body, "mousemove", this);
  __addHandlerCtx(document.body, "mouseup", this);
  __addHandlerCtx(__$(this.thumbID()), "mousedown", this);
}
if (this.pos > 0)
{
  __addHandlerCtx(window, "load", this);
  __addHandlerCtx(window, "resize", this);
  this.resize(null);
}

// ASP.NET AJAX support
try
{
  Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(__getAjaxEventCtx(this, "pageLoaded"));
}
catch(ex){}

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// global helpers
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function __selectMapTool(mapId, toolId, button, arg)
{	
	if (button == null) return;
	
	var prevId = __$(mapId + "_tbutt");
	if (prevId == null) return;
	
    var prevButton = __$(prevId.value);
				
	var tools = __getMapTools(mapId);
	if (tools == null) return;
				
	tools.SetTool(toolId);
	tools.SetArgument(arg);

    // cursor	
	var attr = button.getAttribute("curs");
	if (attr != null)  tools.SetCursor(attr);	
	
	if (prevButton)
	{
	    var attr = prevButton.getAttribute("normimg");
	    if (attr != null)  prevButton.src = attr;				
	    attr = prevButton.getAttribute("normbord");
	    if (attr != "notset") prevButton.style.borderStyle = attr;		
	}
		
	attr = button.getAttribute("selimg");
	if (attr != null)  button.src = attr;
	attr = button.getAttribute("selbord");
	if (attr != "notset") button.style.borderStyle = attr;
		
	prevId.value = button.id;
}

function __markerClick(mapID, argument, index, postbackFunc)
{
    var map = __getMapTools(mapID);
    if (map)
        map.MarkerClick(argument, index, postbackFunc);
}

function __markerInfo(mapID, markerIndex, x, y)
{
    var map = __getMapTools(mapID);
    if (map)
        map.MarkerInfo(markerIndex, x, y);
}

function __hsInfo(mapID, argument, xy)
{
    var map = __getMapTools(mapID);
    if (map)
        map.HotspotInfoClick(argument, xy);
}

function __showQuickInfo(response, mapCtrl)
{
    if (!response || response.length == 0 || !mapCtrl) return;
    mapCtrl.ShowInfo(response);
}

function __hideQuickInfo(mapID)
{
    try
    {   
        __$(mapID + '_infodiv').style.visibility='hidden';
        __$(mapID + '_infoct').style.visibility='hidden';
    }
    catch(e){}
}

function __$(id)
{
    if (id == null || id.length == 0)  return null;
  
    var elem = (document.getElementById ? document.getElementById(id)
			: document.all ? document.all[id]
			: null);
			
    if (elem == null)
    {
        var elemarray = document.getElementsByName(id);
        if (elemarray != null) elem = elemarray[0];
    }
    
    return elem;
}

function __getDivExt(divID)
{
  var target = __$(divID);
  if (!target) return null;

  var top  = 0, left = 0;
  var div = target;

  while (target.offsetParent)
  {
	top  += target.offsetTop;
	left  += target.offsetLeft;
    target  = target.offsetParent;
  }

  top  += target.offsetTop;
  left += target.offsetLeft;

  return {left:left,top:top,right:left+__getDivW(div),bottom:top+__getDivH(div)};
}

function __getDivW(el)
{
	return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0);
}
function __getDivH(el)
{
	return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0);
}
function __clearDiv(elem)
{
    if(elem)
    {
	while (elem.hasChildNodes())
  	   elem.removeChild(elem.firstChild);
	elem.innerHTML = "";
    }
}

function __cancelEvent(e)
{
  e = e ? e : window.event;
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}

// attaches mouse wheel for firefox
function __MWFF(mapID, callback)
{
    var el = __$(mapID);
    if (!el) return;
    
    if (el.addEventListener)
        el.addEventListener('DOMMouseScroll', callback, false);  
}

function __addHandler(el,eventName,handlerName)
{
  if (!el) return;
  if ( el.addEventListener )
     el.addEventListener(eventName, handlerName, false);
  else if ( el.attachEvent )
     el.attachEvent("on" + eventName, handlerName);
  else
     el["on" + eventName] = handlerName;
}

function __addHandlerCtx(el,eventName,ctxObj)
{
   var handler = __getHandlerCtx(ctxObj, eventName);
   __addHandler(el, eventName, handler);
}

function __getHandlerCtx(ctxObj, methodName)
{
    return (function(e)
    {
        return ctxObj[methodName](e);
    });
}                               

function __getAjaxEventCtx(ctxObj, methodName)
{
    return (function(sender, args)
    {
        return ctxObj[methodName](sender, args);
    });
}                               

function __getMapTools(mapID)
{
  var tools = null;
  try{ tools = eval(mapID.toLowerCase()+"_tools"); }catch(ex){}
  return tools;
}

function __getMapToolsName(mapID)
{
  return mapID.toLowerCase()+"_tools";
}

/////////////////////////////////////////////////////////////////////////////////////////
// java script graphics
/////////////////////////////////////////////////////////////////////////////////////////

var jg_ok, jg_ie, jg_fast, jg_dom, jg_moz;

function chkDHTM(x, i)
{
	x = document.body || null;
	jg_ie = x && typeof x.insertAdjacentHTML != "undefined" && document.createElement;
	jg_dom = (x && !jg_ie &&
		typeof x.appendChild != "undefined" &&
		typeof document.createRange != "undefined" &&
		typeof (i = document.createRange()).setStartBefore != "undefined" &&
		typeof i.createContextualFragment != "undefined");
	jg_fast = jg_ie && document.all && !window.opera;
	jg_moz = jg_dom && typeof x.style.MozOpacity != "undefined";
	jg_ok = !!(jg_ie || jg_dom);
}

function pntCnvDom()
{
	var x = this.wnd.document.createRange();
	var canvas = this.cnv();
	x.setStartBefore(canvas);
	x = x.createContextualFragment(jg_fast? this.htmRpc() : this.htm);
	if(canvas) canvas.appendChild(x);
	this.htm = "";
}

function pntCnvIe()
{
    var canvas = this.cnv();
	if(canvas) canvas.insertAdjacentHTML("BeforeEnd", jg_fast? this.htmRpc() : this.htm);
	this.htm = "";
}

function pntDoc()
{
	this.wnd.document.write(jg_fast? this.htmRpc() : this.htm);
	this.htm = '';
}

function pntN()
{
	;
}

function mkDiv(x, y, w, h)
{
	this.htm += '<div style="position:absolute;'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:' + w + 'px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
}

function mkDivIe(x, y, w, h)
{
	this.htm += '%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';
}

function mkDivPrt(x, y, w, h)
{
	this.htm += '<div style="position:absolute;'+
		'border-left:' + w + 'px solid ' + this.color + ';'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:0px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
}

var regex =  /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;
function htmRpc()
{
	return this.htm.replace(
		regex,
		'<div style="overflow:hidden;position:absolute;background-color:'+
		'$1;left:$2px;top:$3px;width:$4px;height:$5px"></div>\n');
}

function htmPrtRpc()
{
	return this.htm.replace(
		regex,
		'<div style="overflow:hidden;position:absolute;background-color:'+
		'$1;left:$2px;top:$3px;width:$4px;height:$5px;border-left:$4px solid $1"></div>\n');
}

function mkLin(x1, y1, x2, y2)
{
	if(x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1;

	if(dx >= dy)
	{
		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx,
		ox = x;
		while(dx > 0)
		{--dx;
			++x;
			if(p > 0)
			{
				this.mkDiv(ox, y, x-ox, 1);
				y += yIncr;
				p += pru;
				ox = x;
			}
			else p += pr;
		}
		this.mkDiv(ox, y, x2-ox+1, 1);
	}

	else
	{
		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy,
		oy = y;
		if(y2 <= y1)
		{
			while(dy > 0)
			{--dy;
				if(p > 0)
				{
					this.mkDiv(x++, y, 1, oy-y+1);
					y += yIncr;
					p += pru;
					oy = y;
				}
				else
				{
					y += yIncr;
					p += pr;
				}
			}
			this.mkDiv(x2, y2, 1, oy-y2+1);
		}
		else
		{
			while(dy > 0)
			{--dy;
				y += yIncr;
				if(p > 0)
				{
					this.mkDiv(x++, oy, 1, y-oy);
					p += pru;
					oy = y;
				}
				else p += pr;
			}
			this.mkDiv(x2, oy, 1, y2-oy+1);
		}
	}
}

function mkLin2D(x1, y1, x2, y2)
{
	if(x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1;

	var s = this.stroke;
	if(dx >= dy)
	{
		if(dx > 0 && s-3 > 0)
		{
			var _s = (s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy) / dx;
			_s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;
		}
		else var _s = s;
		var ad = Math.ceil(s/2);

		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx,
		ox = x;
		while(dx > 0)
		{--dx;
			++x;
			if(p > 0)
			{
				this.mkDiv(ox, y, x-ox+ad, _s);
				y += yIncr;
				p += pru;
				ox = x;
			}
			else p += pr;
		}
		this.mkDiv(ox, y, x2-ox+ad+1, _s);
	}

	else
	{
		if(s-3 > 0)
		{
			var _s = (s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy) / dy;
			_s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;
		}
		else var _s = s;
		var ad = Math.round(s/2);

		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy,
		oy = y;
		if(y2 <= y1)
		{
			++ad;
			while(dy > 0)
			{--dy;
				if(p > 0)
				{
					this.mkDiv(x++, y, _s, oy-y+ad);
					y += yIncr;
					p += pru;
					oy = y;
				}
				else
				{
					y += yIncr;
					p += pr;
				}
			}
			this.mkDiv(x2, y2, _s, oy-y2+ad);
		}
		else
		{
			while(dy > 0)
			{--dy;
				y += yIncr;
				if(p > 0)
				{
					this.mkDiv(x++, oy, _s, y-oy+ad);
					p += pru;
					oy = y;
				}
				else p += pr;
			}
			this.mkDiv(x2, oy, _s, y2-oy+ad+1);
		}
	}
}

/*function mkLinDott(x1, y1, x2, y2)
{
	if(x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1,
	drw = true;
	if(dx >= dy)
	{
		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx;
		while(dx > 0)
		{--dx;
			if(drw) this.mkDiv(x, y, 1, 1);
			drw = !drw;
			if(p > 0)
			{
				y += yIncr;
				p += pru;
			}
			else p += pr;
			++x;
		}
	}
	else
	{
		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy;
		while(dy > 0)
		{--dy;
			if(drw) this.mkDiv(x, y, 1, 1);
			drw = !drw;
			y += yIncr;
			if(p > 0)
			{
				++x;
				p += pru;
			}
			else p += pr;
		}
	}
	if(drw) this.mkDiv(x, y, 1, 1);
}*/

function mkOv(left, top, width, height)
{
	var a = (++width)>>1, b = (++height)>>1,
	wod = width&1, hod = height&1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	ox = 0, oy = b,
	aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,
	st = (aa2>>1)*(1-(b<<1)) + bb2,
	tt = (bb2>>1) - aa2*((b<<1)-1),
	w, h;
	while(y > 0)
	{
		if(st < 0)
		{
			st += bb2*((x<<1)+3);
			tt += bb4*(++x);
		}
		else if(tt < 0)
		{
			st += bb2*((x<<1)+3) - aa4*(y-1);
			tt += bb4*(++x) - aa2*(((y--)<<1)-3);
			w = x-ox;
			h = oy-y;
			if((w&2) && (h&2))
			{
				this.mkOvQds(cx, cy, x-2, y+2, 1, 1, wod, hod);
				this.mkOvQds(cx, cy, x-1, y+1, 1, 1, wod, hod);
			}
			else this.mkOvQds(cx, cy, x-1, oy, w, h, wod, hod);
			ox = x;
			oy = y;
		}
		else
		{
			tt -= aa2*((y<<1)-3);
			st -= aa4*(--y);
		}
	}
	w = a-ox+1;
	h = (oy<<1)+hod;
	y = cy-oy;
	this.mkDiv(cx-a, y, w, h);
	this.mkDiv(cx+ox+wod-1, y, w, h);
}

function mkOv2D(left, top, width, height)
{
	var s = this.stroke;
	width += s+1;
	height += s+1;
	var a = width>>1, b = height>>1,
	wod = width&1, hod = height&1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,
	st = (aa2>>1)*(1-(b<<1)) + bb2,
	tt = (bb2>>1) - aa2*((b<<1)-1);

	if(s-4 < 0 && (!(s-2) || width-51 > 0 && height-51 > 0))
	{
		var ox = 0, oy = b,
		w, h,
		pxw;
		while(y > 0)
		{
			if(st < 0)
			{
				st += bb2*((x<<1)+3);
				tt += bb4*(++x);
			}
			else if(tt < 0)
			{
				st += bb2*((x<<1)+3) - aa4*(y-1);
				tt += bb4*(++x) - aa2*(((y--)<<1)-3);
				w = x-ox;
				h = oy-y;

				if(w-1)
				{
					pxw = w+1+(s&1);
					h = s;
				}
				else if(h-1)
				{
					pxw = s;
					h += 1+(s&1);
				}
				else pxw = h = s;
				this.mkOvQds(cx, cy, x-1, oy, pxw, h, wod, hod);
				ox = x;
				oy = y;
			}
			else
			{
				tt -= aa2*((y<<1)-3);
				st -= aa4*(--y);
			}
		}
		this.mkDiv(cx-a, cy-oy, s, (oy<<1)+hod);
		this.mkDiv(cx+a+wod-s, cy-oy, s, (oy<<1)+hod);
	}

	else
	{
		var _a = (width-(s<<1))>>1,
		_b = (height-(s<<1))>>1,
		_x = 0, _y = _b,
		_aa2 = (_a*_a)<<1, _aa4 = _aa2<<1, _bb2 = (_b*_b)<<1, _bb4 = _bb2<<1,
		_st = (_aa2>>1)*(1-(_b<<1)) + _bb2,
		_tt = (_bb2>>1) - _aa2*((_b<<1)-1),

		pxl = new Array(),
		pxt = new Array(),
		_pxb = new Array();
		pxl[0] = 0;
		pxt[0] = b;
		_pxb[0] = _b-1;
		while(y > 0)
		{
			if(st < 0)
			{
				pxl[pxl.length] = x;
				pxt[pxt.length] = y;
				st += bb2*((x<<1)+3);
				tt += bb4*(++x);
			}
			else if(tt < 0)
			{
				pxl[pxl.length] = x;
				st += bb2*((x<<1)+3) - aa4*(y-1);
				tt += bb4*(++x) - aa2*(((y--)<<1)-3);
				pxt[pxt.length] = y;
			}
			else
			{
				tt -= aa2*((y<<1)-3);
				st -= aa4*(--y);
			}

			if(_y > 0)
			{
				if(_st < 0)
				{
					_st += _bb2*((_x<<1)+3);
					_tt += _bb4*(++_x);
					_pxb[_pxb.length] = _y-1;
				}
				else if(_tt < 0)
				{
					_st += _bb2*((_x<<1)+3) - _aa4*(_y-1);
					_tt += _bb4*(++_x) - _aa2*(((_y--)<<1)-3);
					_pxb[_pxb.length] = _y-1;
				}
				else
				{
					_tt -= _aa2*((_y<<1)-3);
					_st -= _aa4*(--_y);
					_pxb[_pxb.length-1]--;
				}
			}
		}

		var ox = -wod, oy = b,
		_oy = _pxb[0],
		l = pxl.length,
		w, h;
		for(var i = 0; i < l; i++)
		{
			if(typeof _pxb[i] != "undefined")
			{
				if(_pxb[i] < _oy || pxt[i] < oy)
				{
					x = pxl[i];
					this.mkOvQds(cx, cy, x, oy, x-ox, oy-_oy, wod, hod);
					ox = x;
					oy = pxt[i];
					_oy = _pxb[i];
				}
			}
			else
			{
				x = pxl[i];
				this.mkDiv(cx-x, cy-oy, 1, (oy<<1)+hod);
				this.mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);
				ox = x;
				oy = pxt[i];
			}
		}
		this.mkDiv(cx-a, cy-oy, 1, (oy<<1)+hod);
		this.mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);
	}
}

/*function mkOvDott(left, top, width, height)
{
	var a = (++width)>>1, b = (++height)>>1,
	wod = width&1, hod = height&1, hodu = hod^1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,
	st = (aa2>>1)*(1-(b<<1)) + bb2,
	tt = (bb2>>1) - aa2*((b<<1)-1),
	drw = true;
	while(y > 0)
	{
		if(st < 0)
		{
			st += bb2*((x<<1)+3);
			tt += bb4*(++x);
		}
		else if(tt < 0)
		{
			st += bb2*((x<<1)+3) - aa4*(y-1);
			tt += bb4*(++x) - aa2*(((y--)<<1)-3);
		}
		else
		{
			tt -= aa2*((y<<1)-3);
			st -= aa4*(--y);
		}
		if(drw && y >= hodu) this.mkOvQds(cx, cy, x, y, 1, 1, wod, hod);
		drw = !drw;
	}
}*/

function mkRect(x, y, w, h)
{
	var s = this.stroke;
	this.mkDiv(x, y, w, s);
	this.mkDiv(x+w, y, s, h);
	this.mkDiv(x, y+h, w+s, s);
	this.mkDiv(x, y+s, s, h-s);
}

/*function mkRectDott(x, y, w, h)
{
	this.drawLine(x, y, x+w, y);
	this.drawLine(x+w, y, x+w, y+h);
	this.drawLine(x, y+h, x+w, y+h);
	this.drawLine(x, y, x, y+h);
}*/

function jsgFont()
{
	this.PLAIN = 'font-weight:normal;';
	this.BOLD = 'font-weight:bold;';
	this.ITALIC = 'font-style:italic;';
	this.ITALIC_BOLD = this.ITALIC + this.BOLD;
	this.BOLD_ITALIC = this.ITALIC_BOLD;
}
var Font = new jsgFont();

function jsgStroke()
{
	this.DOTTED = -1;
}
var Stroke = new jsgStroke();

function jsGraphicsEx(cnv, wnd)
{
	this.setColor = new Function('arg', 'this.color = arg.toLowerCase();');

	this.setStroke = function(x)
	{
		this.stroke = x;
		if(!(x+1))
		{
			//this.drawLine = mkLinDott;
			//this.mkOv = mkOvDott;
			//this.drawRect = mkRectDott;
		}
		else if(x-1 > 0)
		{
			this.drawLine = mkLin2D;
			this.mkOv = mkOv2D;
			this.drawRect = mkRect;
		}
		else
		{
			this.drawLine = mkLin;
			this.mkOv = mkOv;
			this.drawRect = mkRect;
		}
	};

	this.setPrintable = function(arg)
	{
		this.printable = arg;
		if(jg_fast)
		{
			this.mkDiv = mkDivIe;
			this.htmRpc = arg? htmPrtRpc : htmRpc;
		}
		else this.mkDiv = arg? mkDivPrt : mkDiv;
	};

	this.setFont = function(fam, sz, sty)
	{
		this.ftFam = fam;
		this.ftSz = sz;
		this.ftSty = sty || Font.PLAIN;
	};

	this.drawPolyline = this.drawPolyLine = function(x, y)
	{
		for (var i=x.length - 1; i;)
		{--i;
			this.drawLine(x[i], y[i], x[i+1], y[i+1]);
		}
	};

	this.fillRect = function(x, y, w, h)
	{
		this.mkDiv(x, y, w, h);
	};

	this.drawPolygon = function(x, y)
	{
		this.drawPolyline(x, y);
		this.drawLine(x[x.length-1], y[x.length-1], x[0], y[0]);
	};

	this.drawEllipse = this.drawOval = function(x, y, w, h)
	{
		this.mkOv(x, y, w, h);
	};

/*	this.fillEllipse = this.fillOval = function(left, top, w, h)
	{
		var a = w>>1, b = h>>1,
		wod = w&1, hod = h&1,
		cx = left+a, cy = top+b,
		x = 0, y = b, oy = b,
		aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,
		st = (aa2>>1)*(1-(b<<1)) + bb2,
		tt = (bb2>>1) - aa2*((b<<1)-1),
		xl, dw, dh;
		if(w) while(y > 0)
		{
			if(st < 0)
			{
				st += bb2*((x<<1)+3);
				tt += bb4*(++x);
			}
			else if(tt < 0)
			{
				st += bb2*((x<<1)+3) - aa4*(y-1);
				xl = cx-x;
				dw = (x<<1)+wod;
				tt += bb4*(++x) - aa2*(((y--)<<1)-3);
				dh = oy-y;
				this.mkDiv(xl, cy-oy, dw, dh);
				this.mkDiv(xl, cy+y+hod, dw, dh);
				oy = y;
			}
			else
			{
				tt -= aa2*((y<<1)-3);
				st -= aa4*(--y);
			}
		}
		this.mkDiv(cx-a, cy-oy, w, (oy<<1)+hod);
	};

	this.fillArc = function(iL, iT, iW, iH, fAngA, fAngZ)
	{
		var a = iW>>1, b = iH>>1,
		iOdds = (iW&1) | ((iH&1) << 16),
		cx = iL+a, cy = iT+b,
		x = 0, y = b, ox = x, oy = y,
		aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,
		st = (aa2>>1)*(1-(b<<1)) + bb2,
		tt = (bb2>>1) - aa2*((b<<1)-1),
		// Vars for radial boundary lines
		xEndA, yEndA, xEndZ, yEndZ,
		iSects = (1 << (Math.floor((fAngA %= 360.0)/180.0) << 3))
				| (2 << (Math.floor((fAngZ %= 360.0)/180.0) << 3))
				| ((fAngA >= fAngZ) << 16),
		aBndA = new Array(b+1), aBndZ = new Array(b+1);
		
		// Set up radial boundary lines
		fAngA *= Math.PI/180.0;
		fAngZ *= Math.PI/180.0;
		xEndA = cx+Math.round(a*Math.cos(fAngA));
		yEndA = cy+Math.round(-b*Math.sin(fAngA));
		aBndA.mkLinVirt(cx, cy, xEndA, yEndA);
		xEndZ = cx+Math.round(a*Math.cos(fAngZ));
		yEndZ = cy+Math.round(-b*Math.sin(fAngZ));
		aBndZ.mkLinVirt(cx, cy, xEndZ, yEndZ);

		while(y > 0)
		{
			if(st < 0) // Advance x
			{
				st += bb2*((x<<1)+3);
				tt += bb4*(++x);
			}
			else if(tt < 0) // Advance x and y
			{
				st += bb2*((x<<1)+3) - aa4*(y-1);
				ox = x;
				tt += bb4*(++x) - aa2*(((y--)<<1)-3);
				this.mkArcDiv(ox, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);
				oy = y;
			}
			else // Advance y
			{
				tt -= aa2*((y<<1)-3);
				st -= aa4*(--y);
				if(y && (aBndA[y] != aBndA[y-1] || aBndZ[y] != aBndZ[y-1]))
				{
					this.mkArcDiv(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);
					ox = x;
					oy = y;
				}
			}
		}
		this.mkArcDiv(x, 0, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);
		if(iOdds >> 16) // Odd height
		{
			if(iSects >> 16) // Start-angle > end-angle
			{
				var xl = (yEndA <= cy || yEndZ > cy)? (cx - x) : cx;
				this.mkDiv(xl, cy, x + cx - xl + (iOdds & 0xffff), 1);
			}
			else if((iSects & 0x01) && yEndZ > cy)
				this.mkDiv(cx - x, cy, x, 1);
		}
	};
*/

/* fillPolygon method, implemented by Matthieu Haller.
This javascript function is an adaptation of the gdImageFilledPolygon for Walter Zorn lib.
C source of GD 1.8.4 found at http://www.boutell.com/gd/

THANKS to Kirsten Schulz for the polygon fixes!

The intersection finding technique of this code could be improved
by remembering the previous intertersection, and by using the slope.
That could help to adjust intersections to produce a nice
interior_extrema. */
/*	this.fillPolygon = function(array_x, array_y)
	{
		var i;
		var y;
		var miny, maxy;
		var x1, y1;
		var x2, y2;
		var ind1, ind2;
		var ints;

		var n = array_x.length;
		if(!n) return;

		miny = array_y[0];
		maxy = array_y[0];
		for(i = 1; i < n; i++)
		{
			if(array_y[i] < miny)
				miny = array_y[i];

			if(array_y[i] > maxy)
				maxy = array_y[i];
		}
		for(y = miny; y <= maxy; y++)
		{
			var polyInts = new Array();
			ints = 0;
			for(i = 0; i < n; i++)
			{
				if(!i)
				{
					ind1 = n-1;
					ind2 = 0;
				}
				else
				{
					ind1 = i-1;
					ind2 = i;
				}
				y1 = array_y[ind1];
				y2 = array_y[ind2];
				if(y1 < y2)
				{
					x1 = array_x[ind1];
					x2 = array_x[ind2];
				}
				else if(y1 > y2)
				{
					y2 = array_y[ind1];
					y1 = array_y[ind2];
					x2 = array_x[ind1];
					x1 = array_x[ind2];
				}
				else continue;

				 //  Modified 11. 2. 2004 Walter Zorn
				if((y >= y1) && (y < y2))
					polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);

				else if((y == maxy) && (y > y1) && (y <= y2))
					polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);
			}
			polyInts.sort(CompInt);
			for(i = 0; i < ints; i+=2)
				this.mkDiv(polyInts[i], y, polyInts[i+1]-polyInts[i]+1, 1);
		}
	};
*/
	this.drawString = function(txt, x, y, fcolor, bcolor)
	{
		this.htm += '<div style="position:absolute;white-space:nowrap;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'font-family:' +  this.ftFam + ';'+
			'font-size:' + this.ftSz + ';'+
			'color:' + fcolor + ';' + 
			'background-color:' + bcolor + ';' +
			this.ftSty + '">'+
			txt +
			'<\/div>';
	};

/* drawStringRect() added by Rick Blommers.
Allows to specify the size of the text rectangle and to align the
text both horizontally (e.g. right) and vertically within that rectangle */
/*	this.drawStringRect = function(txt, x, y, width, halign)
	{
		this.htm += '<div style="position:absolute;overflow:hidden;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'width:'+width +'px;'+
			'text-align:'+halign+';'+
			'font-family:' +  this.ftFam + ';'+
			'font-size:' + this.ftSz + ';'+
			'color:' + this.color + ';' + this.ftSty + '">'+
			txt +
			'<\/div>';
	};

	this.drawImage = function(imgSrc, x, y, w, h, a)
	{
		this.htm += '<div style="position:absolute;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'width:' +  w + 'px;'+
			'height:' + h + 'px;">'+
			'<img src="' + imgSrc + '" width="' + w + '" height="' + h + '"' + (a? (' '+a) : '') + '>'+
			'<\/div>';
	};*/

	this.clear = function()
	{
		this.htm = "";
		__clearDiv(this.cnv());
	};

	this.mkOvQds = function(cx, cy, x, y, w, h, wod, hod)
	{
		var xl = cx - x, xr = cx + x + wod - w, yt = cy - y, yb = cy + y + hod - h;
		if(xr > xl+w)
		{
			this.mkDiv(xr, yt, w, h);
			this.mkDiv(xr, yb, w, h);
		}
		else
			w = xr - xl + w;
		this.mkDiv(xl, yt, w, h);
		this.mkDiv(xl, yb, w, h);
	};
	
/*	this.mkArcDiv = function(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects)
	{
		var xrDef = cx + x + (iOdds & 0xffff), y2, h = oy - y, xl, xr, w;

		if(!h) h = 1;
		x = cx - x;

		if(iSects & 0xff0000) // Start-angle > end-angle
		{
			y2 = cy - y - h;
			if(iSects & 0x00ff)
			{
				if(iSects & 0x02)
				{
					xl = Math.max(x, aBndZ[y]);
					w = xrDef - xl;
					if(w > 0) this.mkDiv(xl, y2, w, h);
				}
				if(iSects & 0x01)
				{
					xr = Math.min(xrDef, aBndA[y]);
					w = xr - x;
					if(w > 0) this.mkDiv(x, y2, w, h);
				}
			}
			else
				this.mkDiv(x, y2, xrDef - x, h);
			y2 = cy + y + (iOdds >> 16);
			if(iSects & 0xff00)
			{
				if(iSects & 0x0100)
				{
					xl = Math.max(x, aBndA[y]);
					w = xrDef - xl;
					if(w > 0) this.mkDiv(xl, y2, w, h);
				}
				if(iSects & 0x0200)
				{
					xr = Math.min(xrDef, aBndZ[y]);
					w = xr - x;
					if(w > 0) this.mkDiv(x, y2, w, h);
				}
			}
			else
				this.mkDiv(x, y2, xrDef - x, h);
		}
		else
		{
			if(iSects & 0x00ff)
			{
				if(iSects & 0x02)
					xl = Math.max(x, aBndZ[y]);
				else
					xl = x;
				if(iSects & 0x01)
					xr = Math.min(xrDef, aBndA[y]);
				else
					xr = xrDef;
				y2 = cy - y - h;
				w = xr - xl;
				if(w > 0) this.mkDiv(xl, y2, w, h);
			}
			if(iSects & 0xff00)
			{
				if(iSects & 0x0100)
					xl = Math.max(x, aBndA[y]);
				else
					xl = x;
				if(iSects & 0x0200)
					xr = Math.min(xrDef, aBndZ[y]);
				else
					xr = xrDef;
				y2 = cy + y + (iOdds >> 16);
				w = xr - xl;
				if(w > 0) this.mkDiv(xl, y2, w, h);
			}
		}
	};
*/
	this.setStroke(1);
	this.setFont("verdana,geneva,helvetica,sans-serif", "12px", Font.PLAIN);
	this.color = "#000000";
	this.htm = "";
	this.wnd = wnd || window;
	this.cnvID = cnv;

	if(!jg_ok) chkDHTM();
	if(jg_ok)
	{
		if(cnv)
		{
			if(typeof(cnv) == "string")
				this.cont = document.all? (this.wnd.document.all[cnv] || null)
					: document.getElementById? (this.wnd.document.getElementById(cnv) || null)
					: null;
			else if(cnv == window.document)
				this.cont = document.getElementsByTagName("body")[0];
			// If cnv is a direct reference to a canvas DOM node
			// (option suggested by Andreas Luleich)
			else this.cont = cnv;
			// Create new canvas inside container DIV. Thus the drawing and clearing
			// methods won't interfere with the container's inner html.
			// Solution suggested by Vladimir.
			//this.cnvas = document.createElement("div");
			//this.cont.appendChild(this.cnvas);		
			this.paint = jg_dom? pntCnvDom : pntCnvIe;
		}
		else
			this.paint = pntDoc;
	}
	else
		this.paint = pntN;

	this.setPrintable(false);
	
	this.cnv = function()
	{
	    var canvas = __$(this.cnvID);
	    var intcanvas = canvas.getElementsByTagName("DIV");
	    if (intcanvas == null) return canvas;
		return intcanvas[0];
	}
}

/*Array.prototype.mkLinVirt = function(x1, y1, x2, y2)
{
	var dx = Math.abs(x2-x1), dy = Math.abs(y2-y1),
	x = x1, y = y1,
	xIncr = (x1 > x2)? -1 : 1,
	yIncr = (y1 > y2)? -1 : 1,
	p,
	i = 0;
	if(dx >= dy)
	{
		var pr = dy<<1,
		pru = pr - (dx<<1);
		p = pr-dx;
		while(dx > 0)
		{--dx;
			if(p > 0)    //  Increment y
			{
				this[i++] = x;
				y += yIncr;
				p += pru;
			}
			else p += pr;
			x += xIncr;
		}
	}
	else
	{
		var pr = dx<<1,
		pru = pr - (dy<<1);
		p = pr-dy;
		while(dy > 0)
		{--dy;
			y += yIncr;
			this[i++] = x;
			if(p > 0)    //  Increment x
			{
				x += xIncr;
				p += pru;
			}
			else p += pr;
		}
	}
	for(var len = this.length, i = len-i; i;)
		this[len-(i--)] = x;
};*/

function CompInt(x, y)
{
	return(x - y);
}

function map_enableAutoRefresh()
{
    alert("The map_enableAutoRefresh() function has been deprecated. Use the Map.set_enableAnimation property.");
}

function map_setAnimationInterval()
{
    alert("The map_setAnimationInterval() function has been deprecated. Use the Map.set_animationInterval property.");
}

function map_refreshAnimationLayer()
{
    alert("The map_refreshAnimationLayer() function has been deprecated. Use the Map.refreshAnimationLayer method.");
}


/*function __GetWindowW()
{
    var ieOld = (!document.compatMode || document.compatMode == "BackCompat");
    var db = (!ieOld) ? document.documentElement : (document.body || null);
    var un = "undefined";
	return(document.body && (typeof(document.body.clientWidth) != un) ? document.body.clientWidth
			: (typeof(window.innerWidth) != un) ? window.innerWidth
			: db ? (db.clientWidth || 0)
			: 0);
}
function __GetWindowH()
{
    var ieOld = (!document.compatMode || document.compatMode == "BackCompat");
    var db = (!ieOld) ? document.documentElement : (document.body || null);
    var un = "undefined";
	return(document.body && (typeof(document.body.clientHeight) != un) ? document.body.clientHeight
			: (typeof(window.innerHeight) != un) ? window.innerHeight
			: db ? (db.clientHeight || 0)
			: 0);
}*/
