//--********************************************************************-->
//--                                                                    -->
//--   Frontier Software Pty Ltd                                        -->
//--                                                                    -->
//--   File Name     : ftrmess.js                                       -->
//--                                                                    -->
//--   History       :                                                  -->
//--   005876 - 02.07.00 - JavaScript Rewrite.                          -->
//--   008780 - 01.07.03 - Colours for Messages set in Configuration.   -->
//--   009642 - 11.08.04 - Error Window re-designed.                    -->
//--   009980 - 08.09.04 - Allow searching on Detail Pages.             -->
//--   010063 - 17.12.04 - Opera (10062) & Mozilla (10063) supported    -->
//--   007775 - 06.12.04 - Search by Pay Period                         -->
//--   010546 - 02.03.05 - Show BRE204 if 'i_showempty' keyword present -->
//--   010408 - 01.03.05 - Add new starters                             -->
//--   008780 - 01.04.05 - Status message now configurable              -->
//--   010755 - 03.05.05 - Warning message handling corrected           -->
//--   010791 - 19.05.05 - Change password prompt removed for BRE026    -->
//--   010880 - 17.06.05 - Hard coded payslip message for IRD           -->
//--   011273 - 08.11.05 - Warning and Information Messages corrected   -->
//--   011389 - 28.03.06 - Correct the Draft TR Election display.       -->
//--   013260 - 25.10.06 - Correct the KLR date error.                  -->
//--   013901 - 10.05.07 - loadPageCurrent function created             -->
//--********************************************************************-->

// Error Found Flag and global storage for completion msgs
var bErrorsFound = false;

// Flag indicates that errors are always to pop-up
var bErrorsPopUp = false;

// *********************************************************************
// 009642 - Error Window re-designed
// oMessage is the single global object that stores all of the BRE messages that are
// returned during a single HR21 session. It has 3 boolean attributes and an array 
// attribute. The 3 boolean attributes bError, bWarning, bInformation indicate whether
// to show a certain type of message in the Message Window. 
// The array attribute, aMessages, contains the actual messages as objects.
var oMessage = new Object();
oMessage.bError = true;
oMessage.bWarning = false;
oMessage.bInformation = false;
var oTempDict = aDictDetail["seerrvew"];
if (oTempDict) {
    if ((oTempDict["i_popup"]) && (oTempDict["i_popup"].appendix == "true")) bErrorsPopUp = true;
    if ((oTempDict["i_error"]) && (oTempDict["i_error"].appendix == "false")) oMessage.bError = false;
    if ((oTempDict["i_warning"]) && (oTempDict["i_warning"].appendix == "true")) oMessage.bWarning = true;
    if ((oTempDict["i_info"]) && (oTempDict["i_info"].appendix == "true")) oMessage.bInformation = true;
}
oMessage.aMessages = new Array();

// *********************************************************************
// 009642 - Adds a new message object to oMessage.aMessages[]
// 010755 - Store message status
function messAddMsg(sMessage,sMessageType,sGTRType,sGTRStatus) {
    var oTemp = new Object();
    // error, warning, or info
    oTemp.type = sMessageType;
    // the raw message text as returned by the BRE
    oTemp.text = sMessage;
    // store the GTR type of the message code
    oTemp.gtrType = sGTRType;
    // store the status of the returned GTR
    oTemp.status = sGTRStatus;
    // the BRE message code
    oTemp.breCode = "";
    // data dictionary value associated with the message 
    oTemp.dataDict = false;
    // if the error refers to an actual field on the dataPage form
    oTemp.formErrorFound = false;
    // store the background colour of the offending field, so 
    // that it can be re-instated once the error is cleared.
    oTemp.backgroundColor = "";
    // store the tool tip of the offending field, so 
    // that it can be re-instated once the error is cleared.
    oTemp.title = "";
    // store the name of the page where the error occurred.
    oTemp.errorPage = sDataPage;
    // If the user clicks the 'Clear' button, then the message will
    // not be shown
    oTemp.clear = false;
    // Allow for a tooltip for the actual error message in the Message Window
    oTemp.toolTip = false;
    // Non-form errors we only want displayed once. After it's displayed,
    // this attribute is set to false
    oTemp.showAgain = true;
    // Finish setting up the message object
    oMessage.aMessages[oMessage.aMessages.length] = messConfigureObject(sMessage,oTemp);
    // display the message if the window is already open
    if (bMessWin) messDisplayMessage(oMessage.aMessages.length-1);
    return;
}

