var ie = document.all;
var nn6 = document.getElementById && !document.all;
var isZoom = false;
var isPan = false;
var isMark = false;
var clickX, clickY;
var selectedTool;
var rememberedTool;
var mapBaseUrl;

// bounding box of the displayed map
var mapBoundingBoxNorth;
var mapBoundingBoxSouth;
var mapBoundingBoxEast;
var mapBoundingBoxWest;

// boundary of the whole map
var mapBoundaryNorth;
var mapBoundarySouth;
var mapBoundaryEast;
var mapBoundaryWest;

// image size of the map
var mapImageHeight;
var mapImageWidth;

function zoom_map(e) {
    if (isZoom) {
        var mouseX = nn6 ? e.clientX : event.clientX;
        var mouseY = nn6 ? e.clientY : event.clientY;
        var width, left, height, top;

        if (mouseX > clickX) {
            width = mouseX - clickX;
            left = clickX;
        } else {
            width = clickX - mouseX;
            left = mouseX;
        }

        if (mouseY > clickY) {
            height = mouseY - clickY;
            top = clickY;
        } else {
            height = clickY - mouseY;
            top = mouseY;
        }
        _style('zoom').display = 'block';
        _style('zoom').left = (left - getOffsetLeft(_element('map_container'))) + 'px';
        _style('zoom').top = (top - getOffsetTop(_element('map_container'))) + 'px';
        _style('zoom').width = width + 'px';
        _style('zoom').height = height + 'px';
        _style('zoom').cursor = 'crosshair';
        return false;
    }
}

function pan_map(e) {
    if (isPan) {
        var mouseX = nn6 ? e.clientX : event.clientX;
        var mouseY = nn6 ? e.clientY : event.clientY;

        _style('map_image').left = (tx + mouseX - clickX) + 'px';
        _style('map_image').top  = (ty + mouseY - clickY) + 'px';
        _style('map_image').cursor = 'move';
        
        if (_element('overlay_image') != null) {
	        _style('overlay_image').left = (tx + mouseX - clickX) + 'px';
	        _style('overlay_image').top  = (ty + mouseY - clickY) + 'px';
	        _style('overlay_image').cursor = 'move';
        }
        return false;
    }
}

function mark_map(e) {

}

function mouse_pressed(e) {
    var selObj = nn6 ? e.target : event.srcElement;

    if (selObj.id == "map_image" || selObj.id == "overlay_image") {
        tx = parseInt(_style('map_image').left+0);
        ty = parseInt(_style('map_image').top+0);
        clickX = nn6 ? e.clientX : event.clientX;
        clickY = nn6 ? e.clientY : event.clientY;

        if (tx > clickX || ty > clickY) {
            isPan = false;
        }

        if (selectedTool == 'pan') {
            isPan = true;
            document.onmousemove = pan_map;
        	selObj.style.cursor = 'move';
        } else if (selectedTool == 'zoom') {
            document.onmousemove = zoom_map;
            isZoom = true;
        	selObj.style.cursor = 'crosshair';
        } else if (selectedTool == 'mark') {
            document.onmousemove = mark_map;
            isMark = true;
        }
        return false;
    }
}

