// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.3/standard_patch_03/wwwroot/js/standard/cbkort.js $ 
// $Date: 18-02-08 13:28 $
// $Revision: 19 $ 
// $Author: Kpo $
// =============================================================== 

// -------------------------------------------------------------
// Tool Mode Constants
// -------------------------------------------------------------
var tmZoomIn = 1;
var tmZoomOut = 2;
var tmCenter = 3;
var tmInfo = 4;
var tmDistAndArea = 5;
var tmPolygonSearch = 6;
var tmPoint = 7;
var tmRedline = 8;
var tmPan = 9;
var tmMoveBox = 10;
var tmDynaZoom = 11;
var tmRemove = 12;

function CBKort(mapId, host, mapFile, layers, extent)
{
    this.map = getElement(mapId);
    this.mapImage = getElement("themapimage");
    this.host = host;
    this.mapFile = mapFile;
    this.layers = layers;
    this.defaultLayers = "";
    this.toolMode = tmZoomIn;
    this.captureMouseEvents(this.map);
    this.jitter = 5;
    this.zoomBoxColor = "#FF0000"; // color of zoombox
    this.ovBoxSize = 2;  // zoombox line width;
    this.drawBox = false;
    this.mapWidth = this.mapImage.width;
    this.mapHeight = this.mapImage.height;
    this.mapX = getX(this.map);
    this.mapY = getY(this.map);
    this.mouseMoveHandler = null;
    this.infoHandler = null;
    this.extentArr = extent.split(" ");
    this.zleft=0;
    this.zright=0;
    this.ztop=0;
    this.zbottom=0;
    this.mouseX=0;
    this.mouseY=0;
    this.x1=0;
    this.y1=0;
    this.x2=0;
    this.y2=0;
    this.full_Extent = "";
    this.infoSpatialQuery = "info";
    this.lastMode = -1;
    this.zooming = false;
    this.profile = "";
    this.sessionId = "";
    this.servletUrl = "";
    this.ToolModeChangeHandler = null;
    this.nUserTools = 0;
    this.userTools = new Array();
    this.userToolsLastToolMode = new Array();
    this.currentScale = "";
    this.nMapChangeHandler = 0;
    this.mapChangeHandler = new Array();
    this.mapResizeHandler = new Array();
    this.legendChangeHandler = new Array();
}

CBKort.prototype.getImageXY = function(e)
{
    var xy = getCoords(e);
    this.mouseX = xy[0]-this.mapX;
    this.mouseY = xy[1]-this.mapY;
}

CBKort.prototype.setToolMode = function(m)
{
    var lastTool = -2;

    if (this.toolMode>=100&&this.toolMode<=this.nUserTools+100)
    {
        if (this.userTools[this.toolMode-100].change!=null)
            this.userTools[this.toolMode-100].change();
        if (this.userToolsLastToolMode[this.toolMode-100])
            lastTool = this.toolMode;
    }
    if (this.toolMode==tmZoomIn||this.toolMode==tmZoomOut||this.toolMode==tmCenter||this.toolMode==tmInfo||this.toolMode==tmPan||this.toolMode==tmDynaZoom||this.toolMode==tmRemove||this.toolMode==lastTool)
        this.lastMode = this.toolMode;
    else
        this.lastMode = -1;
    if (this.ToolModeChangeHandler!=null&&m!=this.toolMode)
    {
        this.ToolModeChangeHandler();
        this.ToolModeChangeHandler = null;
    }
    switch(m)
    {
        case tmZoomIn:
            document.mapserv.mode.value = "browse";
            document.mapserv.zoomdir.value = "1";
            this.map.style.cursor = 'url("images/standard/cursors/zoomin.cur"),crosshair';
            this.toolMode = tmZoomIn;
            this.drawBox = true;
        break;

        case tmZoomOut:
            document.mapserv.mode.value = "browse";
            document.mapserv.zoomdir.value = "-1";
            this.map.style.cursor = 'url("images/standard/cursors/zoomout.cur"),crosshair';
            this.toolMode = tmZoomOut;
            this.drawBox = false;
        break;

        case tmCenter:
            document.mapserv.mode.value = "browse";
            document.mapserv.zoomdir.value = "0";
            this.map.style.cursor = 'crosshair';
            this.toolMode = tmCenter;
            this.drawBox = false;
        break;

        case tmInfo:
            this.map.style.cursor = 'crosshair';
            this.toolMode = tmInfo;
            this.drawBox = false;
        break;

        case tmDistAndArea:
            cbKortUdstyr.setPointHandler(distanceHandler);
            showElement(getElement("distanceBox"));
            this.map.style.cursor = 'url("images/standard/cursors/distance.cur"),crosshair';
            this.toolMode = tmDistAndArea;
            this.drawBox = false;
        break;

        case tmPolygonSearch:
            cbKortUdstyr.setPointHandler(pSearchHandler);
            showElement(getElement("pSearchBox"));
            this.map.style.cursor = 'crosshair';
            this.toolMode = tmPolygonSearch;
            this.drawBox = false;
        break;

        case tmPoint:
            this.toolMode = tmPoint;
            this.map.style.cursor = 'crosshair';
            this.drawBox = false;
        break;

        case tmRedline:
            switch (redlineObj.rlType)
            {
                case rltPoint:
                    cbKortUdstyr.drawMode = cbKortUdstyr.cbpCircle;
                break;
                case rltLine:
                    cbKortUdstyr.drawMode = cbKortUdstyr.cbpLine;
                break;
                case rltPolygon:
                    cbKortUdstyr.drawMode = cbKortUdstyr.cbpLine;
                break;
            }
            redlineObj.activate();
            document.mapserv.zoomdir.value = "0";
            this.map.style.cursor = 'crosshair';
            this.toolMode = tmRedline;
            this.drawBox = false;
        break;

        case tmPan:
            document.mapserv.mode.value = "browse";
            document.mapserv.zoomdir.value = "0";
            this.toolMode = tmPan;
            this.map.style.cursor = 'url("images/standard/cursors/i_pan.cur"),move';
            this.drawBox = false;
        break;

        case tmMoveBox:
            this.drawBox = true;
            this.map.style.cursor = 'crosshair';
            this.toolMode = tmMoveBox;
        break;

        case tmDynaZoom:
            document.mapserv.mode.value = "browse";
            document.mapserv.zoomdir.value = "0";
            this.toolMode = tmDynaZoom;
            this.map.style.cursor = 'n-resize';
            this.drawBox = false;
        break;

        case tmRemove:
            this.map.style.cursor = 'crosshair';
            this.toolMode = tmRemove;
            this.drawBox = false;
        break;        
        
        default:
            this.toolMode = m;
            if (m>=100&&m<=this.nUserTools+100)
            {
                if (this.userTools[m-100].init!=null)
                    this.userTools[m-100].init();
            }
        break;
    }
}

