//--********************************************************************-->
//--                                                                    -->
//--   Frontier Software Pty Ltd                                        -->
//--                                                                    -->
//--   File Name     : ftrtree.js                                       -->
//--                                                                    -->
//--   History       :                                                  -->
//--   009445 - 02.07.00 - Created.                                     -->
//--   009442 - 23.03.04 - Return to last staff list page               -->
//--   010063 - 17.12.04 - Opera (10062) & Mozilla (10063) supported    -->
//--   011225 - 25.10.05 - Correctly set the sHold variables            -->
//--   010016 - 02.05.07 - Output vacant staff without radio button     -->
//--   014434 - 23.10.07 - Layout & Colour Enhancements                 -->
//--********************************************************************-->

//Storage area for all the Trees within HR21
var aTreeContainer = new Array();

//Index variable pointing to the element in the aTreeContainer
var iTree = 0;

//Selection value of the element in the aTreeContainer
var iTreeSelected = 0;

//Selection Object for the Search Facility
var aTreeSelected = new Array();

//Indicates whether the Tree is empty or has entries
var bTreeEmpty = false;

// Holds the compiled string of HTML until it is rendered
var sTreeData = "";

// 7335 Tree Structure Staff Tree variables
var sTreeState = "";
var aTreeList = new Array();
var iTreeTotal = 0;

// Level and State Variables for the Tree List
var iPreLvlNo = iCurLvlNo = 0;
var sInitState = sCurrState = "";

// *********************************************************************
function treeTopRowCreate() {
    var iColumnCount = 0;
    var charA, charZ, argI;
    var sFieldNumber, oFieldNumber;
    // Initialise the string that will contain all the dynamic html
    sTreeData = linkBarLists("Staff");
    sTreeData += "<table border='0' align='left' name='TreeTable' cellspacing='" + ((iColumnSpacing) ? iColumnSpacing : "0") + "' cellpadding='2' width='100%'>";
    sTreeData += "<tr style='background-color:" + ((bHorizMenu) ? hHorizActive : hVertActive) + ";'>";
    // If nothing to the far left of screen put a space character
    sTreeData += "<td class='Headings'>&nbsp;</td>";
    // Write heading - depending of the method being used
    if ((oDataPage.oDict) && (oDataPage.oDict["columns"])) {
        iColumnCount = oDataPage.oDict["columns"]["label"];
    } else {
        iColumnCount = arguments.length - 1;
    }
    // Scan through the columns building up the complete heading
    for (var i=1; i<=iColumnCount; i++) {
        sTreeData += "<td class='Headings'";
        sFieldNumber = "field" + ((i < 10) ? "0" : "") + i;
        // Decide where to retrieve heading info from
        if ((oDataPage.oDict) && (oDataPage.oDict["columns"])) {
            oFieldNumber = eval("oDataPage.oDict['" + sFieldNumber + "']");
            argI = oFieldNumber["label"];
        } else {
            argI = arguments[i];
        }
        // Alignment all depends on the align array
        var sAlign = false;
        if (oFieldNumber) sAlign = oFieldNumber["align"];
        switch (sAlign) {
            case "left":
                sTreeData += " align='left'";
                break;
            case "right":
                sTreeData += " align='right'";
                break;
            case "center":
            case "middle":
                sTreeData += " align='center'";
                break;
            case "justify":
                sTreeData += " align='justify'";
                break;
            default:
                charA = argI.charAt(0);
                charZ = argI.charAt(argI.length-1);
                // Check for align indicators with field heading string
                if (charA == " ") {
                    if (charZ == " ") { // centre the title --  special case
                        sTreeData += " align='center'";
                    } else {            // right-align the title
                        if (argI.toString().indexOf("Date") != -1) {
                            sTreeData += " align='right'";
                        } else {
                            sTreeData += " align='" + ((argI == " Staff Number") ? "center'" : "right'");
                        }
                    }
                }
                break;
        }
        sTreeData += (">" + ((argI == " ") ? "&nbsp;" : argI) + "</td>");
    }
    sTreeData += "</tr>";
    return;
}   

