// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.6/standard_upgrade_01/wwwroot/js/standard/cbkort.js $ 
// $Date: 9-03-11 21:10 $
// $Revision: 59 $ 
// $Author: Kpo $
// =============================================================== 

// -------------------------------------------------------------
// Tool Mode Constants
// -------------------------------------------------------------
var tmZoomIn = 1;
var tmZoomOut = 2;
var tmCenter = 3;
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 (options) {
    this.debug = options.debug || 0;
    //Event container
    /*
     * Possible events:
     * MAP_CHANGED, TOOL_CHANGED, THEME_CHANGED, THEMEGROUP_CHANGED, WINDOW_RESIZED
     */
    this.events = new SpatialMap.Events ();
    
    this.profile = options.profile;
    this.servicename = options.servicename || this.profile;
    this.projection = options.projection || 'EPSG:25832';
    if (this.projection.indexOf ('EPSG') < 0) {
        this.projection = 'EPSG:'+this.projection;
    }
    
    this.resolutions = options.resolutions || null;
    options.maxextent = options.maxextent || null;
    this.maxextent = (options.maxextent.hasOwnProperty ('x1') ? options.maxextent : null);

    this.mapId = options.mapId;
    this.map = $(this.mapId);
    this.map.style.color = '#000000';
    this.host = (options.host || '/wms').split(',');
    for (var i=0;i<this.host.length;i++) {
        this.host[i] = jq.trim (this.host[i]);
    }
    this.mapSizeCorrection = {x:2,y:18};  //Used on WINDOW_RESIZED event to fit the map to the window.
    
    this.legendVisible = false;
    this.themeContainer = options.themeContainer;
    
    this.layers = options.startlayers;
    this.defaultLayers = options.defaultlayers;
    this.extentArr = options.extent.split(' ');
    this.startExtent = {x1:this.extentArr[0],y1:this.extentArr[1],x2:this.extentArr[2],y2:this.extentArr[3]};
    this.full_Extent = options.fullextent;
    this.fullExtentArr = options.fullextent.split (' ');
    this.extent = {x1:this.fullExtentArr[0],y1:this.fullExtentArr[1],x2:this.fullExtentArr[2],y2:this.fullExtentArr[3]};
    this.mapObj = null;
    
    this.toolMode = tmPan;
    this.ovBoxSize = 1;  // zoombox line width;
    this.drawBox = false;
    this.mapWidth = getWidth(this.map);
    this.mapHeight = getHeight(this.map);
    this.mapX = getX(this.map);
    this.mapY = getY(this.map);
    this.mouseMoveHandler = null;
    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.lastMode = -1;
    this.zooming = false;
    this.sessionId = options.sessionId;
    this.servletUrl = options.servletUrl;
    this.ToolModeChangeHandler = null;
    this.lastToolStack = [];
    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();
    this.useMouseWheel = false;
    this.factorMouseWheel = 5;
    
    this.currentLayers = [];
    this.currentMap = null;
    
    this.cursors = ['default'];
    
    //Global container for dynamic layers
    this.dynamicLayers = null;
    this.additionalLayers = [];
    
    this.fractional = false;
    this.datasourceselect = null;
    
    this.overviewMapReady = false;

    this.paramHandler = [];
    
    window.onresize = SpatialMap.Function.bind(this.windowResize, this);
    this.events.addListener ('THEME_CHANGED',SpatialMap.Function.bind(this.setTheme, this));
    this.logList = [];
}

CBKort.prototype.log = function() {
    if (this.debug) {
        var d = new Date();
        var arg = [d.toLocaleTimeString ()+'.'+((1000+d.getMilliseconds())+'').toString().slice(1)];
        for(var i = 0; i < arguments.length; i++) {
            arg.push (arguments[i]);
        }
        this.logList.push (arg);
        SpatialMap.Console.log.apply(this,arg);
    }
}

CBKort.prototype.registerParamHandler = function(handler) {
    this.paramHandler.push (handler);
    this.log ('CBKort.registerParamHandler () - ',this.paramHandler);
}
CBKort.prototype.getParams = function() {
    var params = {};
    for (var i=0;i<this.paramHandler.length;i++) {
        var p = this.paramHandler[i]();
        if (p) {
            for (name in p) {
                params[name] = p[name];
            }
        }
    }
    return params;
}
CBKort.prototype.getUrl = function(userparams) {
    var params = {
        profile: this.profile,
        sessionid: this.sessionId
    }
    if (this.debug) {
        params.debug = this.debug;
    }
    params = SpatialMap.Util.applyDefaults (this.getParams (),params);
    if (userparams) {
        params = SpatialMap.Util.applyDefaults (userparams,params);
    }
    this.log ('CBKort.getUrl () - ',SpatialMap.Util.extend ({},params));
    var url = this.getServletUrl();
    var prefix = '?';
    for (name in params) {
        if (params[name] != null) {
            url += prefix+name+'='+params[name];
            prefix = '&';
        }
    }
    return url;
}