CBKort.prototype.setToolModeChangeHandler = function(h)
{
    this.ToolModeChangeHandler = h;
}

CBKort.prototype.registerToolMode = function(initHandler, mouseDownHandler, mouseMoveHandler, mouseUpHandler, statebutton, toolChangeHandler)
{
    var returnValue = this.nUserTools+100;
    this.userToolsLastToolMode[this.nUserTools] = statebutton;
    this.userTools[this.nUserTools++] = {init:initHandler,down:mouseDownHandler,move:mouseMoveHandler,up:mouseUpHandler,change:toolChangeHandler};
    return returnValue;
}


CBKort.prototype.removeSearchResults = function(deletePage,clearFields,waitingboxText)
{
    showWaitingBox(waitingboxText);
    document.mapserv.page.value = deletePage;
    if (clearFields)
    {
        var a = clearFields.split(" ");
        for (var i=0;i<a.length;i++)
            document.mapserv.elements[a[i]].value = " ";
    }
    var oldzoomdir = document.mapserv.zoomdir.value;
    document.mapserv.zoomdir.value = "0";
    document.mapserv.submit();
    document.mapserv.zoomdir.value = oldzoomdir;
}

CBKort.prototype.fullExtent = function()
{
    if (this.full_Extent == "")
        /* The old way */
        location.href = this.getBaseUrl() + "&zoomdir=1&queryfile=&querylayer=&mode=browse&layers="+this.getLayers();
    else
    {
        /* The new way */
        showWaitingBox();
        document.mapserv.zoomdir.value = "0";
        document.mapserv.imgext.value = this.full_Extent;
        document.mapserv.mode.value = "browse";
        document.mapserv.submit();
    }
}

CBKort.prototype.getHost = function()
{
    return this.host;
}

CBKort.prototype.getMapFile = function()
{
    return this.mapFile;
}

CBKort.prototype.getLayers = function(escapeIt)
{
    var a = this.layers.split(" ");
    var b = new Array();
    s = "";
    for (i=0;i<a.length;i++)
    {
        var t = true;
        for (var j=0;j<b.length;j++)
        {
            if (a[i]==b[j])
                t = false;
        }
        if(t)
            b[b.length] = a[i];
    }
    for (var j=0;j<b.length;j++)
    {
        s+=b[j];
        if(j<b.length-1)
            s+=' ';
    }
    if (escapeIt)
        return escape(s);
    else
        return s;
}

CBKort.prototype.getDefaultLayers = function(escapeIt)
{
    if (escapeIt)
        return escape(this.defaultLayers);
    else
        return this.defaultLayers;
}

CBKort.prototype.setDefaultLayers = function(value)
{
    this.defaultLayers = value;
}

CBKort.prototype.setService = function(s)
{
    this.service = s;
}

CBKort.prototype.setFullExtent = function(s)
{
    this.full_Extent = s;
}

CBKort.prototype.getFullExtent = function()
{
    return this.full_Extent;
}

CBKort.prototype.setMapImage = function(s)
{
    this.mapImage = getElement(s);
    this.mapWidth = this.mapImage.width;
    this.mapHeight = this.mapImage.height;
}

CBKort.prototype.getBaseUrl = function()
{
    var url;
    if (this.service)
        url = this.service;
    else
        url = "http://"+this.host+"/scripts/mapserver/mapserv.exe?map="+this.mapFile;
    return url;
}

CBKort.prototype.createLayer = function (name, visible, content)
{
    var e = document.getElementsByTagName("body").item(0);
    var t = '<div id="' + name + '" name="' + name + '" style="position:absolute; overflow:hidden; left:' + this.mapX + 'px; top:' + this.mapY + 'px; width:' + this.mapWidth + 'px; height:' + this.mapHeight + 'px;' + '; z-index:5; visibility:' + (visible ? 'visible;' : 'hidden;') +  '" onmouseup="checkMouseUp(window.event);">';
    t+= content+'</div>';
    appendHTML(e,t);
}

CBKort.prototype.createBox = function ()
{
    // zoom/selection box
    var content;
    content = '<img src="images/standard/1x1.gif" width="1" height="1">';
    this.createLayer("zoomBoxTop",false,content);
    this.boxTop = getElement("zoomBoxTop"),
    this.boxTop.style.backgroundColor = this.zoomBoxColor;

    this.createLayer("zoomBoxLeft",false,content);
    this.boxLeft = getElement("zoomBoxLeft"),
    this.boxLeft.style.backgroundColor = this.zoomBoxColor;

    this.createLayer("zoomBoxRight",false,content);
    this.boxRight = getElement("zoomBoxRight"),
    this.boxRight.style.backgroundColor = this.zoomBoxColor;

    this.createLayer("zoomBoxBottom",false,content);
    this.boxBottom = getElement("zoomBoxBottom"),
    this.boxBottom.style.backgroundColor = this.zoomBoxColor;

}