// *********************************************************************
// 009642 - Configures an object with all the information for a particular message
// 010408 - Set sTemp correctly for non-IE browsers
function messConfigureObject(sMessage,oTemp) {
    var sText = sMessage;
    var sErrorNum = sText.substr(0,6);
    var iColonPos = sText.indexOf(":");
    var sErrorTxt = sText.substr(iColonPos+1);
    oTemp.breCode = sErrorNum;
    // An error has occurred with a particular field on the form,
    // so we'll try to find the field and identify it to the user
    if (iColonPos != 6) {
        var sId = messFieldError(sText, iColonPos);
        var oTitleCell = oDataPage.document.getElementById(sId);
        // We've found the title of the offending field. It will be used
        // to produce a meaningful message (in the tooltip) for the user
        if (oTitleCell) {
            var sTitle = oTitleCell.innerHTML;
            oTemp.dataDict = sTitle;
            oTemp.text = sTitle + ":" + sErrorTxt;
        }
        // Now find the actual field so that we can change the background 
        // colour and put some help in the tooltip
        var aElements = oDataPage.document.getElementsByName(sId);
        if (aElements.length > 0) var oElement = aElements[1];
        // The field has been found, we'll store the tooltip and background colour
        // so that it can be re-instated once the error is cleared.
        if ((oElement) && (oElement.className != "Display")) {
            oTemp.backgroundColor = oElement.style.backgroundColor;
            oTemp.title = oElement.title;
            oTemp.dataDict = sId;
            oTemp.formErrorFound = true;
            oTemp.errorPage = sDataPage;
            var sTempPage = loadPageCurrent();
            var sPage = "";
            if (aVertMenu[sTempPage]) oTempMenu = aVertMenu[sTempPage]; 
            else oTempMenu = aDictMenu[sTempPage];
            sPage = oTempMenu.title;
            if (sPage != "") oTemp.toolTip = "\nThis " + oTemp.type + " message occurred on the " + sPage + " page";
            switch (oTemp.type) {
                case "warning":
                    oElement.style.backgroundColor = hWarning ? hWarning : "#00FF00";
                    break;
                case "error":
                    oElement.style.backgroundColor = hError ? hError : "#FF0000";
                    break;
            }
            oElement.title = sErrorTxt;
            oElement.style.cursor = "help";
        }
        else oTemp.text = sErrorTxt;
    }
    else oTemp.text = sErrorTxt;
    // If the message is a warning and the status is fail, resend GTR
    if ((oTemp.type == "warning") && (oMessage.bWarning) && (oTemp.status != "ok")) messResendGtr(oTemp.gtrType, oTemp.text);
    // The object has been configured, so return it to be stored in oMessage.aMessages[]
    return oTemp;
}

// *********************************************************************
// 009642 - Set the attributes of oMessage that determine the type of messages that
// are displayed in the Message Window.
function messSetChk(object) {
    if (object.checked) eval("oMessage." + object.id + " = true;");
    else eval("oMessage." + object.id + " = false;");
    // delete the existing rows of the table
    messResetTable();
    // redraw the messages
    messRetrieveMsgs();
    return;
}

// *********************************************************************
// 009642 - Delete all of the rows in the existing messages table
function messResetTable() {
    var oTable = oMessWin.document.getElementById("messages");
    if (oTable) for (var iIndex = oTable.rows.length-1; iIndex >= 0; iIndex--) oTable.deleteRow(iIndex);
    return;
}

// *********************************************************************
// 009642 - create the HTML for the Message Window, depending on which message
// types are to be shown. 
function messDisplayMessage(iIndex) {
    var sType = oMessage.aMessages[iIndex].type;
    switch (sType) {
        case "error":
            if ((oMessage.bError) && (!oMessage.aMessages[iIndex].clear)) messCreateRow(iIndex);
            break;
        case "info":
            if ((oMessage.bInformation) && (!oMessage.aMessages[iIndex].clear)) messCreateRow(iIndex);
            break;
        case "warning":
            if ((oMessage.bWarning) && (!oMessage.aMessages[iIndex].clear)) messCreateRow(iIndex);
            break;
    }
    return;
}

