//document.forms[0]

function NLWISMeasureInit(){
    if (document.forms[0].NLWISMAPPROP_UNITS != null){
        dfPixelSize = (document.forms[0].MAP_EXTENTS_MAXX.value - document.forms[0].MAP_EXTENTS_MINX.value)/gMapWiWidth;
        gRulerUserUnit = document.forms[0].NLWISMAPPROP_UNITS.value;
        gRulersUnits = NLWISMeasureAbbrev(gRulerUserUnit);
        var goCWCJSAPI2 = new CWCApplication();
        gRulergblPixelSize = goCWCJSAPI2.oMap.ConvertUnit(gRulersMapUnit, gRulerUserUnit, dfPixelSize);
    }
        
    var sId = "";
    var content = "<IMG SRC='" + NLWISMeasureImagePath("pix") + "'><BR>";
    var content2 = "<IMG SRC='" + NLWISMeasureImagePath("node") + "'><BR>";
    for (var i=1; i<= gRulerNbPoints; i++)
    {
        sId = "pix"+i;
        CWCDHTML_CreateLayer(sId, -10, -10, 10, 10, false, content);
        CWCDHTML_SetLayerZOrder( sId, 20 );
        
        sId = "pInf"+i;
        CWCDHTML_CreateLayer(sId, -10, -10, 10, 10, false, content2);
        CWCDHTML_SetLayerZOrder( sId, 20 );
    }
    //MapLayerDiv is created in MapDHTMLWidget.php.
    //gMapWhspc and gMapWvspc are created in MapDHTMLWidget and are the TL position of the map.
    DistTool = new distancetool(getObject("MapLayerDiv"), gRulerNbPoints,
                                gMapWhspc, gMapWvspc);

    // initialize mouse event for the layer named 'MapLayerDiv'
    //setMapDraggable("MapLayerDiv");
}

function NLWISMeasureWMouseMove(e){
    //make sure variables are initialized.
    //In IE, mouse move may be called before.
    if (document.forms[0] == null ||
      document.forms[0].NAV_CMD == null)
      return true;
    
    if(document.forms[0].NAV_CMD.value != "NLWISMEASURE"){
        //if ruler result is present reset the text field.
        if (document.forms[0].RULER_RESULT != null){
            document.forms[0].RULER_RESULT.value = "";
        }

        //reset other stuff
        DistTool.dtClearPoints();

        if (gRulerHideLayers){
            for(var i=1; i<=gRulerNbPoints; i++)
                hide("pix" + i);
            for(var i=1; i<=gRulerNbPoints; i++)
                hide("pInf" + i);

            gRulerHideLayers = false;
        }

        //remove handlers if they were ours
        if (typeof document.onmousedown != "undefined" && document.onmousedown==startDist)
            document.onmousedown = null;
        if (isIE4 || isNav6){
            if (typeof document.ondblclick != "undefined" && document.ondblclick==stopDist)
                document.ondblclick = null;
            if (typeof document.onkeypress != "undefined" && document.onkeypress==stopDist)
                document.onkeypress= null;
                
            if (isNav6){
                document.removeEventListener("dblclick",stopDist,true);
                document.removeEventListener("keypress",stopDist,true);
            }
        } else {
            if (typeof document.onDblClick != "undefined" && document.onDblClick==stopDist)
                document.onDblClick = null;
            if (typeof document.onKeyPress != "undefined" && document.onKeyPress==stopDist)
                document.onKeyPress= null;
        }
        return true;
    }
    
    //NLWISMeasure tool is active
    var obj = "MapLayerDiv";
    if (isNav4 || isNav6){
        document.captureEvents(Event.MOUSEDOWN);
        document.captureEvents(Event.MOUSEMOVE);
        document.captureEvents(Event.DBLCLICK);
        document.captureEvents(Event.RESIZE);
    }
    
    if(isNav4){
        getObject(obj).onmouseout= mouseOutMap;
        document.onmousedown=startDist;
        document.onDblClick=stopDist ;
        document.onKeyPress=stopDist;
    }
    else if (isIE4 || isNav6){
        var layer  = document.getElementById("MapLayerDiv");
        document.onmousedown=startDist;
        document.ondblclick=stopDist;
        document.onkeypress=stopDist;
        if (isNav6){
          document.addEventListener("dblclick",stopDist,true);
          document.addEventListener("keypress",stopDist,true);
        }
    }
    distIt(e);
}