CBKort.prototype.setJitter = function(j)
{
    this.jitter = j;
}

CBKort.prototype.closeMoveBox = function ()
{
    hideElement(this.boxTop);
    hideElement(this.boxLeft);
    hideElement(this.boxRight);
    hideElement(this.boxBottom);
}

CBKort.prototype.setMoveBoxSize = function(width,height)
{
    this.moveboxwidth = width;
    this.moveboxheight = height;
}

CBKort.prototype.setZoomBoxParams = function(color,lineWidth)
{
    this.zoomBoxColor = color;
    this.ovBoxSize = lineWidth;
}

CBKort.prototype.startZoomBox = function(e)
{
    this.getImageXY(e);
    // keep it within the MapImage
    if ((this.mouseX<this.mapWidth) && (this.mouseY<this.mapHeight) && (this.mouseX>=0) && (this.mouseY>=0))
    {
        if (this.zooming)
        {
            this.zooming = false;
            this.stopZoomBox(e);
        }
        else
        {
            this.x1=this.mouseX-1;
            this.y1=this.mouseY-1;
            this.x2=this.x1+1;
            this.y2=this.y1+1;
            this.zleft=this.x1;
            this.ztop=this.y1;
            this.zbottom=this.y1;
            this.zright=this.x1;
            this.boxIt(this.x1+this.mapX,this.y1+this.mapY,this.x2+this.mapX,this.y2+this.mapY);
            this.zooming=true;
        }
    }
    return false;
}

CBKort.prototype.stopZoomBox = function(e)
{
    this.zooming = false;
    hideElement(this.boxTop);
    hideElement(this.boxLeft);
    hideElement(this.boxRight);
    hideElement(this.boxBottom);
    this.mouseX = 0;
    this.mouseY = 0;
    window.scrollTo(0,0);
    return false;
}

CBKort.prototype.boxIt = function(theLeft,theTop,theRight,theBottom)
{
    sizeLayer(this.boxTop,theLeft,theTop,theRight,theTop+this.ovBoxSize);
    sizeLayer(this.boxLeft,theLeft,theTop,theLeft+this.ovBoxSize,theBottom);
    sizeLayer(this.boxRight,theRight-this.ovBoxSize,theTop,theRight,theBottom);
    sizeLayer(this.boxBottom,theLeft,theBottom-this.ovBoxSize,theRight,theBottom);
    showElement(this.boxTop);
    showElement(this.boxLeft);
    showElement(this.boxRight);
    showElement(this.boxBottom);
}

CBKort.prototype.clipCoords = function()
{
    var tempX=this.x1;
    var tempY=this.y1;
    if (this.x1>this.x2)
    {
        this.zright=this.x1;
        this.zleft=this.x2;
    }
    else
    {
        this.zleft=this.x1;
        this.zright=this.x2;
    }
    if (this.y1>this.y2)
    {
        this.zbottom=this.y1;
        this.ztop=this.y2;
    }
    else
    {
        this.ztop=this.y1;
        this.zbottom=this.y2;
    }

    if ((this.x1 != this.x2) && (this.y1 != this.y2))
        this.boxIt(this.zleft+this.mapX,this.ztop+this.mapY,this.zright+this.mapX,this.zbottom+this.mapY);
}

CBKort.prototype.captureMouseEvents = function(e)
{
    e.onmousedown = checkMouseDown;
    e.onmouseup = checkMouseUp;
    e.onmousemove = checkMouseMove;
}

function checkMouseDown(e)
{
    return cbKort.checkMouseDown(e);
}

function checkMouseUp(e)
{
    return cbKort.checkMouseUp(e);
}

function checkMouseMove(e)
{
    return cbKort.checkMouseMove(e);
}

CBKort.prototype.checkMouseDown = function(e)
{
    if (!isLeftClick(e))
        return false;
    switch (this.toolMode)
    {
        case tmZoomIn:
            document.mapserv.zoomdir.value = "1";
            if (this.drawBox)
                this.startZoomBox(e);
            break;
        case tmZoomOut:
            document.mapserv.zoomdir.value = "-1";
        case tmCenter:
            this.getImageXY(e);
            this.applyPoint(this.mouseX,this.mouseY);
            break;
        case tmInfo:
            this.getImageXY(e);
            var p1 = cbKortUdstyr.getMapCoords(this.mouseX,this.mouseY);
            if (this.infoHandler)
                this.infoHandler(p1.x, p1.y, this.mouseX,this.mouseY,cbKortUdstyr);
            else
            {
                var mapUrl = top.main.location.href;
                setCookie("beforesearch",mapUrl);
                document.mapserv.point.value = p1.x + " " + p1.y;
                document.mapserv.zoomdir.value = "0";
                document.mapserv.page.value = this.resultsPage;
                document.mapserv.spatialquery.value = this.infoSpatialQuery;
                var someLayers =  this.getLayers(false);
                if (someLayers.length>1)
                    document.mapserv.searchlayers.value = someLayers;
                else
                    document.mapserv.searchlayers.value = this.getDefaultLayers(false);
                document.mapserv.searchbuffer.value = "1";
                document.mapserv.searchtext.value = "Det udpegede sted";
                document.mapserv.mapext.value = this.getExtentAsString();
                document.mapserv.mapping.value = "infopoint";
                document.mapserv.dynamiclayer.value = "userpoint";
                document.mapserv.submit();
            }
            break;
        case tmDistAndArea:
        case tmPolygonSearch:
        case tmRedline:
        case tmPoint:
            if (cbKortUdstyr)
            {
                this.getImageXY(e);
                cbKortUdstyr.doPoint();
            }
            break;
        case tmPan:
            this.getImageXY(e);
            this.dragStartX = this.mouseX;
            this.dragStartY = this.mouseY;
            document.forms.mapserv.zoomdir.value="0";
            this.panning = true;
            dragStart(e, this.map.id, getElement("mapcontainer"));
        break;
        case tmMoveBox:             //Bruges af pdfprint-tool
            this.postMoveBoxRequest();
        break
        case tmDynaZoom:
            this.getImageXY(e);
            this.dynaStartX = this.mouseX;
            this.dynaStartY = this.mouseY;
            document.forms.mapserv.zoomdir.value="0";
            this.dynaZooming = true;
            dynaStart(e, "themapimage", document);
            break;
        case tmRemove:
           
            this.getImageXY(e);
            var p1 = cbKortUdstyr.getMapCoords(this.mouseX,this.mouseY);
            if (this.removeHandler)
                this.removeHandler(p1.x, p1.y, this.mouseX,this.mouseY,cbKortUdstyr);
            break;        
        
        default:
            if (this.toolMode>=100&&this.toolMode<=this.nUserTools+100)
            {
                if (this.userTools[this.toolMode-100].down!=null)
                    this.userTools[this.toolMode-100].down(this.mouseX,this.mouseY);
            }
    }
    return false;
}