// *********************************************************************
// 009642 - the message table is empty, display every message again
function messRetrieveMsgs() {
    for (var iIndex = 0; iIndex < oMessage.aMessages.length; iIndex++) {
        messDisplayMessage(iIndex);
    }
    return;
}

// *********************************************************************
// 009642 - Each row in the Message Window consists of 3 cells. The first contains the
// icon to indicate the type of the message, the second contains the message text, and
// the 3rd contains the BRE code.
function messCreateRow(iIndex) {
    var oTable = oMessWin.document.getElementById("messages");
    if (oTable) {
        var sType = oMessage.aMessages[iIndex].type;
        var oRow = oTable.insertRow(oTable.rows.length);
        oRow.style.cursor = "default"; 
        var oCell = oRow.insertCell(oRow.cells.length);
        oCell.width = "20";
        oCell.title = "This is a " + ((sType == "info") ? "information" : sType) + " message"; 
        oCell.innerHTML = "<img src='" + loadPageResource("misc", true) + sType + ".png' border='0'>";
        oCell = oRow.insertCell(oRow.cells.length);
        oCell.title = "This is the message content"; 
        if (oMessage.aMessages[iIndex].toolTip != "") {
            oCell.title += oMessage.aMessages[iIndex].toolTip; 
        }
        oCell.innerHTML = oMessage.aMessages[iIndex].text;
        oCell = oRow.insertCell(oRow.cells.length);
        oCell.title = "This is the BRE code of the message";
        oCell.innerHTML = oMessage.aMessages[iIndex].breCode;
    }
    return;
}

// *********************************************************************
// 009642: Function cycles through the oMessage and locates any
// errors that have occurred on the current dataPage.
function messCheckErrorsOnPage() {
    var bErrorsOnPage = false;
    var oTmpMsg = null;
    for (var i = 0; i < oMessage.aMessages.length; i++) {
        oTmpMsg = oMessage.aMessages[i]; 
        // 013260 - Additional allow for a setting to pop-up errors all the time
        if ((oTmpMsg.type == "error") && (oTmpMsg.errorPage == sDataPage) && (!oTmpMsg.dataDict || bErrorsPopUp) && (oTmpMsg.showAgain)) {
            oMessage.aMessages[i].showAgain = false;
            bErrorsOnPage = true;
        }
    }
    return bErrorsOnPage;
}

// *********************************************************************
// 009642 - Checks any fields that were previously set as warnings and 
// re-instates the correct tooltip and background colour. 
function messResetWarnings(gtrType) {
    for (var iIndex = 0; iIndex < oMessage.aMessages.length; iIndex++) { 
        var oTmpMsg = null;
        oTmpMsg = oMessage.aMessages[iIndex];
        if ((oTmpMsg.errorPage == sDataPage) && (oTmpMsg.gtrType.substr(0,3) == gtrType.substr(0,3))) {
            messResetField(iIndex);
        }
    }
    return;
}

// *********************************************************************
// 009642 - Reinstates the correct tooltip and colour for a field
function messResetField(iIndex) {
    if (oMessage.aMessages[iIndex].dataDict) {
        var aElements = oDataPage.document.getElementsByName(oMessage.aMessages[iIndex].dataDict);
        if (aElements.length > 0) {
            var oElement = aElements[1];
            if (oElement) {
                if (oElement.style.cursor == "help") {
                    oElement.style.backgroundColor = oMessage.aMessages[iIndex].backgroundColor;
                    oElement.title = oMessage.aMessages[iIndex].title;
                    oElement.style.cursor = "auto";
                }
            }
        }
    }
    return;
}

// *********************************************************************
// 009642 - Resends the GTR with the 'ignorewarnings' keyword
function messResendGtr(gtrType,sText) {
    if (confirm(sText)) {
        bIgnoreWarnings = true;
        oDataPage.sendGTR(gtrType);
        loadPageClick();
        bIgnoreWarnings = false;
    }
    return;
}
   