CBKort.prototype.getFormParamAsUrl = function(userparams)
{
    var params = {
        mapheight: getHeight (this.map),
        mapwidth: getWidth (this.map),
        extent: this.getCurrentExtent (true),
        layers: this.getCurrentLayers (true)
    };
    if (userparams) {
        params = SpatialMap.Util.applyDefaults (userparams,params);
    }
    return this.getUrl (params);
}

CBKort.prototype.setMap = function() {
    var a = this.getResolutions (this.fullExtentArr);
    if (!this.resolutions) {
        this.resolutions = a.resolutions;
    }
    if (!this.maxextent) {
        this.maxextent = a.maxextent;
    }
    
    //temporary while CBINFO doesn't support uppercase parameters
    if (!(this.host instanceof Array)) {
        this.host = [this.host];
    }
    for (var i=0;i<this.host.length;i++) {
        this.host[i] = this.host[i]+(this.host[i].indexOf('?')+1 ? '&' : '?')+'sessionid='+this.sessionId;
    }

    var options = {
        //layers: this.themeContainer.getMapThemes (),
        layers: [],
        host: this.host,
        servicename: this.servicename,
        projection: this.projection,
        extent: this.startExtent,
        resolutions: this.resolutions,
        maxextent: this.maxextent,
        mapChangeHandler: SpatialMap.Function.bind(this.callMapChangeHandler, this)
    };

    this.log ('CBKort.setMap () - ',SpatialMap.Util.extend ({},options));

    this.mapObj = new SpatialMap.Map (this.mapId,options);
    
    this.showLayers (this.layers.split (' '));
    //this.themeContainer.setVisibility (this.layers.split (' '));
    
    this.dynamicLayers = new DynamicLayers ();
}

CBKort.prototype.getResolutions = function (extent) {
    //var resolutions = [0.8, 1.6, 3.2, 6.4, 12.8, 25.6, 51.2, 102.4, 204.8, 409.6, 819.2, 1638.4, 3276.8];
    var resolutions = [0.2, 0.4, 0.8, 1.6, 3.2, 6.4, 12.8, 25.6, 51.2, 102.4, 204.8, 409.6, 819.2, 1638.4, 3276.8];
    var maxextent = {x1:120000,y1:5661139.2,x2:958860.8,y2:6500000};

    var w = extent[2]-extent[0];
    var maxresX = Math.log ((w/256) / resolutions[0])/Math.log (2);

    var h = extent[3]-extent[1];
    var maxresY = Math.log ((h/256) / resolutions[0])/Math.log (2);

    var maxres = Math.max(maxresX,maxresY);
    
    var res = [];
    for (var i=0;i<maxres+1;i++) {
        res.push (resolutions[i]);
    }

    var topres = res[res.length-1];
    var tilesize = 256*topres;

    var x = extent[0]-maxextent.x1;
    //nearest number of tiles
    var tilesX = parseInt(x/tilesize);
    var minx = maxextent.x1 + tilesX*tilesize;
    var maxx;
    if (extent[2]>minx+tilesize) {
        maxx = minx+2*tilesize;
    } else {
        maxx = minx+tilesize;
    }

    var y = extent[1]-maxextent.y1;
    //nearest number of tiles
    var tilesY = parseInt(y/tilesize);
    var miny = maxextent.y1 + tilesY*tilesize;
    var maxy;
    if (extent[3]>miny+tilesize) {
        maxy = miny+2*tilesize;
    } else {
        maxy = miny+tilesize;
    }
    return {resolutions:res,maxextent:{x1:minx,y1:miny,x2:maxx,y2:maxy}};
}

/**
 * Method: locateWKT
 * Locate a WKT in the map
 * 
 * obj contains:
 * - dynamiclayer - {String} Name of the dynamiclayer
 * - wkt - {Sting} or {Array} A list of WKT to locate
 * - buffer - {string} OPTIONAL Displaybuffer syntax 
 */
