//--********************************************************************-->
//--                                                                    -->
//--   Frontier Software Pty Ltd                                        -->
//--                                                                    -->
//--   File Name     : intergtr.js                                      -->
//--                                                                    -->
//--   History       :                                                  -->
//--   005876 - 02.07.00 - JavaScript Rewrite.                          -->
//--   008980 - 11.09.03 - Allow for "=" characters in GTRs.            -->
//--   007259 - 28.07.04 - Introducing the ToolBar Window               -->
//--   009980 - 08.09.04 - Allow searching on Detail Pages.             -->
//--   010063 - 17.12.04 - Opera (10062) & Mozilla (10063) supported    -->
//--   010539 - 10.02.05 - Prompt when password is about to expire.     -->
//--   010462 - 03.03.05 - Tables load in correct sequence              -->
//--   009745 - 22.02.05 - Introduced translation                       -->
//--   010902 - 27.06.05 - Exit button on the Time-Out page corrected   -->
//--   011210 - 18.10.05 - Opera: Exit Button Corrected                 -->
//--   011275 - 09.11.05 - Tidy up Date formats                         -->
//--   011355 - 01.12.05 - When no token blank it out                   -->
//--   011560 - 22.02.06 - All dates in CCYY-MM-DD format               -->
//--   011389 - 28.03.06 - Correct the Draft TR Election display.       -->
//--   011498 - 27.03.06 - Carriage returns converted to \n             -->
//--   013668 - 02.03.07 - All times in hh:mm format                    -->
//--   011907 - 17.01.07 - Single Sign-On                               -->
//--   013898 - 09.05.07 - KAS message catered for by token handling    -->
//--   013901 - 10.05.07 - loadPageCurrent function created             -->
//--********************************************************************-->

// *********************************************************************
// This is the single message event for the handling of incoming messages
// to the BRA, IIS or FastCGI versions of HR21.
// The Message property is a string in the format "xxx,tttt:aaaaaaaa...." 
// Where 
//
//      xxx is the Message Type and 
//      tttt is the Message Token and 
//      aaaaaaaa... is the Message Data appropriate for the message. 
//
// Some message types are:
//
//      GTR - if the data is a GTR (send or receive) 
//      PRG - if the message data is a progress message. (receive) 
//      ERR - if the message data is a system error or warning message. (receive) 
//      CAN - if the message is a Cancel Message (send) 
//
function gtrNewMessage(gtr) {
    switch (sComType) {
        // Using BRA no % characters
        case "BRA":
            var sReturnMessage = gtr;
            break;
        // Using IIS or FastCGI unescape % characters
        case "IIS":
        case "FCG":
            var sReturnMessage = unescape(gtr);
            break;
    }
    // Determine Message Type and Data
    var sMessageType = determineMessageType(sReturnMessage);
    var sMessageData = determineMessageData(sReturnMessage);
    // Check the different types of messages that the BRE could deliver 
    switch (sMessageType) {
       case "CAN":
          processCAN(sMessageData);
          break;
       case "ERR":
          processERR(sMessageData);
          break;
       case "GTR":
          processGTR(sMessageData);
          break;
       case "KAS":
          break;
       case "PRG":
          processPRG(sMessageData);
          break;
    }
    return;
}

// *********************************************************************
// Message format is Type,Token:Data                                             
// 011355 - When no token, blank it out
// 013898 - When no token, Do Not blank it out, KAS could fire and casue
//          token to be lost
function determineMessageType(sMessage) {
    // resultant message type to be returned once token has been striped
    var sMsgType;
    // get colon position and return everything to the right
    var sWholeHeader = sMessage.substr(0,(sMessage.indexOf(":")));
    // if there is a comma, this has a token, otherwise reset the token
    var nCommaPosition = sWholeHeader.indexOf(",");
    // if there is a comma, strip out the token for use
    if (nCommaPosition > 0) {
        sMsgType = sWholeHeader.substr(0,(nCommaPosition));
        // if there is still a comma the token ends before it.
        var sTempToken = sWholeHeader.substr((nCommaPosition + 1),(sWholeHeader.length - (nCommaPosition + 1)));
        nCommaPosition = sTempToken.indexOf(",");
        // check for new comma postion
        if (nCommaPosition > 0) {
            sToken = sTempToken.substr(0,(nCommaPosition));
        } else {
            sToken = sTempToken;
        }
    } else {
        // There is no comma in the heading, so the type is the whole header
        sMsgType = sWholeHeader;
        // Note: Do not blank out the token string here as it may cause issues 
        // with long running processes
    }
    return sMsgType;
}

