//--********************************************************************-->
//--                                                                    -->
//--   Frontier Software Pty Ltd                                        -->
//--                                                                    -->
//--   File Name     : sendgtr.js                                       -->
//--                                                                    -->
//--   History       :                                                  -->
//--   005876 - 02.07.00 - JavaScript Rewrite.                          -->
//--   009642 - 24.08.04 - Error Window re-designed.                    -->
//--   010114 - 21.01.05 - move all filtering into ZOF form             -->
//--   008780 - 01.04.05 - Status message now configurable              -->
//--   009745 - 22.02.05 - Introduced translation                       -->
//--   011210 - 18.10.05 - Opera: Exit Button Corrected                 -->
//--   011355 - 01.12.05 - When sending logon GTR blank out the token   -->
//--   011560 - 22.02.06 - All dates in CCYY-MM-DD format               -->
//--   011498 - 27.03.06 - Carriage returns converted to \n             -->
//--   013668 - 02.03.07 - All times in hh:mm format                    -->
//--   013738 - 06.03.07 - Use the ISO date format for all processing   -->
//--   011907 - 17.01.07 - Single Sign-On                               -->
//--   013901 - 10.05.07 - loadPageCurrent function created             -->
//--   013573 - 05.02007 - Allow short dates.  
//--********************************************************************-->

// *********************************************************************
// 011498 - Carriage returns converted to \n
// 011560 - Receives a date string in the format DD/MM/CCYY 
//         (or for sZone of USA it is MM/DD/CCYY)
//         and returns it in ISO 8601 as CCYY-MM-DD
function setStringForBRE(sValue) {
    sValue = sValue.toString();
    var sValueStart = sValueEnd = false;
    // Manipulate if filter is present
    if (sValue.indexOf(":") != -1) {
        var aTemp = sValue.split(":");
        if ((aTemp.length) && (aTemp.length == 4)) {
            sValueStart = aTemp[0] + ":" + aTemp[1];
            sValue = aTemp[2];
            sValueEnd = aTemp[3];
        }
    }
    // Find date type and change the format to the iso 8601 standard
    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[0] = parseInt(aTemp[0],10);
            if (aTemp[0] < 10) aTemp[0] = "0" + aTemp[0];
            aTemp[1] = parseInt(aTemp[1],10);
            if (aTemp[1] < 10) aTemp[1] = "0" + aTemp[1];
            // plug the century into short dates.
            aTemp[2] = parseInt(aTemp[2],10);
            if (aTemp[2] < 50) aTemp[2] =  2000 + aTemp[2];
            if ((aTemp[2] > 49) && (aTemp[2] < 100)) aTemp[2] = 1900 + aTemp[2];
           
            switch (sZone) {
                case "USA":
                    sValue = aTemp[2] + "-" + aTemp[0] + "-" + aTemp[1];
                    break;
                default:
                    sValue = aTemp[2] + "-" + aTemp[1] + "-" + aTemp[0];
                    break;
            }
        }
    }
    // Find date type and change the format to the iso 8601 standard
    sValue = calenISOFormat(sValue);
    // Check for \r\n in IE, \n in all other browsers
    sValue = sValue.replace(/\r\n/g,"\\n");
    sValue = sValue.replace(/\n/g,"\\n");
    // Check if start and end fields are set and load them back in
    if ((sValueStart) && (sValueEnd)) {
        sValue = sValueStart + ":" + sValue + ":" + sValueEnd;
    } else if (sValueStart) {
        sValue = sValueStart + ":" + sValue + ":";
    }
    return sValue;
}

