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 StreetMap.dll.  It is also important to rewrite the layer visibility
   cookie.  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(sLayerVis) {
    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);
    if (!sLayerVis)
        //IMPORTANT: The value for sLayerVis here is the default value if the user has no cookie
        //(Usually this means it's their first visit to the site).
        //In order to produce a consistent match between the checkboxes and the map itself,
        //this initial value MUST reflect the visibility of the layers in the original AXL
        //for the StreetBond map service!!!!!
        sLayerVis = 'MajorStreets-true*Asphalt-true*Slurry-false*StreetCIP-true*StreetData-true*' +
            'Boundary-true*StreetNames-true*Bldgs-true*Parcels-true*Voting-false*Comm-false*Trash-false*FlyOver-true';
    setUpLayerVis(sLayerVis);
    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.target = '_self';
    writeOutLayerVis();
    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);
    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 = 500 - (2 * iBorderWidth) - iNewLeft;
           var iMaxHeight = 500 - (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;
           writeOutLayerVis();
           //Send iStartX, iStartY, iEndX, iEndY to the hidden form!
           if (document.forms.Telephone.MapAction.value == 'ToolIdentifyStr') {
               document.forms.Telephone.Coordinates.value = iStartX + ',' + iStartY;
               document.forms.Telephone.target = '_blank';
           }
           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.target = '_self';
           }
           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 swapRightSide(val) {
    var Legend = document.getElementById('LegendDiv');
    var Checks = document.getElementById('Checklist');
    if (val=='View Legend') {
        Checks.style.visibility = 'hidden';
        Legend.style.visibility = 'visible';
    } else {
        Legend.style.visibility = 'hidden';
        Checks.style.visibility = 'visible';
    }
    return true;
}

function writeOutLayerVis() {
    var sLayerVis = '';
    var aBoxForm = document.getElementById('LayerVisibility');
    for (var i=0; i<aBoxForm.elements.length; i++) {
        if (aBoxForm.elements[i].getAttribute('type') == 'checkbox' || aBoxForm.elements[i].getAttribute('type') == 'radio') {
            if (sLayerVis) sLayerVis += '*';
            sLayerVis += aBoxForm.elements[i].id + '-' + aBoxForm.elements[i].checked;
        }
    }
    var ExpirationDate = new Date((new Date()).getTime() + 1000 * 60 * 60 * 24 * 31); //inc 1 month from now.
    document.cookie = 'Layers=' + encodeURIComponent(sLayerVis) + '; expires=' + ExpirationDate.toUTCString();
    document.forms.Telephone.LayerVis.value = sLayerVis;
}

function changeLayerVis() {
    writeOutLayerVis();
    //If I don't clear the variables below, the user COULD use the back button,
    //change their layer and automatically the last map action will redo itself,
    //PLUS the new layer visiblities will take effect.
    document.forms.Telephone.target = '_self';
    document.forms.Telephone.MapAction.value = '';
    document.forms.Telephone.Coordinates.value = '';
    document.forms.Telephone.submit();
    return;
}

function setUpLayerVis(sLayerString) {
    sLayerVis = sLayerString;
    var aLayerPairs = sLayerVis.split('*');
    var aLayerPair;
    var pBox;
    for (var i=0; i<aLayerPairs.length; i++) {
        aLayerPair = aLayerPairs[i].split('-');
        if (aLayerPair[0] && aLayerPair[1]) {
            pBox = document.getElementById(aLayerPair[0]);
            if (pBox)
                if (aLayerPair[1] == 'true')
                    pBox.checked = true
                else
                    pBox.checked = false;
        }
    }
    //Don't write it as a cookie.  Iff the user makes changes, then those should be saved.
    //Otherwise, I'll want the user to see it as I've programmed it.  That goes for when
    //new map layers are added as well.
    return true;
}

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 hintPopUp(url) {
  var termHint = window.open(url,'street_hint','width=500,height=500,menubar=no,directories=no,scrollbars=yes,resizable=yes,status=yes');
  termHint.focus();
}