function NLWISMeasureDisplayStart(){
    var doc = NLWISMeasureGetTopElement().contentWindow.document;
    doc.open();
    doc.writeln(NLWISMeasureBaseHtml());
    doc.close();
    dNLWISMeasureTotDist = 0;
    bNLWISMeasure_wBackground = 0;
}

function NLWISMeasureDisplay(pointNum, dDist){
	showPage(4, "resultslyr"); // to bring panel to front
    var bSuccess = false;
    bSuccess = NLWISMeasureInsertPointRow(pointNum, dDist);
    if (!bSuccess)
        return false;

    if (pointNum > 1) {
        bSuccess = NLWISMeasureInsertSegmentRow(pointNum, dDist);
        if (!bSuccess)
            return false;
    }
    bNLWISMeasure_wBackground = (bNLWISMeasure_wBackground == 0) ? 1 : 0;
}

function NLWISMeasureInsertPointRow(n, dDist){
    var x = DistTool.aaPointTrace[n - 1][0];
    var y = DistTool.aaPointTrace[n - 1][1];
    var pointId = n + NLWISMeasurePointEnding(n);
    var szProj = document.forms[0].NLWISMEASURE_PROJ.value + ":";
    
    var dfGeoMinX = document.forms[0].MAP_EXTENTS_MINX.value;
    var dfGeoMinY = document.forms[0].MAP_EXTENTS_MINY.value;
    var dfGeoMaxX = document.forms[0].MAP_EXTENTS_MAXX.value;
    var dfGeoMaxY = document.forms[0].MAP_EXTENTS_MAXY.value;
    
    var nMapWidth = document.forms[0].MAP_WIDTH.value;
    var nMapHeight = document.forms[0].MAP_HEIGHT.value;

    var dfGeoPosX = WidgetPix2Geo(x, 0, nMapWidth, dfGeoMinX, dfGeoMaxX, 0);
    var dfGeoPosY = WidgetPix2Geo(y, 0, nMapHeight, dfGeoMinY, dfGeoMaxY, 1); //1 for inverse Y

    var bSuccess = NLWISMeasureAddRow2DistTable(pointId + ' ' + NLWISMeasurePoint(), szProj + ' ' + dfGeoPosX + ', ' + dfGeoPosY, n, dDist);
    if (!bSuccess)
        return false;
    return true;
}

function NLWISMeasureInsertSegmentRow(n, dDist){
    var bSuccess = NLWISMeasureAddRow2DistTable(NLWISMeasureSegmentLength(), Math.round(dDist) + ' ' + gRulersUnits, n, dDist);
    if (!bSuccess)
        return false;
    
    var rfDoc = NLWISMeasureGetTopElement().contentWindow.document;
    var totDistCell = rfDoc.getElementById('totDistCell');
    dNLWISMeasureTotDist += dDist;
    var totDistText = rfDoc.createTextNode(Math.round(dNLWISMeasureTotDist) + ' ' + gRulersUnits);
    totDistCell.replaceChild(totDistText, totDistCell.childNodes[0]);
    NLWISMeasureAddRow2DistTable(' ', ' ', n, dDist); // if it worked above, it will work here
    return true;
}