CBKort.prototype.locateWKT = function(obj) {
    this.log ('cbKort.locateWKT () - ',obj);
    if (obj.dynamiclayer && obj.wkt) {
        if (!obj.wkt instanceof Array) {
            obj.wkt = [obj.wkt];
        }
        for (var i=0;i<obj.wkt.length;i++) {
            cbKort.dynamicLayers.addWKT ({name:obj.dynamiclayer,wkt:obj.wkt[i]});
        }
        var buffer = obj.buffer || 0;
        cbKort.dynamicLayers.zoomTo (obj.dynamiclayer,buffer);
    }
}
    
/**
 * Parameters:
 * options - {Object} Hashtable of layer parameters to use as background layer in the overview map
 *              host
 *              servicename
 *              projection
 *              resolutions (default: [2048,512])
 *              format
 *              width       (default: 150)
 *              height      (default: 103)
 *              minRatio    (default: 8)
 *              maxRatio    (default: 32)
 *              layername   
 */
CBKort.prototype.addOverviewMap = function (overviewMapId,options) {
    var overviewmapdatasource = options.overviewmapdatasource;
    
    var str = '';
    var url = '';
    if (overviewmapdatasource) {
        url = overviewmapdatasource.url;
        prefix = (url.indexOf('?')+1 ? '&' : '?');
        if (overviewmapdatasource.parameters) {
            for (var name in overviewmapdatasource.parameters) {
                url += prefix+name+'='+overviewmapdatasource.parameters[name];
                prefix = '&';
                overviewmapdatasource.srs = null;
                overviewmapdatasource.format = overviewmapdatasource.format || null;
            }
        }
        url += prefix+'sessionid='+cbKort.getSessionId ();
        url = [url];
    } else {
        url = this.host;
        var overviewmapdatasource = {};
        overviewmapdatasource.layers = this.themeContainer.elements[0].elements[0].name;
    }

    options.layername = overviewmapdatasource.layers,
    options.projection = overviewmapdatasource.srs,
    options.format = overviewmapdatasource.format,
    options.host = url


    this.overviewMapId = overviewMapId;
    if (!options) {
        options = {};
    }
    options.projection = options.projection || this.projection;
    if (options.projection.indexOf ('EPSG') < 0) {
        options.projection = 'EPSG:'+options.projection;
    }
    if (options.resolutions.length == 0) {
        var width = this.maxextent.x2 - this.maxextent.x1;
        var wpx = options.width || 150;
        options.resolutions = [width/wpx];
    }
    this.overviewMapOptions = options;
    this.log ('CBkort.addOverviewMap () - ',this.overviewMapOptions);
}

CBKort.prototype.showOverviewMap = function () {
    showElement(getElement("overviewbox"));
    if (this.overviewMapReady == false) {
        this.addOverviewMapInit ();
    }
}

CBKort.prototype.hideOverviewMap = function () {
    hideElement(getElement("overviewbox"));
}

CBKort.prototype.addOverviewMapInit = function () {
    this.overviewMapReady = true;
    this.mapObj.addOverviewMap (this.overviewMapId,this.overviewMapOptions);
}

CBKort.prototype.setFractionalZoom = function (fractional) {
    if (this.fractional != fractional) {
        this.fractional = fractional;
        this.mapObj.setFractionalZoom (this.fractional);
        
        // set the themes
        this.themeContainer.setMap ();
    }
}
CBKort.prototype.getFractionalZoom = function () {
    return this.fractional;
}

CBKort.prototype.setCopyRightText = function () {
    var copyrighttextarray = this.themeContainer.getCopyRightText ();
    var resultarray = [];
    var themenames = [];
    for (var i=0;i<copyrighttextarray.length;i++) {
        themenames.push (copyrighttextarray[i].name);
        var r = copyrighttextarray[i].text;
        for (var j=0;j<resultarray.length;j++) {
            if (r == resultarray[j]) {
                r = null;
                break;
            }
        }
        if (r != null) {
            resultarray.push (r);
        }
    }
    getElement ('statusbarleft').innerHTML = '<span class="copyrightclick" onmousedown="javascript:doCopyRight(event,\''+themenames.join (' ')+'\');">'+resultarray.join (', ')+'</span>';
}

CBKort.prototype.showLayers = function (layernameArray) {
    if (!layernameArray) {
        layernameArray = this.defaultLayers.split (' ');
    }
    SpatialMap.Util.copyArray (this.currentLayers,layernameArray);
    this.layers = layernameArray.join (' ');
    this.themeContainer.setVisibility (layernameArray);
}