function mouse_released(e) {
    if (isZoom) {
    	_style('map_image').cursor = 'default';
    	_style('zoom').cursor = 'default';
        var top = parseInt(_style('zoom').top.replace(/px/, ''));
        var left = parseInt(_style('zoom').left.replace(/px/, ''));
        var bottom = top + parseInt(_style('zoom').height.replace(/px/, ''));
        var right = left + parseInt(_style('zoom').width.replace(/px/, ''));
        if (!isNaN(top) && !isNaN(left) && !isNaN(bottom) && !isNaN(right) && top != bottom && left != right) {
            //alert("zoom: top=" + top + " left=" + left + " bottom=" + bottom + " right=" + right);
            mapZoomToArea(top, left, bottom, right);
        } else {
            imageX = clickX - getOffsetLeft(_element('map_container'));
            imageY = clickY - getOffsetTop(_element('map_container'));
            dX = Math.round(mapImageWidth / 4);
            dY = Math.round(mapImageHeight / 4);
            mapZoomToArea(imageY - dY, imageX - dX, imageY + dY, imageX + dX);
        }
    }
    if (isPan) {
    	_style('map_image').cursor = 'default';
        var panX = -parseInt(_style('map_image').left.replace(/px/, ''));
        var panY = -parseInt(_style('map_image').top.replace(/px/, ''));
        if (isNaN(panX)) {
            panX = 0;
        }
        if (isNaN(panY)) {
            panY = 0;
        }
        if (panX != 0 || panY != 0) {
            //alert("pan: panX=" + panX + " panY=" + panY);
            mapPan(panX, panY);
        } else {
            imageX = clickX - getOffsetLeft(_element('map_container'));
            imageY = clickY - getOffsetTop(_element('map_container'));
            centerX = Math.round(mapImageWidth / 2);
            centerY = Math.round(mapImageHeight / 2);
            //alert("pan: panX=" + (imageX - centerX) + " panY=" + (imageY - centerY));
            mapPan(imageX - centerX, imageY - centerY);
        }
    }
    if (isMark) {
        markX = (nn6 ? e.clientX : event.clientX) - getOffsetLeft(_element('map_container'));
        markY = (nn6 ? e.clientY : event.clientY) - getOffsetTop(_element('map_container'));

        mapMark(markX, markY);
    }
    isPan = false;
    isZoom = false;
    isMark = false;
    //_style('zoom').display = 'none';
}

function copy_clip(meintext)
{
 if (window.clipboardData)
   {

   // the IE-manier
   window.clipboardData.setData("Text", meintext);

   // het is mij echter onbekend vanaf welke versie dit precies werkt:
   }
   else if (window.netscape)
   {


   // you have to sign the code to enable this, or see notes below
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

   // maak een interface naar het clipboard
   var clip = Components.classes['@mozilla.org/widget/clipboard;1']
                 .createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return;

   // maak een transferable
   var trans = Components.classes['@mozilla.org/widget/transferable;1']
                  .createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;

   // specificeer wat voor soort data we op willen halen; text in dit geval
   trans.addDataFlavor('text/unicode');

   // om de data uit de transferable te halen hebben we 2 nieuwe objecten
   // nodig om het in op te slaan
   var str = new Object();
   var len = new Object();

   var str = Components.classes["@mozilla.org/supports-string;1"]
                .createInstance(Components.interfaces.nsISupportsString);

   var copytext=meintext;

   str.data=copytext;

   trans.setTransferData("text/unicode",str,copytext.length*2);

   var clipid=Components.interfaces.nsIClipboard;

   if (!clip) return false;

   clip.setData(trans,null,clipid.kGlobalClipboard);

   }
   //alert("Following info was copied to your clipboard:\n\n" + meintext);
   return false;
}


function mapZoomToArea(top, left, bottom, right) {
    var url = getBoundingBoxUrl() + '&t=' + top + '&l=' + left + '&b=' + bottom + '&r=' + right + '&tool=' + rememberedTool + getScrollCoordinates();

    document.location = url;

    return false; // don't want the link to be executed as well.
}



function mapPan(panX, panY) {
    var url = getBoundingBoxUrl() + '&panX=' + panX + '&panY=' + panY + '&tool=' + rememberedTool + getScrollCoordinates();
    document.location = url;
}

function mapZoomByFactor(factor) {
    var url = getBoundingBoxUrl() + '&zoom=' + factor + '&tool=' + rememberedTool + getScrollCoordinates();
    document.location = url;
}

function mapMark(markX, markY) {
    var url = getBoundingBoxUrl() + '&markX=' + markX + '&markY=' + markY + '&tool=' + rememberedTool + getScrollCoordinates();
    document.location = url;
}



function mapOverview() {
    var url = getBoundaryUrl() + '&tool=' + rememberedTool + getScrollCoordinates();
    document.location = url;
}