// add a 2 column row to the table in frame
function NLWISMeasureAddRow2DistTable(headerText, dataText, n, dDist){
    var rfDoc = NLWISMeasureGetTopElement().contentWindow.document;
    if (rfDoc == null){
        setTimeout("NLWISMeasureDisplay(" + n + ", " + dDist + ")", 100);
        return false;
    }
    var distTBody = rfDoc.getElementById('distTBody');
    var totDistRow = rfDoc.getElementById('totDistRow');
    if (distTBody == null || totDistRow == null){
        setTimeout("NLWISMeasureDisplay(" + n + ", " + dDist + ")", 100);
        return false;
    }
    
    var titleCell = rfDoc.createElement("td");
    titleCell.setAttribute("class", "measureBold");
    var titleCellText = rfDoc.createTextNode(headerText);
    titleCell.appendChild(titleCellText);
    
    var dataCell = rfDoc.createElement("td");
    dataCell.setAttribute("class", "measure");
    var dataCellText = rfDoc.createTextNode(dataText);
    dataCell.appendChild(dataCellText);
    if (bNLWISMeasure_wBackground == 1 && headerText != ' '){
        titleCell.style.backgroundColor = "#ffffcc";
        dataCell.style.backgroundColor = "#ffffcc";
    }
    
    var newRow = rfDoc.createElement("tr");
    newRow.appendChild(titleCell);
    newRow.appendChild(dataCell);
    distTBody.insertBefore(newRow, totDistRow);
    return true;
}

// The following set of functions return endings for displaying numbers;
// 1st, 2nd, 3rd, 4th, 11th, 12th, 21st, 22nd, etc. -OR- 1er, 2ème, 11ème, 13ème, etc.
function NLWISMeasurePointEnding(n){
    if (document.forms[0].LANGUAGE.value == "en-CA"){
        return NLWISMeasurePointEnding_en(n);
    } else { // "fr-CA"
        return NLWISMeasurePointEnding_fr(n);
    }
}
function NLWISMeasurePointEnding_fr(n){
    if (n == 1) 
        return "er";
    return "ème";
}
function NLWISMeasurePointEnding_en(n){
    n += ''; // convert to string
    if (n.length > 1){
        var subn = n.substring(n.length - 2);
        switch (subn){
            case "11":
            case "12":
            case "13":
                return "th";
        }
        subn = n.substring(n.length - 1);
        return NLWISMeasurePointEnding1Char(subn);
    } else {
        return NLWISMeasurePointEnding1Char(n);
    }
}
function NLWISMeasurePointEnding1Char(n){
    switch (n){
        case "1":
            return "st";
        case "2":
            return "nd";
        case "3":
            return "rd";
        default:
            return "th";
    }
}

// Utility function to convert from pixel to georef coordinates.
function WidgetPix2Geo(nPixPos, dfPixMin, dfPixMax, dfGeoMin, dfGeoMax, nInversePix)
{
    dfWidthGeo = dfGeoMax - dfGeoMin;
    dfWidthPix = dfPixMax - dfPixMin;

    dfPixToGeo = dfWidthGeo / dfWidthPix;

    if (Math.abs(dfPixToGeo) < 1)
        dNbDecimal = Math.abs(Math.log(dfPixToGeo))/Math.log(10)+1;
    else
        dNbDecimal = 0;

    if (nInversePix == 0)
    {
        dfDeltaPix = nPixPos - dfPixMin;
    }
    else
    {
        dfDeltaPix = dfPixMax - nPixPos;
    }

    dfDeltaGeo = dfDeltaPix * dfPixToGeo;

    dfPosGeo = new String(new Number(dfGeoMin) + new Number(dfDeltaGeo));
    aPosGeo = dfPosGeo.split(".");

    if (dNbDecimal > 0 && aPosGeo.length == 2)
    {
        dfPosGeo = aPosGeo[0]+"."+aPosGeo[1].substr(0, dNbDecimal);
    }
    else
    {
        dfPosGeo = aPosGeo[0];
    }
    return dfPosGeo;
}

// clears the frame's doc, resets total distance, clears points array and
// hides displayed points/nodes
function NLWISClearPoints(){
    if(document.forms[0].NAV_CMD.value == "NLWISMEASURE"){
        DistTool.dtClearPoints();
        NLWISMeasureDisplayStart();
    }
}

