var zoom = false;
var downCoord = null;
var mapDownCoord = null;
var tempCoord = null;
var map = null;
var infoBox = null;
var zoomBox = null;
var lastPoint = null
var ids = new Array();
var points = new Array();
var antPoints = 0;
var pointersize = 4;
var MSIE = navigator.userAgent.indexOf('MSIE') > -1 ? true : false;
var navigatorVersion = navigator.appVersion.replace(/.*?MSIE (\d\.\d).*/g, '$1') / 1;
var contextMenuObj;
function initContextMenu()
{
    contextMenuObj = document.getElementById('ContextMenu1_ContextMenu_map');
    contextMenuObj.style.display = 'none';
}
function initMap(mapScript, currentZoom, minZoomLevel, maxZoomLevel, initCenter) {
    if (map == null) {
        map = new AJAXMAP('map', mapScript, false, 'finnsenderen');
        map.setCRS('EPSG:4326');
        map.init(initCenter, currentZoom);
        map.disableAnnotationInfo();
        map.setZoomlevelMin(minZoomLevel);
        map.setZoomlevelMax(maxZoomLevel);
        var drawCanvas = new WAPICanvas();
        map.addDrawCanvas(drawCanvas);

        infoBox = $('infoBox');
        zoomBox = $('zoomrect');

        Event.observe('map', 'annotation:mouseIn', function(e) {
            showInfoBox(e.memo.annotation);
        });
        Event.observe('map', 'annotation:mouseOut', function(e) {
            hideInfoBox();
        });
        /*Event.observe('map', 'map:zoomedIn', function(e) {
         updateMastedataAtZoomlevel();
         //BoundingBox bb = map.getBoundingBox();
         //var zoomlevel = (bb.right - bb.left)/map.getWidth();
         });*/
        Event.observe('map', 'map:zoomed', function(e) {
            updateMastedataAtZoomlevel();
        });
        /*Event.observe('map', 'map:zoomedOut', function(e) {
         updateMastedataAtZoomlevel();
         });*/
        Event.observe('map', 'map:moved', function(e) {
            updateMastedataAtZoomlevel();
        });
        Event.observe('map', 'map:grabbed', function(e) {
            startZoom(e.memo);
        });
        Event.observe('map', 'map:mouseUp', function(e) {
            doZoom(e.memo);
        });
        Event.observe('map', 'map:mouseMoved', function(e) {
            placeInfoBox(e.memo);
        });

        zoomBox.onmouseup = zoomboxZoom;
        zoomBox.onmousemove = zoomBoxMove;
    }
    var theMap = document.getElementById('map');
    theMap.oncontextmenu = showContextMenu;
    theMap.onclick = hideContextMenu;
}

function zoomboxZoom() {
    if (tempCoord != null) {
        doZoom(tempCoord);
    }
}
function startZoom(down) {
    if (zoom) {
        var offset = Position.cumulativeOffset($('map'));
        var d = down.mouseCoords;
        var top = d.y + offset[1] - pointersize;
        var left = d.x + offset[0] + pointersize;
        zoomBox.style.top = top + 'px';
        zoomBox.style.left = left + 'px';
        zoomBox.style.width = '1px';
        zoomBox.style.height = '1px';
        downCoord = new Coordinate(left, top);
        mapDownCoord = down.mouseMapCoords;
    }
}
function doZoom(up) {
    if (zoom && downCoord != null) {
        var d = up.mouseMapCoords;
        var leftX = mapDownCoord.x;
        var rightX = d.x;
        var topY = mapDownCoord.y;
        var bottomY = d.y;
        if (mapDownCoord.x > d.x) {
            leftX = d.x;
            rightX = mapDownCoord.x;
        }
        if (mapDownCoord.y < d.y) {
            topY = d.y;
            bottomY = mapDownCoord.y;
        }
        var coordTop = new Coordinate(leftX, topY);
        //var newTop = coordTop.transform('EPSG:4326');
        var coordBottom = new Coordinate(rightX, bottomY);
        //var newBottom = coordBottom.transform('EPSG:4326');
        map.zoomOnBoundingBox({'x1':coordTop.x,'y1':coordTop.y,'x2':coordBottom.x,'y2':coordBottom.y});
        downCoord = null;
        tempCoord = null;
        mapDownCoord = null;
        zoomBox.style.width = '1px';
        zoomBox.style.height = '1px';
    }
}
function printPage() {
    if (window.print) {
        window.print();
    }
}

function closeWindow() {
    window.close()
}