function mapOriginal() {
    var url = mapBaseUrl + (mapBaseUrl.indexOf('?') >= 0 ? '&' : '?') + 'tool=' + rememberedTool + getScrollCoordinates();
    document.location = url;
}

function getBoundingBoxUrl() {
    return mapBaseUrl + (mapBaseUrl.indexOf('?') >= 0 ? '&' : '?') + 'n=' + mapBoundingBoxNorth + '&s=' + mapBoundingBoxSouth + '&e=' + mapBoundingBoxEast + '&w=' + mapBoundingBoxWest;
}

function getBoundaryUrl() {
    return mapBaseUrl + (mapBaseUrl.indexOf('?') >= 0 ? '&' : '?') + 'n=' + mapBoundaryNorth + '&s=' + mapBoundarySouth + '&e=' + mapBoundaryEast + '&w=' + mapBoundaryWest;
}

function _element(id) {
    return document.getElementById(id);
}

function _style(id) {
    return document.getElementById(id).style;
}

function getOffsetLeft (el) {
    var left;
    if (document.documentElement && document.documentElement.scrollLeft) {
        left = document.documentElement.scrollLeft;
    } else if (document.body) {
        left = document.body.scrollLeft;
    } else {
        left = window.pageXOffset;
    }
    var ol = el.offsetLeft;
    while ((el = el.offsetParent) != null)
        ol += el.offsetLeft;
    return ol - left;
}

function getOffsetTop (el) {
    var top;
    if (document.documentElement && document.documentElement.scrollTop) {
        top = document.documentElement.scrollTop;
    } else if (document.body) {
        top = document.body.scrollTop;
    } else {
        top = window.pageYOffset;
    }
    var ot = el.offsetTop;
    while((el = el.offsetParent) != null)
        ot += el.offsetTop;
    return ot - top;
}

/**
 * Select pan tool
 * @param remember if true, this tool value will be passed on to further requests
 */
function mapSelectPanTool(remember) {
    selectedTool = 'pan';
    if (remember) {
        rememberedTool = 'pan';
    }
    //alert("mapSelectPanTool()");
}

/**
 * Select zoom tool
 * @param remember if true, this tool value will be passed on to further requests
 */
function mapSelectZoomTool(remember) {
    selectedTool = 'zoom';
    if (remember) {
        rememberedTool = 'zoom';
    }
    //alert("mapSelectZoomTool()");
}

/**
 * Select mark tool
 * @param remember if true, this tool value will be passed on to further requests
 */
function mapSelectMarkTool(remember) {
    selectedTool = 'mark';
    if (remember) {
        rememberedTool = 'mark';
    }
    //alert("mapSelectMarkTool()");
}

function mapSetBaseUrl(url) {
    mapBaseUrl = url;
    //alert("mapSetBaseUrl: " + url);
}


function mapSetBoundingBox(north, south, east, west) {
    mapBoundingBoxNorth = north;
    mapBoundingBoxSouth = south;
    mapBoundingBoxEast = east;
    mapBoundingBoxWest = west;
}

function mapSetBoundary(north, south, east, west) {
    mapBoundaryNorth = north;
    mapBoundarySouth = south;
    mapBoundaryEast = east;
    mapBoundaryWest = west;
}

function copyToClipboard(lat, lon) {
    var coords = "(" + lat + ";" + lon + ")";
    copy_clip(coords);
}



function mapSetImageSize(width, height) {
    mapImageWidth = width;
    mapImageHeight = height;
}

var mapNewScrollX;
var mapNewScrollY;

function getScrollCoordinates() {
    scrollx = (document.all)?document.body.scrollLeft:window.pageXOffset;
    scrolly = (document.all)?document.body.scrollTop:window.pageYOffset;
    return '&scrollX=' + scrollx + '&scrollY=' + scrolly;
}

function setNewScrollCoordinates(x, y) {
    mapNewScrollX = x;
    mapNewScrollY = y;
}

function scrollToCoordinates() {
    window.scrollTo(mapNewScrollX, mapNewScrollY);
}

document.onmousedown = mouse_pressed;
document.onmouseup = mouse_released;