// *********************************************************************
function treeSetRowActive(oRow) {
    if (oRow.style.background.toLowerCase() != hSearch.toLowerCase()) {
        oRow.style.background = hHighlight;
    }
    return;
}

// *********************************************************************
function treeSetRowInactive(oRow, bAlternate) {
    if (oRow.style.background.toLowerCase() == hSearch.toLowerCase()) oRow.style.background = hSearch;
    else if (bAlternate == true) oRow.style.background = hAlternate;
    else if (bAlternate == false) oRow.style.background = hVertBG;
    else oRow.style.background = hWindowBG;
    return;
}

// *********************************************************************
function treeSetRowHref(iCounter) {
    var sHtml = " href='javascript:void(0);' onClick='oGlob.listStaffClick(" + iCounter + ",\"tree" + iCounter + "\"); return true;'";
    return sHtml;
}

// *********************************************************************
function treeRowsCreate(oRow) {
    var sFieldNumber;
    // Load up the string that contains the html
    sTreeData += "<tr";                               
    // Set mouse over for row if required
    if ((oDataPage.oDict["drill"]) && (oDataPage.oDict["drill"].labeltext == "Block")) {
        sTreeData += " style=";
        if ((oRow["rowCounter"] % 2) == 1) sTreeData += "'background:" + hAlternate + ";cursor:hand;' ";
        else sTreeData += "'cursor:hand;' ";
        sTreeData += "onMouseOver='oGlob.treeSetRowActive(this);return true;' onMouseOut='oGlob.treeSetRowInactive(this" + (((oRow["rowCounter"] % 2) == 1) ? ",true" : "") + ");return true;'";
        sTreeData += treeSetRowHref(oRow["rowCounter"]+1);
    } else {
        if ((oRow["rowCounter"] % 2) == 1) sTreeData += " style='background:" + hAlternate + ";' ";
    }
    sTreeData += ">";
    sTreeData += treeAddFields(oRow);
    sTreeData += "</tr>";
    return oRow;
}