// *********************************************************************
// Searches the gtrContainer for an error code and if present displays
// the message in the Message Window.
function messBreError(oContainer) {
    // the X in error0X, info0X, etc
    var iIndex = 1;
    var sError, sInfo, sWarning, bMessage;
    // Check composite bits of msg
    var sGTRType = getGTRField(oContainer,"cbr");
    var sGTRStatus = getGTRField(oContainer,"status");
    // 010791 - If we hit "BRE026:X Days until access expiry. Contact your System Administrator"
    // then we want to display it in the msg window
    var bBre026 = false; 
    messResetWarnings(sGTRType);
    do {
        sError = messGtrNext(oContainer,"e",iIndex);
        // Ignore the BRE204 msg - "Entry does not exist. Must be added first."
        // 010546 - Display BRE204 only if "i_showempty" is present in the GTR
        if (sError != "") {
            var bBre204 = (sError.indexOf("BRE204") != -1 ? true : false); 
            if ((bBre204 && findGTRField(oContainer,"i_showempty")) || (!bBre204)) {
                bErrorsFound = true;
                messAddMsg(sError,"error",sGTRType,sGTRStatus);
            }
        }
        sInfo = messGtrNext(oContainer,"i",iIndex);
        // Ignore the BRE260 msg - "Field does not belong to form. Field ignored."
        if ((sInfo != "") && (sInfo.indexOf("BRE260") == -1)) {
            if (sInfo.indexOf("BRE026") != -1) bBre026 = true;
            messAddMsg(sInfo,"info",sGTRType,sGTRStatus);
        }
        sWarning = messGtrNext(oContainer,"w",iIndex);
        // Ignore the BRE260 msg - "Field does not belong to form. Field ignored."
        if ((sWarning != "") && (sWarning.indexOf("BRE260") == -1)) messAddMsg(sWarning,"warning",sGTRType,sGTRStatus);
        // increment counter and check for more messages
        iIndex++;
        bMessage = ((sError == "") && (sInfo == "") && (sWarning == ""));
    } while (!bMessage);
    // 009642 - If the error is not to do with a field on the dataPage form,
    // Then pop-up the Message Window and show the user the error message.
    if ((messCheckErrorsOnPage() && (oMessage.bError)) || (bBre026 && oMessage.bInformation)) messShowMessages();
    // Set the return value dependant on the status of the message
    if (getGTRField(oContainer,"status") != "ok") {
        return true;
    } else {
        return false;
    }
}

// *********************************************************************
//  Checks for error0X, info0X or warning0X in the returned gtr.
function messGtrNext(gtrContainer,sType,iIndex) {
    var sTemp = "";
    // For this interface do not report any note messages.
    if (gtrContainer["cbr"].toString().substring(0,3) != "nte") {
        var iReference = (iIndex < 10) ? "0" + iIndex : iIndex;
        // Split processing for message type
        switch (sType) {
            case "e" :
                sTemp = "error" + iReference;
                break;
            case "i" :
                sTemp = "info" + iReference;
                break;
            case "w" :
                sTemp = "warning" + iReference;
                break;
        }
        sTemp = getGTRField(gtrContainer,sTemp);
    }
    return sTemp;
}

// *********************************************************************
// 009642 - Manages the new Message Window
function messShowMessages() {
    // If Message Window is closed, set the flag to indicate the fact
    if (oMessWin && oMessWin.closed) {
        bMessWin = false;
    }
    // If Message Window is not open, make sure it is opened
    if (!bMessWin) {
        var sWindowParameter = "width=580,height=360,screenX=0,left=0,screenY=0,top=0," + sDefaultWindow;
        oMessWin = window.parent.open("seerrvew.htm","",sWindowParameter,true);
        bMessWin = true;
    } else {
        oMessWin.focus();
    }
    if (!oMessWin.opener) {
        oMessWin.opener = window;
    }
    return;
}