CBKort.prototype.checkMouseUp = function(e)
{
    if ((this.toolMode == tmZoomIn) && (this.zooming))
    {
        this.stopZoomBox(e);
        if (Math.abs(this.x2-this.x1)>this.jitter)
            this.applyBox(this.x1,this.y1,this.x2,this.y2);
        else
            this.applyPoint(this.x1,this.y1);
    }
    if (this.toolMode==tmPan&&this.panning)
    {
        this.panning = false;
        this.getImageXY(e);
        var deltaX = this.mouseX - this.dragStartX;
        var deltaY = this.mouseY - this.dragStartY;
        var newX = div(this.mapWidth,2)-deltaX;
        var newY = div(this.mapHeight,2)-deltaY;
        //if(deltaX>0||deltaY>0)
        this.applyPoint(newX,newY);
    }
    if (this.toolMode>=100&&this.toolMode<=this.nUserTools+100)
    {
        if (this.userTools[this.toolMode-100].up!=null)
            this.userTools[this.toolMode-100].up(this.mouseX,this.mouseY);
    }
    return false;
}

CBKort.prototype.checkMouseMove = function(e)
{
    this.getImageXY(e);

    if ((this.mouseX>this.mapWidth) || (this.mouseY>this.mapHeight) || (this.mouseX<=0) ||(this.mouseY<=0))
    {
        if (this.zooming)
        {
            this.stopZoomBox(e);
        }
    }
    else
        if (this.zooming)
        {
            this.x2=this.mouseX;
            this.y2=this.mouseY;
            this.clipCoords();
        }

    if (this.toolMode == tmMoveBox) //Dette bruges af pdfprint-tool
    {
        this.moveMoveBox(e);
    }
    else
       if (this.toolMode>=100&&this.toolMode<=this.nUserTools+100)
       {
           if (this.userTools[this.toolMode-100].move!=null)
               this.userTools[this.toolMode-100].move(this.mouseX,this.mouseY);
       }

    if (this.mouseMoveHandler)
    {
        this.mouseMoveHandler(this.mouseX,this.mouseY);
    }
    return false;
}

CBKort.prototype.getExtent = function()
{
    return this.extentArr;
}

CBKort.prototype.getExtentAsString = function(sep)
{
    if (!sep)
       sep = " ";
    return this.extentArr[0]+" "+this.extentArr[1]+" "+this.extentArr[2]+" "+this.extentArr[3];
}

CBKort.prototype.getMapCenter = function()
{
    var a = this.extentArr;
    var x0 = +a[0];
    var y0 = +a[1];
    var x1 = +a[2];
    var y1 = +a[3];
    var x_ = x0+(x1-x0)/2;
    var y_ = y0+(y1-y0)/2;
    return {x:x_,y:y_};
}

CBKort.prototype.getMapPhysicalSize = function()
{
    var arr = cbKort.getExtent();
    var theWidth = Math.abs(arr[2]-arr[0]);
    var theHeight = Math.abs(arr[3]-arr[1]);
    return {width:theWidth,height:theHeight};
}

CBKort.prototype.getMapWidthAsText = function()
{
    var phys = this.getMapPhysicalSize();
    var width = phys.width;
    if(width)
    {
        if (width<1000)
            return "Kortet viser et udsnit på "+Math.round(width)+" meter i bredden";
        else
            return "Kortet viser et udsnit på "+Math.round(width/100)/10+" km i bredden"
    }
    else
        return '';
}

CBKort.prototype.zoomToMapWidth = function(reqWidth,minWidth, maxWidth)
{
    var reg = new RegExp("[^0-9]");
    if (reg.test(reqWidth))
    {
        alert("Indtast venligst et heltal");
        return;
    }

    if(minWidth&&maxWidth&&(reqWidth<minWidth||reqWidth>maxWidth))
    {
        alert("Der kan kun indtastes værdier mellem "+minWidth+" og "+maxWidth+" meter");
        return;
    }

    var arr = this.getExtent();

    var width = Math.abs(arr[2]-arr[0]);
    var height = Math.abs(arr[3]-arr[1]);
    var centerx = width/2+parseFloat(arr[0]);
    var centery = height/2+parseFloat(arr[1]);
    var mapforhold = this.mapWidth/this.mapHeight;

    var x1 = centerx - reqWidth/2 ;
    var x2 = centerx + reqWidth/2 ;
    var y1 = centery - reqWidth/(2*mapforhold) ;
    var y2 = centery + reqWidth/(2*mapforhold) ;

    showWaitingBox();
    document.mapserv.imgext.value = x1+"+"+y1+"+"+x2+"+"+y2;
    document.mapserv.zoomdir.value = "0";
    document.mapserv.submit();
}