// *********************************************************************
function isDigit(c) {
    return ((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9'));
}

// *********************************************************************
function isNumeric(iInput) {
    var iOutput = parseInt(iInput,10);
    return !isNaN(iOutput);
}

// *********************************************************************
function padZero(iInput) {
    if (iInput < 10){ 
        return ('0' + iInput);
    } else {
        return iInput;
    }
}

// *********************************************************************
// 013668 - Ensure Type03 fields are in format hh:mm 
function setTimeForBRE(sValue) {
    // Perform some initial tidying up of the input string
    sValue = sValue.toLowerCase();
    sValue = sValue.replace(" ","");
    sValue = sValue.replace(".",":");
    sValue = sValue.replace("-","");
    // Perform the best validation we can and try and pass the BRE,
    // something it will know what to do with.
    var sTemp = new String(sValue);
    var iTemp = sTemp.length;
    switch (iTemp) {
        case 1:
            if (isDigit(sTemp)) {
                sValue = padZero(sTemp) + ":00";
            }
            break;
        case 2:
            if (isNumeric(sTemp)) {
                sValue = padZero(sTemp) + ":00";
            }
            break;
        case 3:
            var sTemp0 = sTemp.substring(0,2);
            var sTemp1 = sTemp.substring(1,3);
            if (isNumeric(sTemp)) {
                if (parseInt(sTemp0,10) <= 23){
                    sValue = sTemp0 + ":" + sTemp.charAt(2) + "0";
                } else {
                    sValue = padZero(sTemp.charAt(0)) + ":" + sTemp1;
                }
            }
            break;
        case 4:
            if (isNumeric(sTemp)) {
                sValue = sTemp.charAt(0) + sTemp.charAt(1) + ":" + sTemp.charAt(2) + sTemp.charAt(3);
            }
            break;
        default:
            break;
    }
    return sValue;
}

// *********************************************************************
// This function sets a field term and its value, if the oContainer 
// doesn't exist then create it.
function setGTRField(oContainer,sField,sValue) {
    // Take action if the value in the GTR is not null
    if (sValue != null) {
        // if value has any " characters, we need to do a bit more work
        var sTemp = new String(sValue);
        if (sTemp.indexOf("\"", 0) != -1) {
            var rExp = new RegExp("\"","g");
            sValue = sTemp.replace(rExp,cQuote);
        }
        // If the Value is empty skip this processing
        if (sValue != "") {
            // Find out if an array
            var iArrayType = sField.indexOf("[",0);
            var sFieldTemp = new String(sField);
            if (iArrayType != -1) {
                sFieldTemp = sField.substring(0,iArrayType);
            }
            // Find out if Type03
            if (oDataPage && oDataPage.oDict[sFieldTemp] && oDataPage.oDict[sFieldTemp]["datatype"] == "3") {
                sValue = setTimeForBRE(sValue);
            }
        }
        // Normal processing of GTR strings for the BRE.
        oContainer[sField] = setStringForBRE(sValue);
    } else {
        oContainer[sField] = "";
    }
    return;
}

// *********************************************************************
// 011355 - Do not transmit token when logon GTR being composed
function composeGTR(oContainer) {
    var sTemp = "";
    var sGTR = "GTR";
    var gtrType = getGTRField(oContainer,"cbr");
    if (bIgnoreWarnings) setGTRField(oContainer,"ignorewarning");
    // Scan the GTR container loading up each element to be sent
    for (var sValue in oContainer) {
        sTemp += (sValue + "=" + cDelimiter + oContainer[sValue] + cDelimiter + ",");
    }
    // remove last comma
    if (sTemp.charAt(sTemp.length - 1) == ",") sTemp = sTemp.substring(0,sTemp.length-1);
    // Pass the token if required
    if ((gtrType == "logon") || (sToken == "")) sGTR += ":" + sTemp;
    else sGTR += "," + sToken + ":" + sTemp;
    return sGTR;
}

// *********************************************************************
function isErrorFrame(oFrame) {
    var sFrame = new String(oFrame);
    return (oFrame == "[Object]");
}

// *********************************************************************
function sendHR21(gtrContainer, iProcessMsg) {
    // If configuration is set to the construction page then send no GTR's
    if (oDataPage.oDict == null) {
        return;
    } else if (sComType == "DEM") {
        messStatus("Note: in Demo Mode, therefore no GTR's have been sent to the Business Rules Engine.","Error");
        return;
    } else {
		// 009642 - set i_location if not previously set
        if (!gtrContainer["i_location"]) {
            setGTRField(gtrContainer,"i_location",loadPageLocation());
        }
    }
    // Set the correct processing message for the sending of the GTR
    if (arguments[1] != null) {
        if (isNaN(iProcessMsg)) {
            messStatus(iProcessMsg.toString(),"Status");
        } else {
            var rExp1 = new RegExp("%action%","g");
            var sStatMess = sStatus.replace(rExp1,messAction(iProcessMsg));
            var rExp2 = new RegExp("%title%","g");
            sStatMess = sStatMess.replace(rExp2,oDataPage.oMenu["title"]);
            messStatus(sStatMess,"Status");
        }
    }
    return;
}

// *********************************************************************
function sendGTR(gtrContainer, iProcessMsg) {
    // Store frame number of frame sending the gtr
    var oFrameNum;
    // If not logged on and not sending the logon cbr then return
    // 11907 - We don't want to be kicked out if logging in again using SSO
    if ((!bLoggedOn) && (sDataPage.indexOf("seusr") == -1) && (!bSSO)) {
        return location.replace(sHR21Location);
    }
    sendHR21(gtrContainer,iProcessMsg);
    // Split the processing of messages by communication type and for cgiview gtr
    switch (sComType) {
        case "BRA":
            // BRA: if debugging, show gtr string
            if (gDebug) alert("[BRA] " + composeGTR(gtrContainer));
            // BRA: send the GTR
            FTRBra.Message = composeGTR(gtrContainer);
            break;
        case "IIS":
        case "FCG":
            var iFrameStart = 2;
            if (bVertMenu && bHorizMenu) iFrameStart = 3;
            //isErrorFrame(frames[j].location)
            // Search for free frame
            for (var j=iFrameStart; j<frames.length; j++) {
                if ((!frames[j]) || (frames[j].document.forms.length != 2)) {
                    // It is a server generated error as communication page 
                    // is not loaded in that frame
                    if (oServerWin != null) {
                        oServerWin = window.parent.open("","Server Error",sNewWindow,true);
                        if (!oServerWin.opener) oServerWin.opener = window.parent;
                        oServerWin.location.replace(frames[j].location);
                        oServerWin.document.close();
                    }
                    // Reload communication page into error frame
                    switch (sComType) {
                        case "IIS":
                            frames[j].location.replace("segtrsnd.asp");
                            break;
                        case "FCG":
                            frames[j].location.replace("segtrsnd.htm");
                            break;
                    }
                    return;
                } else if (frames[j].document.control.state.value != "used") {
                    frames[j].document.control.state.value = "used";
                    oFrameNum = eval("oGlob.frames[" + j + "].document.gtrform");
                    break;
                }
            }
            // IIS,FCG: if debugging, show gtr string
            if (gDebug) alert("[" + sComType + "] " + composeGTR(gtrContainer));
            // Set the MESSAGE0 to be posted from the composed GTR string
            oFrameNum.MESSAGE0.value = composeGTR(gtrContainer);
            // IIS,FCG: submit the GTR
            oFrameNum.submit();
            break;
    }
    return;
}

// *********************************************************************