// *********************************************************************
function messFieldError(sError, iColonPos) {
    var sFieldNam = sError.substring(6,iColonPos);
	// 013260 - Switch klr date error for all clients.
    if (sFieldNam == "klreffdate") sFieldNam = "laccalcrun";
    // Get rid of all forward slash characters
    if (sFieldNam.indexOf("/", 0) != -1) {
        var rExp = new RegExp("/", "g");
        sFieldNam = sFieldNam.replace(rExp, "");
    }
    var iBracketPos = sError.indexOf("[");
    if (iBracketPos != -1) {
        sFieldNam = sError.substring(6,iBracketPos);
    }
    var oErrorFld = oDataPage.document.getElementById(sFieldNam);
    if (oErrorFld) {
        return sFieldNam;
    } else {
        return sFieldNam;
    }
}           

// *********************************************************************
// Creates all the elements for a message inidicating the successful
// completion of a report and that it's location will be in sefrilst
function messCreateReport(sReport) {
    var sHtml;
    switch (sKskType) {
        case "IRD":
            sHtml = "Completed - view by accessing ";
            break;
        default:
            if (sReport) sHtml = sReport;
            else sHtml = "Report";
            sHtml += " added within ";
            break;
    }
    var oTemp = menuObjectLoad("sefrilst");
    if (oTemp) sHtml += oTemp["title"] + ".";
    else sHtml += "View Reports."
    return sHtml;
}

// *********************************************************************
// Tests to see which framesets are active so as to locate
// the top level frame with the Mess box used for displaying the sMsg
function messStatus(sMsg, sType) {
    var oMsgBox = oDataPage.document.getElementById("messageBox");
    var sTemp;  // Temporary storage
    // Format status message correctly  
    switch (sType) {
        case "Clear":
            sTemp = "";
            break;
        case "Error":
            sTemp = "<font class='Error' color='" + hError + "'>" + sMsg + "</font>";
            break;
        case "Warning":
            sTemp = "<font class='Warning' color='" + hWarning + "'>" + sMsg + "</font>";
            break;
        case "Complete":
            sTemp = "<font class='Complete' color='" + hComplete + "'>" + sMsg + "</font>";
            break;
        default:
            sTemp = "<font class='Status' color='" + hStatus + "'>" + sMsg + "</font>";
            break;
    }
    // Write msgs to page
    if (oMsgBox) oMsgBox.innerHTML = sTemp;
    return;
}

// *********************************************************************
// Called when gtr interpreting is complete & generates a status message
// to indicate this.
function messCompletion(num, success) {
    var sTemp;  // Holds message to display
    var sButtMess;  //Holds Button label text
    var rExp1 = new RegExp("%title%","g");
    var rExp2 = new RegExp("%action%","g");
    // Ensure failuer is reported as an error
    if (isNaN(num)) num = 0;
    if (isNaN(success)) success = 1;
    if ((bErrorsFound) || (success < 0)) {
        bErrorsFound = false;
        sTemp = sError.replace(rExp2,messAction(num));
        sTemp = sTemp.replace(rExp1,oDataPage.oMenu["title"]);
        messStatus(sTemp,"Error");
        return;
    }
    // Increment successful GTR count and check for an error
    iSuccessCount++;
    if (iSuccessCount == success) {
        sTemp = sComplete.replace(rExp2,messAction(num));
        sTemp = sTemp.replace(rExp1,oDataPage.oMenu["title"]);
        messStatus(sTemp,"Complete");
    } else if (success == 0) {
        if (oDataPage.oDict["updat"]) sButtMess = (oDataPage.oDict["updat"].labeltext) ? oDataPage.oDict["updat"].labeltext : "Update";
        else sButtMess = "Update";
        sTemp = sAddNew.replace(rExp1,oDataPage.oMenu["title"]);
        rExp2 = new RegExp("%button%","g");
        sTemp = sTemp.replace(rExp2,sButtMess);
        messStatus(sTemp,"Complete");
    }
    // 10063 - realign the divs to finish off
    if (!is.ie) loadDivsAlign();
    return;
}

// *********************************************************************
// returns a number which is used to show correct stat msg
function messType(gtrType) {
    switch (gtrType.substr(3,3)) {
        case "add":
        case "upd":
        case "btn":
            return 3;
        case "del":
            return 2;
        default:
            return 0;
    }   
}

// *********************************************************************
// Assigns the ZOS string with apporpriate action
function messAction(num) {
    switch (num) {
        case 3:
            return sUpdate;
        case 2:
            return sDelete;
        default:
            return sRetrieve;
    }   
}

// *********************************************************************