CBKort.prototype.showFormParams = function()
{
    var s = "";
    for (var a in document.mapserv)
        for (var b in document.mapserv[a])
            if (b=="value")
                s+= a+" = "+document.mapserv[a].value+"\n";
    return s;
}

CBKort.prototype.formToUrl = function()
{
    var s = "";
    var prefix = "?";
    for (var a in document.mapserv)
        for (var b in document.mapserv[a])
            if (b=="value")
            {
                s+= prefix+a+"="+document.mapserv[a].value;
                prefix = "&";
            }
    return s;
}

CBKort.prototype.getFormParamAsUrl = function()
{
    var s = this.getServletUrl();
    s = s.split("/");
    s = '/'+s[s.length-1];
    var prefix = "?";
    for (var i=0;i<document.mapserv.elements.length;i++)
    {
        s+= prefix+document.mapserv.elements[i].name+"="+document.mapserv.elements[i].value;
        prefix = "&";
    }
    return s;
}

CBKort.prototype.applyBox = function(minx, miny, maxx, maxy)
{
    showWaitingBox();
    var temp = minx;
    if (temp>maxx)
    {
        minx = maxx;
        maxx = temp;
    }
    temp = miny;
    if (temp>maxy)
    {
        miny = maxy;
        maxy = temp;
    }
    document.mapserv.imgbox.value = minx + " " + miny + " " + maxx + " " + maxy;
    document.mapserv.imgxy.value = minx + " " + miny;
    document.mapserv.submit();
}

CBKort.prototype.applyPoint = function(minx, miny)
{
    showWaitingBox();
    document.mapserv.imgxy.value = minx + " " + miny;
    document.mapserv.submit();
}

CBKort.prototype.registerLegendChangeHandler = function(handler)
{
    this.legendChangeHandler[this.legendChangeHandler.length] = {handler:handler};
}
CBKort.prototype.callLegendChangeHandler = function()
{
    for(var ti=0;ti<this.legendChangeHandler.length;ti++)
    {
        if(this.legendChangeHandler[ti].handler!=null)
            this.legendChangeHandler[ti].handler();
    }
}

CBKort.prototype.setProfile = function(value)
{
    this.profile = value;
}

CBKort.prototype.getProfile = function()
{
    return this.profile;
}


CBKort.prototype.setSessionId = function(value)
{
    this.sessionId = value;
}

CBKort.prototype.getSessionId = function()
{
    return this.sessionId;
}

CBKort.prototype.setServletUrl = function(value)
{
    this.servletUrl = value;
}

CBKort.prototype.getServletUrl = function()
{
    return this.servletUrl;
}

var dynaObj = new Object();
dynaObj.zIndex = 4;