// ********************************************************************
// 7335 Code separated from above method
function treeAddFields(oRow) {
    var sHtml = "";
    var sFieldNumber, oFieldNumber, iColumnCount;
    // Write data - depending of the method being used
    if ((oDataPage.oDict) && (oDataPage.oDict["columns"])) {
        if (isNaN(parseInt(oDataPage.oDict["columns"]["label"]))) alert("Error: Remember to set columns value in the configuration file for the current Tree page.");
        else iColumnCount = oDataPage.oDict["columns"]["label"];
    } else {
        if (isNaN(parseInt(oRow["i_maxcols"]))) {
            if (gDebug) alert("Error: Remember to set i_maxcols value in the current Tree page.");
        } else {
            iColumnCount = parseInt(oRow["i_maxcols"]) + 1;
        }
    }
    // Scan through the columns building up the complete row
    for (var i=1; i<=iColumnCount; i++) {
        sFieldNumber = "field" + ((i < 10) ? "0" : "") + i;
        if ((oDataPage.oDict) && (oDataPage.oDict["columns"])) {
            oFieldNumber = eval("oDataPage.oDict['" + sFieldNumber + "']");
            if (oFieldNumber["translation"]) {
                var sFieldTrans = "i_" + oFieldNumber["datadict"];
                oRow[sFieldNumber] = sFieldTrans;
                oRow[sFieldTrans] = getGTRField(oRow,oFieldNumber["datadict"] + ".trn");
            }
        }
        sHtml += "<td ";
        // Align is set within config.js, otherwise,
        // 
        // Types of Tree items are as follows;
        // 
        // Staff Number - centred
        // Positive Number - right hand justified
        // Negative Number - right hand justified
        // Time - right hand justified
        // Date - right hand justified
        // Text (default) - left hand justified
        //
        var sName = oRow[sFieldNumber];
        var sItem = "";
        if (oRow[oRow[sFieldNumber]]) {
            sItem = oRow[oRow[sFieldNumber]];
        } else {
            if (gDebug) alert("Error: " + sName + " data dictionary has no associated value in the current Tree page.");
        }
        var iCount = oRow["rowCounter"];
        var sType = "text";
        // First column always left justified
        if ((sFieldNumber != "field01")) {
            if (sItem != "") {
                // Align attribute set.
                var sAlign = false;
                if (oFieldNumber) sAlign = oFieldNumber["align"];
                if ((oDataPage.oDict) && (sAlign)) {
                    if (isNaN(sItem) && (sItem.indexOf("-") != -1)) sType = "nnum";
                    switch (oFieldNumber["align"]) {
                        case "right":
                            sHtml += "align='right' ";
                            break;
                        case "center":
                        case "middle":
                            sHtml += "align='center' ";
                            break;
                        case "justify":
                            sHtml += " align='justify' ";
                            break;
                        default:
                            sHtml += "align='left' ";
                            break;
                    }
                } else {
                    if (sItem.charAt(0) == " ") sType = "right";
                    if (isFinite(sItem) || (sItem.indexOf("$") != -1) || (sItem.indexOf("%") != -1)) sType = "pnum";
                    if ((sName.indexOf("detnumber") != -1) || (sName.indexOf("wfeempno") != -1)) sType = "enum";
                    if (isNaN(sItem) && (sItem.indexOf("-") != -1) && (sType == "pnum")) sType = "nnum";
                    if (isNaN(sItem) && ((sName.toLowerCase().indexOf("date") != -1) || (validIsDate(sItem)))) sType = "date";
                    if (isNaN(sItem) && (sItem.indexOf(":") != -1)) sType = "i_time";
                }
            }
        }
        // Having decided on the type do the work needed to display data correctly
        switch (sType) {
            case "date":
            case "pnum":
            case "right":
                sHtml += "class='Prompt' align='" + ((sName == "pdtcode") ? "left" : "right") + "'";
                break;

            case "enum":
                sHtml += "class='Prompt' align='center'";
                break;

            case "nnum":
                var theRest = sItem.substring(0,sItem.length-1);
                if (isFinite(theRest)) {
                    sHtml += "style='color:" + hNegative + ";'";
                    if ((!oDataPage.oDict) || (!oDataPage.oDict["columns"])) sHtml += " align='right'";
                    var iLeading = theRest.lastIndexOf(" ");
                    sItem = "-" + ((iLeading != -1) ? theRest.substr(iLeading+1) : theRest);
                } else {
                    sHtml += "class='Prompt'";
                }
                break;

            case "i_time":
                var colonPos = sItem.indexOf(":");
                sHtml += "class='Prompt'";
                if ((isFinite(sItem.substring(0,colonPos))) && (isFinite(sItem.substring((colonPos+1),sItem.length)))) {
                    sHtml += " align='right'";
                }
                break;

            default:
                sHtml += "class='Prompt'";
                break;
        }
        // Set the correct tags to complete the html
        sHtml += ">";
        if ((oDataPage.oDict["drill"]) && (oDataPage.oDict["drill"].labeltext == "Block")) {
            sHtml += "<a class='HTMLLabel' " + treeSetRowHref(oRow["rowCounter"]+1) + ">";
            sHtml += ((sItem == "") ? "&nbsp;" : sItem) + "</a>";
        } else {
            sHtml += ((sItem == "") ? "&nbsp;" : sItem);
        }
        sHtml += "</td>";
    }
    return sHtml;
}

// *********************************************************************
function treeEmptyCreate(divObj, gtrContainer) {
    bTreeEmpty = ((getGTRField(gtrContainer,"warning01").substr(0,6) == "BRE268") || (getGTRField(gtrContainer,"info01").substr(0,6) == "BRE267")) ? true : false;
    if (divObj) {
        if (bTreeEmpty) {
            sTreeData += "</table><br><br><br>";
            sTreeData += "<div align='center'><img src='" + loadPageResource("misc") + "empty.png' border='0' alt=''></div>";
            // Wipe out the buttons if the Tree is empty
            divObj.buttons = new Array();
        } else {
            iTree--;
            sTreeData += "</table>";
        }
        divObj.innerHTML = sTreeData;
        // 010063
        if (!is.ie) loadDivsAlign();
        // Debug Window
        if (gDHTMLDebug) loadDebugPage("treeEmptyCreate:\n" + sTreeData + "\n");
    }
    // Return flag indicating the file is empty 
    return bTreeEmpty;
}