CBKort.prototype.setTheme = function(event,theme) {
    if (theme.visible) {
        for (var i=0;i<this.currentLayers.length;i++) {
            if (this.currentLayers[i] == theme.name) {
                return;
            }
        }
        this.currentLayers.push (theme.name);
    } else {
        for (var i=0;i<this.currentLayers.length;i++) {
            if (this.currentLayers[i] == theme.name) {
                this.currentLayers.splice(i,1);
                break;
            }
        }
    }
}
CBKort.prototype.getCurrentLayers = function(converToString) {
    if (!converToString) {
        return this.currentLayers;
    } else {
        return this.currentLayers.join (' ');
    }
}

CBKort.prototype.getCurrentExtent = function(converToString) {
    if (!converToString) {
        return this.currentMap.extent;
    } else {
        return this.currentMap.extent.join (' ');
    }
}

CBKort.prototype.getCurrentMapCenter = function()
{
    var a = this.currentMap.extent;
    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.showLegend = function () {
    this.legendVisible = true;
    this.themeContainer.setLegend ('legendbox_container', 'legend_themegroupselement');
}

CBKort.prototype.hideLegend = function () {
    this.legendVisible = false;
}

/**
 * 
 */
/**
 * Method: setThemeVisibility
 * Turn themes on and off 
 * 
 * Parameters:
 * themename - {String} Name of the theme
 * visible - {boolean} OPTIONAL Show or hide the theme. If not available, theme visibility is toggled
 * redraw - {boolean} OPTIONAL Make the browser reload all tiles 
 */
CBKort.prototype.setThemeVisibility = function (themename,visible,redraw) {
    var theme = this.themeContainer.getTheme (themename);
    if (theme && visible!=null) {
        theme.setVisibility (visible);
    }
    if (redraw) {
        theme.redraw ();
    }
}

CBKort.prototype.setLayerOrder = function () {
    var a = this.themeContainer.getMapLayersID ();
    a.sort (function (a,b) {return a.renderingorder - b.renderingorder;})
    var b = [];
    for (var i=0;i<a.length;i++) {
    	b.push (a[i].id);
    }
    if (this.additionalLayers.length) {
        b = b.concat (this.additionalLayers);
    }
    if (b.length) {
        cbKort.mapObj.setLayerOrder (b);
    }
}

CBKort.prototype.addAdditionalLayer = function (layer) {
    if (layer.id) {
        for (var i=0;i<this.additionalLayers.length;i++) {
            if (this.additionalLayers [i] == layer.id) {
                this.log ('CBKort.addAdditionalLayer () - Layer already added - ',layer);
                return;
            }
        }
        this.additionalLayers.push (layer.id);
        this.mapObj.addLayer (layer);
    }        
}
CBKort.prototype.setAdditionalLayerVisibility = function (id,visible,redraw) {
    if (id) {
        var layerReady = false;
        for (var i=0;i<this.additionalLayers.length;i++) {
            if (this.additionalLayers [i] == id) {
                layerReady = true;
            }
        }
        if (layerReady) {
            if (visible!=null) {
                if (visible === true) {
                    this.mapObj.showLayer (id);
                } else if (visible === false){
                    this.mapObj.hideLayer (id);
                }
            }
            if (redraw) {
                this.mapObj.redrawLayer (id);
            }
            this.log ('CBKort.setAdditionalLayerVisibility () - ',id,visible,redraw);
        } else {
            this.log ('CBKort.setAdditionalLayerVisibility () - Layer NOT added - ',id);
        }
    }
}

CBKort.prototype.getDatasourceSelect = function () {
    if (this.datasourceselect == null) {
        this.datasourceselect = new SelectObject ();
    }
    return this.datasourceselect;
}

CBKort.prototype.getCurrentSelectorGroups = function () {
    return this.themeContainer.getExpanded ();
}

CBKort.prototype.windowResize = function() {
    var size = this.getWindowSize ();
    this.resizeMap ('WINDOW_RESIZED',size);
    this.events.fireEvent ('WINDOW_RESIZED',size);
}    
    
CBKort.prototype.resizeMap = function (event,size) {
    if (event == 'WINDOW_RESIZED') {
        var corr = (ie ? 1 : 0);
        this.mapWidth = size.width-this.mapX-this.mapSizeCorrection.x;
        this.mapHeight = size.height-this.mapY-this.mapSizeCorrection.y;
        setWidth (this.map,this.mapWidth);
        setHeight (this.map,this.mapHeight);
    }
}    

CBKort.prototype.getWindowSize = function() {
    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;
    }
    var size = {
        width: frameWidth,
        height: frameHeight
    };
    return size;
}