function initPrintableMap(mapScript, currentZoom, centerCoord) {
    if (map == null) {
        //map = new AJAXMAP('map', 'http://webcache.test.gisline.no/', false);
        map = new AJAXMAP('map', mapScript, false);
        map.setCRS('EPSG:4326');
        map.init(centerCoord, currentZoom);
        Event.stopObserving('map', 'mousewheel');
        Event.stopObserving('map', 'DOMMouseScroll');
        Event.stopObserving('mapmouselayer', 'mousemove');
        Event.stopObserving('mapmouselayer', 'dblclick');

        getMastedataAtZoomlevel();
    }
}
function changeMapAction(action) {
    $('pan').className = "mapActions firstaction";
    $('zoom').className = "mapActions";
    zoomBox.style.width = '1px';
    zoomBox.style.height = '1px';
    downCoord = null;
    mapDownCoord = null;
    tempCoord = null;
    if (action == 1) {
        map.allowMouseNavigation();
        zoom = false;
        zoomBox.style.display = 'none';
        $('pan').className = "mapActions selected firstaction";
    } else if (action == 2) {
        map.disallowMouseNavigation();
        zoom = true;
        zoomBox.style.display = 'block';
        $('zoom').className = "mapActions selected";
    }
}
function showInfoBox(annotation) {
    infoBox.style.display = 'block';
    infoBox.innerHTML = annotation.title;
}

function hideInfoBox() {
    infoBox.style.display = 'none';
    infoBox.innerHTML = '';
}

function zoomBoxMove(e) {
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
    }
    placeZoomBox(posx, posy);
    // posx and posy contain the mouse position relative to the document
    // Do something with this information
}


function placeZoomBox(left, top) {

    if (zoom && downCoord != null) {
        if (downCoord.x > left) {
            zoomBox.style.width = downCoord.x - left + 'px';
            zoomBox.style.left = left - pointersize * 2 + 'px';

        } else {
            zoomBox.style.width = left - downCoord.x + 'px';
            zoomBox.style.left = downCoord.x + 'px';
        }
        if (downCoord.y > top) {
            zoomBox.style.height = downCoord.y - top + 'px';
            zoomBox.style.top = top + pointersize * 2 + 'px';

        } else {
            zoomBox.style.height = top - downCoord.y + 'px';
            zoomBox.style.top = downCoord.y + 'px';
        }
    }
}
function getComputedHeight(theElt) {
    var tmphght;
    if (MSIE) {
        //tmphght = document.getElementById(theElt).offsetHeight;
        tmphght = theElt.offsetHeight;
    }
    else {
        //var docObj = document.getElementById(theElt);
        var docObj = theElt;
        var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("height");
        tmphght = tmphght1.split('px');
        tmphght = tmphght[0];
    }
    return tmphght;
}
function placeInfoBox(e) {
    // Add this so the pointer is not obscuring the infobox
    var coordinate = e.mouseCoords;
    tempCoord = e;
    var tempmap = $('map');
    var offset = Position.cumulativeOffset(tempmap);
    var top = coordinate.y + offset[1] - pointersize;
    var left = coordinate.x + offset[0] + pointersize;

    infoBox.style.top = top + 'px';
    infoBox.style.left = left + 'px';
    placeZoomBox(left, top);
}
function updateMastedataAtZoomlevel() {
    var hidden = document.getElementById('callbackurl');
    var coor = map.getCenterCoordinate();
    var boundingbox = map.getBoundingBox();
    //var newTop = map.UTMToLatLon(new Coordinate(boundingbox.left, boundingbox.top,'EPSG:32633'));
    //var newBottom = map.UTMToLatLon(new Coordinate(boundingbox.right, boundingbox.bottom,'EPSG:32633'));
    var coordTop = new Coordinate(boundingbox.left, boundingbox.top);
    //var newTop = coordTop.transform('c');
    var coordBottom = new Coordinate(boundingbox.right, boundingbox.bottom);
    //var newBottom = coordBottom.transform('EPSG:32633');

    var vget = hidden.value + '&zoom=' + map.getZoomLevel() +
               '&bottom=' + coordBottom.y + '&right=' + coordBottom.x + '&top=' + coordTop.y + '&left=' + coordTop.x +
               '&centerX=' + coor.x + '&centerY=' + coor.y;
    var wcall = wicketAjaxGet(vget, function() {
    }, function() {
    });
}