function dynaStart(event)
{

  dynaObj.elNode = getElement("themapimage");

  // Get cursor position with respect to the page.
  if (!event)
      event = window.event;

  dynaObj.cursorStartX = event.clientX;
  dynaObj.cursorStartY = event.clientY;
  dynaObj.orgWidth =  parseInt(dynaObj.elNode.style.width,10);
  dynaObj.orgHeight = parseInt(dynaObj.elNode.style.height,10);
  dynaObj.elStartLeft  = parseInt(dynaObj.elNode.style.left, 10);
  dynaObj.elStartTop   = parseInt(dynaObj.elNode.style.top,  10);
  if (isNaN(dynaObj.orgWidth)) dynaObj.orgWidth = dynaObj.elNode.width;
  if (isNaN(dynaObj.orgHeight)) dynaObj.orgHeight = dynaObj.elNode.height;
  if (isNaN(dynaObj.elStartLeft)) dynaObj.elStartLeft = 0;
  if (isNaN(dynaObj.elStartTop))  dynaObj.elStartTop  = 0;

  dynaObj.elNode.style.zIndex = ++dynaObj.zIndex;

  // Capture mousemove and mouseup events on the page.
  if (ie)
  {
    document.attachEvent("onmousemove", dynaGo);
    document.attachEvent("onmouseup",   dynaStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (nn6)
  {
    document.addEventListener("mousemove", dynaGo,   true);
    document.addEventListener("mouseup",   dynaStop, true);
    event.preventDefault();
  }
}

function dynaGo(event)
{
  if (!event)
      event = window.event;

  dynaObj.elNode.style.position = "absolute";
  dynaObj.elNode.style.overflow = "hidden";
  var diff = event.clientY - dynaObj.cursorStartY;
  var f = dynaFactor(diff);
  var newWidth = Math.round(dynaObj.orgWidth * f);
  var newHeight = Math.round(dynaObj.orgHeight * f);
  dynaObj.elNode.style.width = newWidth+"px";
  dynaObj.elNode.style.height = newHeight+"px";
  var xDiff = dynaObj.orgWidth-newWidth;
  var yDiff = dynaObj.orgHeight-newHeight;
  
  var x = dynaObj.cursorStartX-cbKort.mapX;
  var y = dynaObj.cursorStartY-cbKort.mapY;
  if(x==0) x=1;
  if(y==0) y=1;
  dynaObj.factorX = (dynaObj.orgWidth-x)/x;
  dynaObj.factorY = (dynaObj.orgHeight-y)/y;
  var left = Math.round(dynaObj.elStartLeft+(xDiff/(1+dynaObj.factorX)));
  var top = Math.round(dynaObj.elStartTop+(yDiff/(1+dynaObj.factorY)));

  dynaObj.elNode.style.left = left+"px";
  dynaObj.elNode.style.top = top+"px";

  if (ie)
  {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (nn6)
    event.preventDefault();
}

function dynaStop(event)
{
    return dynaStopBase(event, document);
}

function dynaFactor(diff)
{
    if (diff >= dynaObj.orgHeight)
        diff = dynaObj.orgHeight-1;
    else if (diff <= -dynaObj.orgHeight)
        diff = -dynaObj.orgHeight-1;
    return Math.pow(1-(diff/dynaObj.orgHeight),4);
}

function dynaStopBase(event)
{

    if (!event)
      event = window.event;

    // Stop capturing mousemove and mouseup events.
    if (ie)
    {
        document.detachEvent("onmousemove", dynaGo);
        document.detachEvent("onmouseup",   dynaStop);
    }
    if (nn6)
    {
        document.removeEventListener("mousemove", dynaGo,   true);
        document.removeEventListener("mouseup",   dynaStop, true);
    }

    var diff = event.clientY - dynaObj.cursorStartY;

    var factor = dynaFactor(diff);
    //var factor = dynaObj.orgWidth/parseInt(dynaObj.elNode.style.width,10);
    //factor = Math.pow(factor, 7/5);
    var arr = cbKort.getExtent();

    var width = Math.abs(arr[2]-arr[0]);
    var height = Math.abs(arr[3]-arr[1]);
    //var reqWidth = factor * width;
    var reqWidth = width/factor;
    var reqHeight = height/factor;

    var zoomcenter = cbKort.getWorldCoordinate(dynaObj.cursorStartX-cbKort.mapX,dynaObj.cursorStartY-cbKort.mapY).split(" ");
    var cx = zoomcenter[0];
    var cy = zoomcenter[1];

    var x1 = cx - 0 - reqWidth*((dynaObj.cursorStartX-cbKort.mapX)/dynaObj.orgWidth);
    var x2 = cx - 0 + reqWidth*(1-((dynaObj.cursorStartX-cbKort.mapX)/dynaObj.orgWidth)) - 0;
    var y1 = cy - 0 - reqHeight*(1-((dynaObj.cursorStartY-cbKort.mapY)/dynaObj.orgHeight)) - 0;
    var y2 = cy - 0 + reqHeight*((dynaObj.cursorStartY-cbKort.mapY)/dynaObj.orgHeight) - 0;
    
    if(factor)
    {
        showWaitingBox();
        document.mapserv.imgext.value = x1+"+"+y1+"+"+x2+"+"+y2;
        document.mapserv.zoomdir.value = "0";
        document.mapserv.submit();
    }
}

function getUrlParamAdv(name,url)
{
    if(!url)
        url = location.search;
    url = url.substring(1, url.length);
    var params = url.split("&");
    for (var i=0; i<params.length; i++)
    {
        var varval = params[i].split("=");
        if (varval[0] == name)
        {
            var returnval = varval[1];
            if(varval.length>2)
            {
                for(var j = 2;j<varval.length;j++)
                    returnval+= '='+varval[j];
            }
            return returnval;
        }
    }
    return "";
}

function replaceUrlParam(name, value, url)
{
    if(!url)
        url = location.search;

    var temp = url.split("?");
    
    if(!temp[1])
        temp[1]=url;
    
    params = temp[1].split("&");
    var found = false;
    
    for (i=0; i<params.length; i++)
    {
        var varval = params[i].split("=");
        if (varval[0] == name)
            found = true;
    }

    if(found)
    {
        // Finder den angivet parameter samt dens værdi
        var k = '([?&])('+name+')=[^&]*';
        var re1 = new RegExp(k,'g') ;
        var t = re1.exec(url);
        if(value=='')
        {
            var testererer = '';
            url = url.replace(re1,testererer);
        }
        else
            url = url.replace(re1,t[1]+t[2]+'='+value);
    }
    else
        if(value!='')
            url+='&'+name+'='+value;

    return url;
}

CBKort.prototype.setCurrentScale = function(s)
{
    this.currentScale = s;
}

CBKort.prototype.getCurrentScale = function()
{
    return this.currentScale;
}

CBKort.prototype.getWorldCoordinate = function(dcx,dcy)
{
    var wcx = 0;
    var wcy = 0;

    if(!dcx)
        dcx = this.mouseX;
    if(!dcy)
        dcy = this.mouseY;

    var wcx1 = parseFloat(this.extentArr[0]);
    var wcy1 = parseFloat(this.extentArr[3]);
    var wcx2 = parseFloat(this.extentArr[2]);
    var wcy2 = parseFloat(this.extentArr[1]);

    var w = parseInt(this.mapWidth);
    var h = parseInt(this.mapHeight);

    wcx = wcx1 + ((wcx2-wcx1)*dcx)/w;
    wcy = wcy1 + ((wcy2-wcy1)*dcy)/h;

    return wcx+' '+wcy;
}

function resetMapElement(e)
{
    e.style.left = '0px';
    e.style.top = '0px';
    e.style.width = cbKort.mapWidth+'px';
    e.style.height = cbKort.mapHeight+'px';
}

function layerChecked()
{
    setHelperframeSrc();
    showWaitingBox();
}

// Alle functioner, der skal kaldes når kortet opdateres, skal registeres med denne funktion
CBKort.prototype.registerMapChangeHandler = function(initHandler)
{
    this.mapChangeHandler[this.nMapChangeHandler++] = {init:initHandler};
}

CBKort.prototype.callMapChangeHandler = function()
{
    for(var ti=0;ti<this.mapChangeHandler.length;ti++)
    {
        if(this.mapChangeHandler[ti].init!=null)
            this.mapChangeHandler[ti].init();
    }
}

CBKort.prototype.registerResizeHandler = function(resizeHandler)
{
    this.mapResizeHandler[this.mapResizeHandler.length] = {handler:resizeHandler};
}
CBKort.prototype.mapResize = function(newMapWidth,newMapHeight)
{
    var corr = (ie ? 1 : 0);
    var frameWidth = 0;
    var frameHeight = 0;
    if (self.innerWidth)
    {
        frameWidth = self.innerWidth;
        frameHeight = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
    {
        frameWidth = document.documentElement.clientWidth;
        frameHeight = document.documentElement.clientHeight;
    }
    else if (document.body)
    {
        frameWidth = document.body.clientWidth;
        frameHeight = document.body.clientHeight;
    }
    
    if(newMapWidth)
        newMapWidth = parseInt(newMapWidth,10)+'px';
    else
        newMapWidth = parseInt(frameWidth - cbKort.mapX - 5 + corr,10)+'px';
    if(newMapHeight)
        newMapHeight = parseInt(newMapHeight,10)+'px';
    else
        newMapHeight = parseInt(frameHeight - cbKort.mapY - 20 + corr,10)+'px';

    var difw = parseInt(this.mapWidth)-parseInt(newMapWidth);
    var difh = parseInt(this.mapHeight)-parseInt(newMapHeight);
    if(Math.abs(difw)<2 && Math.abs(difh)<2)
        return;

    var oldMapWidth = this.mapWidth;
    var oldMapHeight = this.mapHeight;
    this.mapWidth = parseInt(newMapWidth);
    this.mapHeight = parseInt(newMapHeight);
    var mapWidthCorr = pixelAdd(this.mapWidth,'-'+oldMapWidth);
    var mapHeightCorr = pixelAdd(this.mapHeight,'-'+oldMapHeight);
    mapWidthCorr = pixelAdd(mapWidthCorr,-corr);
    mapHeightCorr = pixelAdd(mapHeightCorr,-corr);
    
    var w2 = this.mapWidth/2;
    var h2 = this.mapHeight/2;
    document.mapserv.mapwidth.value = this.mapWidth;
    document.mapserv.mapheight.value = this.mapHeight;
    document.mapserv.map_size.value = this.mapWidth + ' ' + this.mapHeight;
    document.mapserv.imgxy.value = w2 + ' ' + h2;
    
    e = getElement('zoomBoxTop');
    if(e)
    {
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    e = getElement('zoomBoxBottom');
    if(e)
    {
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    e = getElement('zoomBoxLeft');
    if(e)
    {
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    e = getElement('zoomBoxRight');
    if(e)
    {
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }

    var e = getElement('billedfrisebaggrund');
    if(e)
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
    var e = getElement('topbar');
    if(e)
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
    e = getElement('bottombar');
    if(e)
    {
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    
    e = getElement('statusbarright');
    if(e)
    {
        e.style.left = pixelAdd(e.style.left,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    e = getElement('statusbarcenter');
    if(e)
    {
        e.style.left = pixelAdd(parseInt(pixelAdd(e.style.left,mapWidthCorr),10)/2,-100);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    e = getElement('statusbarleft');
    if(e)
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    e = getElement('mapwidthdiv');
    if(e)
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);

    e = getElement('updateBox');
    if(e)
    {
        e.style.left = pixelAdd(e.style.left,mapWidthCorr);
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    }
    
    e = getElement('mapcontainer');
    if(e)
    {
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);
        e.style.height = pixelAdd(e.style.height,mapHeightCorr);
    }
    e = getElement('controls');
    if(e)
        e.style.width = pixelAdd(e.style.width,mapWidthCorr);

    leftBar.setDefault();
    e = getElement('leftbar');
    if(e)
        e.style.height = pixelAdd(e.style.height,mapHeightCorr);

    var o = leftBar.currentheigth;
    leftBar.currentheigth = pixelAdd(leftBar.currentheigth,mapHeightCorr);
    leftBar.defaultheigth = pixelAdd(leftBar.defaultheigth,mapHeightCorr);
    leftBar.maxheigth = pixelAdd(leftBar.maxheigth,mapHeightCorr);
    leftBar.setToCurrentHeigth();

    e = getElement('overviewbox');
    if(e)
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);
    
    for(var handlerCount = 0;handlerCount < this.mapResizeHandler.length;handlerCount++)
        this.mapResizeHandler[handlerCount].handler(mapWidthCorr,mapHeightCorr);

    showWaitingBox();
    document.mapserv.zoomdir.value = '0';
    
    var cbKortUrl = cbKort.getFormParamAsUrl();
    setHelperframeSrc(cbKortUrl);
}


CBKort.prototype.setCopyright = function(width,height,left,top)
{
    var copyrightdiv = getElement('copyrightdiv');
    if(!copyrightdiv)
        return;
    copyrightdiv.style.left = left+'px';
    copyrightdiv.style.height = height+'px';
    copyrightdiv.style.left = left+'px';
    copyrightdiv.style.top = top+'px';
}

CBKort.prototype.getProfileParam = function(xpath)
{
    if(!xpath)
    {
        alert('xpath is missing');
        return null;
    }
    var url = cbKort.getServletUrl();
        url+='?page=get.profile.nodevalue';
        url+='&profile='+this.profile;
        url+='&xpath='+xpath;
        url+="&jdaf.error.xslt=";
        url+="&jdaf.error.contenttype=text/xml";
    
    var request = new CBhttp ();
    pcol = request.executeUrl(url);
    if (pcol!=null)
    {
        var val = pcol.get(0).column("nodevalue").getValue();
        if(val)
            return val;
    }
    return '';
}


// Helperframe functioner
function setHelperframeSrc(url)
{
    var src = 'about:blank';
    if(url)
        src = url;
    var e = getElement('helperframe');
    if(e)
        postToTarget(src,'helperframe');
}

function showHelperframe()
{
    var e = getElement('helperframediv');
    if(e)
        e.style.display = 'block';
}
function hideHelperframe()
{
    var e = getElement('helperframediv');
    if(e)
        e.style.display = 'none';
}

//Kortet opdateres box
var waitingBoxCount = 1;
function showWaitingBox(text,n)
{
    if(n)
        waitingBoxCount = n;
    if(!text)
        text = 'Kortet opdateres...';
    var e = getElement('updateBox');
    if(e)
    {
        writeHTML(e,text);
        showElement(e);
        e = getElement('statusbarright');
        if(e){hideElement(e)}
    }
    return true;
}

function hideWaitingBox()
{
    var e = getElement('updateBox');
    if(e)
    {
        waitingBoxCount--;
        if(waitingBoxCount<1)
        {
            waitingBoxCount = 1;
            writeHTML(e,'');
            hideElement(e);
            e = getElement('statusbarright');
            if(e){showElement(e)}
        }
    }
}

//  Vis et tooltip (GENEREL)
function showHint(event, hint)
{
    if(hint)
    {
        var hint = hint || '';
        var e = getElement('buttonhint');
        if(e)
        {
            var xy = getCoords(event);
            setY(e,xy[1]+20);
            setX(e,xy[0]);
            writeHTML(e,hint);
            showElement(e);
        }
    }
}
//  Skjul tooltip (GENEREL)
function hideHint()
{
    var e = getElement('buttonhint');
    if(e)
        hideElement(e);
}

var cbKort;

function ThemeGroupMouseEvent()
{
    this.mouseoverevent = new Array();
    this.mouseoutevent = new Array();
}

ThemeGroupMouseEvent.prototype.setMouseOverEventHandler = function(handler)
{
    this.mouseoverevent = handler;
}
ThemeGroupMouseEvent.prototype.setMouseOutEventHandler = function(handler)
{
    this.mouseoutevent = handler;
}

function tgOver(event,element,text)
{
    element.style.fontWeight='bolder';
    showHint(event,text);
}
function tgOut(element)
{
    element.style.fontWeight='normal';
    hideHint();
}

var themeGroupMouseEvent = new ThemeGroupMouseEvent();
themeGroupMouseEvent.setMouseOverEventHandler(tgOver);
themeGroupMouseEvent.setMouseOutEventHandler(tgOut);


// Rettigheder
function permissionLogin(servlet)
{
    var target = 'parent';
    var cbKortUrl = cbKort.getFormParamAsUrl();
    cbKortUrl = replaceUrlParam('page', '', cbKortUrl);
    cbKortUrl = escape(escape(cbKortUrl));
    
    var loginUrl = "/" + servlet +"?page=targetloader&target=" + target +"&url=" + cbKortUrl;
    var l = cbKort.mapX + cbKort.mapWidth/2 - 90;
    var t = cbKort.mapY + cbKort.mapHeight/2 - 80;

    showDivBox('Log ind', loginUrl, false, l+'px', t+'px', '163px', '127px');
}

function permissionLogout()
{
    var servlet = 'cblogout';
    var url = cbKort.getFormParamAsUrl();
    url = replaceUrlParam('sessionid', '', url)
    url = replaceUrlParam('page', '', url)
    url = url.replace(/cbkort?/,servlet);
    this.location.href = url;
}

function getFormParam(name)
{
    var elem = document.forms[0].elements[name];
    return elem.value;
}

// Error handler
// set 
function ErrorHandler()
{
    this.error_message = '';
    this.error_exception = '';
    this.error_servlet = '';
    this.error_jdaf_version = '';
    this.error_cbinfo_version = '';
    this.error_stacktrace = '';
    
    this.dialog = new Dialog('Fejlmeddelelse',null);
    var h = '<table class="divtable" style="width:100%;">'
          + '   <tr align="left">'
          + '       <td class="heading3td">Der er opstået en fejl</td>'
          + '   </tr>'
          + '   <tr align="left">'
          + '       <td>Tryk på knappen for at få vist detaljer</td>'
          + '   </tr>'
          + '   <tr align="right">'
          + '       <td>'
          + '           <button id="okbutton" class="menubutton" onclick="errorHandler.showDetails();">Vis detaljer</button>'
          + '           <button id="okbutton" class="menubutton" onclick="errorHandler.dialog.closeDialog();" style="width:50px">Luk</button>'
          + '       </td>'
          + '   </tr>'
          + '</table>';
    
    this.dialog.addContentHTML(h);
    var l = cbKort.mapWidth/2;
    var t = cbKort.mapHeight/2;
    this.dialog.setDialogWidth('250px');
    this.dialog.setDialogPosition(l+'px',t+'px');
    this.dialog.showDialog();
}
ErrorHandler.prototype.setError = function(error_message,error_exception,error_servlet,error_jdaf_version,error_cbinfo_version,error_stacktrace)
{
    this.error_message = error_message;
    this.error_exception = error_exception;
    this.error_servlet = error_servlet;
    this.error_jdaf_version = error_jdaf_version;
    this.error_cbinfo_version = error_cbinfo_version;
    this.error_stacktrace = error_stacktrace.replace(/######/g,'\n');

    this.dialog.showDialog();
}
ErrorHandler.prototype.showDetails = function()
{
    this.dialog.closeDialog();
    
    var h = '<table class="divtable" style="width:100%;">'
          + '   <tr align="left">'
          + '       <td><textarea readonly="true" style="width:480px;height:400px">'+this.error_message+'\n\n'+this.error_exception+'\n\nCBINFO-version: '+this.error_cbinfo_version+'\nJDAF-version: '+this.error_jdaf_version+'\n\nStacktrace:\n'+this.error_stacktrace+'</textarea></td>'
          + '   </tr>'
          + '   <tr align="right">'
          + '       <td>'
          + '           <button id="okbutton" class="menubutton" onclick="errorHandler.dialog.closeDialog();" style="width:50px">Luk</button>'
          + '       </td>'
          + '   </tr>'
          + '</table>';
    this.dialog.addContentHTML(h);
    var l = cbKort.mapWidth/2-200;
    var t = cbKort.mapHeight/2-150;
    this.dialog.setDialogWidth('500px');
    this.dialog.setDialogPosition(l+'px',t+'px');
    this.dialog.showDialog();
}

var errorHandler;