CBKort.prototype.roundToDecs = function(a,d) {
    if (a.toFixed)
        return a.toFixed(d);
    var power = Math.pow(10,d);
    return Math.round(a*power)/power;
}
CBKort.prototype.formatDistance = function(d, numdecimals) {
    if (d<10000) {
        if (numdecimals || numdecimals == 0){
            return [this.roundToDecs(d, numdecimals),"m"];
        } else {
            return [d, cbInfo.getString("standard.units.length")];
        }
    } else {
        return [this.roundToDecs(d/1000,1),cbInfo.getString("standard.units.length_1000")];
    }
}
CBKort.prototype.formatArea = function(a, numdecimals) {
    if (a<10000) {
        if (a<5) {
            if (numdecimals)
                return [this.roundToDecs(a, numdecimals),cbInfo.getString("standard.units.area")];
            else
                return [this.roundToDecs(a, 0),cbInfo.getString("standard.units.area")];
        } else {
            return [this.roundToDecs(a, 0),cbInfo.getString("standard.units.area")];
        }
    } else {
       if (a<1000000)
          return [this.roundToDecs(a/10000,1),cbInfo.getString("standard.units.area_10000")];
       else   
          return [this.roundToDecs(a/1000000,1),cbInfo.getString("standard.units.area_1000000")];
    }
}









CBKort.prototype.getImageXY = function(e)
{
    var xy = getCoords(e);
    this.mouseX = xy[0]-this.mapX;
    this.mouseY = xy[1]-this.mapY;
}

CBKort.prototype.setCursor = function(cursor)
{
    if (!cursor) {
        cursor = 'default';
    }
    this.map.style.cursor = cursor;
}

CBKort.prototype.removeCursor = function(cursor)
{
    if (cursor) {
        this.cursors.push (cursor);
    } else if (this.cursors.length > 1) {
        this.cursors.pop ();
    }
    this.map.style.cursor = cursor;
}