// *********************************************************************
// Reset the page variables
function treeResetVariables() {
    sInitState = "";
    iPreLvlNo = iCurLvlNo = 0;
    sCurrState = sTreeState;
    return;
}

// *********************************************************************
// Onclick of plus or minus
function treeToggleState(iSub) {
    if (iSub != 0) {
        var sNewString = "";
        var sExpandedString = sCurrState.substring(iSub-1, iSub); 
        sNewString += sCurrState.substring(0, iSub-1);
        sNewString += sExpandedString ^ 1;
        sNewString += sCurrState.substring(iSub, sCurrState.length);
        sTreeState = sNewString;
    }
    treeResetVariables();
    treeComplete();
    return;
}

// *********************************************************************
// Returns padded spaces (in multiples of 4) for indenting
function treePadSpaces(iSub) {
    var sPadding = "";
    for (var iIndex0 = 1; iIndex0 <= iSub; iIndex0++) { 
        sPadding += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; 
    }
    return sPadding;
}

// *********************************************************************
// Find the search employee
function treeStaffNameSearch() {
    var bMatchFound = false;
    var iLastMatch = iLastMatchIndent = iLastIndent = 0;
    // Reset state local varaibles
    sCurrState = sInitState = "";
    // Save away the validation string
    var sTreeSurInit = sEmpSurInit;
    // Search through the entire array
    for (var iIndex0 = 1; iIndex0 < aTreeList.length; iIndex0++) { 
        if (aTreeList[iIndex0].wfesurinit.substring(0,(sTreeSurInit.length)) == sTreeSurInit) {
            // We've found a matching entry so set the employee variables
            aTreeList[iIndex0].match = true;
            if (!bMatchFound) {
                sEmpNo = sHoldEmpNo = aTreeList[iIndex0].wfeempno;
                sEmpSurInit = sHoldEmpSurInit = aTreeList[iIndex0].wfesurinit;
                bMatchFound = true;
            }
            // The matching entry isn't at level 0 so the tree has to be expanded
            sInitState = "";
            iLastIndent = aTreeList[iIndex0].indent;
            // Set all prior employees to 1 except level 0
            for (var iIndex1 = iIndex0; iIndex1 > iLastMatch; iIndex1--) { 
                if (aTreeList[iIndex1].indent >= iLastIndent) {
                    sInitState = "0" + sInitState;
                } else {
                    sInitState = "1" + sInitState;
                    iLastIndent = aTreeList[iIndex1].indent;
                }
            }
            // If the previous match was for a lower level, we need to change it to expanded
            if (iLastMatchIndent < iLastIndent) {
                sCurrState = sCurrState.substring(0, sCurrState.length - 1) + "1";
            }
            // Update the current status of the array
            sCurrState += sInitState
            iLastMatch = iIndex0;
            iLastMatchIndent = aTreeList[iIndex0].indent;
        } else {
            aTreeList[iIndex0].match = false;
        }
    }
    // Collapse the portion of the tree after the last match
    for (var iIndex0 = iLastMatch+1; iIndex0 < aTreeList.length; iIndex0++) {     
        sCurrState += "0";
    }
    sInitState = sCurrState;
    sTreeState = sCurrState;
    treeComplete();
    messCompletion(4);
    return;    
}