/*function getMastedataAtZoomlevel() {
 var hidden = document.getElementById('callbackurl');
 var coor = map.getCenterCoordinate();
 var boundingbox = map.getBoundingBox();
 //var c = map.fromUTM(coor.x, coor.y, 33);
 //alert('top: ' + boundingbox.top + ' x:' + c.x + ' left: ' + boundingbox.left + ' y: ' + c.y);
 var vget = hidden.value + '&zoom=' + map.getZoomLevel() +
 '&bottom=' + boundingbox.bottom + '&right=' + boundingbox.right + '&top=' + boundingbox.top + '&left=' + boundingbox.left +
 '&centerX=' + coor.x + '&centerY=' + coor.y;
 var wcall = wicketAjaxGet(vget, function() {
 }, function() {
 });
 } */

function hideContextMenu(e) {
    if (document.all) e = event;
    //alert(e.button);
    //if (e.button == 0 && !MSIE) {
    //} else {
    //contextMenuObj = $('ContextMenu1_ContextMenu_map');
    contextMenuObj.style.display = 'none';
    //}
}

function showContextMenu(e) {
    if (map != null && map.getZoomLevel() >= 14) {
        var contextMenuSource = this;
        if (document.all)e = event;
        var xPos = e.clientX;
        if (xPos + contextMenuObj.offsetWidth > (document.documentElement.offsetWidth - 20)) {
            xPos = xPos + (document.documentElement.offsetWidth - (xPos + contextMenuObj.offsetWidth)) - 20;
        }

        var yPos = e.clientY;
        if (window.document.body.scrollTop > 0)
        {
            yPos = (window.screen.Height) ? e.clientY + window.document.body.scrollTop - 20 : e.clientY - 20;
        }
        else if (window.pageYOffset)
        {
            yPos = (window.pageYOffset > 0) ? e.clientY + window.pageYOffset - 20 : e.clientY - 20;
        }
        else if (document.documentElement.scrollTop > 0) {
                yPos = e.clientY + document.documentElement.scrollTop - 20;
            }
            else
            {
                yPos = e.clientY - 20;
            }
        lastPoint = map.getMouseDownMapCoords();
        contextMenuObj.style.left = xPos + 'px';
        contextMenuObj.style.top = yPos + 'px';
        contextMenuObj.style.display = 'block';
        return false;
    }
}

function addPoint() {
    if (map != null && antPoints <= 1) {
        var corr = lastPoint;
        var id = map.addAnnotation(new Annotation(corr, 'x: ' + lastPoint.x + '<br>y: ' + lastPoint.y, 'null', 'images/measure_point.gif', -7, -7));
        ids[antPoints] = id;
        var temp = corr.transform('EPSG:32633');
        points[antPoints] = new Coordinate(temp.x, temp.y, 'EPSG:32633');

        antPoints ++;
    }
    if (antPoints == 2) {
        var dist = map.getDistance(points);
        var distance = document.getElementById('distance');
        distance.value = 'Avstand: ' + dist + 'm';

        addNonIELine();

    }
    hideContextMenu();
}

function addNonIELine() {
    map.getDrawCanvas().clear();
    var line = new PolyLine([], {'rgba' : "rgba(0,0,0,0.6)", 'lineWidth' : 1});
    line.addPoint(points[0]);
    line.addPoint(points[1]);
    map.getDrawCanvas().addPolyLine(line);
}
function removePoint() {
    if (map != null && antPoints > 0) {
        clearLine();
        var id = ids[antPoints - 1];
        map.removeAnnotation(id);
        antPoints --;
    }
    hideContextMenu();
    var distance = document.getElementById('distance');
    distance.value = '';

}
function clearLine() {
    map.getDrawCanvas().clear();
}
function removeAllPoints() {
    if (map != null && antPoints > 0) {
        clearLine();
        for (i = 0; i < antPoints; i ++) {
            map.removeAnnotation(ids[i]);
        }
        antPoints = 0;
        var distance = document.getElementById('distance');
        distance.value = '';
    }
    hideContextMenu();
}


function moveMap(x, y) {
    map.move(new Move(x, y));
}
function zoomOut() {
    map.zoomOut();
}
function zoomIn(minZ) {
    map.zoomIn();
}

function changeMapType(t_type) {
    var t_schemeNumber = 0;
    $('kart').src = 'images/btn-kart_normal.png';
    $('foto').src = 'images/btn-flyfoto_normal.png';
    $('hybrid').src = 'images/btn-hybrid_normal.png';

    if (t_type == "foto") {
        t_schemeNumber = 1;
        $('foto').src = 'images/btn-flyfoto_selected.png';
    }
    else {
        if (t_type == "kart") {
            t_schemeNumber = 0;
            $('kart').src = 'images/btn-kart_selected.png';
        } else  {
            if (t_type == "hybrid") {
                t_schemeNumber = 2;
                $('hybrid').src = 'images/btn-hybrid_selected.png';
            }
        }
    }

    map.setMapStyle(t_schemeNumber);
}