CBKort.prototype.setToolMode = function(m)
{
    //reset cursor
    this.setCursor ();
    
    if (m!=this.toolMode && m!=null) {
        this.lastToolStack.push (this.toolMode);
    } else if (m==null) {
        m = this.lastToolStack.pop ();
    }

    var lastTool = -2;

    if (m!=this.toolMode && 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 (m!=this.toolMode && (this.toolMode==tmZoomIn||this.toolMode==tmZoomOut||this.toolMode==tmCenter||this.toolMode==tmPan||this.toolMode==tmDynaZoom||this.toolMode==tmRemove||this.toolMode==lastTool))
        this.lastMode = this.toolMode;
    else
        this.lastMode = -1;

    this.log ('TOOL_CHANGED - ','lastMode:'+this.lastMode,', newMode:'+m);
    this.events.fireEvent ('TOOL_CHANGED',{lastMode:this.lastMode,newMode:m});

    if (this.ToolModeChangeHandler!=null&&m!=this.toolMode) {
        this.ToolModeChangeHandler();
        this.ToolModeChangeHandler = null;
    }
    switch(m) {
        case tmZoomIn:
            this.toolMode = tmZoomIn;
            this.setCursor ('url("images/standard/cursors/zoomin.cur"),crosshair');
            this.mapObj.zoom ();
            this.mapObj.setClickEvent ();
        break;

        case tmZoomOut:
            this.toolMode = tmZoomOut;
            this.setCursor ('url("images/standard/cursors/zoomout.cur"),crosshair');
            this.mapObj.panzoom ();
            this.mapObj.setClickEvent ( SpatialMap.Function.bind (function () {
                this.mapObj.zoomOut ();
            },this));
        break;

        case tmPan:
            this.toolMode = tmPan;
            this.setCursor ('url("images/standard/cursors/i_pan.cur"),move');
            this.mapObj.panzoom ();
            this.mapObj.setClickEvent ();
        break;

        default:
            this.toolMode = m;
            if (m>=100&&m<=this.nUserTools+100) {
                this.setCursor (this.userTools[m-100].cursor);
                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, cursor)
{
    var returnValue = this.nUserTools+100;
    this.userToolsLastToolMode[this.nUserTools] = statebutton;
    this.userTools[this.nUserTools++] = {init:initHandler,down:mouseDownHandler,move:mouseMoveHandler,up:mouseUpHandler,change:toolChangeHandler, cursor:cursor};
    return returnValue;
}


CBKort.prototype.removeSearchResults = function(deletePage,clearFields,waitingboxText)
{
    //MOVED TO SPATIALQUERY.JS
    return;


    //OLD
    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() {
    var extentArray = this.full_Extent.split(' ');
    this.zoomToExtent (extentArray);
}
CBKort.prototype.zoomToExtent = function(extent) {
    if (!extent) {
        extent = this.extent;
    }
    if (extent instanceof Array) {
        extent = {x1:extent[0],y1:extent[1],x2:extent[2],y2:extent[3]};
    }
    this.log ('CBKort.zoomToExtent - ',extent)
    this.mapObj.zoomToExtent (extent);
}

CBKort.prototype.getHost = function()
{
    return this.host;
}

CBKort.prototype.getLayers = function(escapeIt)
{
    return this.currentLayers.join (' ');
}



CBKort.prototype.addLayer = function(layer)
{
    var a = this.layers.split(" ");
    for (var i=0;i<a.length;i++) {
        if (a[i] == layer) {
            return false;
        }
    }
    this.layers += ' '+layer;
    document.mapserv.layers.value = this.layers;
    return true;
}

CBKort.prototype.removeLayer = function(layer)
{
    var a = this.layers.split(" ");
    for (var i=0;i<a.length;i++) {
        if (a[i] == layer) {
            a.splice (i,1);
            this.layers = a.join (' ');
            document.mapserv.layers.value = this.layers;
            return true;
        }
    }
    return false;
}


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()
{
    return this.service;
}

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)
{
    //NOT IN USE
    return;


    e.onmousedown = checkMouseDown;
    e.onmouseup = checkMouseUp;
    e.onmousemove = checkMouseMove;

    if (document.attachEvent)
        getElement('mapcontainer').attachEvent('onmousewheel', checkMouseWheel);
    else
        getElement('mapcontainer').addEventListener('DOMMouseScroll', checkMouseWheel, false);
}

function checkMouseDown(e)
{
    //NOT IN USE
    return;


    return cbKort.checkMouseDown(e);
}

function checkMouseUp(e)
{
    //NOT IN USE
    return;


    return cbKort.checkMouseUp(e);
}

function checkMouseMove(e)
{
    //NOT IN USE
    return;


    return cbKort.checkMouseMove(e);
}

function checkMouseWheel(e)
{
    //NOT IN USE
    return;


    return cbKort.checkMouseWheel(e);
}

CBKort.prototype.checkMouseDown = function(e)
{
    //NOT IN USE
    return;
    
    
    
    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 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;
            if (this.map)
                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)
{
    //NOT IN USE
    return;


    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)
{
    //NOT IN USE
    return;


    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.checkMouseWheel = function(event)
{
    //NOT IN USE
    return;


    if(this.useMouseWheel)
    {
        var mouse_x = event.clientX;
        var mouse_y = event.clientY;
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
                /** In Opera 9, delta differs in sign as compared to IE.
                 */
                if (window.opera)
                        delta = -delta;
        } else if (event.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                delta = -event.detail/3;
        }
        /** If delta is nonzero, handle it.
         * Basically, delta is now positive if wheel was scrolled up,
         * and negative, if wheel was scrolled down.
         */
        if (delta)
                zoomResize(this.factorMouseWheel*delta,{x:mouse_x,y:mouse_y});
        /** Prevent default actions caused by mouse wheel.
         * That might be ugly, but we handle scrolls somehow
         * anyway, so don't bother here..
         */
        if (event.preventDefault)
            event.preventDefault();
        event.returnValue = 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 cbInfo.getString ("standard.message.the_map_extent_is", 
                   Math.round(width),         
                   cbInfo.getString("standard.units.length"));
        else
            return cbInfo.getString ("standard.message.the_map_extent_is", 
                   Math.round(width/100)/10, 
                   cbInfo.getString("standard.units.length_1000"));
    }
    else
        return '';
}

CBKort.prototype.zoomToMapWidth = function(reqWidth,minWidth, maxWidth)
{
    alert('Deprecated!');
    return;
    
    var reg = new RegExp("[^0-9]");
    if (reg.test(reqWidth))
    {
        alert(cbInfo.getString("standard.message.type_in_integer"));
        return;
    }

    if(minWidth&&maxWidth&&(reqWidth<minWidth||reqWidth>maxWidth))
    {
        var unit = cbInfo.getString("standard.units.length");
        alert( cbInfo.getString("standard.error.value_out_of_range", minWidth, maxWidth, unit));
        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.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();
    }
}





var dynamicZoom;
function DynamicZoom()
{
    this.image = getElement("themapimage");
    this.orgWidth =  parseInt(this.image.style.width,10) || this.image.width;
    this.orgHeight = parseInt(this.image.style.height,10) || this.image.height;
    this.elStartLeft  = parseInt(this.image.style.left, 10) || 0;
    this.elStartTop   = parseInt(this.image.style.top,  10) || 0;
    this.zIndex = 4;

    this.zoomValue = 0;
    this.zoomPoint = {x:parseInt(cbKort.mapX+cbKort.mapWidth/2),y:parseInt(cbKort.mapY+cbKort.mapHeight/2)};
    this.zoomTimer;
}
DynamicZoom.prototype.getFactor = function()
{
    if (this.zoomValue >= this.orgHeight)
        this.zoomValue = this.orgHeight-1;
    else if (this.zoomValue <= -this.orgHeight)
        this.zoomValue = -this.orgHeight-1;
    return Math.pow(1-(this.zoomValue/this.orgHeight),4);
}

function zoomUpdateMap()
{
    if(!dynamicZoom)
        return;

    var x = getX(dynamicZoom.image);
    var y = getY(dynamicZoom.image);
    var w = getWidth(dynamicZoom.image);
    var h = getHeight(dynamicZoom.image);
    
    var arr = cbKort.getExtent();
    var width = Math.abs(arr[2]-arr[0]);
    var height = Math.abs(arr[3]-arr[1]);
    var reqWidth = width/dynamicZoom.getFactor();
    var reqHeight = height/dynamicZoom.getFactor();
    var zoomcenter = cbKort.getWorldCoordinate(dynamicZoom.zoomPoint.x-cbKort.mapX,dynamicZoom.zoomPoint.y-cbKort.mapY).split(" ");
    var cx = zoomcenter[0];
    var cy = zoomcenter[1];

    var x = dynamicZoom.zoomPoint.x-cbKort.mapX || 0;
    var y = dynamicZoom.zoomPoint.y-cbKort.mapY || 0;
    var x1 = cx - 0 - reqWidth*(x/dynamicZoom.orgWidth);
    var x2 = cx - 0 + reqWidth*(1-(x/dynamicZoom.orgWidth));
    var y1 = cy - 0 - reqHeight*(1-(y/dynamicZoom.orgHeight));
    var y2 = cy - 0 + reqHeight*(y/dynamicZoom.orgHeight);

    if(dynamicZoom.zoomValue)
    {
        showWaitingBox();
        document.mapserv.imgext.value = x1+"+"+y1+"+"+x2+"+"+y2;
        document.mapserv.zoomdir.value = "0";
        document.mapserv.submit();
        dynamicZoom = null;
    }
}
function zoomStart(point)
{
    if(!dynamicZoom)
        dynamicZoom = new DynamicZoom();
    if(point)
        dynamicZoom.zoomPoint = point;
}

function zoomResize(direction,point)
{
    zoomStart(point);
    clearTimeout(dynamicZoom.zoomTimer);
    dynamicZoom.zoomValue -= direction;
    
    dynamicZoom.image.style.zIndex = ++dynamicZoom.zIndex;
    dynamicZoom.image.style.position = "absolute";
    dynamicZoom.image.style.overflow = "hidden";
    var f = dynamicZoom.getFactor();
    setWidth(dynamicZoom.image,Math.round(dynamicZoom.orgWidth * f));
    setHeight(dynamicZoom.image,Math.round(dynamicZoom.orgHeight * f));
    
    var x = dynamicZoom.zoomPoint.x-cbKort.mapX || 0;
    var y = dynamicZoom.zoomPoint.y-cbKort.mapY || 0;
    setX(dynamicZoom.image,x - x * f);
    setY(dynamicZoom.image,y - y * f);
    
    dynamicZoom.zoomTimer = setTimeout('zoomUpdateMap()',1000);
}




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;
            break;
        }
    }

    if(found) {
        // Identify the parameter and value
        var k = '([?&])('+name+')=[^&]*';
        var re1 = new RegExp(k,'g') ;
        var t = re1.exec(url);
        if(value=='') {
            var testererer = (t[1] == '?' ? '?' : '');
            url = url.replace(re1,testererer);
        } else {
            url = url.replace(re1,t[1]+t[2]+'='+value);
        }
    } else {
        if(value!='') {
            url+= (url.indexOf('?')+1 ? '&' : '?')+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(handler)
{
    this.mapChangeHandler[this.nMapChangeHandler++] = {init:handler};
}

CBKort.prototype.callMapChangeHandler = function(map) {
    if (!map) {
        map = this.mapObj.getMapState();
    }
    this.currentMap = map;
    this.setCurrentScale(map.scale);
    
    if (this.legendVisible) {
        this.themeContainer.setLegend ('legendbox_container', 'legend_themegroupselement');
    }

    this.log ('MAP_CHANGED - ',map);
    this.events.fireEvent ('MAP_CHANGED',map);

    this.checkThemeMinMacScale ();

    for(var ti=0;ti<this.mapChangeHandler.length;ti++) {
        if(this.mapChangeHandler[ti].init!=null)
            this.mapChangeHandler[ti].init(map);
    }
}

CBKort.prototype.checkThemeMinMacScale = function () {
    if (checkThemeMinMacScale) {
        checkThemeMinMacScale ();
    }
}


CBKort.prototype.registerResizeHandler = function(resizeHandler)
{
    this.mapResizeHandler[this.mapResizeHandler.length] = {handler:resizeHandler};
}
CBKort.prototype.mapResizeOLD = function()
{
    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;
    }

    cbKort.log ()
    return;
    
    
    
    
    
    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 - getX(this.map) - 5 + corr,10)+'px';
    if(newMapHeight)
        newMapHeight = parseInt(newMapHeight,10)+'px';
    else
        newMapHeight = parseInt(frameHeight - getY(this.map) - 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 = getWidth(this.map);
    var oldMapHeight = getHeight(this.map);
    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);
    }
    alert(111);
    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);

    e = getElement('overviewbox');
    if(e)
        e.style.top = pixelAdd(e.style.top,mapHeightCorr);

    if(leftBar)
    {
        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();
    }

    this.log ('MAP_RESIZED');
    this.events.fireEvent ('MAP_RESIZED');

    for(var handlerCount = 0;handlerCount < this.mapResizeHandler.length;handlerCount++)
        this.mapResizeHandler[handlerCount].handler(mapWidthCorr,mapHeightCorr);
}