// *********************************************************************
// get colon position and then return everything to the RIGHT of it
function determineMessageData(sMessage) {
    var nColonPosition = sMessage.indexOf(":");
    var sMsgData = sMessage.substr((nColonPosition + 1),(sMessage.length - (nColonPosition + 1)));
    return sMsgData;
}

// *********************************************************************
// Cancel messages.
function processCAN(sReturnMsg) {
    messStatus("Message Cancelled","Warning");
    return;
}

// *********************************************************************
// The Error event is raised when errors occur.
function processERR(sReturnMsg) {
    alert(oGlob.sKskTitle + " :\n\n" + sReturnMsg);
    return;
}

// *********************************************************************
// Close all other opened browser sessions on timeout
function closeWindows() {
    // Close Time Window
    if ((oTimeWin) && (oTimeWin != null) && (!oTimeWin.closed)) oTimeWin.close();
    // Close Calendar Window
    if ((oCalWin) && (oCalWin != null) && (!oCalWin.closed)) oCalWin.close();
    // Close Enquiry Calendar Window
    if ((oEmpCalWin) && (oEmpCalWin != null) && (!oEmpCalWin.closed)) oEmpCalWin.close();
    // Close Help Window
    if ((oHelpWin) && (oHelpWin != null) && (!oHelpWin.closed)) oHelpWin.close();
    // Close Message Window
    if ((oMessWin) && (oMessWin != null) && (!oMessWin.closed)) oMessWin.close();
    // Close ToolBar Window
    if ((oToolWin) && (oToolWin != null) && (!oToolWin.closed)) oToolWin.close();
    // Close Server Window
    if ((oServerWin) && (oServerWin != null) && (!oServerWin.closed)) oServerWin.close();
    // Close View Window
    if ((oVewSelWin) && (oVewSelWin != null) && (!oVewSelWin.closed)) oVewSelWin.close();
    // Set the oDataPage Object back to be the dataFrame
    oDataPage = dataFrame;
    return;
}

// *********************************************************************
// 010391 - If "i_dataframe" is detected in the gtrContainer, then handle
// the "tablelist" GTR within the page rather than within ftroptns.js
function gtrTables(oContainer) {
    var bTable = false;
    var sCbr = getGTRField(oContainer,"cbr");
    switch (sCbr) {
        case "tablelist":
            if (!findGTRField(oContainer, "i_dataframe")) bTable = true;
            break;
        case "tablst":
        case "ktflst":
        case "loclst":
        case "ptalst":
        case "ptflst":
        case "ptslst":
        case "tpclst":
            bTable = true;
            break;
    }
    return bTable;
}