// *********************************************************************
// Creates and writes the tree to the page
function treeComplete() {  
    // Display the link buttons and the heading line
    treeTopRowCreate("Staff");
    // Set the initial state if no current state or length changed
    if (sCurrState == "" || sCurrState.length != (aTreeList.length-1)) {
        sCurrState = "";
        sInitState = "";
        for (iIndex0 = 1; iIndex0 < aTreeList.length; iIndex0++) { 
            sInitState += "0";
            sCurrState += "0";
        }
        sTreeState = sInitState;
    }
    var iPrevIndentDisplayed = 0;
    var iShowChild = 0;
    var bMatchFound = false;
    var iLineNum = 0;
    var iPointer = 0;    
    // Cycle through each entry in the aTreeList array
    for (var iIndex0 = 1; iIndex0 < aTreeList.length; iIndex0++) {
        // Get the indent level of this employee
        var iCurrIndent = aTreeList[iIndex0].indent;
        // Get the current state of this employee
        var iExpanded = sCurrState.substring(iIndex0-1, iIndex0);
        // Display entry only if it meets one of three criteria:
        // 1. It's at Level 0
        // 2. It's lower or equal to a previously displayed entry
        // 3. The parent level wants the child level displayed
        if ((iCurrIndent == 0 || iCurrIndent <= iPrevIndentDisplayed || (iShowChild == 1 && (iCurrIndent - iPrevIndentDisplayed == 1)))) {
            sTreeData += "<tr";
            // Set mouse over for row if required
            if ((oDataPage.oDict["drill"]) && (oDataPage.oDict["drill"].labeltext == "Block")) {
                sTreeData += " style=";
                if (aTreeList[iIndex0].match) {
                    sTreeData += "'background:" + ((hSearch) ? hSearch : "#FFFF77") + ";cursor:hand;'"; 
                } else {
                    if ((iLineNum % 2) == 1) sTreeData += "'background:" + hAlternate + ";cursor:hand;' ";
                    else sTreeData += "'cursor:hand;' ";
                }
                sTreeData += "onMouseOver='oGlob.treeSetRowActive(this);return true;' onMouseOut='oGlob.treeSetRowInactive(this" + (((iLineNum % 2) == 1) ? ",true" : "") + ");return true;'";
                sTreeData += treeSetRowHref(iIndex0);
            } else {
                if ((iLineNum % 2) == 1) sTreeData += " style='background:" + hAlternate + ";' ";
            }
            sTreeData += "><td>";
            sTreeData += treePadSpaces(iCurrIndent);
            sTreeData += "<a href='javascript:void(0)' onClick='oGlob.treeToggleState(" + iIndex0 + ");' onMouseOver='window.parent.status=\"Click to collapse\";return true;'>";
            // Add the +, - or a blank images
            if (!(aTreeList[iIndex0].parent)) {
                sTreeData += "<img src='" + loadPageResource("menu") + "pixel.png' width='16' height='16' border='0'>";
            } else { 
                if (iExpanded == 1) {
                   sTreeData += "<img src='" + loadPageResource("menu") + "minus.png' width='16' height='16' border='0'>";
                } else {
                   sTreeData += "<img src='" + loadPageResource("menu") + "plus.png' width='16' height='16' border='0'>";
                }
            }
            sTreeData += "</a>";
            // Add the radio button
			if (aTreeList[iIndex0].wfeempno != "Vacant")
			{
                sTreeData += "<input type='radio' name='tree' id='tree" + iIndex0 + "' value='";
	            // Save the Staff Number and Name depending on which values are in the GTR
                var sTempNo = new String();
                sTempNo = aTreeList[iIndex0].wfeempno.replace("'","\`");
                var sTempName = new String();
	            sTempName = aTreeList[iIndex0].wfesurinit.replace("'","\`");
                sTreeData += sTempNo + cSeparator + sTempName + "'" + treeSetRowHref(iIndex0);
                if ((!bMatchFound) && (aTreeList[iIndex0].wfeempno == sEmpNo)) {
                   sTreeData += " checked";
                   bMatchFound = true;
	            }
		            sTreeData += ">&nbsp;</td>";
			}
            // Add the name and number
            sTreeData += treeAddFields(aTreeList[iIndex0].record);
            iPrevIndentDisplayed = iCurrIndent;
            iShowChild = iExpanded;
            iLineNum++;
        }
    }
    // Tidy up the tree list
    var divObj = oDataPage.document.getElementById("dataDiv0");
    treeEmptyCreate(divObj,false);
    return;
}

// *********************************************************************