CBKort.prototype.getString = function(key, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)
{
    return cbInfo.getString (key, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
}

CBKort.prototype.setCopyright = function(width,height,left,top)
{
    alert('setCopyright');
    return;
    var copyrightdiv = getElement('copyrightdiv');
    if(!copyrightdiv)
        return;
    if(width!=null && width!='')
        setWidth(copyrightdiv,width);
    if(height!=null && height!='')
        setHeight(copyrightdiv,height);
    if(left!=null && left!='')
        setX(copyrightdiv,left);
    if(top!=null && top!='')
        setY(copyrightdiv,top);
}

CBKort.prototype.getProfileParam = function(xpath)
{
    if(!xpath)
    {
        alert('xpath is missing');
        return null;
    }
    var url = this.getServletUrl();
        url+='?page=get.profile.nodevalue';
        url+='&profile='+this.profile; 
        url+='&xpath='+encodeURIComponent (xpath);
        url+="&jdaf.error.xslt=";
        url+="&jdaf.error.contenttype=text/xml";
        url+="&sessionid=" + this.getSessionId();        
    
    var request = new CBhttp ();
    var 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)
{
    prompt('This is wrong!!! Fix it...',url);
    return;
    
    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 = cbInfo.getString("standard.message.the_map_is_updating") + "...";
    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.className='themegrouplabelFocus';
    showHint(event,text);
}
function tgOut(element)
{
    element.className='themegrouplabel';
    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)
{
    alert('deprecated');
    return null;
    
    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(cbInfo.getString("standard.error.error"),null);
    var h = '<table class="divtable" style="width:100%;">'
          + '   <tr align="left">'
          + '       <td class="heading3td">' + cbInfo.getString("standard.error.an_error_occurred") + '</td>'
          + '   </tr>'
          + '   <tr align="left">'
          + '       <td>' + cbInfo.getString("standard.message.show_details") + '</td>'
          + '   </tr>'
          + '   <tr align="right">'
          + '       <td>'
          + '           <button id="okbutton" class="menubutton" onclick="errorHandler.showDetails();">' + cbInfo.getString("standard.button.show_details") + '</button>'
          + '           <button id="okbutton" class="menubutton" onclick="errorHandler.dialog.closeDialog();" style="width:50px">' + cbInfo.getString("standard.button.close") + '</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">' + cbInfo.getString("standard.button.close") + '</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;

function reloadSession()
{
    document.mapserv.sessionid.value = '';
    document.mapserv.page.value = '';
    window.location.href = cbKort.getFormParamAsUrl();
    return;
}