// *********************************************************************
// When the GTR returns it triggers the process GTR method.  We will then
// clear the array and call utilities to deconstruct the GTR and call a
// function on the web page in the content frame to deal with the
// deconstructed GTR.
// *********************************************************************
// 11210: Use href to load all the menu settings over the frames
function processGTR(sReturnMsg) {
    // Debug message. This message will show the GTR that is returned.
    if (gDebug) alert(sReturnMsg);
    // Check if there is a token expiry, and if so, go to the password screen
    if ((sReturnMsg.indexOf("BRE123") != -1) || (sReturnMsg.indexOf("BRE124") != -1) || (sReturnMsg.indexOf("BRE125") != -1) || (sReturnMsg.indexOf("BRE126") != -1)) {
        bLoggedOn = false;
        // Ensure other browser sessions are closed
        closeWindows();
        // Store the location of the vertFrame
        var iLocation;
        if (bHorizMenu) {
            iLocation = horizFrame.location.href.lastIndexOf("/");
            sMenuLocn = horizFrame.location.href.substr(iLocation+1);
        }
        if (bVertMenu) {
            iLocation = vertFrame.location.href.lastIndexOf("/");
            sMenuLocn = vertFrame.location.href.substr(iLocation+1);
        }
        // Store the location of the dataFrame
        iLocation = dataFrame.location.href.lastIndexOf("/");
        sDataLocn = dataFrame.location.href.substr(iLocation+1,8);
        // Load the menu and data frames with password re-entry
        switch (sKskType) {
            case "ZRM":
                var iLocation = location.href.lastIndexOf("/");
                var sReadLocn = location.href.substr(0,iLocation+1);
                dataFrame.location.replace(sReadLocn + "setuppas.htm");
                break;
            default:
                // 11907 - If SSO is set then we want to login again rather
                // than throw to seusrpas.htm 
				if (bSSO == true) {
					loadSendLogon();
					return;
				}
				else {
					if (bHorizMenu) horizFrame.location.href = sHR21Location + "sehorlog.htm";
					if (bVertMenu) vertFrame.location.href = sHR21Location + "severlog.htm";
					dataFrame.location.replace(sHR21Location + "seusrpas.htm");
                }
				break;
        }
        return;
    } 
    // Strip out the GTR information, converting it into string objects for future manipulation 
    var returnGTRContainer = parseGTR(sReturnMsg);
    // 010902: Ensure the Exit button on the Time-Out page functions correctly
    var bLogoff = (getGTRField(returnGTRContainer,"cbr") == "logoff");
    // Check currently logged on or a logon page is loaded and logoff GTR or message indicating no logon 
    if (((bLoggedOn) || (sDataPage.indexOf("seusr") != -1)) && ((bLogoff) || (sReturnMsg.indexOf("BRE102") != -1))) {
        bLoggedOn = false;
        switch (sKskType) {
            case "ZRM":
                var sReadLocn = "readme.htm";
                if (location.search) {
                    var iLocation = location.href.lastIndexOf("?");
                    sReadLocn = location.href.substr(0,iLocation);
                }
                if (window.parent.opener == null) {
                    return location.replace(sReadLocn);
                } else {
                    window.close();
                }
                break;
            default:
                if ((bLogoff) && (aDictMenu["seexidet"])) {
                    if (bHorizMenu) horizFrame.location.href = sHR21Location + "sehorlog.htm";
                    if (bVertMenu) vertFrame.location.href = sHR21Location + "severlog.htm";
                    return dataFrame.location.replace(sHR21Location + "seexidet.htm");
                } else {
                    return location.replace(sHR21Location);
                }
                break;
        }
    }
    // Dependant on the type of file forward on the GTR's
    if (findGTRField(returnGTRContainer,"cbr")) {
        // Only a pageLocLength length string is used from the right of the location string
        var sTempLocation = loadPageLocation();
        if (getGTRField(returnGTRContainer,"i_location") == sTempLocation) {
            switch (sTempLocation.substr(sTempLocation.length-7,3)) {
                case "dfa":
                case "sel":
                    if (!oVewSelWin.closed) oVewSelWin.interpretGTR(returnGTRContainer);
                    else dataFrame.interpretGTR(returnGTRContainer); 
                    break;
                case "vew":
                    if (!oVewSelWin.closed) {
                        if (gtrTables(returnGTRContainer)) optnsInterpret(returnGTRContainer);
                        else oVewSelWin.interpretGTR(returnGTRContainer);
                    } else {
                        dataFrame.interpretGTR(returnGTRContainer);
                    }
                    break;
                default:
                    // 11907 - If logging in again using SSO we want to handle a few things in 
                    // the scripts before throwing back to the original page. 
					if (findGTRField(returnGTRContainer, "i_sso")) {
                        loadProcessLogon(returnGTRContainer);
					} else {
						if (gtrTables(returnGTRContainer)) optnsInterpret(returnGTRContainer);
						else dataFrame.interpretGTR(returnGTRContainer);
                    }
					break;
            }
        }
    }
    return;
}

