var bButtonDown = false;
var iStartX, iStartY, iEndX, iEndY;
var pActiveToolImage = null;
//DOM objects
var ZoomRectangleDiv; //Div element node with id ZoomRect
var ZoomBoxStyleObj;  //In-line style attribute object for ZoomRect
var ZoomBoxCSSObj;    //Calculated style object for ZoomRect

/* Developer note: When the user takes any map action whatsoever, it is important
   to write all of Telephone's elements' values, except for MapCoords (those come
   from DitchMap.dll.
   Why are these things important?  Consistency.  If the user performs
   an action, then clicks the Back button, we want the new action taken to reflect
   ONLY the new action, not a combination of the old and new actions together. */

function init() {
    var sActiveTool = '';
    iStartX = iStartY = iEndX = iEndY = 0;
    ZoomRectangleDiv = document.getElementById('ZoomRect');
    if (ZoomRectangleDiv) {
        ZoomBoxStyleObj = ZoomRectangleDiv.style;
        if (window.getComputedStyle)
            ZoomBoxCSSObj = window.getComputedStyle(ZoomRectangleDiv, null);
        else
            ZoomBoxCSSObj = ZoomRectangleDiv.currentStyle;
    }
    //What if it's undefined?
    sActiveTool = getCookieValue('ActiveTool');
    if (!sActiveTool)
        sActiveTool = 'ToolZoomIn';
    activateTool(sActiveTool);
    return true;
}

function executeCommand(id) {
    document.forms.Telephone.MapAction.value = id;
    if (id == 'Geocode') {
        addrInput = prompt('Type the address you would like to move the map to:', addrInput ? addrInput : '');
        if (addrInput)
            document.forms.Telephone.MapAction.value += (' ' + addrInput)
        else
            return 1;
    }
    document.forms.Telephone.Coordinates.value = '';
    document.forms.Telephone.ImageOn.value = document.getElementById( 'ImageCheck' ).checked;
    document.forms.Telephone.submit();
}

function activateTool(sToolId) {
    //Deactivate previous ActiveTool
    if (pActiveToolImage)
        pActiveToolImage.className = 'MapTool';
    //Activate the tool by changing its CSS class and writing the new active tool to the cookie.
    pActiveToolImage = document.getElementById(sToolId);
    if (pActiveToolImage) {
        pActiveToolImage.className = 'ActiveTool';
        document.forms.Telephone.MapAction.value = sToolId;
        document.cookie = 'ActiveTool=' + sToolId;
    }
    return pActiveToolImage;
}