// *********************************************************************
// Progress messages.
function processPRG(sReturnMsg) {
    messStatus(sReturnMsg,"Status");
    return;
}

// *********************************************************************
// Checks to see if the gtrType is in the oContainer.
// Returns false if gtrType is not found and not an update.
// Set bSearch to true to force a check for presence of gtrType.
function getGTRType(oContainer,sValue,bSearch) {
    var sTemp = oContainer["cbr"].substr(3,3);
    // Ensures that if an update is being sent true is returned
    if ((bSearch) && ((sTemp == "upd") || (sTemp == "add"))) {
        return sTemp;
    } else {
        for (var sIndex in oContainer) {
            if (sIndex == sValue) {
                return sTemp;
            }
        }
    }
    return false;
}

// *********************************************************************
// Checks to see if the gtrType Field is in the oContainer.
// Returns false if Field is not found for gtrType.
function findGTRField(oContainer,sValue) {
    if (oContainer[sValue]) {
        return true;
    } else {
        return false;
    }
}

// *********************************************************************
function getGTRField(gtrContainer,gtrType) {
    if (gtrContainer[gtrType]) {
        return gtrContainer[gtrType];
    } else {
        return "";
    }
}


// *********************************************************************
function removeLeadSpaces(sSpaces) {
    if (sSpaces.charAt(0) != " ") {
        return sSpaces;
    } else {
        while (sSpaces.charAt(0) == " ") {
            sSpaces = sSpaces.substring(1,sSpaces.length-1);
        }
    }
    return sSpaces;
}

// *********************************************************************
// 011498 - Carriage returns converted to \n
// 011560 - Receives a date string in the ISO 8601 format of CCYY-MM-DD 
//          and returns it as DD/MM/CCYY
//         (or for sZone of USA it returns it as MM/DD/CCYY)
function getStringFromBRE(sValue) {
    sValue = sValue.toString();
    if ((sValue.indexOf("-") != -1) && (sValue.length <= 10)) {
        var aTemp = sValue.split("-");
        if (aTemp.length && aTemp.length == 3) {
            for (var date in aTemp) if (isNaN(aTemp[date])) return sValue;
            aTemp[1] = parseInt(aTemp[1],10);
            if (aTemp[1] < 10) aTemp[1] = "0" + aTemp[1];
            aTemp[2] = parseInt(aTemp[2],10);
            if (aTemp[2] < 10) aTemp[2] = "0" + aTemp[2];
            switch (sZone) {
                case "USA":
                    sValue = aTemp[1] + "/" + aTemp[2] + "/" + aTemp[0];
                    break;
                default:
                    sValue = aTemp[2] + "/" + aTemp[1] + "/" + aTemp[0];
                    break;
            }
        }
    }
    sValue = sValue.replace(/\\n/g,"\n");
    return sValue;
}

// *********************************************************************
function parseGTRField(oContainer,sType,sValue) {
    if (sValue != null) {
        oContainer[sType] = getStringFromBRE(sValue);
    } else {
        oContainer[sType] = "";
    }
    return;
}

// *********************************************************************
function parseGTR(oContainer) {
    // make a new container for the returned gtr
    var returnedGTR = new Object();
    var i,j;
    // Split the Container by comma - returns an array of substrings
    var sTemp = new Array();
    sTemp = oContainer.split(",");
    // As we split by comma - make sure one isn't buried in one of the values.
    for (i=0; i<sTemp.length; i++) {
        sTemp[i] = removeLeadSpaces(sTemp[i]);
        while ((sTemp[i].indexOf(cDelimiter) != -1) && (sTemp[i].indexOf(cDelimiter) == sTemp[i].lastIndexOf(cDelimiter)) && (sTemp[i].indexOf(cQuote) != 2)) {
            sTemp[i] += ",";
            sTemp[i] += sTemp[i+1];
            // renumber substrings
            for (j=i+1; j<sTemp.length; j++) {
                // ... j = 4
                if ((sTemp[j+1] == "undefined") || (sTemp[j+1] == null)) {
                    sTemp[j] = "";
                } else {
                    sTemp[j] = sTemp[j+1];
                }
            }
        }
    }
    // for each validated substring, split by equality sign
    for (i=0; i<sTemp.length; i++) {
        var sTemp2 = sTemp[i].split("=");
        // 008980 - If sTemp2.length > 2, then more than one equality sign has been found in the substring.     
        // iEqualCharCount stores the number of equality sign occurences in the temp string.
        // aCharAt stores the corresponding indexes of the equality signs within the temp string,
        // so then it can be used to split the string into sKeyword and sValue.
        if (sTemp2.length > 2) {
            sTemp2 = sTemp[i];
            var iEqualCharCount = 0;
            var aCharAt = new Array();
            for (j=0; j < sTemp2.length; j++) {
                if (sTemp2.charAt(j) == "=") aCharAt[iEqualCharCount++] = j;
            }
            sKeyword = sTemp[i].substr(0,aCharAt[0]);
            sValue = sTemp[i].substr(aCharAt[0] + 1, sTemp[i].length);
        } else {
            sKeyword = sTemp2[0];
            sValue = sTemp2[1];
        }
        // for each sKeyword & sValue, remove leading spaces
        sKeyword = removeLeadSpaces(sKeyword);
        if (sValue != null) {
            sValue = removeLeadSpaces(sValue);
            // if sValue is surounded by quotes, remove quotes
            if ((sValue.substring(0,1) == cDelimiter) && (sValue.substr((sValue.length - 1),1) == cDelimiter)) {
                sValue = sValue.substring(1, sValue.length - 1);
            }
            // if sValue has any double quotes, we need to do a bit more work
            if (sValue.indexOf(cQuote) != -1) {
                var rExp = new RegExp(cQuote, "g");
                sValue = sValue.replace(rExp, "\"");
            }
        } else {
            // Getting the list to work in a logical fashion
            // So that the templates can use a structured case statement
            switch (sKeyword) {
                case "startoflist":
                    sKeyword = "i_listposition";
                    sValue = "i_start";
                    break;
                case "endoflist":
                    sKeyword = "i_listposition";
                    sValue = "i_end";
                    break;
            }
        }
        // assign to keyword-value pairs in container
        parseGTRField(returnedGTR, sKeyword, sValue);
    }
    return returnedGTR;
}

// *********************************************************************
// Checks to see if returned msg contains a 'record does not exist' type error (BRE204)
//          If yes - sends add gtr.
//          If no - doesn't send add gtr & instead displays the error msg.
function addNotUpdate(oContainer, gtrType) {
    // If the ability to update is being prevented then return false
    if (!bDisabledUpdate) {
        var updGtr = gtrType + "upd";
        if ((getGTRField(oContainer,"status") != "ok") && (getGTRError(oContainer,"BRE204"))) {
            switch (getGTRField(oContainer,"cbr")) {
                case updGtr:
                    return true;
            }
        }
    }
    return false;
}

// *********************************************************************
// ZBG #8935: Cater for the BRE moving the error codes around.
// Checks to see if the error code is in the oContainer.
// Returns false if error code is not found, and
// Returns error string if error code is found.
function getGTRError(oContainer) {
    for (var iIndex=1; iIndex<arguments.length; iIndex++) {
        for (var sIndex in oContainer) {
            if (oContainer[sIndex].indexOf(arguments[iIndex]) != -1) {
                var sTemp = oContainer[sIndex].toString();
                return sTemp.substring(7,sTemp.length);
            }
        }
    }
    return false;
}

// *********************************************************************