function doDynamicBox(e) {
    var X, Y;
    if (!ZoomBoxStyleObj) return false;
    var iBorderWidth = parseInt(ZoomBoxCSSObj.borderWidth.replace(/[^0-9]/g, ""));
    var elem = null;
    if (navigator.appName.indexOf("Netscape")>-1) {
        X = e.pageX;
        Y = e.pageY;
        elem = document.getElementById('MapImageNode');
        while (elem) {
            X = X - elem.offsetLeft;
   	    Y = Y - elem.offsetTop;
 	    elem = elem.offsetParent;
        }
        //I have to return false, because I have yet to find a way to let the user draw a div over an image.
        return false;
    } else /*IE*/ {
        X = e.offsetX;
        Y = e.offsetY;
        if (e.srcElement == ZoomRectangleDiv) {
            //If the ZoomRect caught the event, displace the left and top by its border width
            X += parseInt(ZoomBoxStyleObj.left.replace(/[^0-9]/g, "")) + iBorderWidth;
   	    Y += parseInt(ZoomBoxStyleObj.top.replace(/[^0-9]/g, "")) + iBorderWidth;
        }
    }
    switch (e.type) {
       case 'mousedown' :
           ZoomBoxStyleObj.visibility = 'visible';
           ZoomBoxStyleObj.width = '0px';
           ZoomBoxStyleObj.height = '0px';
           ZoomBoxStyleObj.left = X + 'px';
           ZoomBoxStyleObj.top = Y + 'px';
           iStartX = X;
           iStartY = Y;
           break;
       case 'mousemove' :
           var iNewLeft, iNewTop, iNewWidth, iNewHeight;
           iNewLeft = Math.min(iStartX, X);
           iNewTop = Math.min(iStartY, Y);
           //Apparently, Width and Height are for the content and therefore don't
           //include a border.
           //Suppose iStartX = 5 and X = 10.  The difference is 5, but the actual
           //width is 6, so we add one (pixel 5, 6, 7, 8, 9, and 10 makes six pixels).
           //The left and right borders take a total of 4 away, making the inner
           //content width equal 2.  Same principal goes for height.
           iNewWidth = Math.abs(iStartX - X) + 1 - (2 * iBorderWidth);
           iNewHeight = Math.abs(iStartY - Y) + 1 - (2 * iBorderWidth);
           //Negative Width and Height in the style object throw exceptions.
           iNewWidth = iNewWidth < 0 ? 0 : iNewWidth;
           iNewHeight = iNewHeight < 0 ? 0 : iNewHeight;
           //Remember max width and height are for the content of the zoom box.
           var iMaxWidth = iMapSize - (2 * iBorderWidth) - iNewLeft;
           var iMaxHeight = iMapSize - (2 * iBorderWidth) - iNewTop;
           ZoomBoxStyleObj.left = Math.max(0, iNewLeft) + 'px';
           ZoomBoxStyleObj.width = Math.min(iMaxWidth, iNewWidth) + 'px';
           ZoomBoxStyleObj.top = Math.max(0, iNewTop) + 'px';
           ZoomBoxStyleObj.height = Math.min(iMaxHeight, iNewHeight) + 'px';
           break;
       case 'mouseup' :
           ZoomBoxStyleObj.visibility = 'hidden';
           iEndX = X;
           iEndY = Y;
           //Send iStartX, iStartY, iEndX, iEndY to the hidden form!
           if (document.forms.Telephone.MapAction.value == 'ToolInfo')
               document.forms.Telephone.Coordinates.value = iStartX + ',' + iStartY
           else
               document.forms.Telephone.Coordinates.value = Math.min(iStartX, iEndX) + ',' + Math.min(iStartY, iEndY) + ',' + Math.max(iStartX, iEndX) + ',' + Math.max(iStartY, iEndY);
           document.forms.Telephone.ImageOn.value = document.getElementById( 'ImageCheck' ).checked;
           document.forms.Telephone.submit();
    }
    return true;
}

function doAllow(e) {
    var bProcess = false;
    var object;
    if (e.target)
        object = e.target
    else
        object = e.srcElement;
    bProcess =
        object == ZoomRectangleDiv ||
        object == document.getElementById('MapImageNode') ||
        object == document.getElementById('EventCatcher');
    if (navigator.appName.indexOf("Netscape")>-1)
        bProcess = bProcess && e.button == 0
    else
        bProcess = bProcess && e.button == 1;
    return bProcess;
}

function hMouseDown(event) {
    if (doAllow(event)) {
        bButtonDown = true;
        doDynamicBox(event);
    }
    return false;
}

function hMouseMove(event) {
    if (bButtonDown && doAllow(event))
        doDynamicBox(event);
    return false;
}

function hMouseUp(event) {
    if (bButtonDown && doAllow(event)) {
        bButtonDown = false;
        doDynamicBox(event);
    }
    return false;
}

function getCookieValue(cookieName) {
    var cookiePairs = document.cookie.split(';');
    var cookiePart;
    for (var i=0; i<cookiePairs.length; i++) {
        cookiePart = cookiePairs[i].split('=');
        //Cookie names are split with ;<space> pairs so I have to strip out the space
        //to get this to work.
        cookiePart[0] = cookiePart[0].replace(/\s/, '');
        if (cookiePart[0] == cookieName)
            return cookiePart[1];
    }
}

function zoomToCanal() {
    var oDropDown = document.getElementById('lstCanals');
    var canalName = oDropDown.options[ oDropDown.selectedIndex ].text;
    document.forms.Telephone.MapAction.value = 'CanalZoom ' + canalName;
    document.forms.Telephone.ImageOn.value = document.getElementById( 'ImageCheck' ).checked;
    document.forms.Telephone.Coordinates.value = '';
    document.forms.Telephone.submit();
}

function toggleImage(bImageOn) {
    document.forms.Telephone.ImageOn.value = bImageOn;
    document.forms.Telephone.MapAction.value = '';
    document.forms.Telephone.Coordinates.value = '';
    document.forms.Telephone.submit();
}
