<?php
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Expires: 0');
    // Header to allow Cross-Server AJAX Connection
    header('Access-Control-Allow-Origin: *');
    set_time_limit(0);
    date_default_timezone_set('Europe/London');
    // Enable exceptions for MySQLi errors
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
    session_start();
    // Check if the session variables are set
    if (isset($_SESSION['user']))
    {
        $userId = $_SESSION['user'];
        $password = $_SESSION['password'];
    } 
    else 
    {
        // Handle the case where userData is not set
        $userId = null;
        $password = null;
    }
?>
<!doctype html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script type="text/javascript" src="fkeys.js?v=datetime.now()"></script>
    <script src="ocr/tesseract.min.js"></script>
    <link rel="stylesheet" href="css/styles.css">
    <link href="js/libs/fontawesome-pro-5.13.0-web/css/all.css" rel="stylesheet" />
    <title>Vims Scanning</title>
    <style>
        .ok 
        {
            background-color: green;
            color: white;
        }
        .error 
        {
            background-color: red;
            color: white; /* or any other color */
        }
        
        header
        {
            background-color: var(--dark-color);
            color: var(--light-grey);
            padding: 5px 8px;
            width: 100%;
            height: 40px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: flex-start;
        }
        
        body
        {
            font-family: RedHatDisplay, sans-serif;
            font-size: 1em;
            margin: 0;
            padding: 0;
            touch-action: manipulation;
            background-color: grey;
            overflow: scroll;
            background-image: url("./images/se-bg-02.jpg");
            background-position: center;
            background-repeat: no-repeat;
        }
        
        #user-icon::after
        {
            font-family: faSolid;
            font-size: 1.5em;
            color: white;
            content: "\f2bd";
            box-sizing: border-box;
        }
        
        #header-block
        {
            float: left;
            display: flex;
            align-items: center;
            flex-grow: 2;
        }
        
        .modal {
            display: none;
            position: fixed;
            left: 0;
            top: 5vh;
            width: 99vw;
            height: 95vh;
            overflow: auto;
            background-color: rgba(128, 128, 128, 0.9);
            z-index: 50;
        }

        .modal-content {
            background-color: #fff;
            margin: 0;
            border: 1px solid #888;
            width: 95%;
            height: 85%;
            z-index: 501;
        }
        
        .edit-modal 
        {
            display: none; /* Hidden by default */
            position: fixed; /* Stay in place */
            z-index: 1; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%; /* Full height */
            overflow: auto; /* Enable scroll if needed */
            background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */
            padding-top: 60px;
        }
        .edit-modal-content 
        
            background-color: #fefefe;
            margin: 5% auto; /* 15% from the top and centered */
            padding: 20px;
            border: 1px solid #888;
            width: 80%; /* Could be more or less, depending on screen size */
            border-radius: 5px; /* Rounded corners */
        }
        
        .close-modal 
        {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close-modal:hover,
        .close-modal:focus 
        {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
        
        .editNavPanel
        {
            width: 100%;
            background-color: var(--dark-color);
            padding: 5px 8px;
            max-width: 100%;
            box-sizing: border-box;
            display: flex;
            justify-content: space-between;
            box-sizing: border-box;
        }
        #saveBtn {
            margin-top: 20px; /* Space above the save button */
        }
        
        .popupTableContainer
        {
            overflow: scroll;
            width: 100%;
            height: 75%;
        }
        
        #popupTextContainer 
        {
            display: none; /* Hidden by default */
            border: 1px solid #ccc;
            padding: 10px;
            background-color: #f9f9f9;
            position: absolute;
            width: 300px;
            height: 3%;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            display: flex; /* Use Flexbox for alignment */
            align-items: center; /* Center align items vertically */
        }
        .popupText 
        {
            margin-right: 10px; /* Space between text and image */
            flex-grow: 1; /* Allow text to take available space */
        }
        #popupImg 
        {
            height: 100%; /* Match the height of the container */
            width: auto; /* Maintain aspect ratio */
        }
        
        .input
        {
            border: 1px solid #dddddd;
            padding: 8px;
            font-family: RedHatDisplay, sans-serif;
            outline: black;
            background-color: transparent;
            width: 100%;
            display: inline-block;
            text-align: left;
            font-weight: 300;
            font-size: calc(1em + .6vw);
        }
        
        .div-table
        {
            width: 100%;
            display: table;
        }
        
        .div-table-body
        {
            display: table-row-group;
        }
        
        .div-table-header
        {
            top: 0;
            position: sticky;
            z-index: 2;
            display: table-cell;
            border: 1px solid #dddddd;
            padding: 8px;
            line-height: 1.42857143;
            vertical-align: center;
            background-color: var(--dark-color);
            color: #fff;
        }
        
        .div-table-row
        {
                display: table-row;
        }
        
        .div-table-cell
        {
                display: table-cell;
                border: 1px solid #dddddd;
                line-height: 1.42857143;
                vertical-align: top;
                background-color: #eee;
                font-size: small;
        }
        
        .input-box
        {
            display: block;
            color: black;
            width: 100%;
            border: none;
            padding: 5px;
            border-radius: 3px;
            font-size: calc(1em + .4vw);
        }
        
        @media screen and (max-width: 320px)
        {
            .input-box
            {
                font-size: calc(.9em + .3vw);
            }
        }
        
        @media screen and (min-width: 321px) and (max-width: 720px)
        {
            .input-box
            {
                font-size: calc(1em + .4vw);
            }
        }
        
        #alert
        {
            position: fixed;
            visibility: hidden;
            transform: translate(-50%, 0px);
            z-index: 1000;
            width:auto;
            text-align:center;
            background:red;
            color: white;
            font-size: 1.4em;
            font-weight: 800;
            overflow-wrap: break-word;
            box-sizing: border-box;
            position: absolute;
            left: 50%;
            top: 65%;
        }
        
        #alert.show {
            visibility: visible;
            animation: slide-up 5s ease forwards;
        }
        
        @keyframes slide-up {
          0% {
            opacity: 0;
            top: 99%;
          }
          10% {
            opacity: 1;
          }
          90% {
            opacity: 1;
          }
          100% {
            opacity: 0;
            top: 5%;
          }
        }
        
        #popupMessageContainer 
        {
            display: flex; /* Use flexbox to center items */
            justify-content: center; /* Center items horizontally */
            align-items: center; /* Center items vertically */
            display: none; /* Hidden by default */
            border: 1px solid #ccc;
            left: 50%; /* Move right 50% of the viewport width */
            transform: translate(-50%, 0%); /* Adjust position back by half of its own size */
            width: 75%;
            height: 5%;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            border-radius: 5px;
        }
        #rdtmessage 
        {
            /* background-color: #2196F3; */
            font-size: 15px;
            font-weight: bold;
            color: white;
            text-align: center;
            width: 100%;
            height: 100%;
            align-items: center;
            border-radius: 5px;
            white-space: nowrap;
        }
        
        #loadingmsg
        {
            visibility: visible;
            color: black;
            background: #CECFD0;
            padding: 10px;
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 501;
            margin-left: 1px;
            margin-top: 1px;
        }
        
        #gallery
        {
            display: flex;
            flex-wrap: wrap;
        }
        
        .thumbnail
        {
            width: 200px;
            height: 150px;
            margin: 10px;
        }
        
        .highlight {
          border: 2px solid red;
        }
        
        ::placeholder
        {
            color: darkred;
        }
        
        .selected 
        {
            background-color: #007BFF;
        }
        
        .placeholder-white::-webkit-input-placeholder
        {
          font-style: italic;
          color: mintcream !important;
        }
        
        .placeholder-white:-moz-placeholder
        {
          font-style: italic;
          color: mintcream !important;
        }
        
        .placeholder-white::-moz-placeholder
        {
          font-style: italic;
          color: mintcream !important;
        }
        
        .placeholder-white:-ms-input-placeholder
        {
          font-style: italic;
          color: mintcream !important;
        }
        
        .placeholder-white::input-placeholder
        {
            font-style: italic;
            color: mintcream !important;
        }
        
        .placeholder-white::placeholder
        {
            font-style: italic;
            color: mintcream !important;
        }
        iframe 
        {
            width: 100%;
            height: 95%;
            border: 1px solid #ccc;
            display: flex;
            flex-wrap: wrap;
        }
        a 
        {
            display: inline-block;
            margin-top: 10px;
            padding: 10px 15px;
            background-color: #007BFF;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        a:hover 
        {
            background-color: #0056b3;
        }
    </style>
</head>
<body virtualkeyboardpolicy="manual">
    <main id="myMain">
        <header>
            <input type="text" id="menuOption" value="" />
            <img id="vantecLogo" src="images/vantec-logo-white.png" alt="Vantec logo" onclick="toggleScreen();">
            <span id="header-block">
                <label id="txtCompany">VIMS RDT</label>
                <input type="text" id="txtTranType" value="" readonly="readonly" />
                <input type="hidden" id="txtSystem" value="" readonly="readonly" />
                <input type="hidden" id="txtstoredvalue" value="" />
                <input type="hidden" id="txtPwd" value="" />
                <input type="hidden" id="txtConnect" value="" />
                <input type="hidden" id="txtConnectTrn" value="" />
                <input type="hidden" id="txtMqServer" value="" />
                <input type="hidden" id="txtMainMenu" value="MENU1" />
                <input type="hidden" id="txtPageNum" />
                <input type="text" id="txtUser" value="" readonly="readonly" />
                <input type="hidden" id="txtTab" value="" readonly="readonly" />
                <span id="user-icon"></span>

            </span>
        </header>
        <section>
            <!-- <div id="mainPanel" onchange="navigator.virtualKeyboard.hide();"> !-->
            <div id="mainPanel">
                <table id="dataTable"></table>
				<table id="jsonTable"></table>
                <div id="results">
                    <span id="final_span" class="final"></span>
                    <span id="interim_span" class="interim"></span>
                </div>
            </div>
            <select name="txtSelect" id="txtSelect" onchange="getSelect()">
                <option value=""></option>
            </select>
        </section>
        <footer id="navPanel" class="Panel">
            <div id="btnPanel" class="Panel">
            </div>
        </footer>
    </main>
        <div class="confirm-panel" id="confirmpanel" onkeydown="tableKeyDown(this, event)">
            <input type="text" id="confirmtext" readonly="readonly"></input>
            <input type="text" id="confirminput"></input>
            <input type="text" id="txtyesaction" readonly="readonly" style="display:none"></input>
            <input type="text" id="txtnoaction" readonly="readonly" style="display:none"></input>
            <input type="text" id="txtcurraction" readonly="readonly" style="display:none" value=""></input>
            <p>
            <button id="yesbtn">Yes</button>
            <button id="nobtn">No</button>
            </p>
        </div>
        <div id='alertoverlay' class='alertoverlay'></div>
        <div id='alertbox' class='alertbox'>
            <div>
                <div id='alertboxhead' class='alertboxhead'></div>
                <div id='alertboxbody' class='alertboxbody'></div>
                <div id='alertboxfoot' class='alertboxfoot'></div>
            </div>
        </div>
        
        <div id='popupPanel' class='modal'>
           <div id='popupContent' class='modal-content'>
                <div id='inputPanel' class='panel'>
                    <H2 id='popupHeader' class='popupHeader'>Table</H2>
                    <span style="display:inline-flex">
                    <label for="popupref" style="display:inline-flex;width:auto; height:3%">Select: </label>
                    <input type="text" id="popupref" name="popupref" class="input" style="display:inline-flex;border:1px solid;padding:0;width:auto;height:3%;font-size:110%" onkeydown="popupInput(this, event)"></input>
                    </span>
                    <button style="float:right;display:inline-flex;width:auto; height:2em" onclick='popupClose()'>Close</button>
                </div>
                <div class="popupTableContainer">
                    <div id='popupTable' class='div-table'></div>
                    <div id="imageContainer">
                        <div id="gallery"></div>
                        <div class="Panel">
                            <button style="float:right;display:inline-flex;width:auto; height:2em" onclick='ocrImage()'>ocr</button>
                            <button style="float:right;display:inline-flex;width:auto; height:2em" onclick='uploadImage()'>Upload</button>
                            <button id="deleteImgBtn" style="float:right;display:inline-flex;width:auto;height:2em" onclick='deleteImage()'>Delete</button>
                            <button style="float:right;display:inline-flex;width:auto; height:2em" onclick="popupClose()">Close</button>
                            <img id="img-preview" style="width:150px;" alt=""></img>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="popupTextContainer">
            <div id="popupText" class="popupText"></div>
            <img id="popupImg" style="float:right;display:inline-flex;width:auto"></img>
        </div>
        <div id="popupMessageContainer">
            <div id="rdtmessage" class="ok"></div>
        </div>
        <div id="loadingContainer" class="modal">
            <div id="loadingmsg">please wait...</div>
        </div>

        <div id="iframeModal" class="modal">
            <div class="modal-content">
                <iframe id='printIframe' name='printIframe'></iframe>
                <button style="float:left;display:inline-flex;width:auto; height:2em" onclick="iframeClose()">Close</button>&nbsp&nbsp
                <button style="float:right;display:inline-flex;width:auto; height:2em" onclick="iframePrint()">Print</button>
            </div>
        </div>
        
        <div id="docPanel" style="width:50%"></div>
        <div id="alert"></div>
        <div id="file-link-container"></div>
        <div id="modalContainer"></div>
</body>
<script type="text/javascript">

// Main Program Processing      
// Initialises Current Screen Counter, Current RowId, Current ValidationId
var loadingIndicator = null;
var cs = 0;
var eol = 0;
var id = 0;
var idx = 0;
var screenCount = 0;
var firstRow = 0;
var lastRow = 0;
var lastTableRow = 0;
var currentRow = 0;
var prvRow = 0;
var keyCode = null;
var mouseCode = null;
var mouseX = null;
var mouseY = null;  
var cellFail = false;
var userColour = "";
var backgroundColour = "silver";
var boxColour = "gainsboro";
var buttonColour = "black";
var messageType = "alert";
//      var rdtStart = "2019-01-01 00:00:01"; 
var rdtStart = now();
var rdtEnd = now();
var keyDownTime = null;
var handKey = "Y";
var trys = 3;
var changeTranData = "";
// Transaction Main Table
var dataTable = "dataTable";
// Ajax URL Path
var ajaxPath = "rdtvims/";
// User-Settings Array
var userSettings = [];
var userStatus = "";
var userBlocked = "";
var userLevel = "3";
// Dynamic Button Array
var buttons = [];
// Transaction Property Arrays
var trnRowCount = [];
var trnName = [];
var trnPrefix = [];
var trnValidation = [];
var trnScreenOption = [];
var trnValue = [];
var trnMin = [];
var trnMax = [];
var trnBarcode = [];
var trnMand = [];
var trnHidden = [];
var trnPreprocess = [];
var inputRdt = "";
var inputChar = "";
var jsonObject = "";

// Speech Recognition
var final_transcript = '';
var recognizing = false;
var ignore_onend = false;
var start_timestamp;
var speech = false;
var fullScr = false;
var timeOut = 120000;
const timeoutObjects = {};

var lockInd = false;
var lockScreen = false;

var two_line = /\n\n/g;
var one_line = /\n/g;
var first_char = /\S/;

var elem = document.documentElement;

// Browser Version
var browserVersion = "";

let disableBlur = false;

// Global object declaration
const globalObject = {
    alertSounds: {
        audioFolder: './audio/',
        soundFiles: ['buzzer.mp3', 'ok.mp3']
    },
    externalJsScripts: ['fkeys.js']
};

globalObject.externalJsScripts.forEach((jsScript) => reloadJsScriptBySrc(jsScript));

if ("virtualKeyboard" in navigator) 
{
    navigator.virtualKeyboard.overlaysContent = true;
}

// Implement Trim function for ie8
if(!String.prototype.trim) 
{
    String.prototype.trim = function () 
    {
        return this.replace(/^\s+|\s+$/g,'');
    };
}

// User Icon -> Sign-on
const userIcon = document.querySelector("#user-icon");
userIcon.onclick = () => {
    changeTran("LOGON");
    document.querySelector("#txtUser").value = "";
}

// Initial Function
window.onload = function() 
{
    var browserVersion = detectIE();
//    setSelect();

// Preloads sound files declared on global object
    globalObject.alertSounds.soundFiles.forEach((soundFile) => 
    {
        preloadSound(globalObject.alertSounds.audioFolder + soundFile);
    });

// Hide Screen Elements
    document.getElementById("popupMessageContainer").style.display = "none";
    document.getElementById("confirmpanel").style.display = "none";
    document.getElementById("results").style.display = "none";
    document.getElementById("alertbox").style.display = "none";
    document.getElementById('iframeModal').style.display = "none";
    document.getElementById('loadingContainer').style.display = 'none';
//          if (browserVersion != false)
    if((navigator.userAgent.indexOf("MSIE") != -1 ))
    {
        document.getElementById("loadimagefile").style.visibility = "hidden";
    }
    else
    {
    }

    document.getElementById("txtUser").value = browserVersion;  
    const modal = document.getElementById('iframeModal');
    
// Initial Params
    var inputTran = "";
    var inputUser = "";
    var inputPwd = "";
    
    inputUser = "<?php echo $userId; ?>";
    inputPwd = "<?php echo $password; ?>";
    
    var href = (window.location.href).toLowerCase();
    
// look for initial RDT-Id
    var s = href.indexOf("id=");
    if (s > 0)
    {
        s = s+3;
        var e = href.indexOf("&",s);
        if (e < s)
            e = href.length;
        var l = e-s;
        inputRdt = href.substring(s,e);
    }
    
// look for initial User-Id
    var s = href.indexOf("user=");
    if (s > 0)
    {
        s = s+5;
        var e = href.indexOf("&",s);
        if (e < s)
            e = href.length;
        var l = e-s;
//        inputTran = href.substring(s,e);
        inputUser = href.substring(s,e);
    }
    
    var s = href.indexOf("password=");
    if (s > 0)
    {
        s = s+9;
        var e = href.indexOf("&",s);
        if (e < s)
            e = href.length;
        var l = e-s;
        inputPwd = href.substring(s,e);
    }
    
    var s = href.indexOf("function=");
    if (s > 0)
    {
        s = s+9;
        var e = href.indexOf("&",s);
        if (e < s)
            e = href.length;
        var l = e-s;
        inputTran = href.substring(s,e);
    }
    else
    {
        inputTran = "";
    }
    
//    if (document.getElementById("txtUser").value != null)
    if (inputUser != "")
    {
        if (inputUser != "")
        {
            var userId = inputUser;
            var password = inputPwd;
            var data = "user="+userId+"&password="+password;
            url = ajaxPath+"rdtphp/user.php"+
            "?function=userlogin&userid="+userId+"&password="+password+
            "&filter=";
            get(url).then(function(response) 
            {
                backgroundColour = "#C0C0C0";
                messageType = "alertsound";
                document.getElementById("txtUser").value = userId;
                userLoggedIn(response,inputTran);
                gotoHere();
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
        }
        else
        {
            document.getElementById("txtUser").value = "";
            changeTran("LOGON");
            gotoHere();
        }
    }
    else
    {
// First Sign-on
        document.getElementById("txtUser").value = "";
        changeTran("LOGON");
        gotoHere();
    }
}
/*
window.onunload = function()
{
    tabRemove(document.getElementById('txtUser').value);
}
*/

// Detect Refresh
window.onbeforeunload = function() 
{
    tabRemove(document.getElementById('txtUser').value);
/*
//  return "No";
    if (document.getElementById('txtTranType').value != document.getElementById('txtMainMenu').value)
    {
        changeTran(document.getElementById('txtMainMenu').value);
        return false;
    }
*/
}

window.onhashchange = function()
{
    gotoPrev();
}

// Key-Press Event
document.onkeydown = function(e) 
{
    var keycode=0;
    if (window.event)
    {
        keycode = window.event.keyCode;
    }   
    else if (e)
    {
        keycode = e.which;
    }
    keyCode = keycode;
    if ((keycode >= "112") && (keycode <= "120"))
    {
        if (window.event)
            window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
        else
            e.preventDefault ? e.preventDefault() : (e.returnValue = false);
    }
    if (keycode == 0 || keycode == 229)
    {
        return;
    }
        tableKeyDown(self,e);
        return;
};

document.onmousedown = function(e)
{
    mouseY = e.clientY;
    mouseX = e.clientX;
}

menuOption.addEventListener('input',function(e) {menuInputHandler(e.data)});

function manageTimeout(action, key, callback, duration) 
{
    if (action === "set") 
    {
        if (timeoutObjects[key]) 
        {
            clearTimeout(timeoutObjects[key]);
        }

        timeoutObjects[key] = setTimeout(() => 
        {
            callback(); // Execute the callback function
            delete timeoutObjects[key]; // Clean up after execution
        }, duration); // Duration in milliseconds

    } 
    else if (action === "clear") 
    {
        // Clear the timeout for the given key
        if (timeoutObjects[key]) 
        {
            clearTimeout(timeoutObjects[key]);
            delete timeoutObjects[key]; // Clean up
        }
    }
}

async function get(url, timeout = 120000, retry = 3) 
{
    const currentTran = document.getElementById("txtTranType").value;

    const controller = new AbortController();

    // Use the manageTimeout function to set the timeout
    manageTimeout("set", "fetchTimeout", () => 
    {
        controller.abort();
        getMessage("FAIL-Network Timed Out");
        changeTran(currentTran);
    }, timeout);

    loading("on");

    try 
    {
        const response = await fetch(url, { signal: controller.signal });
        // Clear the timeout when the fetch is successful
        manageTimeout("clear", "fetchTimeout");
        loading("off");
    
        if (!response.ok) 
        {
            getMessage('FAIL- status ' + response.status);
        }
        const result = await response.text();
        return result;
    } 
    catch (error) 
    {
        // Clear timeout if it was still set
        manageTimeout("clear", "fetchTimeout");

        if (error.name === 'AbortError') 
        {
            if (retry > 0) 
            {
                // Retry the fetch request
                return get(url, timeout, retry - 1);
            } 
            else 
            {
                getMessage("FAIL-Network Timed Out");
            }
        } 
        else 
        {
            getMessage("FAIL-" + error);
        }
    }
}

async function post(url, data, header = 'application/json', timeout = 120000, retry = 3) 
{
    const currentTran = document.getElementById("txtTranType").value;

    const controller = new AbortController();
    manageTimeout("set", "postTimeout", () => 
    {
        controller.abort();
        getMessage("FAIL-Network Timed Out");
        changeTran(currentTran);
    }, timeout);
    
    loading("on");

    const headers = new Headers();
    if (header === 'file') {
        headers.delete('Content-Type');
    } else {
        headers.set('Content-Type', header);
    }

    const options = {
        method: 'POST',
        headers: headers,
        body: data,
        signal: controller.signal // Move signal here
    };

    try 
    {
        const response = await fetch(url, options); // Await fetch
        manageTimeout("clear", "postTimeout");
        loading("off");

        if (!response.ok) 
        {
            getMessage('FAIL- status ' + response.status);
        }

        const result = await response.text();
        return result;
    } 
    catch (error) 
    {
        manageTimeout("clear", "postTimeout");
        loading("off");

        if (error.name === 'AbortError') 
        {
            if (retry > 0) 
            {
//                console.log("Retry " + retry);
                return await post(url, data, header, timeout, retry - 1); // Await recursive call
            } 
            else 
            {
                getMessage("FAIL-Network Timed Out");
            }
        } 
        else 
        {
            getMessage("FAIL-" + error.message); // Log the error message
        }
    }
}

function preloadSound(audioSrc) {
    // Creates audio object
    const audio = new Audio();
    audio.src = audioSrc;
    audio.preload = 'auto';
    audio.load();
}

// Loads External JS script declared on the global object
function reloadJsScriptBySrc(scriptSrc, elementSelector = 'head') {
    // Selects the parent element
    const parentElement = document.querySelector(elementSelector);

    // Creates new script element
    const newScriptElement = document.createElement('script');
    const uniqueTag = Date.now();
    newScriptElement.src = `${scriptSrc}?v=${uniqueTag}`;
    newScriptElement.defer = true;

    // Appends new script to parent element
    parentElement.append(newScriptElement);
}

// toggle slider Message
function toggleSlider(el)
{
    var isOpen = el.classList.contains('slideIn');
    el.setAttribute('class', isOpen ? 'slideOut' : 'slideIn');
}

// Current TimeStamp
function now()
{
    var today = new Date();
    var yy = (today.getFullYear()<10?'0':'') + today.getFullYear();
    var mm = (today.getMonth()+1);
    if (mm < 10)
        mm = '0'+mm;
    var dd = (today.getDate()<10?'0':'') + today.getDate();
    var h = (today.getHours()<10?'0':'') + today.getHours();
    var m = (today.getMinutes()<10?'0':'') + today.getMinutes();
    var s = (today.getSeconds()<10?'0':'') + today.getSeconds();
    var date = yy+"-"+mm+"-"+dd;
    var time = h+"colon"+m+"colon"+s;
    var dateTime = date+' '+time;
//  alert("now-"+dateTime);
    return dateTime;
}

function tabAdd(currentUser)
{
    const currentUrl = window.location.href;
    let tabUrl = "";
    let tabCount = [];
    let tabFound = false;
    
    if (localStorage.getItem('url'))
        tabUrl = localStorage.getItem('url');
    if ( localStorage.getItem('count'))
    {
            tabCount = JSON.parse(localStorage.getItem('count'));
    }
    if (tabCount.length > 5)
        tabCount.length = 0;
    if (tabCount.length > 0)
    {
        for (i=0;i<tabCount.length;i++)
        {
            if (tabCount[i] == "")
            {
                tabCount[i] = i+1;
                document.getElementById("txtTab").value = i+1;
                tabFound = true;
                break;
            }
        }
    }
    if (tabFound == false)
    {
        i = tabCount.length;
        tabCount.push(i+1);
        document.getElementById("txtTab").value = i+1;
        localStorage.clear();
    }
    
    localStorage.setItem('url', currentUrl);
    localStorage.setItem('count', JSON.stringify(tabCount));
}

function tabRemove(currentUser)
{
    let tabUrl = "";
    let tabCount = [];
    
    if (localStorage.getItem('url'))
        tabUrl = localStorage.getItem('url');
    if ( localStorage.getItem('count'))
    {
        tabCount = JSON.parse(localStorage.getItem('count'));
    }
    
    if (tabCount.length > 0)
    {
        for (let i = 0; i < tabCount.length; i++)
        {
            if (tabCount[i] == document.getElementById('txtTab').value)
            {
                tabCount[i] = "";
                break;
            }
        }
    }
    else
    {
        localStorage.Clear();
        tabCount.push("");
    } 
    localStorage.setItem('url', tabUrl);
    localStorage.setItem('count', JSON.stringify(tabCount));
}

function popupOpen(func,filter)
{
	popupTextHide();
    if (func == "IMAGE")
    {
        popupImage(func,filter);
        return false;
    }
    if (filter.indexOf("=") <=0)
        filter = "reference="+filter;
    try
    {
        url = ajaxPath+"rdtphp/tables.php"+
                "?function="+func+
                "&connection="+
                "&host="+userSettings[0].dbhost+
                "&user="+userSettings[0].dbuser+
                "&pword="+userSettings[0].dbpwd+
                "&dbase="+userSettings[0].dbase+
                "&mqserver="+userSettings[0].mqserver+
                "&filter="+filter;
    }
    catch(e)
    {
        alert("FAIL-AJAX ERROR");
    }
    
    get(url).then(function(response)
    {
        loading("off");
        if (response == undefined)
        {
            alert("Invalid Response");
        }
        else if (response.substr(0,2)=="FA")
        {
            alert(response);
        }
        else
        {
            document.getElementById('popupref').value = "";
            document.getElementById('popupPanel').style.display = "block";
            document.getElementById("popupHeader").innerHTML=func;
            document.getElementById('imageContainer').style.display = "none";
            document.getElementById('popupTable').style.display = "block";
            document.getElementById('inputPanel').style.display = "block";
            CreateTableFromJSON(response,"popupTable");
        }
        return false;
    }, 
    function(error) 
    {
        getMessage("FAIL-"+error);
    })
}

function popupInput(key,e)
{
    var keycode;
    if (window.event)
    {
        keycode = window.event.keyCode;
    }   
    else if (e)
    {
        keycode = e.which;
    }
    keyCode = keycode;
    if (keycode == "13")
    {
        popupOpen(document.getElementById("popupHeader").innerHTML,document.getElementById("popupref").value);
        return;
    }
}

function popupClose()
{
    document.getElementById('popupPanel').style.display = "none";
}

// display list of images
function popupImage(func,filter)
{
    if (filter.length == 0)
    {
        filter = document.getElementById('txtUser').value;
    }
    let url = ajaxPath+"rdtphp/photogallery.php"+
            "?function="+func+
            "&folder="+filter+
            "&connection="+
            "&host="+userSettings[0].dbhost+
            "&user="+userSettings[0].dbuser+
            "&pword="+userSettings[0].dbpwd+
            "&dbase="+userSettings[0].dbase+
            "&mqserver="+userSettings[0].mqserver;

    get(url).then(function(response) 
    {
        loading("off");
        if (response == undefined)
        {
            alert("Invalid Response");
        }
        else if (response.substr(0,2)=="FA")
        {
            alert(response);
        }
        else
        {
            var gallery = document.getElementById('gallery');
            document.getElementById('popupref').value = filter;
            document.getElementById('popupPanel').style.display = "block";
            document.getElementById("popupHeader").innerHTML='images';
            document.getElementById('popupTable').style.display = "none";
            document.getElementById('inputPanel').style.display = "none";
            document.getElementById('imageContainer').style.display = "block";
            gallery.innerHTML = '';
            photos = JSON.parse(response.substr(7));
            
// Loop through the photo URLs and create thumbnail elements
            photos.forEach(function(photoUrl)
            {
                var thumbnail = document.createElement('img');
                thumbnail.classList.add('thumbnail');
                
// Store selected Image Url.
                thumbnail.onclick = function(e)
                {
                    var images = document.getElementsByTagName('img');
                    for (var i = 0; i < images.length; i++) 
                    {
                        images[i].classList.remove('highlight');
                    }
//                    alert("Image:"+photoUrl);
                    document.getElementById("txtstoredvalue").value = photoUrl;
                    thumbnail.classList.add('highlight');
                    handleImageClick(photoUrl);
                }
                thumbnail.src = photoUrl;
                gallery.appendChild(thumbnail);
            });
        }
        return false;
    }, 
    function(error) 
    {
        getMessage("FAIL-"+error);
    });
}

function handleImageClick(photoUrl) {}

function popupMessageShow(text)
{
    const popup = document.getElementById('popupMessageContainer');
    const message = document.getElementById('rdtmessage');
    const mainPanel = document.getElementById('mainPanel');
    const panelWidth = mainPanel.offsetWidth;
    popup.style.width = `${panelWidth}px`;
    
    if (text.substr(0,2) == "FA")
    {
        message.classList.remove('ok');
        message.classList.add('error');
        text = text.substr(5);
    }
    else if(text.substr(0,2) == "OK")
    {
        message.classList.remove('error');
        message.classList.add('ok');
        text = text.substr(5);
    }

    if (text != "" && text != null && text != undefined)
    {
        message.innerHTML = text;
        if (message.scrollWidth > message.clientWidth) 
        {
            let rdtMessage = "<marquee>"+text+"</marquee>";
// Create a marquee element
            message.innerHTML = rdtMessage;
        } 
        else 
        {
            let rdtMessage = "<div>"+text+"</div>";
// Set it as normal text in a div
            message.innerHTML = rdtMessage;
        }
    }

    popup.style.position = 'absolute';
    const posElement = document.getElementById('popupTextContainer');
    if (!posElement)
    {
        const posElement = document.getElementById('navPanel');
    }
    if (posElement) 
    {
        // Position the popup above the navPanel
        const posTop = posElement.getBoundingClientRect().top;
        const posHeight = posElement.offsetHeight;
        popup.style.bottom  = (posElement.offsetHeight+40) + 'px';
    } 
    else 
    {
        popup.style.bottom = '20px'; // Fallback position if navPanel doesn't exist
    }
//    popup.style.left = posElement.offsetLeft + 'px';
//    popup.style.width = posElement.offsetWidth + 'px';
    popup.style.display = 'flex';

    popup.addEventListener('mouseover', function() 
	{
        popup.style.opacity = '0'; // Hides the element
    });

    popup.addEventListener('mouseout', function() 
	{
        popup.style.opacity = '1'; // Shows the element again
    });

    manageTimeout("set", "popupTimeout", () => 
    {
        popup.style.display = 'none';
    }, 100000);
}

function popupTextShow(text)
{
    document.getElementById('popupImg').src = '';
    const popup = document.getElementById('popupTextContainer');
    const posElement = document.getElementById('navPanel');
    document.getElementById('popupText').innerHTML=text;
    popup.style.position = 'absolute';
    popup.style.bottom = posElement.offsetHeight + 'px'; // Position above the footer
    popup.style.left = posElement.offsetLeft + 'px';
    popup.style.width = posElement.offsetWidth + 'px';
    popup.style.display = 'flex';
    
	popup.addEventListener('mouseover', function() 
	{
        popup.style.opacity = '0'; // Hides the element
    });

    popup.addEventListener('mouseout', function() 
	{
        popup.style.opacity = '1'; // Shows the element again
    });
	
    setTimeout(() => 
    {
        popup.style.display = 'none';
    }, 100000);
	
}
function popupTextHide()
{
    const popup = document.getElementById('popupTextContainer');
    popup.style.display = 'none';
}
// Background colour
function getScreenColour(colour)
{
    colour = colour.toLowerCase();
    document.getElementById("header").style.backgroundColor = colour;
    document.getElementById("dataTable").style.backgroundColor = colour;
    document.getElementById("navPanel").style.backgroundColor = colour;
    document.getElementById("btnPanel").style.backgroundColor = colour;
    document.getElementById("msgPanel").style.backgroundColor = colour;
    var box = 'lightgrey';
    var button = 'black';
    switch(colour)
    {
        case "red":
            box = 'lightsalmon';
            button = 'darkred';
            break;
        case "green":
            box = 'lightgreen';
            button = 'darkgreen';
            break;
        case "blue":
            box = 'aqua';
            button = 'darkblue';
            document.getElementById("msgPanel").style.color = 'white';
            break;
        case "steelblue":
            box = 'aqua';
            button = 'darkblue';
            break;
        case "silver":
            // box = 'lightgrey';
            box = '#2C1434';
            button = 'black';
            document.getElementById("msgPanel").style.color = 'black';
            break;
        case "yellow":
            box = 'lemonchiffon';
            button = 'darkblue';
            document.getElementById("msgPanel").style.color = 'black';
            break;
        case "white":
            box = '#F0F3F4';
            button = 'darkblue';
            document.getElementById("msgPanel").style.color = 'black';
            break;
        default:
            box = 'lightgrey';
            button = 'black';
            document.getElementById("msgPanel").style.color = 'black';
    } 
    return box+","+button;
}

function menuInputHandler(e)
{
    if (e >= "1" && e <= "9")
    {
        r = parseInt(e);
        if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
        {
            if (document.getElementById("txtTranType").value.substr(0,4) == "MENU")
                currentTran = trnName[r];
            else if (document.getElementById("txtTranType").value.substr(0,6) == "SELECT")
            {
                currentTran = trnName[r+1];
            }
            else if (document.getElementById("txtTranType").value.substr(0,8) == "DOCUMENT")
            {
                showDocument(trnValue[r+1]);
                return false;
            }
        }
        document.getElementById("menuOption").value = "";
        changeTran(currentTran);
        return false;
    }       
}

// upload file to server
function uploadImage(folder)
{
// get image folder
    if (document.getElementById('popupref').value.length>0)
    {
        folder = document.getElementById('popupref').value;
    }
// Create an input element dynamically
    var input = document.createElement("input");
    input.type = "file";

// Listen for the change event on the input element
    input.addEventListener("change", async function()
    {
// Send the FormData object to the server using AJAX
        var formData = new FormData();
// Get selected Image
        var file = input.files[0];
// Get URI of image
        const dataUri = await dataUriFromFormField(file);
// Create Image Element
        const imgEl = document.createElement('img');
// Add Event-listener for Image Element
        imgEl.addEventListener('load', function() 
        {
// Resize the Image
            const resizedDataUri = resizeImage(imgEl, 1200, 0.8);
// Preview the Resized Image
            document.getElementById('img-preview').style.display = "block";
            document.getElementById('img-preview').src = resizedDataUri;
// Add Image to formData & send to Server
            fetch(resizedDataUri)
            .then(function(response) 
            {
                return response.blob();
            })
            .then(function(blob)
            {
                var formData = new FormData();
                formData.append('file', blob, file.name);
                try
                {
                    var url = ajaxPath+"rdtphp/uploadfile.php?function=uploadimg";
                    if (folder != undefined)
                        url = url+"&folder="+folder+"/";
                    var data = formData;
                    post(url,data,'file').then(function(response)
                    {
                        document.getElementById('img-preview').style.display = "none";
                        popupImage("IMAGE",folder);
                        rowValidated(response);
                    }, 
                    function(error) 
                    {
                        getMessage("FAIL-"+error);
                    })
                    return;
                }
                catch(e)
                {
                    alert("FAIL-Image Upload Error");
                }
            });
        });
// Add Image URI to Image Element & trigger event-listener
        imgEl.src = dataUri;
    });

// Trigger a click event on the input element
    input.click();
}

function dataUriFromFormField (field) 
{
  return new Promise(function(resolve) 
  {
    const reader = new FileReader();
    reader.addEventListener('load', function() 
    {
        resolve(reader.result);
    }); 
    reader.readAsDataURL(field);
  });
}

function resizeImage (imgEl, width, quality=0.8) 
{
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

  const aspect = imgEl.width / imgEl.height;

  canvas.width = width;
  canvas.height = width / aspect;

  ctx.drawImage(imgEl, 0, 0, canvas.width, canvas.height);
  return canvas.toDataURL('image/jpeg', quality);
}

function deleteImage(folder)
{
// Send the FormData object to the server using AJAX
    try
    {
        var url = ajaxPath+"rdtphp/uploadfile.php?function=delete&file="+document.getElementById('txtstoredvalue').value;
        folder = "";
        if (document.getElementById('popupref').value.length > 0)
        {
            folder = document.getElementById('popupref').value;
        }
        get(url).then(function(response)
        {
            popupImage("IMAGE",folder);
            rowValidated(response);
        }, 
        function(error) 
        {
            getMessage("FAIL-"+error);
        })
        return;
    }
    catch(e)
    {
        alert("FAIL-Image Upload Error");
    }
}

// upload file to server
function ocrImage(folder)
{
// get image folder
    if (document.getElementById('popupref').value.length>0)
    {
        folder = document.getElementById('popupref').value;
    }
// Create an input element dynamically
    var input = document.createElement("input");
    input.type = "file";

// Listen for the change event on the input element
    input.addEventListener("change", async function()
    {
        loading('on');
// Get selected Image
        const file = input.files[0];
        
        if (file) 
        {
            const { data: { text } } = await Tesseract.recognize(file);
            popupTextShow(text);
            const reader = new FileReader();
            reader.onload = function(e) 
            {
                const img = new Image();
                img.onload = function() 
                {
                    const canvas = document.createElement("canvas");
                    const context = canvas.getContext("2d");
                    const size = 160; // Desired dimensions
                    canvas.width = size;
                    canvas.height = size;
                    context.drawImage(img, 0, 0, size, size);
                    const dataurl = canvas.toDataURL(file.type);
                    document.getElementById('popupImg').src = dataurl;
                    loading('off');
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
// Trigger a click event on the input element
    input.click();
}

function handler() 
{
  console.log("row left!");
}

function getRandomInt(min, max) 
{
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Populate Select Options
function setSelect(selStr)
{
    var select = document.getElementById("txtSelect");
    try
    {
        var selJson = JSON.parse(selStr);
    }
    catch(e)
    {
        var selJson = [
        {value: "xxxx", text: "text 1"}
        ];
    }
    var i, L = select.options.length - 1;
    for(i = L; i >= 0; i--) 
    {
        select.remove(i);
    }
    option = document.createElement("option");
    option.setAttribute('value', "select");
    option.appendChild(document.createTextNode("--Select--"));
    select.appendChild(option);
    for (var i=0 ; i < selJson.length; i++) 
    {
        option = document.createElement("option");
        option.setAttribute('value', selJson[i].value);
        option.appendChild(document.createTextNode(selJson[i].text));
        if (selJson[i].colour)
        {
            option.style.backgroundColor = selJson[i].colour;
        }
        select.appendChild(option);
    }
}

function getSelect()
{
    const dataTableElement = document.getElementById('dataTable');
    var table = document.getElementById(dataTable); 
    var selectBox = document.getElementById("txtSelect");
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;
    var selectedText = selectBox.options[selectBox.selectedIndex].text;
    document.getElementById("txtSelect").selectedIndex = 0;
// if select.value has ':' split into value & text - select.value is in the format screen_field_name:value,screen_field_name:value,...
    txtArray = selectedValue.split(",");
    var txtFocus = "";
    for (var r=0;r<txtArray.length;r++)
    {
        txtResult = txtArray[r];
// populate named rows
        if (txtResult.split(":")[0])
        {
            for (var i = 1; i < table.rows.length; i++)
            {
                if (trnName[i] == txtResult.split(":")[0])
                {
                    document.getElementById(''+i).value = txtResult.split(":")[1];
                    trnValue[i] = txtResult.split(":")[1];
                    if (txtFocus == "")
                    {
                        txtFocus = i;
                    }
                }
                if (trnName[i]+"content" == txtResult.split(":")[0])
                {
                    document.getElementById(''+i).placeholder = txtResult.split(":")[1];
                    document.getElementById(''+i).value = "";
                    trnValue[i] = "";
                    if (txtFocus == "")
                    {
                        txtFocus = i;
                    }
                }
                if (trnName[i]+"skipap" == txtResult.split(":")[0])
                {
                    lockScreen = false;
                    loading('off');
                    var skipTo = trnName[i];
                    id = i;
                    rowValidated("DATA:"+skipTo+":"+txtResult.split(":")[1]+"::skipap"+skipTo);
                    return false;
                }
            }
            if (txtFocus != "")
            {
                i = txtFocus;
                document.getElementById(''+i).focus();
                gotoHere();
            }
        }
        else
        {
            for (var i = 1; i < table.rows.length; i++)
            {
                if (trnName[i] == selectedValue)
                {
                    document.getElementById(''+i).value = selectedText;
                    trnValue[i] = selectedText;     
                    document.getElementById(''+i).focus();
                    gotoHere();
                    break;
                }
                if (trnName[i]+"content" == selectedValue)
                {
                    document.getElementById(''+i).placeholder = selectedText;
                    document.getElementById(''+i).value = "";
                    trnValue[i] = "";
                    document.getElementById(''+i).focus();
                    gotoHere();
                    break;
                }
                if (trnName[i]+"skipap" == selectedValue)
                {
                    lockScreen = false;
                    loading('off');
                    var skipTo = trnName[i];
                    id = i;
                    rowValidated("DATA:"+skipTo+":"+selectedText+"::skipap"+skipTo);
                    return false;
                }
            }
        }
    }
}

function hideSelect()
{
    document.getElementById("txtSelect").style.visibility = "hidden";
 // Recursive Call to perform next Cell Validation instruction
    try
    {
        var validate = trnValidation[row];
    }
    catch (e)
    {
        validate = "";
    }
    idx = idx+1;
    if (document.getElementById("txtcurraction").value != "")
    {
        rowValidated("OK  -showSelect");
    }
    return false;   
}

function showSelect()
{
    document.getElementById("txtSelect").style.visibility = "visible";
// Recursive Call to perform next Cell Validation instruction
    try
    {
        var validate = trnValidation[row];
    }
    catch (e)
    {
        validate = "";
    }
    idx = idx+1;
    if (document.getElementById("txtcurraction").value != "")
    {
        rowValidated("OK  -showSelect");
    }
    return false;
}

function setDataList(selStr) 
{
    const elem = selStr.split(":")[0];
    const selJson = selStr.substr(elem.length+1);
    const table = document.getElementById(dataTable); 
    try
    {
        var selArray = JSON.parse(selJson);
    }
    catch(e)
    {
        var selArray = [
        ];
    }
    if (selArray.length>0)
    {
        for (var i = 1; i < table.rows.length; i++)
        {
            if (trnName[i] == elem)
            {
                container = document.getElementById(''+i);
                break;
            }
        }
        if (container)
        {
// Remove any existing datalist child elements
            while (container.firstChild) 
            {
                container.removeChild(container.firstChild);
            }
            container.addEventListener('focus', () => 
            {
                container.value = '';
            });
// Create the datalist
            const dataList = document.createElement('datalist');
            dataList.setAttribute('id', 'DL'+i);
            dataList.style.fontSize = '16px';
            dataList.style.color = '#333';
            dataList.style.backgroundColor = 'red';
            dataList.style.border = '2px solid #ccc';
            dataList.style.borderRadius = '8px';
            dataList.style.padding = '8px';
            dataList.style.maxHeight = '10px';
            dataList.style.overflowY = 'auto';
            dataList.addEventListener('focus', () => 
            {
                container.value = '';
            });
            container.setAttribute('list', 'DL'+i);
            dataList.innerHTML = '';
// Add the options to the datalist
            for (var i = 0; i < selArray.length; i++)
            {
                var option = document.createElement('option');
                option.value = selArray[i].value; // This is what will be submitted
                option.textContent = selArray[i].text; // This is what will be displayed
                dataList.appendChild(option);
            }
// Append the container to the main container
            container.appendChild(dataList);
        }
    }
}

// disable / enable button
function togglebutton(button,onoff)
{
    if(onoff == 'on')
        document.getElementById(button).disabled=false;
    else
        document.getElementById(button).disabled=true;
    return;
}

// table KeyDown - Trap Keyboard events
function tableKeyDown(element,e)
{
    var table = document.getElementById(dataTable);
    var keycode=0;
    if (window.event)
    {
        keycode = window.event.keyCode;
    }   
    else if (e)
    {
        keycode = e.which;
    }
    keyCode = keycode;
// Is "loading" displayed?
    if (document.getElementById('loadingContainer').style.display != "none")
    {
        if (window.event)
            window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
        else
            e.preventDefault ? e.preventDefault() : (e.returnValue = false);
        return false;
    }
// If Message Panel displayed only allow Enter
    if (document.getElementById('alertbox').style.display != "none")
    {
        if (keycode != "13")
        {
            if (window.event)
                window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
            else
                e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            cellFail = true;
            return false;
        }
    }
// is confirm panel displayed?
    if (document.getElementById('confirmpanel').style.display != "none")
    {
        if (document.getElementById('confirminput').style.display != "none")
        {
            document.getElementById('confirminput').focus();
            if ((keycode == "13"))
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                confirmConfirm(row,"yes",document.getElementById('txtyesaction').value);
            }
            else if ((keycode == "27"))
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                confirmConfirm(row,"no",document.getElementById('txtnoaction').value);
            }
        }
        else
        {
            if ((keycode == "112") || (keycode == "89"))
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                confirmConfirm(row,"yes",document.getElementById('txtyesaction').value);
            }
            else if ((keycode == "113") || (keycode == "78"))
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                confirmConfirm(row,"no",document.getElementById('txtnoaction').value);
            }
            else
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            }
        }
        return false;
    }
// Menu Screen Processing
    else if ((document.getElementById("txtTranType").value.substr(0,4) == "MENU") || (document.getElementById("txtTranType").value.substr(0,6) == "SELECT") || (document.getElementById("txtTranType").value.substr(0,6) == "DOCUMENT"))
    {
        var r = 0;
        var currentTran = "";
// Standard Number Keys
        if((keycode>="48") && (keycode<="57"))
        {
            if (window.event)
                window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
            else
                e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            try
            {
                r = (parseInt(keycode)-48);
                if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
                {
                    currentTran = trnName[r];
                }
                changeTran(currentTran);
                return false;
            }
            catch(e)
            {
                try
                {
                    changeTran(currentTran);
                    return false;
                }
                catch(e)
                {
                    currentTran = document.getElementById("txtMainMenu").value;
                    changeTran("currentTran");
                    return false;
                }
            }
            return false;
        }
// Numeric Keypad
        else if((keycode>="96") && (keycode<="105"))
        {
            if (window.event)
                window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
            else
                e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            try
            {
                r = (parseInt(keycode)-96);
                if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
                {
                    currentTran = trnName[r];
                }
                changeTran(currentTran);
                return false;
            }
            catch(e)
            {
                try
                {
                    changeTran(currentTran);
                    return false;
                }
                catch(e)
                {
                    currentTran = document.getElementById("txtMainMenu").value;
                    changeTran("currentTran");
                    return false;
                }
            }
            return false;
        }
// F3
        else if ((keycode == "27") || (keycode == "114"))
        {
            if (window.event)
                window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
            else
                e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            if (document.getElementById("txtTranType").value != document.getElementById("txtMainMenu").value)
                var currentTran = document.getElementById("txtMainMenu").value;
            else
            {
                tabRemove(document.getElementById('txtUser').value);
                currentTran = "LOGON";
            }
            changeTran(currentTran);
            return false;
        }
    }
// Active Function Keys for this Transaction
    else if ((keycode >= "112") && (keycode <= "122"))
    {
        if (window.event)
            window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
        else
            e.preventDefault ? e.preventDefault() : (e.returnValue = false);
// Check if Function Key is active for this Transactiobn (in Buttons Array)
        var buttonFound = false;
        for(var i = 0; i < buttons.length; i++)
        {
            if (buttons[i].altkey == keycode)
            {
                buttonFound = true;
                buttonClick(buttons[i].name);
                break;
            }
        }
// If no Active function Key - Try Generic Action
        if (buttonFound == false)
        {
// F1
            if (keycode == "112")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                gotoPrev();
            }
// F2
            else if (keycode == "113")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                gotoNext();
            }
// F3
            else if ((keycode == "27") || (keycode == "114"))
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                var currentTran = document.getElementById("txtMainMenu").value;
                changeTran(currentTran);
                return false;
            }
            else if (keycode == "115")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F4Action();
            }
            else if (keycode == "116")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F5Action();
            }
            else if (keycode == "117")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F6Action();
            }
            else if (keycode == "118")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F7Action();
            }
            else if (keycode == "119")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F8Action();
            }
            else if (keycode == "120")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F9Action();
            }
            else if (keycode == "121")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F10Action();
            }
            else if (keycode == "122")
            {
                if (window.event)
                    window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                else
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                F11Action();
            }
        }
    }
}

// Ajax Call to Get Transaction Data & build RDT screen 
function ajaxGetScreen(transactionType,screenData)
{
    var tranDef = "trandef";
    try
    {
        tranDef=userSettings[0].trandef;
    }
    catch(e)
    {
        tranDef = "trandef";
    }
    try
    {
        var url = ajaxPath+"rdtphp/getcolumns.php"+
            "?function=row"+
/*
            "&connection="+document.getElementById("txtConnect").value+
            "&host="+userSettings[0].dbhost+
            "&user="+userSettings[0].dbuser+
            "&pword="+userSettings[0].dbpwd+
            "&dbase="+userSettings[0].dbase+
*/
            "&company="+document.getElementById("txtCompany").innerHTML+
            "&trantype="+tranDef+"/"+transactionType;
    }
    catch(e)
    {
        var url = ajaxPath+"rdtphp/getcolumns.php"+
            "?function=row"+
/*
            "&connection="+document.getElementById("txtConnect").value+
*/
            "&company="+document.getElementById("txtCompany").innerHTML+
            "&trantype="+tranDef+"/"+transactionType;
    }

    get(url).then(function(response) 
    {
        buildScreen(response,screenData,transactionType);
    }, 
    function(error) 
    {
        getMessage("FAIL-"+error);
    })
    return;
}


// Ajax Call to Get Transaction Buttons
function ajaxGetButtons(transactionType,screenData)
{
    var tranDef = "trandef";
    try
    {
        tranDef=userSettings[0].trandef;
    }
    catch(e)
    {
        var tranDef = "trandef";
    }
    var url = ajaxPath+"rdtphp/getcolumns.php"+
        "?function=button"+
        "&connection="+
        "&trantype="+tranDef+"/"+transactionType;
    if (document.getElementById("txtTranType").value.substr(0,6) != "SELECT")
    {
/*
        get(url).then(function(response) 
        {
            buildButtons(response);
        }, 
        function(error) 
        {
            getMessage("FAIL-"+error);
        })
*/
        fetch(url)
        .then(response => 
        {
            if (response.ok) 
            {
                return response.text();
            }
            exit('FAIL-Network response was not ok.');
        })
        .then(data => 
        {
            buildButtons(data);
        });
    }
}
// Build Screen from JSON
function buildScreen(strJSON, screenData,currentTran)
{
    document.getElementById('header-block').style.backgroundColor='#3A1D49';
    document.getElementById('navPanel').style.backgroundColor='#3A1D49';
    deleteRow(dataTable);
    keyDownTime = null;
    idx = 0;
// Set default Transaction Connection Path
    document.getElementById("txtConnectTrn").value = document.getElementById("txtConnect").value;
    firstRow = 0;
    lastRow = 0;
    // Check for Valid Screen Definition
     if (strJSON == undefined)
        return;
    if (strJSON == "[]")
        return;
    if ((strJSON.substr(0,2)=="FA") && (strJSON.substr(4,1)=="-"))
    {
        alert(strJSON);
    }
    try
    {
        var objJSON = eval("(function(){return " + strJSON + ";})()");
    }
    catch(e)
    {
        getMessage("FAIL-Transaction Error -"+strJSON,'alert');
    }
// Get User Status Value(s)
    var userStatus = "";
    try
    {
        userStatus = userSettings[0].status;
    }
    catch (e)
    {
        userStatus = "";
    }
// Get Count of Elements
    var triggerIdx = 0;
    var i=0;
    for (var x in objJSON)
    {
        if(objJSON.hasOwnProperty(x))
        {
            var screenStatus = "";
// Get Screen Status Level
            if (objJSON[x].status != undefined)
            {
                try
                {
                    screenStatus = objJSON[x].status;
                }
                catch (e)
                {
                    screenStatus = "";
                }
            }
// Hide options that are not allowed.
            var s = userStatus.indexOf(screenStatus);
            if ((userStatus != "") && (s == -1))
            {
                s = userStatus.indexOf(objJSON[x].name);
                if (s == -1)
                {
                    objJSON[x].screenoption = "X";
                }
            }
            s = userBlocked.indexOf(objJSON[x].name);
            if (s != -1)
            {
                objJSON[x].screenoption = "X";
            }
                addRow(dataTable,objJSON[x]);
// If transaction has a Connect Path - populate txtConnectTrn
            if (objJSON[x].path != undefined)
            {
                try
                {
                    screenStatus = objJSON[x].path;
                }
                catch (e)
                {
                    screenStatus = "";
                }
            }
            if ((screenStatus != null) && (screenStatus != ""))
            {
                if (screenStatus.substr(0,4)=="http")
                    document.getElementById("txtConnectTrn").value = screenStatus;
                else if(screenStatus.substr(0,1)==":")
                {
                    document.getElementById("txtConnectTrn").value=document.getElementById("txtConnectTrn").value.replace(":8081/vantec/",screenStatus);
                }
            }
// Auto Run Validation Command (screenoption='T' & validation <> '')
            if ((objJSON[x].screenoption.substr(cs,1) =="T") && (objJSON[x].validation != ""))
            {
                triggerIdx = parseInt(x);
            }
// Screen Colour scheme
            if (userColour != "")
            {
                backgroundColour = userColour;
            }
            else if ((objJSON[x].name == "colour") && (objJSON[x].validation != ""))
            {
                backgroundColour = objJSON[x].validation;
            }   
// Screen Message Type
            if ((objJSON[x].name == "message") && (objJSON[x].validation != ""))
            {
                messageType = objJSON[x].validation;
            }           
            i++;
        }
    }
    var colour = "silver";
    boxColour = colour.split(",") [0];
    buttonColour = colour.split(",") [1];
    
    if ((currentTran.substr(0,4) == "MENU") || (currentTran.substr(0,6) == "SELECT") || (currentTran.substr(0,8) == "DOCUMENT"))
    {
        document.getElementById("txtPageNum").focus();
        errorMsg = "";
    }
    
    ajaxGetButtons(currentTran,screenData);
    
    cellFail = true;
    document.getElementById("txtPageNum").value = 1;
    cs = 0;
    gotoHere(screenData);
// Auto Run Validation Command (screenoption='T' & validation <> '')
    if (triggerIdx > 0)
    {
        document.getElementById("txtcurraction").value = objJSON[triggerIdx].validation;
        cellValidation(dataTable,triggerIdx);
    }    
}

// Add Row to Dynamic Table
function addRow(tableId,obj) 
{
    var table = document.getElementById(tableId);
// Table Header
//  if (x == 0)
    if (table.rows.length == 0)
    {
        var hrow = table.insertRow(0);
    }
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
// Display or Hide Row based on 'screenoption' parameter
    if ((obj.screenoption.substr(cs,1)=="H") || (obj.screenoption.substr(cs,1)=="T"))
    {
        row.style.display = "none";
    }
    else if (obj.screenoption.substr(cs,1)=="X")
    {
        row.style.display = "none";
    }
    else
    {
        row.style.display= "block";
    }
    var cell1 = row.insertCell(0);
    cell1.className = "td1";
    cell1.id = "td1"+rowCount;
    const td1Text = document.createElement("SPAN");
    td1Text.className = "td1text";
    td1Text.id = 'td1t'+rowCount;
//    cell1.style.background = "transparent";
    if ((obj.label == ".") || (obj.label == false))
        td1Text.innerHTML = '';
    else
        td1Text.innerHTML = obj.label;
    cell1.appendChild(td1Text);
        
// Tool-Tip - Used to display value of element2 when cell1 is clicked.
    const ttBox = document.createElement("DIV");
    const ttText = document.createElement("SPAN");
    ttBox.id = 'tt'+rowCount;
    ttText.id = 'ttt'+rowCount;
    ttBox.className = "tooltip";
    ttBox.appendChild(ttText);
    ttBox.style.display="none";
    cell1.appendChild(ttBox);
    
    cell1.onclick = function(e)
    {
        var r = rowCount;
        if (document.getElementById("txtTranType").value.substr(0,4) == "MENU")
        {
            currentTran = document.getElementById("txtTranType").value;
            try
            {
                if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
                {
                    currentTran = trnName[r];
                }
                changeTran(currentTran);
                return false;
            }
            catch(e)
            {
                try
                {
                    changeTran(currentTran);
                }
                catch(e)
                {
                    currentTran = document.getElementById("txtMainMenu").value;
                    changeTran(currentTran);
                }
                return false;
            }
            return false;
        }
        else if (document.getElementById("txtTranType").value.substr(0,6) == "SELECT")
        {
            if (r <= 1)
                return false;
            currentTran = document.getElementById("txtTranType").value;
            try
            {
                if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
                {
                    currentTran = trnName[r];
                }
                changeTran(currentTran);
                return false;
            }
            catch(e)
            {
                try
                {
                    changeTran(currentTran);
                }
                catch(e)
                {
                    currentTran = document.getElementById("txtMainMenu").value;
                    changeTran(currentTran);
                }
                return false;
            }
            return false;
        }
        else if (document.getElementById("txtTranType").value.substr(0,8) == "DOCUMENT")
        {
            if (r <= 1)
                return false;
            currentTran = document.getElementById("txtTranType").value;
            try
            {
                if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
                {
                    showDocument(trnValue[r]);
                }
                return false;
            }
            catch(e)
            {
                currentTran = document.getElementById("txtMainMenu").value;
                changeTran(currentTran);
            }
            return false;
        }
        var r = rowCount;
        if (trnValue[r] != null && trnValue[r] != "")
        {
            document.getElementById('ttt'+r).innerHTML = document.getElementById(''+r).placeholder;
            if (document.getElementById('tt'+r).style.display=="none")
                document.getElementById('tt'+r).style.display="inline-block";
            else
                document.getElementById('tt'+r).style.display="none";
        }
    };
    cell1.onmouseout = function(e)
    {
        var r = rowCount;
        document.getElementById('tt'+r).style.display="none";
    };
    var r = rowCount;
    var cell2 = row.insertCell(1);
    if (document.getElementById("txtTranType").value.substr(0,4) == "MENU")
        cell2.className = "tw1";
    else
        cell2.className = "td2";
    if ((obj.screenoption.substr(cs,1) !="$"))
    {
        var element2 = document.createElement("input");
        element2.setAttribute('autocomplete', 'off');
        if ((obj.name == "Password") || (obj.screenoption.substr(cs,1)=="*") || (obj.screenoption.indexOf("*") != -1))
        {
            element2.type = "password";
        }
        else
        {
            element2.type = "text";
        }
        if (obj.hidden == "none")
        {
            element2.setAttribute('inputmode','none');
        }
        else
        {
            element2.setAttribute('inputmode','text');
        }
        element2.id = rowCount;
        if (obj.hidden == "N")
        {
            element2.type = "number";
        }
        if (obj.hidden == "E")
        {
            element2.type = "email";
        }
        if (obj.hidden == "B")
        {
            element2.className = "barcode-box";
        }
        else
        {
            element2.className = "input-box";
        }
        element2.tabindex=0;
        try
        {
            element2.value = obj.input;
            if (obj.content != "mandatory")
            {
                element2.placeholder = obj.content;
                trnValue[r] = obj.content;
            }
        }
        catch(e)
        {
            alert("MENU Error:"+e);
        }
// Standard Input Form
        if ((document.getElementById("txtTranType").value.substr(0,4) != "MENU") && (document.getElementById("txtTranType").value.substr(0,6) != "SELECT") && (document.getElementById("txtTranType").value.substr(0,8) != "DOCUMENT"))
        {
// protected Field
            if ((obj.screenoption.substr(cs,1)=="P") || (obj.screenoption.substr(cs,1)=="H") || (obj.screenoption.substr(cs,1)=="T") || (obj.screenoption.substr(cs,1)=="X"))
            {
                element2.readOnly = true;
                element2.className = "read-only-box";
            }               
            element2.oninput = 
            function(e)
            {
            };
            element2.onkeydown = 
            function(e)
            {
// If the field is defined as 'bar-code' hand-keying is not allowed (done by testing the delay between keypress).
                    mouseCode = null;
                    var d = new Date();
                    var n = d.getTime();
                    if (keyDownTime != null)
                    {
                        var keyTimeElapsed = n - keyDownTime;
                        if (userLevel > 1)
                        {
                            if ((trnBarcode[this.id] == "B") && (document.getElementById(''+this.id).value != null) && (document.getElementById(''+this.id).value != ''))
                            {
                                if (keyTimeElapsed>42)
                                {
                                    element2.className = "barcode-box";
                                    document.getElementById(''+this.id).value = '';
                                    document.getElementById(''+this.id).focus();
                                    element2.value = "";
                                    keyDownTime = null;
                                    return false;
                                }
                            }
                        }
                    }
                    keyDownTime = n;
                    var keycode=0;
                    if (window.event)
                        keycode = window.event.keyCode;
                    else if (e)
                        keycode = e.which;
                    keyCode = keycode;
                    if(keycode==9)
                    {
//                      alert("Tab");
                        idx = 0;
                        cellFail = false;
                        document.getElementById("txtcurraction").value = trnValidation[this.id];
                        if (element2.value.length == 0)
                        {
                            alert(trnName[this.id]+" cannot be blank");
                            cellFail = true;
                        }
                        else
                        {
                            cellValidation(dataTable,this.id);
                        }
                        if ((cellFail == false) && (document.getElementById("loadingContainer").style.display == "none"))
                            changeCurrentRow(dataTable,this.id,1);
                            keyDownTime = null;
                        return false;
                    }
                    else if (keycode == 38) 
                    {
//                      alert("Up");                            
                        idx = 0;
                        if ((document.getElementById("loadingContainer").style.display == "none"))
                            changeCurrentRow(dataTable,this.id,-1);
                        keyDownTime = null;
                        return false;
                    }
                    else if (keycode == 40) 
                    {
//                      alert("Down");                          
                        idx = 0;
                        cellFail = false;
                        document.getElementById("txtcurraction").value = trnValidation[this.id];
                        if (element2.value.length == 0)
                        {
                            alert(trnName[this.id]+" cannot be blank");
                            cellFail = true;
                        }
                        else
                        {
                            cellValidation(dataTable,this.id);
                        }
                        if ((cellFail == false) && (document.getElementById("loadingContainer").style.display == "none") && (this.id < lastTableRow) && (document.getElementById("txtTranType").value != "SELECT"))
                            changeCurrentRow(dataTable,this.id,1);
                            keyDownTime = null;
                        return false;
                    }
                    else if (keycode == 13) 
                    {
//                      alert("Enter");
//                      element2.setAttribute('inputmode','none');
                        if (window.event)
                            window.event.preventDefault ? window.event.preventDefault() : (window.event.returnValue = false);
                        else
                            e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                        idx = 0;
                        document.getElementById("txtcurraction").value = trnValidation[this.id];
                        cellFail = false;
                        if (document.getElementById("alertbox").style.display != "none")
                            customAlert('off');
                        else
                        {
                            document.getElementById("txtcurraction").value = trnValidation[this.id];
                            cellValidation(dataTable,this.id);
                            if ((cellFail == false) && (document.getElementById("loadingContainer").style.display == "none"))
                                changeCurrentRow(dataTable,this.id,1);
                        }
                        keyDownTime = null;
                        return false;
                    }
            };
            element2.onkeyup = 
            function(e)
            {
//                alert("TESTUP-"+e.keyCode+"-"+e.key+"-"+this.value);
            };
            element2.onmousedown = 
            function(e)
            {
                mouseCode = 1;
            };
            element2.onfocus = 
            function(e)
            {
                if ("virtualKeyboard" in navigator) 
                {
                    if (trnHidden[this.id] == "none")
                        navigator.virtualKeyboard.hide();
                    else
                    {
                        navigator.virtualKeyboard.show();
                        if (trnHidden[this.id] == "numeric")
                            element2.setAttribute('inputmode','numeric');
                        else
                            element2.setAttribute('inputmode','text');
                    }
                }
                else
                {
                    if (trnHidden[this.id] == "none")
                    {
                        element2.setAttribute('inputmode','none');
                    }
                    else if (trnHidden[this.id] == "numeric")
                        element2.setAttribute('inputmode','numeric');
                    else
                        element2.setAttribute('inputmode','text');
                }
                if (trnName[this.id] != "toPlt")
                    element2.select();
                if ((document.getElementById("txtTranType").value.substr(0,4) == "MENU") || (document.getElementById("txtTranType").value.substr(0,6) == "SELECT") || (document.getElementById("txtTranType").value.substr(0,8) == "DOCUMENT") || (document.getElementById("alert").innerHTML.substr(0,2)=="FA"))
                {
                    if((document.getElementById("rdtMessage")) && (document.getElementById("rdtMessage").innerHTML != ""))
                    {
                        let text = document.getElementById("rdtMessage").innerHTML
                        popupMessageShow(text);
                    }
                }
                else
                {
                    var i = "td1"+this.id;
                }
            };
            element2.onblur = 
            function(e)
            {
                if ("virtualKeyboard" in navigator) 
                {
                    navigator.virtualKeyboard.hide();
                }
                else
                {
//                    element2.setAttribute('inputmode','none');
                }
                    
                if ((document.getElementById("txtTranType").value.substr(0,4) == "MENU") || (document.getElementById("txtTranType").value.substr(0,6) == "SELECT") || (document.getElementById("txtTranType").value.substr(0,3) == "DOC") || (document.getElementById("alert").innerHTML.substr(0,2)=="FA"))
                {
                    if((document.getElementById("rdtMessage")) && (document.getElementById("rdtMessage").innerHTML != ""))
                    {
                        let text = document.getElementById("rdtMessage").innerHTML
                        popupMessageShow(text);
                    }
                }
                else
                {
                    if (document.getElementById(''+this.id).value != '')
                    {
                        if (mouseCode == 1)
                        {
//                          console.log("MouseY"+mouseY);
                            if (mouseY >= 600) 
                            {
                                disableBlur = false;
                            }
                            else
                            {
                                cellFail = false;
                                idx = 0;
                                document.getElementById("txtcurraction").value = trnValidation[this.id];
                                cellValidation(dataTable,this.id);
                                var i=0;
                                for (i=0;i<20000;i++)
                                {
                                }
                            }
                        }
                    }
                    else
                    {
                        if(keyCode != '113' && keyCode != '114')
                        {
                        }
                    }
                    mouseCode = null;
                    var i = "td1"+this.id;
                    document.getElementById(i).style.background = "transparent";
                }
            };
        }
        else
        {
            element2.readOnly = true;
            element2.className = "read-only-box";
        }
        element2.onclick = function(e)
        {
            element2.setAttribute('inputmode','text');
            var r = rowCount;
            if ((document.getElementById("txtTranType").value.substr(0,4) == "MENU") || (document.getElementById("txtTranType").value.substr(0,6) == "SELECT") || (document.getElementById("txtTranType").value.substr(0,3) == "DOC"))
            {
                currentTran = document.getElementById("txtTranType").value;
                try
                {
                    if ((trnScreenOption[r] != "H") && (trnScreenOption[r] != "T") && (trnScreenOption[r] != "X"))
                    {
                        currentTran = trnName[r];
                    }
                    changeTran(currentTran);
                    return false;
                }
                catch(e)
                {
                    try
                    {
                        changeTran(currentTran);
                    }
                    catch(e)
                    {
                        currentTran = document.getElementById("txtMainMenu").value;
                        changeTran(currentTran);
                    }
                    return false;
                }
                return false;
            }
            else
            {
//                      alert("Click");
                    cellFail = false;
                    idx = 0;
                    if ((cellFail == false) && (document.getElementById("loadingContainer").style.display == "none") && (mouseCode == null))
                    {
                        if (element2.className != "read-only-box")
                        {
                            changeCurrentRow(dataTable,this.id,"M");
                        }
                    }
                    return false;
            }
        };
        element2.ondblclick = function(e)
        {
            if (element2.className != "read-only-box")
            {
                var text = element2.placeholder;
                if (navigator.clipboard) 
                {
                    navigator.clipboard.writeText(text).then(function() 
                    {
//                        console.log('Async: Copying to clipboard was successful!');
                    }, 
                    function(err) 
                    {
                        console.error('Async: Could not copy text: ', err);
                    });
                }
                else
                {
                    document.getElementById(''+this.id).value=text;
                    document.getElementById(''+this.id).select();
                    var successful = document.execCommand('copy');
                    document.getElementById(''+this.id).value="";
                }
            }
        };
        cell2.appendChild(element2);
    }
// Store Transaction Properties
    trnRowCount[rowCount] = obj.rowCount;
    trnPrefix[rowCount] = obj.prefix;
    trnHidden[rowCount] = obj.hidden;
    try
    {
        trnMin[rowCount] = obj.min;
    }
    catch(e)
    {
        trnMin[rowCount] = "";
    }
    try
    {
        trnMax[rowCount] = obj.max;
    }
    catch(e)
    {
        trnMax[rowCount] = "";
    }
    trnName[rowCount] = obj.name.replace(".","");
    trnValidation[rowCount] = obj.validation;
    trnScreenOption[rowCount] = obj.screenoption;
    if (document.getElementById("txtTranType").value.substr(0,8) == "DOCUMENT")
        trnValue[rowCount] = obj.content;
    else
        trnValue[rowCount] = "";
    if (obj.hidden == "B")
        trnBarcode[rowCount] = "B";
    else    
        trnBarcode[rowCount] = "";
    if (obj.content == "mandatory")
        trnMand[rowCount] = "M";
// Store First & Last Editable Rows         
    if ((obj.screenoption.substr(cs,1) !="P") && (obj.screenoption.substr(cs,1) !="H") && (obj.screenoption.substr(cs,1) !="T") && (obj.screenoption.substr(cs,1) !="X"))
    {
        if ((firstRow == 0) || (firstRow > rowCount))
            firstRow = rowCount;
        lastRow = rowCount;
    }
// Store Number Of Screens for this Transaction
    if (screenCount == 0)
        screenCount = obj.screenoption.length;
// test for last table row for this transaction
    if (obj.screenoption.indexOf("I") > -1)
        lastTableRow = rowCount;
    if (trnValidation[rowCount] != null)
    {
        if (trnValidation[rowCount].substr(0,10)=="HANDKEY:NO")
            handKey = "N";
    }
	trnPreprocess[rowCount] = obj.preprocess;
}

// Event Called when Dynamic Buttons have been loaded
function buildButtons(xmlDoc)
{   
    var btnPanel = document.getElementById("btnPanel");
// remove any existing buttons
    if (buttons.length > 0)
    {
        document.getElementById("btnPanel").innerHTML = "";
    }
// create new buttons
// Create Transaction JSON Object
    try
    {
        var strJSON = xmlDoc.responseText;
    }
    catch(e)
    {
        var strJSON = xmlDoc;
    }
    if (strJSON == undefined)
        var strJSON = xmlDoc;
    var objJSON = eval("(function(){return " + strJSON + ";})()");
// Get Count of Elements    
    buttons = objJSON;
    var panelWidth = 70;
    if (objJSON != undefined)
    {
        for(var i = 0; i < objJSON.length; i++)
        {
            var button2 = document.createElement("button");
            button2.className = "button";
            button2.id = objJSON[i].name;
            button2.name = objJSON[i].altkey;
            button2.innerHTML = objJSON[i].text;
            button2.style.backgroundColor = buttonColour;
            if (objJSON[i].name.substr(0,5).toLowerCase() == "popup")
            {
                button2.style.styleFloat = 'right';
                button2.style.cssFloat = 'right';
            }
            btnPanel.appendChild(button2);
            document.getElementById(objJSON[i].name).addEventListener('click', function() 
            {
//              console.log("buttonClick" + this.id);
                buttonClick(this.id);
            });
        } 
/*        
// add action
        for(var i = 0; i < objJSON.length; i++)
        {
            document.getElementById(objJSON[i].name).onclick = function() 
            {
                buttonClick(this.id);
            }
        }
*/
    }
    cellFail = true;
}

function nextScreen(xmlDoc,screenData,currentTran)
{
    if (currentTran == 'PBTM' || currentTran == 'PBTP')
    {
        if (document.getElementById("txtPageNum").value > 1)
            changeTran("MENUPICK");
        else
            changeTran("MENUPICK");
    }
    else if(currentTran == "RBTC")
    {
        idx = 999;
        id = screenData;
        document.getElementById(''+id).value = "";
        document.getElementById("txtPageNum").value = "3";
        gotoHere();
    }
    else if(currentTran == "RBTD")
    {
        changeTran("MENUREC");
    }
}

function onMouseClick(row)
{
//  alert("mouseclick:"+row);
    event = event || window.event;
    alert("Mouse "+event.pageX+" "+event+pageY);
    
}

// Change Current Active (focused) Screen Row
function changeCurrentRow(tableId, row, direction)
{
    errorMsg = "";
    
    var table = document.getElementById(tableId);
    var endRow = parseInt(lastRow);
    if ((prvRow==undefined) || (parseInt(prvRow) < parseInt(firstRow)))
        prvRow = parseInt(firstRow);
    if (prvRow == 0)
        prvRow = 1;
    if ((direction != "M") && (direction <-1 || direction >9))
    {
        for (var r = 1; r < table.rows.length; r++)
        {
            if (trnName[r] == direction)
            {
                s = trnScreenOption[r].indexOf("I");
                if (s == -1)
                    s = trnScreenOption[r].indexOf("*");
                if (s != -1)
                    cs = s;
                cellFail = true;
                prvRow = row;
                refreshScreen(tableId,cs);
                if (document.getElementById(''+row) != null)
                    document.getElementById(''+row).focus();
                return;
            }
        }
    }
    else if ((direction == "M") || (direction == 0))
    {
        var s = 0;
        try
        {
            s = trnScreenOption[row].indexOf("I");
            if (s == -1)
                s = trnScreenOption[row].indexOf("*");
        }
        catch(e)
        {
            s = -1;
        }
        if (s != -1)
        {
            cs=s;
        }
        cellFail = true;
        prvRow = row;
        refreshScreen(tableId,cs);
        if (document.getElementById(''+row) != null)
            document.getElementById(''+row).focus();
        return;
    }
    else
    {
        endRow = parseInt(row)+parseInt(direction);
    }
    if (direction == 0)
    {
        cellFail = true;
        return;
    }
        
    if (direction == 1)
    {
        prvcs = cs;
        count = 0;
        while ((parseInt(row) < parseInt(endRow)) && (count < 10))
        {
            count++;
            row=parseInt(row)+1;
            if ((parseInt(row) > parseInt(lastRow)) && (parseInt(lastRow) < table.rows.length))
            {
                if (parseInt(row)  < parseInt(lastTableRow))
                    cs = cs+1;
                refreshScreen(tableId,cs);
                currentRow = parseInt(row);
            }
            else
            {
                currentRow = parseInt(row);
            }
            if ((parseInt(row) == parseInt(endRow)) && (trnScreenOption[row]))
                if ((trnScreenOption[row].substr(cs,1) != "I") && (trnScreenOption[row].substr(cs,1) != "*"))
                    endRow = parseInt(endRow)+1;
        }
    }
    else if (direction == -1)
    {
        var count = 0;
/*
        while (count < 10)
        {
            count++;
            row=parseInt(row)-1;
            if (row < 0)
            {
                row = prvRow;
            }
            var s = trnScreenOption[row].indexOf("I");
            if (s != -1)
            {
                cs=s;
                refreshScreen(tableId,cs);
                count = 10;
            }
        }
*/
        while ((parseInt(row) > parseInt(endRow)) && (count < 10))
        {
            count++;
            row=parseInt(row)-1;
            if ((parseInt(row) < parseInt(firstRow)) && (parseInt(firstRow) > 1))
            {
                if (cs > 0)
                    cs = cs-1;
                refreshScreen(tableId,cs);
                currentRow = parseInt(row);
            }
            else
            {
                currentRow = parseInt(row);
            }
            if ((parseInt(row) == parseInt(endRow)) && (trnScreenOption[row].substr(cs,1) != "I") && (trnScreenOption[row].substr(cs,1) != "*"))
            {
                endRow = parseInt(endRow)-1;
                if (endRow <= 0)
                {
                    endRow = prvRow;
                    break;
                }
            }
        }
    }
    cellFail = true;
    prvRow = row;
    if (document.getElementById(''+row) != null)
        document.getElementById(''+row).focus();
    return;
}


// Delete Row from Dynamic Table
function deleteRow(tableID) 
{
    try 
    {
        var table = document.getElementById(tableID);
        table.innerHTML = "";
        trnRowCount.length = 0;
        trnPrefix.length = 0;
        trnName.length = 0;
        trnScreenOption.length = 0;
        trnValidation.length = 0;
        trnValue.length = 0;
		try
		{
			var rowCount = table.rows.length;
		}
		catch(e)
		{
		}
    }
    catch(e) 
    {
//        alert(e);
    }
    screenCount = 0;
    firstRow = 0;
    lastRow = 0;
    lastTableRowRow = 0;
}


// Navigation
function gotoNext()
{
    var pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
    if (pageNum < screenCount)
        pageNum++;
    else
        pageNum=1;
    cs = pageNum-1;
    prevLastRow = lastRow;
    refreshScreen(dataTable,cs);
    document.getElementById("txtPageNum").value = pageNum;
    lockScreen = false;
    loading('off');
}

function gotoPrev()
{
    var pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
    pageNum--;
    if (pageNum < 1)
        pageNum = 1;
    cs = pageNum-1;
    refreshScreen(dataTable,cs);
    prevLastRow = lastRow;
    document.getElementById("txtPageNum").value = pageNum;
    lockScreen = false;
    loading('off');
}

function gotoHere(screenData,focusOn='')
{
    const currentTran = document.getElementById("txtTranType").value;
    if (currentTran.substr(0,4) == "MENU")
    {
        document.getElementById("txtPageNum").value = 1;
    }
    let pageNum = 1;
//    pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
    let numtest = document.getElementById("txtPageNum").value;
    pageNum = Number(document.getElementById("txtPageNum").value);
    if (pageNum < 1)
        pageNum = 1;
    cs = pageNum-1;
    refreshScreen(dataTable,cs,screenData,focusOn);
    document.getElementById("txtPageNum").value = pageNum;
    lockScreen = false;
    loading('off');
}

function gotoField(direction)
{
    var table = document.getElementById(dataTable);
    var PageNum = 1;
    for (var r = 1; r < table.rows.length; r++)
    {
        if (trnName[r] == direction)
        {
            s = trnScreenOption[r].indexOf("I");
            if (s == -1)
                s = trnScreenOption[r].indexOf("*");
            if (s == -1)
            {
                s = trnScreenOption[r].length;
                for (var i = 1;i<table.rows.length;i++)
                {
                    if (trnScreenOption[i].substr(s,1) == "I")
                        trnScreenOption[i].substr(s,1) = "H";
                }
                s = s-1;
                trnScreenOption[r].substr(s,1) = "I";
            }
            if (s != -1)
                document.getElementById("txtPageNum").value = s+1;
            break;
        }
    }
    pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
    if (pageNum < 1)
        pageNum = 1;
    cs = pageNum-1;
    refreshScreen(dataTable,cs);
    document.getElementById("txtPageNum").value = pageNum;
    lockScreen = false;
    loading('off');
}


// Get All FieldNames & Values From the Screen
function getScreenData(table)
{
    var currentTran = document.getElementById("txtTranType").value;
    var vldStr = "";
    var urlp = "";
// populate string with field names & values
    for (var i = 1; i < table.rows.length; i++)
    {
// format URL string for post
// option 1 - FormattedInput
        if (trnValue[i].substr(0,1) != "")
        {
            vldStr = vldStr+urlp+trnName[i]+"="+trnValue[i].toUpperCase().trim();
            urlp = "|AND|";
        }
// option 2 - currentInput
        else if (document.getElementById(''+i).value.trim() != "")
        {   
            if (trnPrefix[i] != "")
                vldStr = vldStr+urlp+trnName[i]+"="+trnValue[i].substr(1).toUpperCase().trim();
            else
                vldStr = vldStr+urlp+trnName[i]+"="+trnValue[i].toUpperCase().trim();
            urlp = "|AND|";
        }
// option 3 - presetContent
        else if (document.getElementById(''+i).placeholder.trim() != "")
        {
            vldStr = vldStr+urlp+trnName[i]+"="+document.getElementById(''+i).placeholder.toUpperCase().trim();
            urlp = "|AND|";
        }
    }
// add UserId to string
    vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
// add TransactionTypeId to string
    vldStr = vldStr+"|AND|transactionTypeId="+document.getElementById("txtTranType").value;
    return vldStr;
}

// Refresh Current screen Data / Layout
function refreshScreen(tableId, cscr,screenData,focusOn='')
{
    firstRow = 0;
    lastRow = 0;
    var table = document.getElementById(tableId);
    var currentTran = document.getElementById("txtTranType").value;
    if (currentTran.substr(0,5) == "TABLE")
    {
        return false;
    }
    for (var r = 1; r < table.rows.length; r++) 
    {
        if (trnScreenOption.length > 0 && r < trnScreenOption.length)
        {
            if ((!trnScreenOption[r].substr(cscr,1)) || (trnScreenOption[r].substr(cscr,1)==""))
            {
    //          return false;
                table.rows[r].style.display = "none";
                continue;
            }
            if ((trnScreenOption[r].substr(cscr,1)=="H") || (trnScreenOption[r].substr(cscr,1)=="T"))
            {
                table.rows[r].style.display = "none";
            }
            else
            {
                table.rows[r].style.display= "flex";
            }
            try
            {
                var element2 = document.getElementById(''+r); 
                if (document.getElementById("txtTranType").value.substr(0,4) != "MENU")
                {
                    if (trnScreenOption[r].substr(cscr,1)=="P")
                    {
                        element2.readOnly = true;
                        element2.className = "read-only-box";
                    }
                    else
                    {
                        element2.readOnly = false;
                        element2.disabled = false;
                        if (trnBarcode[r] == "B")
                            element2.className = "barcode-box";
                        else
                            element2.className = "input-box";
                    }
                }
                else
                {
                    element2.readOnly = true;
                    if (trnScreenOption[r].substr(cscr,1)=="X")
                    {
                        element2.disabled=true;
                        element2.readOnly = true;
                        element2.className = "read-only-box";
                        element2.style.color = "lightgrey";
                    }
                }
            }
            catch (e)
            {
                alert("Element Error");
            }
            if ((trnScreenOption[r].substr(cscr,1) != "P") && (trnScreenOption[r].substr(cscr,1) != "H") && (trnScreenOption[r].substr(cscr,1) != "T") && (trnScreenOption[r].substr(cscr,1) != "X"))
            {
                if ((firstRow == 0) || (firstRow > r))
                    firstRow = r;
                lastRow = r;
            }
// test for last table row
            if (trnScreenOption[r].indexOf("I") > -1)
                lastTableRow = r;
        }
        if (element2 != undefined)
        {
			if (trnHidden[r] == "none")
			{
				element2.setAttribute('inputmode','none');
			}
			else
			{
				element2.setAttribute('inputmode','text');
			}
        }
    }
    document.getElementById("txtPageNum").value = cscr+1;
    try
    {
        document.getElementById(''+firstRow).setAttribute('tabindex', 0); 
        if (focusOn != "")
        {
            document.getElementById(''+focusOn).focus();
            row = focusOn;
        }
        else
        {
            document.getElementById(''+firstRow).focus();
            row = firstRow;
        }
    }
    catch(e)
    {
        var currentTran = document.getElementById("txtMainMenu").value;
        if ((currentTran.substr(0,4) == "MENU") || (currentTran.substr(0,6) == "SELECT") || (currentTran.substr(0,8) == "DOCUMENT"))
        {
            try
            {
                <!-- document.getElementById("menuOption").focus(); -->
            }
            catch(e)
            {
                document.getElementById("txtPageNum").focus();
            }
        }
    }
// populate screen if required
    if ((screenData != undefined) && (screenData != ""))
    {
        screenData = screenData.split("=").join(":");
        screenData = screenData.split("|AND|").join(",");
        refreshData(table,screenData);
    }
    return false;
}

// Check for pre-Process
function preprocess(dataTable,page=null)
{
	var table = document.getElementById(dataTable);
// pre-process current page
	if (page == null)
	{
		pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
		if (pageNum < 1)
			pageNum = 1;
		page = pageNum;
	}
// pre-process Previous-page
    else if (page == "page-")
    {
        pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
		if (pageNum < 1)
			pageNum = 1;
		page = pageNum-1;
        var row = 0;
// find previous input-capable page
        while(page>-1)
        {
            for (i = 1; i < trnScreenOption.length; i++)
            {
                if ((trnScreenOption[i].substr(page, 1) === "I") || (trnScreenOption[i].substr(page, 1) === "*")) 
                {
                    row = i;
                    break;
                }
            }
            if (row > 0)
            {
                break;
            }
            if (page > 0)
            {
                page=page-1;
            }
            else
            {
                return false;
            }
        }
    }
// pre-process Next-page
    else if (page == "page+")
    {
        pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
		if (pageNum < 1)
			pageNum = 1;
		page = pageNum+1;
    }
// pre-process specified page
    else if (page.substr(0.4) == "page")
    {
        page = page.substr(4);
    }
	if (!isNaN(Number(page)))
	{
		page--;
		for (var r = 1; r < table.rows.length; r++)
		{
			if (trnScreenOption[r].substr(page,1) == "I" || trnScreenOption[r].substr(page,1) == "*")
			{
				if (trnPreprocess[r] != "")
				{
                    var strIdx = idx;
                    var strAction = document.getElementById('txtcurraction').value;
					document.getElementById('txtcurraction').value = trnPreprocess[r];
					cellValidation(dataTable,r);
                    idx = strIdx;
                    document.getElementById('txtcurraction').value = strAction;
				}
			}
		}
	}
	else
// pre-process by row name.
	{
		for (var r = 1; r < table.rows.length; r++)
		{
			if (trnName[r].toLowerCase() == page.toLowerCase())
			{
				if (trnPreprocess[r] != "")
				{
					var strIdx = idx;
                    var strAction = document.getElementById('txtcurraction').value;
					document.getElementById('txtcurraction').value = trnPreprocess[r];
					cellValidation(dataTable,r);
                    idx = strIdx;
                    document.getElementById('txtcurraction').value = strAction;
				}
			}
		}
	}
    return false;
}

// Display 'Confirm' Panel
function showConfirm(rdtText,row,yesBtnTxt,noBtnTxt)
{
    document.getElementById('confirmtext').value = rdtText;
    document.getElementById('confirmpanel').style.display = "block";
    document.getElementById('confirmpanel').style.position = "absolute";
    document.getElementById('confirmpanel').style.left = '20px';
    document.getElementById('confirmpanel').style.top = '50px';
    <!-- document.getElementById('menuOption').focus(); -->
    document.getElementById('confirminput').style.display = "none";
    document.getElementById('alertoverlay').style.display = "block";
    document.getElementById('yesbtn').innerHTML=yesBtnTxt;
    document.getElementById('nobtn').innerHTML=noBtnTxt;
//  document.getElementById('txtcurraction').value = "";
    currentRow = row;
    cellFail = true;
	lockScreen = false;
    loading("off");
    document.getElementById('yesbtn').onclick = function()
    {
        confirmConfirm(row,yesBtnTxt,document.getElementById('txtyesaction').value);
    };
    document.getElementById('nobtn').onclick = function()
    {
        confirmConfirm(row,noBtnTxt,document.getElementById('txtnoaction').value);
    };
            
    return false;
}

// Display 'Confirm Input' Panel
function showConfirmInput(rdtText,row,yesBtnTxt,noBtnTxt)
{
    try
    {
        document.getElementById("dataTable").disabled=true;
    }
    catch(e)
    {
        document.getElementById("dataTable").disabled=false;
    }
    document.getElementById('confirmtext').value = rdtText;
    document.getElementById('confirmpanel').style.display = "block";
    document.getElementById('confirmpanel').style.position = "absolute";
    document.getElementById('confirmpanel').style.left = '20px';
    document.getElementById('confirmpanel').style.top = '50px';
    document.getElementById('confirminput').style.display = "block";
    document.getElementById('alertoverlay').style.display = "block";
    document.getElementById('yesbtn').innerHTML=yesBtnTxt;
    document.getElementById('nobtn').innerHTML=noBtnTxt;
//  document.getElementById('txtcurraction').value = "";
    document.getElementById('confirminput').focus();
    currentRow = row;
    cellFail = true;
            
    document.getElementById('yesbtn').onclick = function()
    {
        confirmConfirm(row,yesBtnTxt,document.getElementById('txtyesaction').value);
    };
    document.getElementById('nobtn').onclick = function()
    {
        confirmConfirm(row,noBtnTxt,document.getElementById('txtnoaction').value);
    };
            
    return false;
}


// confirm button - current row, yes/no text, action - "OK" / "FAIL"
function confirmConfirm(row,yesno,txtResult)
{
    document.getElementById('confirmpanel').style.display = "none";
    document.getElementById('alertoverlay').style.display = "none";

// No Confirm Action specified - use Transaction Actions    
    if ((yesno.toLowerCase() == 'no') && ((txtResult == "") || (txtResult == undefined)))
    {
// If NO - return to screen
        cellFail = true;
        document.getElementById(''+row).value = "";
        trnValue[row] = "";
        changeCurrentRow(dataTable,this.id,0);
        idx = 999;
        return false;
    }
    if ((yesno.toLowerCase() == 'yes') && ((txtResult == "") || (txtResult == undefined)))
    {
// If YES process next default validation instruction
        cellFail = false;
        idx = idx+1;
        try
        {
            var validate = trnValidation[row].split(",")[idx];
            var s = trnValidation[row].indexOf(validate);
            if (s > -1)
                validate = trnValidation[row].substr(s);
            document.getElementById('txtcurraction').value = validate;
        }
        catch (e)
        {
            validate = "";
        }
        
        if (document.getElementById("txtcurraction").value != "" && document.getElementById("txtcurraction").value != undefined)
        {
            cellValidation(dataTable,row);
//            changeCurrentRow(dataTable,this.id,1);
            return false;
        }
        else
        {
//            changeCurrentRow(dataTable,this.id,1);
            return false;
        }
    }
    if (yesno.toLowerCase() == 'continue')
    {
// If continue process next default validation instruction
        cellFail = false;
        idx = idx+1;
        try
        {
            var validate = trnValidation[row].split(",")[idx];
            if (validate == undefined)
            {
                idx = idx-1;
                var validate = trnValidation[row].split(",")[idx];
            }
            var s = trnValidation[row].indexOf(validate);
            if (s > -1)
                validate = trnValidation[row].substr(s);
            document.getElementById('txtcurraction').value = validate;
        }
        catch (e)
        {
            validate = "";
        }
        var n = 0;
        if (trnName[row] == 'post')
            n = -1;
        if (document.getElementById("txtcurraction").value != "" && document.getElementById("txtcurraction").value != undefined)
        {
            cellValidation(dataTable,row);
            changeCurrentRow(dataTable,this.id,n);
            return false;
        }
        else
        {
            changeCurrentRow(dataTable,this.id,n);
            return false;
        }
    }
    if (yesno.toLowerCase() == 'retry')
    {
// If continue process next default validation instruction
        idx = idx-1;
        cellFail = false;
        try
        {
            var validate = trnValidation[row].split(",")[idx];
            var s = trnValidation[row].indexOf(validate);
            if (s > -1)
                validate = trnValidation[row].substr(s);
            document.getElementById('txtcurraction').value = validate;
        }
        catch (e)
        {
            validate = "";
        }
        
        if (document.getElementById("txtcurraction").value != "" && document.getElementById("txtcurraction").value != undefined)
        {
            cellValidation(dataTable,row);
            changeCurrentRow(dataTable,this.id,0);
            return false;
        }
        else
        {
            changeCurrentRow(dataTable,this.id,0);
            return false;
        }
    }
// Confirm Action Processing
    if ((txtResult != undefined) && (txtResult != "") && (txtResult != null))
    {
        if (yesno.toLowerCase() == 'yes')
        {
//          trnValidation[row] = txtResult;
            cellFail = false;
            document.getElementById('txtcurraction').value = txtResult;
            var i = txtResult.indexOf('page:');
            idx = 1;
            cellValidation(dataTable,row);
//            if (i == -1)
//                changeCurrentRow(dataTable,this.id,1);
            return false;
          
        }
        if (yesno.toLowerCase() == 'no')
        {
//          trnValidation[row] = txtResult;
            cellFail = true;
            document.getElementById('txtcurraction').value = txtResult;
            var i = txtResult.indexOf('page:');
            idx = 1;
            cellValidation(dataTable,row);
//            if (i == -1)
//                changeCurrentRow(dataTable,this.id,0);                               
            return false;
        }
    }
    return false;
}


function cancelConfirm(row)
{
    try
    {
        document.getElementById('confirmpanel').style.display = 'none';
    }
    catch(e)
    {
    }
    document.getElementById(''+row).setAttribute('tabindex', 0); 
    document.getElementById(''+row).focus();
    cellFail = true;
    idx = 999;
    return false;
}


// Screen Transaction
function changeTran(mCurrentTran)
{
    if (mCurrentTran == "LOGON")
    {
//        window.location.href = "/rdtlogon/rdtlogon.php";
        window.history.back();
        return false;
    }
    if (document.getElementById("txtTranType").value != mCurrentTran)
	{
		popupTextHide();
	}
//    document.getElementById('popupTextContainer').style.display='none';
	deleteRow('jsonTable');
    lockScreen = false;
    loading('off');
    hideSelect();
    document.getElementById('iframeModal').style.display = "none";
    cs=0;
    id = 0;
    idx = 0;
    changeTranData = "";
    if (mCurrentTran.split("?") [1] != undefined)
    {
        var currentTran = mCurrentTran.split("?") [0];
        var mData = mCurrentTran.split("?") [1];
        mData = validationFormat(mData);
    }
    else
    {
        var currentTran = mCurrentTran;
        var mData = "";
    }
    document.getElementById('txtcurraction').value = "";
    changeTranData = "";
    if (document.getElementById("txtUser").value == "")
        currentTran = "LOGON";
// Test for Outstanding Error Message
    var errorMsg = "";
// Check / Add Transaction to Screen
    var tranFound = false;
//  deleteRow(dataTable);
    pageNum = 1;
    cs = pageNum-1;
    document.getElementById("txtPageNum").value = 1;
    pageNum = document.getElementById("txtPageNum").value;
    if ((currentTran == "") || (currentTran == null))
        currentTran = "MENU1";
    if ((currentTran != "") && (currentTran != null))
        document.getElementById("txtTranType").value = currentTran;
    if (currentTran.substr(0,4) == "MENU")
    {
        document.getElementById("popupMessageContainer").style.display = "none";
    }
    ajaxGetScreen(currentTran,mData);
    return false;
}


// RDT TimeStamp
function rdtTimestamp(action,row)
{
    if (action == "start")
    {
        rdtStart = now();
        rdtEnd = now();
    }
    if (action == "stop")
    {
        rdtEnd = now();
    }
// Recursive Call to perform next Cell Validation instruction
    try
    {
        var validate = trnValidation[row];
    }
    catch (e)
    {
        validate = "";
    }
    idx = idx+1;
    if (document.getElementById("txtcurraction").value != "")
    {
        cellValidation(dataTable,row);
    }
    else if(document.getElementById('txtcurraction').value != "")
    {
        cellValidation(dataTable,row);
    }
    return false;
}


// Clear Specified Screen, either by page number, or field name
function clearScreen(tableId,screen,row)
{
    var table = document.getElementById(tableId);
    
    var clearRow = "";
    var clearType = "";
    var screenNum = false;
// Test for Screen?row
    if (screen.split("?") [2] != undefined)
    {
        clearType = screen.split("?") [2];
        clearRow = screen.split("?") [1];
        screen = screen.split("?") [0]; 
    }
    else if (screen.split("?") [1] != undefined)
    {
        clearType = "";
        clearRow = screen.split("?") [1];
        screen = screen.split("?") [0]; 
    }
    if (/^[0-9]+$/.test(screen))
    {
        screenNum = true;
    }
    if (screenNum)
    {
        if (screen > 0)
            screen = screen-1;
    }

    errorMsg = "";

    for (var i = 1; i < table.rows.length; i++)
    {
        try
        {
            if (screenNum)
            {
                if ((clearRow == "") || ((clearRow != "") && (clearRow == i)))
                {
// get Display Options for Current Screen
                    if (trnScreenOption[i].substr(screen,1) != "")
                    {
                        var o = trnScreenOption[i].substr(screen,1);
                        if ((o == "I") || (o == "V") || (o == "*") || (clearRow == i))
                        {
                            document.getElementById(''+i).value = "";
                            trnValue[i] = "";
                        }
                        if ((clearType != "I") && ((o == "I") || (o == "V") || (o == "P") || (o == "*")))
                        {
                            document.getElementById(''+i).placeholder = "";
                        }
                    }
                }
            }
            else
            {
// get Display Options for Current Screen
                if (trnName[i] == screen)
                {
                    document.getElementById(''+i).value = "";
                    trnValue[i] = "";
                    if (clearType != "I")
                    {
                        document.getElementById(''+i).placeholder = "";
                    }
                }
            }
        }
        catch(e)
        {
        }
    }
// Recursive Call to perform next Cell Validation instruction
    try
    {
        var validate = trnValidation[row];
    }
    catch (e)
    {
        validate = "";
    }
    idx = idx+1;
    if (document.getElementById("txtcurraction").value != "")
    {
        cellValidation(dataTable,row);
    }
    else if(document.getElementById('txtcurraction').value != "")
    {
        cellValidation(dataTable,row);
    }
    return false;
}


// Clear RDT Message
function clearMessage(row)
{
    try
    {
        document.getElementById("rdtmessage").innerHTML = "";
        document.getElementById("popupMessageContainer").style.display = none;
    }
    catch(e)
    {
    }
    if (row == undefined)
        return;
// Recursive Call to perform next Cell Validation instruction
    try
    {
        var validate = trnValidation[row];
    }
    catch (e)
    {
        validate = "";
    }
    idx = idx+1;
    if (document.getElementById("txtcurraction").value != "")
    {
        cellValidation(dataTable,row);
    }
    else if(document.getElementById('txtcurraction').value != "")
    {
        cellValidation(dataTable,row);
    }
    return;
}

// Refresh Screen Data
function refreshData(table,newData)
{
    const dataTableElement = document.getElementById('dataTable');
    var skip = false;
    var focusOn = "";
    var message = "";
    var page = document.getElementById("txtPageNum").value;
    if (newData.substr(0,2)=="DA")
	{
        newData = newData.substr(5);
	}
    if (newData.split("!")[1])
    {
        cmd = newData.split("!") [1];
        newData = newData.split("!") [0];
    }
    else
    {
        cmd = "";
    }
// Loop through Screen Table
    for (var i = 1; i < table.rows.length; i++)
    {
		let lowerName = "";
		try
		{
			lowerName = trnName[i].toLowerCase();
		}
		catch(error)
		{
			lowerName = "";
		}
// Loop through returned server data
        for (var c = 0; c < newData.split(",").length; c++)
        {
// Split-out validation string
            var vldStr = (newData.split(",") [c]);
// Split-out returned values
            if ((vldStr.split(":") [0]) == "")
                continue;
            if ((vldStr.split(":") [0]) == undefined)
                continue;
// Check returned field-name against screen-row field-name
            vldName = vldStr.split(":") [0];
            var replaceInput = "";
            if (vldName.toLowerCase() == "confirminput")
            {
                document.getElementById("confirminput").value = (vldStr.split(":") [1]);
                continue;
            }
            else if ((vldName.toLowerCase() == "storedvalue") || (vldName.toLowerCase() == "txtstoredvalue"))
            {
                document.getElementById("txtstoredvalue").value = (vldStr.split(":") [1]);
                continue;
            }
            else if (vldName.toLowerCase() == lowerName+"input")
            {
                vldName = trnName[i];
                replaceInput = "y";
            }
            else if (vldName.toLowerCase() == lowerName+"content")
            {
                vldName = trnName[i];
                replaceInput = "c";
            }
            else if (vldName.toLowerCase() == lowerName+"value")
            {
                vldName = trnName[i];
                replaceInput = "v";
            }
// Test for alert message
            else if (vldName.toLowerCase() == "alert")
            {
                message = (vldStr.split(":") [1])
                continue;
            }
            if (vldName.toLowerCase() == lowerName)
            {
// Test for RDT message
                if (lowerName == "rdtmessage")
                {
                    if ((messageType == "speak") || (messageType == "speech"))
                    {
                        if (vldStr.split(":") [1] != null && vldStr.split(":") [1] != undefined)
                        {
                            getMessage(vldStr.split(":") [1],"");
                        }
                    }
                    else
                    {
                        if (vldStr.split(":") [1] != null && vldStr.split(":") [1] != undefined && vldStr.split(":") [1] != "")
                        {
                            document.getElementById("rdtmessage").innerHTML = (vldStr.split(":") [1]);
                            let text = vldStr.split(":") [1];
                            popupMessageShow(text);
                        }
                    }
                    continue;
                }
// Test for Confirm Input
                if (lowerName == "confirminput")
                {                   
                    document.getElementById("confirminput").value = (vldStr.split(":") [1]);
                } 
// Test for Stored Value
                if ((lowerName == "storedvalue") || (lowerName == "txtstoredvalue"))
                {                   
                    document.getElementById("txtstoredvalue").value = (vldStr.split(":") [1]);
                }                 
// Replace screen values
                if ((vldStr.split(":") [1]) != undefined)
                {
                    try
                    {
// Store Returned Value
                        trnValue[i] = (vldStr.split(":") [1]);
                        trnValue[i] = trnValue[i].split('COLON').join(':');
// Store Returned Value in 'Content'
                        if ((vldStr.split(":") [1]) != "")
                        {
// Clear All Values
                            if ((vldStr.split(":") [1]) == "*")
                            {
                                trnValue[i] = "";
                                var element = document.getElementById(''+i);
                                element.value = "";
                                element.placeholder = "";
                            }
// Populate content
                            else if ((replaceInput == "c") || (replaceInput == "") || (replaceInput == "v"))
                            {
                                var element = document.getElementById(''+i);
                                var suggest = (vldStr.split(":") [1]);
                                suggest = suggest.split('COLON').join(':');
                                element.value = "";
                                element.placeholder = suggest;
//                              alert(element.placeholder);
                            }
// Replace 'Input' with Returned value if required
                            else if (((replaceInput == "" && document.getElementById(''+i).value != "") && (document.getElementById(''+i).value.trim() != "")) || (replaceInput == "y"))
                            {
                                var prefix = trnPrefix[i];
                                document.getElementById(''+i).value = prefix.substr(0,1)+(vldStr.split(":") [1]);
                                element.placeholder = "";
                            }
// Content Only
                            else if (replaceInput == "c")
                            {
                                document.getElementById(''+i).value = "";
                                trnValue[i] = "";
                                document.getElementById(''+i).placeholder = prefix.substr(0,1)+(vldStr.split(":") [1]);
                            }
// Content & Value
                            else if (replaceInput == "v")
                            {
                                document.getElementById(''+i).value = "";
                            }
// Virtual Pallet
                            if ((vldName.toLowerCase() == "toplt") && (replaceInput != "c") && (vldStr.split(":") [1]) != "*")
                            {
// Populate Pallet on Screen
                                var prefix = trnPrefix[i];
                                document.getElementById(''+i).value = prefix.substr(0,1)+(vldStr.split(":") [1]);
// Change Display Properties if required                                        
                                if ((vldStr.split(":") [2]) != "")
                                {
// Substitute Single Page Setting
                                    if ((vldStr.split(":") [2]).length==1)
                                    {
                                        if (cs < page-1)
                                        {
                                            cs = page-1;
                                        }
                                        if (cs > 0)
                                            trnScreenOption[i] = trnScreenOption[i].substr(0,cs)+(vldStr.split(":") [2])+trnScreenOption[i].substr(cs+1);
                                        else
                                            trnScreenOption[i] = (vldStr.split(":") [2])+trnScreenOption[i].substr(cs+1);
                                    }
// Substitute all Page Settings
                                    else
                                    {
                                        trnScreenOption[i] = (vldStr.split(":") [2])
                                    }
                                }
                                if ((vldStr.split(":") [3]) != "")
                                {
                                    if ((vldStr.split(":") [3]) == "clear")
                                    {
                                        document.getElementById(''+i).value = "";
                                        lockScreen = false;
                                        idx = 999;
                                    }
                                    else if ((vldStr.split(":") [3]) == "skip")
                                    {
                                        lockScreen = false;
                                        idx = 999;
                                        cs = cs+1;
                                        document.getElementById("txtPageNum").value = cs+1;
                                        page = cs+1;
                                        skip = true;
                                    }
// skip with auto-process (ap)
                                    else if ((vldStr.split(":") [3]).substr(0,6) == "skipap")
                                    {
                                        lockScreen = false;
                                        var direction = (vldStr.split(":") [3]).substr(6);
                                        if (!isNaN(direction))
                                        {
                                            idx = 999;
                                            document.getElementById("txtPageNum").value = parseInt(direction);
                                            skip = true;
                                            page = parseInt(direction);
                                        }
                                        else
                                        {
                                            for (var r = 1; r < table.rows.length; r++)
                                            {
                                                if (trnName[r] == direction)
                                                {
                                                    s = trnScreenOption[r].indexOf("I");
                                                    if (s == -1)
                                                        s = trnScreenOption[r].indexOf("*");
                                                    if (s == -1 || s == trnScreenOption[r].length-1)
                                                    {
                                                        s = trnScreenOption[r].length-1;
                                                        for (var i = 1;i<table.rows.length;i++)
                                                        {
                                                            if (trnScreenOption[i].substr(s,1) == "I")
                                                                trnScreenOption[i] = trnScreenOption[i].substr(0,s)+"H";
                                                        }
                                                        trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"I";
                                                        if ((trnName[r] == "post") || (trnName[r] == "rdtMessage"))
                                                           trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"P"; 
            //                                            s = s-1;
                                                    }
                                                    if (s != -1)
                                                        document.getElementById("txtPageNum").value = s+1;
                                                    idx = 999;
                                                    skip = true;
                                                    page = s+1;
                                                    document.getElementById("txtcurraction").value = trnValidation[r];
                                                    row = r;
                                                    focusOn = r;
                                                }
                                            }
                                        }
                                        s = page-1;
                                        idx = 0;
 //                                       cellValidation(dataTable,row);
                                    }
                                    else if ((vldStr.split(":") [3]).substr(0,4) == "skip")
                                    {
                                        lockScreen = false;
                                        var direction = (vldStr.split(":") [3]).substr(4);
                                        if (!isNaN(direction))
                                        {
                                            idx = 999;
                                            document.getElementById("txtPageNum").value = parseInt((vldStr.split(":") [3]).substr(4));
                                            skip = true;
                                            page = parseInt((vldStr.split(":") [3]).substr(4));
                                        }
                                        else
                                        {
                                            for (var r = 1; r < table.rows.length; r++)
                                            {
                                                if (trnName[r] == direction)
                                                {
                                                    s = trnScreenOption[r].indexOf("I");
                                                    if (s == -1)
                                                        s = trnScreenOption[r].indexOf("*");
                                                    if (s == -1 || s == trnScreenOption[r].length-1)
                                                    {
                                                        s = trnScreenOption[r].length-1;
                                                        for (var i = 1;i<table.rows.length;i++)
                                                        {
                                                            if (trnScreenOption[i].substr(s,1) == "I")
                                                                trnScreenOption[i] = trnScreenOption[i].substr(0,s)+"H";
                                                        }
                                                        if ((trnName[r] == "post") || (trnName[r] == "rdtMessage"))
                                                            trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"P"; 
                                                        else
                                                            trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"I";
            //                                            s = s-1;
                                                    }
                                                    if (s != -1)
                                                        document.getElementById("txtPageNum").value = s+1;
                                                    idx = 999;
                                                    skip = true;
                                                    page = s+1;
                                                    focusOn = r;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        gotoNext();
                                        return;
                                    }
                                }
                                else
                                {
// Go to Next Page
                                    gotoNext();
                                    return;
                                }
                                break;
                            }
                        }
                        else
                        {
                            document.getElementById(''+i).value = "";
                        }
                    }
                    catch(e)
                    {
                    }
                }
                if ((vldStr.split(":") [2]) != undefined)
                {
// Check for Display Format Change
                    if ((vldStr.split(":") [2]) != "")
                    {
                        if ((vldStr.split(":") [2]).length==1)
                        {
                            if (cs < page-1)
                            {
                                cs = page-1;
                            }
                            if (cs > 0)
                                trnScreenOption[i] = trnScreenOption[i].substr(0,cs)+(vldStr.split(":") [2])+trnScreenOption[i].substr(cs+1);
                            else
                                trnScreenOption[i] = (vldStr.split(":") [2])+trnScreenOption[i].substr(cs+1);
                        }
                        else
                        {
                            trnScreenOption[i] = (vldStr.split(":") [2])
                        }
                        refreshScreen(dataTable,cs);
                    }
                }
// Replace Validation Text
                if ((vldStr.split(":") [3]) != undefined)
                {
// Check for Validation Text
                    if ((vldStr.split(":") [3]) != "")
                    {
                        if ((vldStr.split(":") [3]) == "clear")
                        {
                            document.getElementById(''+i).value = "";
                            lockScreen = false;
                            idx = 999;
                        }
                        else if ((vldStr.split(":") [3]) == "skip")
                        {
                            lockScreen = false;
                            idx = 999;
                            cs = cs+1;
                            page = cs+1
                            skip = true;
                        }
// skip with auto-process (ap)
                        else if ((vldStr.split(":") [3]).substr(0,6) == "skipap")
                        {
                            lockScreen = false;
                            var direction = (vldStr.split(":") [3]).substr(6);
                            if (!isNaN(direction))
                            {
                                idx = 999;
                                document.getElementById("txtPageNum").value = parseInt(direction);
                                skip = true;
                                page = parseInt(direction);
                            }
                            else
                            {
                                for (var r = 1; r < table.rows.length; r++)
                                {
                                    if (trnName[r] == direction)
                                    {
                                        s = trnScreenOption[r].indexOf("I");
                                        if (s == -1)
                                            s = trnScreenOption[r].indexOf("*");
                                        if (s == -1 || s == trnScreenOption[r].length-1)
                                        {
                                            s = trnScreenOption[r].length-1;
                                            for (var i = 1;i<table.rows.length;i++)
                                            {
                                                if (trnScreenOption[i].substr(s,1) == "I")
                                                    trnScreenOption[i] = trnScreenOption[i].substr(0,s)+"H";
                                            }
                                            if ((trnName[r] == "post") || (trnName == "rdtMessage"))
                                                trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"P";
                                            else
                                                trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"I";
//                                            s = s-1;
                                        }
                                        if (s != -1)
                                            document.getElementById("txtPageNum").value = s+1;
                                        idx = 999;
                                        skip = true;
                                        page = s+1;
                                        document.getElementById("txtcurraction").value = trnValidation[r];
                                        row = r;
                                        focusOn = r;
                                    }
                                }
                            }
                            idx = 0;
//                            cellValidation(dataTable,row);
                        }
                        else if ((vldStr.split(":") [3]).substr(0,4) == "skip")
                        {
                            lockScreen = false;
                            var direction = (vldStr.split(":") [3]).substr(4);
                            if (!isNaN(direction))
                            {
                                idx = 999;
                                document.getElementById("txtPageNum").value = parseInt((vldStr.split(":") [3]).substr(4));
                                skip = true;
                                page = parseInt((vldStr.split(":") [3]).substr(4));
                            }
                            else
                            {
                                for (var r = 1; r < table.rows.length; r++)
                                {
                                    if (trnName[r] == direction)
                                    {
                                        s = trnScreenOption[r].indexOf("I");
                                        if (s == -1)
                                            s = trnScreenOption[r].indexOf("*");
                                        if (s == -1 || s == trnScreenOption[r].length-1)
                                        {
                                            s = trnScreenOption[r].length-1;
                                            for (var i = 1;i<table.rows.length;i++)
                                            {
                                                if (trnScreenOption[i].substr(s,1) == "I")
                                                    trnScreenOption[i] = trnScreenOption[i].substr(0,s)+"H";
                                            }
                                            trnScreenOption[r] = trnScreenOption[r].substr(0,s)+"I";
//                                            s = s-1;
                                        }
                                        if (s != -1)
                                            document.getElementById("txtPageNum").value = s+1;
                                        idx = 999;
                                        skip = true;
                                        page = s+1;
                                        focusOn = r;
                                    }
                                }
                            }
// Replace Validation / Processing script
                            vldStr = vldStr.split(":") [3];
                            if (vldStr.split(";") [1] != undefined)
                            {
                                trnValidation[firstRow] = vldStr.split(";") [1];
                                trnValidation[firstRow] = trnValidation[firstRow].split("|COMMA|").join(",");
                                trnValidation[firstRow] = trnValidation[firstRow].split("|COLON|").join(":");
                            }                               
                        }
                        else if ((vldStr.split(":") [3]) == "page+")
                        {
                            idx = 999;
                            gotoNext();
                            return;
                        }
                        else if ((vldStr.split(":") [3]) == "page-")
                        {
                            idx = 999;
                            gotoPrev();
                            return;
                        }
                        else
                        {
                            trnValidation[i] = (vldStr.split(":") [3])
                            trnValidation[i].split(";").join(":");
                            idx = 0;
                            refreshScreen(dataTable,cs);
                        }
                    }
                }
// Replace Background
                if ((vldStr.split(":") [4]) != undefined)
                {
                    if ((vldStr.split(":") [4]).substr(0,4)=="head")
                    {
                        let colour = (vldStr.split(":") [4]).substr(4);
                        if (colour != "default")
                        {
                            document.getElementById('td1'+i).style.backgroundColor=colour;
                            document.getElementById('td1t'+i).style.backgroundColor='black';
                            document.getElementById('td1t'+i).style.color='white';
//                            document.getElementById('td1t'+i).style.mixBlendMode='difference';
//                            document.getElementById('td1t'+i).style.backgroundBlendMode='difference';
                            document.getElementById('header-block').style.backgroundColor=colour;
                            document.getElementById('navPanel').style.backgroundColor=colour;
                        }
                        else
                        {
                            document.getElementById('td1'+i).style.backgroundColor='transparent';
                            document.getElementById('td1t'+i).style.backgroundColor='transparent';
                            document.getElementById('td1t'+i).style.color='black';
                            document.getElementById('header-block').style.backgroundColor='#3A1D49';
                            document.getElementById('navPanel').style.backgroundColor='#3A1D49';
                        }
                    }
                    else
                    {
                        document.getElementById('td1'+i).style.backgroundColor=vldStr.split(":") [4];
                    }
                }
// Replace text colour
                if ((vldStr.split(":") [5]) != undefined)
                {
                    document.getElementById(''+i).style.color=vldStr.split(":") [5];
                }
//                break;
            }   
        }
    }
    
    if (cmd != "")
    {
// Test for Initial Command to Run
        idx = 998;
        document.getElementById("txtcurraction").value = cmd;
        cellValidation(dataTable,row);
        cellFail = true;
        document.getElementById("txtPageNum").value = page;
        gotoHere();
    }
    
    if (skip == true)
    {
        cellFail = true;
        document.getElementById("txtPageNum").value = page;
        gotoHere('',focusOn);
    }
    
    if (message != "")
    {
        getMessage(message);
    }
}

// format Transaction Validation String - Replace Text between '/' with associated screen Input values.
function validationFormat(vldStr)
{
    var table = document.getElementById(dataTable);
    var findStr = "";
    var replaceStr = "";
    for (var i = 1; i < table.rows.length; i++)
    {
        var prefix = trnPrefix[i];
// replace with formatted value stored in trnValue
        try
        {
            findStr = "/"+trnName[i]+"/";
            if (trnValue[i].substr(0,1) != "")
            {
                replaceStr = trnValue[i];
            }
            else
            {
                replaceStr = document.getElementById(''+i).value;
                if ((prefix != "") && (prefix != null))
                    replaceStr = replaceStr.substring(1);
            }
            vldStr = vldStr.split(findStr).join(replaceStr);
        }
        catch(e)
        {
        }
// replace with content column
        try
        {
            findStr = "/"+trnName[i]+"content/";
            if (document.getElementById(''+i).placeholder != "")
            {
                replaceStr = document.getElementById(''+i).placeholder;
            }
            else
            {
                replaceStr = document.getElementById(''+i).value;
                if ((prefix != "") && (prefix != null))
                    replaceStr = replaceStr.substring(1);
            }
            vldStr = vldStr.split(findStr).join(replaceStr);
        }
        catch(e)
        {
        }
// replace with value from input column
        try
        {
            findStr = "/"+trnName[i]+"input/";
            replaceStr = document.getElementById(''+i).value;
            if ((prefix != "") && (prefix != null))
                replaceStr = replaceStr.substring(1);
            vldStr = vldStr.split(findStr).join(replaceStr);
        }
        catch(e)
        {
        }
    }
    try
    {
        findStr = "/user/";
//      replaceStr = $("#txtUser").val();
        replaceStr = document.getElementById('txtUser').value;
        vldStr = vldStr.split(findStr).join(replaceStr);
    }
    catch(e)
    {
    }
    try
    {
        findStr = "/confirminput/";
        replaceStr = document.getElementById('confirminput').value;
        vldStr = vldStr.split(findStr).join(replaceStr);
    }
    catch(e)
    {
    }
    try
    {
        findStr = "/storedvalue/";
        replaceStr = document.getElementById('txtstoredvalue').value;
        vldStr = vldStr.split(findStr).join(replaceStr);
    }
    catch(e)
    {
    }
    try
    {
        findStr = "/txtstoredvalue/";
        replaceStr = document.getElementById('txtstoredvalue').value;
        vldStr = vldStr.split(findStr).join(replaceStr);
    }
    catch(e)
    {
    }
    try
    {
        findStr = "/dbase/";
        replaceStr = userSettings[0].dbase;
        vldStr = vldStr.split(findStr).join(replaceStr);
    }
    catch(e)
    {
    }
    try
    {
        findStr = "/trys/";
        replaceStr = trys;
        vldStr = vldStr.split(findStr).join(replaceStr);
    }
    catch(e)
    {
    }
    return vldStr;
}

// Cell Validation / post / next page
function cellValidation(tableId, row)
{
    if (lockScreen == false)
    {
        lockScreen = true;
    }
    const dataTableElement = document.getElementById('dataTable');
    if (row == undefined)
    {
        row = parseInt(tableId.split('comma')[1]);
        tableId = tableId.split('comma')[0];
    }
    if (idx >= 999)
    {
        lockScreen = false;
        loading('off');
        rowValidated("OK  -datatableshow");
//        cellFail = false;
        return false;
    }
    
    if (document.getElementById('txtcurraction').value == "")
    {
        lockScreen = false;
        loading('off');
        rowValidated("OK  -datatableshow");
//        cellFail = false;
        return false;
    }
    if (row == 0)
    {
        var vldStr = document.getElementById('txtcurraction').value;
        vldFunction = vldStr.split(":") [0];
//		console.log("curr1-"+idx+" "+vldStr+" "+vldFunction);
// Change Transaction / Reload Screen
        if ((vldFunction == "changetran") || (vldFunction == "CHGTRAN"))
        {
            document.getElementById('txtcurraction').value = "";
            if (vldFunction == "changetran")
                vldStr = vldStr.substr(11);
            if (vldFunction == "CHGTRAN")
                vldStr = vldStr.substr(8);
            changeTran(vldStr);
            idx = 999;
            cellFail = true;
            document.getElementById("popupMessageContainer").style.display = "none";
            return false;
        }
    }
    var errorMsg = "";
    var vldStr = "";
    cellFail = false;
    var txtConnection = document.getElementById("txtConnectTrn").value;
    var table = document.getElementById(tableId);
    try
    {
        var currentInput = document.getElementById(''+row).value;
    }
    catch (e)
    {
        currentInput = "";
    }
    try
    {
        var prefix = trnPrefix[row].toUpperCase();
    }
    catch (e)
    {
        prefix = "";
    }
/*    
    try
    {
        var validate = trnValidation[row];
    }
    catch (e)
    {
        validate = "";
    }
*/
/*
// first pass of row validation
    if (idx == 0)
    {
        document.getElementById('txtcurraction').value = trnValidation[row];
    }
*/
// test for outstanding actions
	eol = 0;
    if (document.getElementById('txtcurraction').value != "")
    {
        var validate = document.getElementById('txtcurraction').value;
        var i = validate.indexOf(',');
        if (i > 0)
        {
            document.getElementById('txtcurraction').value = validate.substr(i+1);
			eol = 0;
        }
        else
        {
            document.getElementById('txtcurraction').value = "";
			eol = 1;
        }
		if (validate.substr(0,4) == "skip")
		{
			eol = 0;
            lockScreen = false;
            loading('off');
		}
		if (validate.substr(0,4) == "page")
		{
			eol = 0;
            lockScreen = false;
            loading('off');
		}
//      if (validate.substr(0,1) != ",")
//          validate = ","+validate;
//      idx = 1;
    }
//    console.log("curr2-"+idx+" "+validate);
    if ((validate == null) || (validate == undefined))
    {
        validate = "";
    }
// Log-On
    if (validate.substr(0,21).toLowerCase() == "validate:registeruser")
    {
        document.getElementById("txtUser").value = document.getElementById("1").value;
        document.getElementById("txtPwd").value = document.getElementById("2").value;
        var userId = document.getElementById("1").value;
        var password = document.getElementById("2").value;
        url = ajaxPath+"rdtphp/user.php"+
            "?function=userlogin&userid="+userId+"&password="+password+
            "&filter=";
        get(url).then(function(response) 
        {
            userLoggedIn(response);
        }, 
        function(error) 
        {
            getMessage("FAIL-"+error);
        })
        return;
    }
// Local Validation - Only checked if idx = 0
    if (idx == 0)
    {  
// Prefix - Only Checked if idx=0
        if (prefix != "")                    
        {
            var firstChar = currentInput.substr(0,1).toUpperCase();
            var s = prefix.indexOf(firstChar);
            if (s == -1)
            {
                id = row;
                rowValidated("FAIL-Prefix Error");
                cellFail = true;
                return false;
            }
        }
// Input cannot be blank - Only Checked if idx = 0
//      if ((trnScreenOption[row].substr(cs,1)=="I") && ((currentInput == "") || (currentInput == null) || (currentInput.substr(0,1) == " ") || ((prefix != "") && (currentInput.substr(1,1) == ""))))
        if (row < 99)
        {
            if((trnScreenOption[row]==undefined) || (currentInput == undefined))
            {
                document.getElementById(''+row).value="";
                trnValue[row] = "";
                errorMsg = "Content Error - "+table.rows[row].cells[0].innerHTML;
                getMessage("content error",table.rows[row].cells[0].innerHTML);
                cellFail = true;
                return false;
            }
            else if((trnScreenOption[row].substr(cs,1)=="I") && ((currentInput == "$") || (currentInput.substr(0,1) == "$") || ((prefix != "") && (currentInput.substr(1,1) == ""))))
            {
                document.getElementById(''+row).value="";
                trnValue[row] = "";
                errorMsg = "Content Error - "+table.rows[row].cells[0].innerHTML;
                getMessage("content error",table.rows[row].cells[0].innerHTML);
                cellFail = true;
                return false;
            }
            else
            {
                if (prefix != "")
                    trnValue[row] = currentInput.substr(1).toUpperCase();
                else
                    trnValue[row] = currentInput.toUpperCase();
            }
    // Test for Pre-Set Content     
            var vldStr = "";
            var errorMsg = "";
            var s = 0;
    // Hard-coded test for Vendor Part Contents
            if ((trnScreenOption[row].substr(cs,1)=="V") && (table.rows[row].cells[0].innerHTML == "S.Part"))
            {
    // look for content in input string
                vldStr = currentInput;
                s = vldStr.indexOf(table.rows[row].cells[2].innerHTML);
                if (s == -1)
                {
                    document.getElementById(''+row).value="";
                    trnValue[row] = "";
                    errorMsg = "Content Error - "+table.rows[row].cells[0].innerHTML;
                    getMessage("content error",table.rows[row].cells[0].innerHTML);
                    cellFail = true;
                    return false;
                }
            }
            else if ((trnScreenOption[row].substr(cs,1)=="V"))
            {
                vldStr = "";
                errorMsg = "";
    // If 'content' cell contains ',' separated entries - validate against each entry
                for (var i = 0; i<5; i++)
                {
                    vldStr = (document.getElementById(''+row).placeholder).split(",") [i];
                    if ((i == 0) && (vldStr == ""))
                        vldStr = document.getElementById(''+row).placeholder;
                    if ((vldStr != "") && (vldStr != null) && (vldStr != undefined))
                    {
                        if (prefix != "")
                            vldStr = prefix+vldStr;
                        if (currentInput != vldStr)
                            errorMsg = "FAIL";
                    }
                }
                if ((errorMsg != "") && (errorMsg == "FAIL"))
                {
                    document.getElementById(''+row).value="";
                    trnValue[row] = "";
                    errorMsg = "Content Error - "+table.rows[row].cells[0].innerHTML;
                    getMessage("content error",table.rows[row].cells[0].innerHTML);
                    cellFail = true;
                    return false;
                }
            }  
        }
    }

// Server Validation / processing
    if (validate != "")
    {
        const dataTableElement = document.getElementById('dataTable');
        
        i = validate.indexOf(",");
        if (i==-1)
            var vldStr = validate;
        else
            var vldStr = validate.split(",") [0];
        var vldFunction = "";

// Extract Validation Function (delimited by ':' - (eg. validate:, replace:, refresh:, update:, post:, page:, changetran:, clearscreen, etc.))
        if (vldStr == undefined)
        {
            idx = 999;
            lockScreen = false;
            loading('off');
            rowValidated("OK  -datatableshow");
            return false;
        }
        vldFunction = vldStr.split(":") [0];
        if (vldFunction == "listen")
        {
            if (vldStr.split(":") [1] == "start")
            {
                recognition.start();
            }
            if (vldStr.split(":") [1] == "stop")
            {
                recognition.stop();
            }
        }

// Record Start & End TimeStamp
        else if (vldFunction == "rdttime")
        {
            if (vldStr.split(":") [1] == "start")
            {
                rdtTimestamp("start",row);
            }
            if (vldStr.split(":") [1] == "stop")
            {
                rdtTimestamp("stop",row);
            }
            return false;
        }

// Change Transaction / Reload Screen
        else if ((vldFunction == "changetran") || (vldFunction == "CHGTRAN"))
        {
            vldStr = vldStr.split(":") [1];
            changeTran(vldStr);
            idx = 999;
            cellFail = true;
            document.getElementById("popupMessageContainer").style.display = "none";
            return false;
        }

// Clear Screen Input Fields
        else if (vldFunction.toLowerCase() == "clearscreen")
        {
            vldStr = vldStr.split(":") [1];
            clearScreen(dataTable,vldStr,row);
            return false;
        }
// Text Panel hide
        else if (vldFunction.toLowerCase() === 'popuptexthide')
        {
            popupTextHide();
            rowValidated("OK  -datatableshow");
            return false;
        }        
// DataTable Element Hide/Show
        else if (vldFunction.toLowerCase() === 'datatablehide')
        {
            dataTableElement.style.opacity = '0';
            rowValidated("OK  -datatablehide");
            return false;
        }
        else if (vldFunction.toLowerCase() === 'datatableshow')
        {
            dataTableElement.style.opacity = '1';
            rowValidated("OK  -datatableshow");
            return false;
        }
// lock / unlock screen
        else if (vldFunction.toLowerCase() === 'lock')
        {
            lockScreen = true;
            rowValidated("OK  -lockscreen");
            return false;
        }
        else if (vldFunction.toLowerCase() === 'unlock')
        {
            lockscreen = false;
            rowValidated("OK  -unlockscreen");
            return false;
        }        
// Display Next Requested Screen / Page
        else if (vldFunction == "page")
        {
            cs = parseInt(document.getElementById("txtPageNum").value-1);
            vldStr = vldStr.split(":") [1];
            if ((vldStr == "page"))
                cs=cs+0;
            else if ((vldStr == "page+"))
            {
                cs=cs+1;
                row = 0;
                while(cs<trnScreenOption.length)
                {
                    for (i = 1; i < trnScreenOption.length; i++)
                    {
                        if ((trnScreenOption[i].substr(cs, 1) === "I") || (trnScreenOption[i].substr(cs, 1) === "*")) 
                        {
                            row = i;
                            break;
                        }
                    }
                    if (row > 0)
                    {
                        break;
                    }
                    cs=cs+1;
                }
                if (cs >= 0)
                {
                    document.getElementById("txtPageNum").value = cs+1;
                    gotoHere('',row);
                }
                else
                {
                    rowValidated("OK  -page");
                }
                return false;
            }
            else if (vldStr.substr(0,5) == "page+")
            {
                cs=cs+parseInt(vldStr.substr(5));
            }
            else if ((vldStr == "page-"))
            {
                cs=cs-1;
                row = 0;
                while(cs>-1)
                {
                    for (i = 1; i < trnScreenOption.length; i++)
                    {
                        if ((trnScreenOption[i].substr(cs, 1) === "I") || (trnScreenOption[i].substr(cs, 1) === "*")) 
                        {
                            row = i;
                            document.getElementById(''+i).value = "";
                            break;
                        }
                    }
                    if (row > 0)
                    {
                        break;
                    }
                    cs=cs-1;
                }
                if (cs >= 0)
                {
                    document.getElementById("txtPageNum").value = cs+1;
                    gotoHere('',row);
                    idx = 999;
                    cellFail=true;
                    return false;
                }
                else
                {
                    rowValidated("OK  -page");
                }
                return false;
            }
            else if (vldStr.substr(0,5) == "page-")
            {
                cs=cs-parseInt(vldStr.substr(5));
            }
            else if (vldStr.substr(0,4) == "page")
            {
                cs=parseInt(vldStr.substr(4));
                cs=cs-1;
            }
            
            if (cs < 0)
            {   
                changeTran("LOGON");
                return false;
            }   
            document.getElementById("txtPageNum").value = cs+1;
            gotoHere();
            idx = 999;
            cellFail=true;
            return false;
        }
		else if (vldFunction == "preprocess")
		{
			var cs = vldStr.split(":") [1];
			if (cs == undefined)
			{
				cs = null;
			}
			preprocess(dataTable,cs);
            console.log("current:"+document.getElementById('txtcurraction').value);
            id = row;
            rowValidated("OK  -preprocess");
            return false;
		}
        else if (vldFunction == "togglebutton" || vldFunction == "toggle")
        {
            var button = vldStr.split(":") [1];
            var onoff = vldStr.split(":") [2];
            togglebutton(button,onoff);
            rowValidated("OK  -togglebutton");
            return false;
        }
        // Full Screen
        if ((vldFunction == "fullscreen") || (vldFunction == "FULLSCREEN"))
        {
            var onoff = vldStr.split(":") [1];
            toggleScreen(onoff);
            id = row;
            rowValidated("OK  -fullscreen");
            return false;
        }
        // Skip
        if ((vldFunction == "skip") || (vldFunction == "SKIP"))
        {
            lockScreen = false;
            loading('off');
            var skipTo = vldStr.split(":") [1];
            if (skipTo == "sequence")
            {
                skipTo = getCurrentRow();
            }
            id = row;
            rowValidated("DATA:"+skipTo+":::skip"+skipTo);
            return false;
        }
        // SkipAP (skip & auto-process next step)
        if ((vldFunction == "skipap") || (vldFunction == "SKIPAP"))
        {
            var skipTo = vldStr.split(":") [1];
            lockScreen = false;
            loading('off');
            id = row;
            rowValidated("DATA:"+skipTo+":::skipap"+skipTo);
            return false;
        }
        // DATA Process DATA:
        if ((vldFunction == "data") || (vldFunction == "DATA"))
        {
            var data = vldStr.split(":") [1];
            id = row;
            rowValidated("DATA:"+data);
            return false;
        }
        // image
        if ((vldFunction == "image") || (vldFunction == "IMAGE"))
        {
            var imageFolder = vldStr.split(":") [1];
            imageFolder = validationFormat(imageFolder);
            popupImage('IMAGE',imageFolder);
            id = row;
            rowValidated("OK  -popupimage");
            return false;
        }
        else if (vldFunction === 'ocr')
        {
            ocrImage();
            lockscreen = false;
            rowValidated("OK  -ocr");
            return false;
        }  
        else if(vldFunction.toLowerCase() == "checkmandatory")
        {
            cellFail = checkMandatory();
            if (cellFail == false)
            {
                id = row;
                rowValidated("OK  -checkmandatory");
            }
            return false;            
        }
// ValidateRDT - generic Validation / Return Values
        else if (vldFunction.toLowerCase() == "validaterdt")
        {
//                  loading("on");
            vldProgram = vldFunction;
            vldStr = vldStr.split(":") [1];
            vldType = vldStr.split("?") [0];
            vldStr = vldStr.split("?") [1];
            vldStr = validationFormat(vldStr);
            vldStr = vldStr.split("#").join("");
// add UserId to string
            vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
            
            url = ajaxPath+"rdtphp/"+vldProgram+".php"+
                    "?function="+vldType+
/*
                    "&connection="+userSettings[0].path+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
*/
                    "&table="+
                    "&returnfields=";

            id = row;
            vldStr = vldStr.split("|AND|").join(",");
            vldStr = vldStr.split("=").join(":");
            var dataArray = vldStr.split(",");
            dataObj = {};
            for (let i = 0; i < dataArray.length; i++) 
            {
                dataField = dataArray[i].split(":")[0];
                dataValue = dataArray[i].split(":")[1];
                dataObj[dataField]=dataValue;
            }
            
            post(url,JSON.stringify(dataObj)).then(
            function(response)
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            
            return false;
        }
// Pick label
        else if (vldFunction.toLowerCase() == "post")
        {
            vldStr = vldStr.split(":") [1];
            vldProgram = vldStr.split("?") [0];
            vldStr = vldStr.split("?") [1];
            vldStr = validationFormat(vldStr);
            vldStr = vldStr.split("#").join("");
// add UserId to string
            vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|userId="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
                        
            url = ajaxPath+vldProgram+
                    "?function="+vldFunction+
                    "&connection="+userSettings[0].path+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
                    "&returnfields=";

            id = row;
            vldStr = vldStr.split("|AND|").join(",");
            vldStr = vldStr.split("=").join(":");
            var data = encodeURI(vldStr);
            var dataArray = data.split(",");
            dataObj = {};
            for (let i = 0; i < dataArray.length; i++) 
            {
                dataField = dataArray[i].split(":")[0];
                dataValue = dataArray[i].split(":")[1];
                dataObj[dataField]=dataValue;
            }
            post(url,JSON.stringify(dataObj)).then(function(response)
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            
            return false;
        }

// Call specified URL
        else if (vldFunction.toLowerCase() == "url")
        {
            vldStr = vldStr.split(":") [1];
            vldProgram = vldStr.split("?") [0];
            vldStr = vldStr.split("?") [1];
            vldStr = validationFormat(vldStr);
            vldStr = vldStr.split("#").join("");
// add UserId to string
            vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|userId="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
                        
            url = vldProgram+
                    "?function="+vldFunction+
                    "&connection="+userSettings[0].path+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
                    "&returnfields=";

            id = row;
            vldStr = vldStr.split("|AND|").join(",");
            vldStr = vldStr.split("=").join(":");
            var data = encodeURI(vldStr);
            var dataArray = data.split(",");
            dataObj = {};
            for (let i = 0; i < dataArray.length; i++) 
            {
                dataField = dataArray[i].split(":")[0];
                dataValue = dataArray[i].split(":")[1];
                dataObj[dataField]=dataValue;
            }
            post(url,JSON.stringify(dataObj)).then(function(response)
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            
            return false;
        }
// Call specified URL
        else if (vldFunction.toLowerCase() == "pdf")
        {
            vldStr = vldStr.split(":") [1];
            vldProgram = vldStr.split("?") [0];
            vldStr = vldStr.split("?") [1];
            vldStr = validationFormat(vldStr);
            vldStr = vldStr.split("#").join("");
// add UserId to string
            vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|userId="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
                        
            url = vldProgram+
                    "?function="+vldFunction+
                    "&filter="+vldStr+
                    "&returnfields=";

            id = row;
            loading('on');
            fetch(url)
            .then(response => 
            {
                if (response.ok) 
                {
                    return response.text();
                }
                exit('FAIL-Network response error.');
            })
            .then(data =>
            {
                loading('off');
                try
                {
                    jsonObject = JSON.parse(data);
                }
                catch
                {
                    return fetch(url)
                    .then(response => response.blob())
                    .then(blob =>
                    {
                        if (blob != undefined)
                        {
                            const url = URL.createObjectURL(blob);
                            const modal = document.getElementById('iframeModal');
                            const iframe = document.getElementById('printIframe');
                            iframe.src = url;
                            modal.style.display = 'block';
                        }
                    });
                }
                if (jsonObject.status.substr(0,4) == "OKGD")
                {
                    const iframe = document.getElementById('printIframe');
                    const modal = document.getElementById('iframeModal');
                    const url = jsonObject.url;
                    if (jsonObject.type == "pdf")
                    {
                        iframe.src = url;
                    }
                    else if (jsonObject.type == "image")
                    {
                        const img = new Image();
                        img.src = url;
                        img.onload = function()
                        {
                            const resizedDataUri = resizeImage(img, 500, 0.8);
                            iframe.style.display = 'flex';
                            iframe.style.maxWidth = '100%';
                            iframe.style.maxHeight = '100%';
                            iframe.style.objectFit = 'contain';
                            iframe.src = resizedDataUri;
                            modal.style.display = 'block';
                        }

                    }
                    else if (jsonObject.type == "blob")
                    {
                        const url = URL.createObjectURL(jsonObject.blob);
                        iframe.src = url;
                        modal.style.display = 'block';
                    }
                    else if (jsonObject.type == "xlsx")
                    {
                        var _window = window.open(url, '_blank');
                    }
                    else if (jsonObject.type == "url")
                    {
                        const url = jsonObject.url;
                        const iframe = document.getElementById('printIframe');
                        const modal = document.getElementById('iframeModal');
                        const currRow = document.getElementById(row);
// URL Link
                        const linkContainer = document.getElementById('file-link-container');
// Create an anchor element
                        const link = document.createElement('a');
                        link.href = url;
                        link.textContent = 'View File';
                        link.target = '_blank';
// Append the link to the container
                        linkContainer.appendChild(link);
                        linkContainer.style.position = 'absolute';
                        const posElement = document.querySelector('footer');
                        linkContainer.style.bottom = posElement.offsetHeight + 'px'; // Position above the footer
                        linkContainer.style.left = posElement.offsetLeft + 'px';
                        linkContainer.style.width = posElement.offsetWidth + 'px';
                        linkContainer.style.zIndex = 2000;
                        linkContainer.style.display = 'flex';
                        manageTimeout("set", "linkTimeout", () =>
                        {
                            linkContainer.style.display = 'none';
                            linkContainer.innerHTML = '';
                        }, 10000);
                        rowValidated("OK  -iframeClose");
                        return false;
                    }
                    else
                    {
                        try
                        {
                            document.getElementById("printIframe").innerHTML = '<object id="docPanel" class="contain" data="'+url+'"></object>';
                            modal = document.getElementById('iframeModal');
                            modal.style.display = 'block';
                        }
                        catch(e)
                        {
                            var _window = window.open(url, '_blank');
                        }
                    }
                }
                else
                {
                    return false;
                }
            })
            .catch(error => {
                alert('FAIL-There was a problem with the fetch operation:', error);
                loading("off");
            }); 
            cellFail = false;
            return false;
        }
// assembly - generic Validation / Return Values
        else if (vldFunction.toLowerCase() == "receiving")
        {
//                  loading("on");

            vldStr = vldStr.split(":") [1];
            vldType = vldStr.split("?") [0];
            vldStr = vldStr.split("?") [1];
            vldStr = validationFormat(vldStr);
            vldStr = vldStr.split("#").join("");    
// add UserId to string
            vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
            vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
            
// Encode String
            vldStr = encodeURI(vldStr);
            vldStr = vldStr.replace(/%20/g, " ");
            vldStr = vldStr.split("+").join("%2B");
            vldStr = vldStr.split("&").join("%26");
            
            url = ajaxPath+"rdtphp/receiving.php"+
                    "?function="+vldType+
                    "&connection="+userSettings[0].path+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
                    "&table="+
                    "&returnfields="+
                    "&filter="+vldStr;
            id = row;
            get(url).then(function(response) 
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            return false;
        }
// getdata - SQL/CMD string from Transaction
        else if (vldFunction == "getdata")
        {
//                  loading("on");
            vldStr = vldStr.split(":") [1];
            vldTable = vldStr.split("?") [0];
            vldStr = vldStr.split("?") [1];
            vldStr = validationFormat(vldStr);
            
// Encode String
            vldStr = encodeURI(vldStr);
            vldStr = vldStr.replace(/%20/g, " ");
            vldStr = vldStr.split("+").join("%2B");
            vldStr = vldStr.split("&").join("%26");
            url = ajaxPath+"rdtphp/validaterdt.php"+
                    "?function="+vldFunction+
/*
                    "&connection="+userSettings[0].path+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
*/
                    "&table="+vldTable+
                    "&returnfields="+
                    "&filter="+vldStr;
            id = row;
            
            get(url).then(function(response) 
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            return;
        }
        else if (vldFunction == "clearmessage")
        {
            clearMessage(row);
        }
        else if (vldFunction == "confirm")
        {
            showConfirm(vldStr,row,"OK","FAIL","");
        }
// Screen Colour
        else if(vldFunction == "colour")
        {
            vldStr = vldStr.split(":") [1];
            userColour = validationFormat(vldStr);
            colour = getScreenColour(userColour);
            boxColour = colour.split(",") [0];
            buttonColour = colour.split(",") [1];
        }
// hide / show select
        else if (vldFunction == "hideselect")
        {
            hideSelect();
            return false;
        }
        else if(vldFunction == "showselect")
        {
            showSelect();
            return false;
        }
        else if (vldFunction == "handkey")
        {
            vldStr = vldStr.split(":") [1];
            if (vldStr == "NO")
                handKey = "N";
            else
                handKey = "Y";
//            ajaxGet(url, rowValidated);
            get(url).then(function(response) 
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            return false;
        }
// Unspecified Function
        else if (vldFunction != "")
        {
//                  rdtEnd = now();
            
            vldProgram = vldFunction;
            if (vldStr == undefined)
                var vldStr = "";
                
            if (vldStr.split(":") [1] != undefined)
            {
                vldStr = vldStr.split(":") [1];
// No Parameters
                if (vldStr.split("?") [1] == undefined)
                {
                    vldFunction = vldStr;
                }
                             
                else
                {
                    vldFunction = vldStr.split("?") [0];
// Use Screen Values
                    if (vldStr.split("?") [1] == undefined)
                    {
                        vldStr = getScreenData(table);
                    }
// Use Transaction Parameters
                    else
                    {
                        vldStr = vldStr.split("?") [1];
                        vldStr = validationFormat(vldStr);
                    }
                }

                vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
                vldStr = vldStr+"|AND|currentTab="+document.getElementById("txtTab").value;
                vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
            }
                                                                                
/*            
// Encode String
            filter = encodeURI(vldStr);
            filter = filter.replace(/%20/g, " ");
            filter = filter.split("+").join("%2B");
            filter = filter.split("&").join("%26");
    
            url = ajaxPath+"rdtphp/"+vldProgram+".php"+
                "?function="+vldFunction.toLowerCase()+
                "&connection="+userSettings[0].path+
                "&host="+userSettings[0].dbhost+
                "&user="+userSettings[0].dbuser+
                "&pword="+userSettings[0].dbpwd+
                "&dbase="+userSettings[0].dbase+
                "&mqserver="+userSettings[0].mqserver+
                "&filter="+filter;  
            id = row;
            get(url).then(function(response) 
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
*/
            id = row;
			filter = encodeURI(vldStr);
            filter = filter.replace(/%20/g, " ");
            filter = filter.split("+").join("%2B");
            filter = filter.split("&").join("%26");
            url = ajaxPath+"rdtphp/"+vldProgram+".php"+
                "?function="+vldFunction.toLowerCase()+
				"&connection="+userSettings[0].path+
                "&host="+userSettings[0].dbhost+
                "&user="+userSettings[0].dbuser+
                "&pword="+userSettings[0].dbpwd+
                "&dbase="+userSettings[0].dbase+
                "&mqserver="+userSettings[0].mqserver+
				"&filter="+filter;
            vldStr = vldStr.split("|AND|").join(",");
            vldStr = vldStr.split("=").join(":");
            var dataArray = vldStr.split(",");
            dataObj = {};
            for (let i = 0; i < dataArray.length; i++) 
            {
                dataField = dataArray[i].split(":")[0];
                dataValue = dataArray[i].split(":")[1];
                dataObj[dataField]=dataValue;
            }
            
            post(url,JSON.stringify(dataObj)).then(
            function(response)
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            
            return false;

//          return;
        }
        else
        {
            return;
        }    
    }
    else
    {
        try
        {
            if (trnPrefix[row] != "")
                trnValue[row] = document.getElementById(''+row).value.substring(1).toUpperCase();
            else
                trnValue[row] = document.getElementById(''+row).value.toUpperCase();
        }
        catch(e)
        {
            trnValue[row] = "";
        }
        lockScreen = false;
        loading('off');
    }
    return false;
}

// Server Response Row-Validation (id = current row)
function rowValidated(xmlDoc)
{
    const dataTableElement = document.getElementById('dataTable');
    var errorMsg = "";
    cellFail = false;
    var table = document.getElementById(dataTable);
    if (typeof xmlDoc === 'string')
    {
        var txtResponse = xmlDoc;
        var txtData = "";
    }
    else
    {
        if ((xmlDoc.txtResponse) && (xmlDoc.txtResponse != "") && (xmlDoc.txtResponse != undefined))
        {
            txtResponse = xmlDoc.txtResponse;
        }
        else
        {
    // Extract status & Data from JSON Object (from Ajax Call) 
            try
            {
                try
                {
                    var strJSON = xmlDoc.responseText;
                }
                catch(e)
                {
                    var strJSON = xmlDoc;
                }
                if (strJSON == undefined)
                    var strJSON = xmlDoc;
                var objJSON = eval("(function(){return " + strJSON + ";})()");
                var txtResult = objJSON.status;
                var txtData = objJSON.data;
            }
            catch(e)
            {
                var txtResponse = strJSON;
                var txtData = "";
            }
        }
    }
// Split Return String to Array Elements
    var txtRow = "";
    if (txtResponse.substr(0,4) == "ROW<")
    {
//              txtResponse = txtResponse.substr(5);
        txtRow = txtResponse.split(">") [0];
        row = parseInt(txtRow.substr(4));
        txtRow = txtRow.substr(0,3);
//              row = parseInt(row);
        txtResponse = txtResponse.split(">") [1];
// Check current row
        if (id < row)
            id = row;
        currentRow = row;
    }
// Build Dynamic Table Screen
	else if ((txtResponse).substr(0,6) == "TABLEP")
    {
        document.getElementById('popupref').value = "";
		document.getElementById('popupPanel').style.display = "block";
		document.getElementById("popupHeader").innerHTML="Table";
		document.getElementById('imageContainer').style.display = "none";
		document.getElementById('popupTable').style.display = "block";
		document.getElementById('inputPanel').style.display = "block";
		CreateTableFromJSON(txtResponse,"popupTable");
        cellFail = false;
        lockScreen = false;
        loading("off");
        return false;
    }            
    else if ((txtResponse).substr(0,5) == "TABLE")
    {
//        idx = 0;
//        deleteRow(dataTable);
//        var pageNum = 1;
//        cs = pageNum-1;
//        document.getElementById("txtPageNum").value = pageNum;
//        document.getElementById('txtTranType').value = (txtResponse).substr(0,5);
        var s = txtResponse.indexOf(":");
        if (s >0 && s < 50)
            CreateTableFromJSON(txtResponse,"jsonTable","Y");
        else
            CreateTableFromJSON(txtResponse,"jsonTable","Y");
        try
        {
//            document.getElementById("menuOption").focus();
        }
        catch(e)
        {
            document.getElementById("txtPageNum").focus();
        }
        try
        {
            document.getElementById("popupMessageContainer").style.display = "none";
        }
        catch(e)
        {
        }
//        cs = 0;
        cellFail = false;
        lockScreen = false;
        loading("off");
        return false;
    }            
    txtArray = txtResponse.split("$");
// Loop Through Array
    for (var r=0;r<txtArray.length;r++)
    {
        txtResult = txtArray[r];
// Record Start & End TimeStamp
        if (txtResult.split(":") [0] == "rdttime")
        {
            if (txtResult.split(":") [1] == "start")
            {
                rdtStart = now();
            }
            if (txtResult.split(":") [1] == "stop")
            {
                rdtEnd = now();
            }
            continue;
        }
// Paging
        else if (txtResult.split(":") [0] == "page")
        {
            i = txtResult.split(":") [1].substr(-1,1);
            cs = parseInt(i)-1;
            cellFail = true;
//          refreshScreen(dataTable,cs);
            document.getElementById("txtPageNum").value = cs+1;
            gotoHere();
            break;
        }
// unexpected error
        else if (txtResult == "FAIL-" || txtResult == "")
        {
            getMessage("FAIL-Unexpected Error");
            cellFail = true;
            idx = 999;
            break;
        }
// Hard-Coded Pallet Box-Count Failure
        else if (txtResult.indexOf("Wrong Box Count") > -1)
        {
            for (var i = 1; i < table.rows.length; i++)
                           
                                          
            {
                try
                {
                    if (trnName[i] == "boxCountQty")
                    {
                        document.getElementById(''+i).value = "";
                        document.getElementById(''+i).setAttribute('tabindex', 0); 
                        document.getElementById(''+1).focus();
                    }
    // reduce no. of 'wrong answer' count
                    if (trnName[i] == "comment")
                    {
                        if (document.getElementById(''+i).value == 3)
                            document.getElementById(''+i).value = 2;
                        else if(document.getElementById(''+i).value == 2)
                            document.getElementById(''+i).value = 1;
                        else if(document.getElementById(''+i).value == 1)
                            document.getElementById(''+i).value = 0;
                        trys = parseInt(document.getElementById(''+i).value);
                    }
                }
                catch(e)
                {
                 
                }
            }
            if ((trys != "") && (trys != 0))
            {
                if (trys != 1)
                {
                    getMessage("FAIL-wrong count - "+trys+" Attempts Left.");
                    document.getElementById("rdtmessage").innerHTML = trys+" Attempts";
                    popupMessageShow();
                }   
                else
                {
                    getMessage("FAIL-last chance");
                    document.getElementById("rdtmessage").innerHTML = "Last Chance";
                    popupMessageShow();
                }
                gotoHere();
            }
            else
            {
    //                  getMessage("FAIL-wrong count - Please re-scan");
                getMessage("FAIL-wrong count - Please see your Supervisor");
                document.getElementById("rdtmessage").innerHTML = "";
                trys = 3;
                gotoPrev();
                gotoPrev();
                gotoPrev();
            }
            break;
        }
// Populate DropDown Selection
        else if ((txtResult).substr(0,4) == "DROP")
        {
            setSelect(txtResult.substr(5));
            showSelect();
    // Recursive Call to perform next Cell Validation instruction
            idx = idx+1;
            var validate = trnValidation[id];
            try
            {
                if (document.getElementById("txtcurraction").value != "")
                {
                    cellValidation(dataTable,id);
                }
            }
            catch(e)
            {
                validate = "";
                idx = 999;
            }
            lockScreen = false;
            loading('off');
            break;
        }
// Populate dataList Selection
        else if ((txtResult).substr(0,4) == "LIST")
        {
            setDataList(txtResult.substr(5));
    // Recursive Call to perform next Cell Validation instruction
            idx = idx+1;
            var validate = trnValidation[id];
            try
            {
                if (document.getElementById("txtcurraction").value != "")
                {
                    cellValidation(dataTable,id);
                }
            }
            catch(e)
            {
                validate = "";
                idx = 999;
            }
            lockScreen = false;
            loading('off');
            break;
        }

// Returned Message
        else if ((txtResult).substr(0,4) == "MESS")
        {
            var errorMsg = "";
    // Loop through returned server data
            var msgData = txtResult.substr(5);
            var msgCode = "";
            for (var c = 0; c < msgData.split(",").length; c++)
            {
    // Split-out validation string
                var vldStr = (msgData.split(",") [c]);
    // Split-out returned values
                if ((vldStr.split(":") [0]) == "")
                    break;
                if ((vldStr.split(":") [0]) == "short_text")
                    msgCode="messageCode:"+vldStr.split(":") [1];
                if ((vldStr.split(":") [0]) == "long_text")
                    errorMsg=vldStr.split(":") [1];
                if ((vldStr.split(":") [0]) == "file_text")
                    errorMsg += " "+vldStr.split(":") [1];
            }
    // Refresh Screen Contents with Server Response Data (remove 'MESS' from start of text)
            if (msgCode != "")
            {
                var table = document.getElementById(dataTable);
                refreshData(table, msgCode);
            }
            if (errorMsg != "")
            {
                var msg = new SpeechSynthesisUtterance(errorMsg);
                window.speechSynthesis.speak(msg);
            }
    //                  return;
            break;
        }

// Log-Out Response
        else if (txtResult.substr(0,4) == "FALO")
        {
            getMessage("FAIL-"+txtResult.substr(5),"");
            changeTran("LOGON");
//                  return;
            break;
        }
// Failure - Blank the Input Screen Entry
        else if (txtResult.substr(0,4) == "FAIL")
        {
// Test for command following error message
            var s = txtResult.indexOf(",");
            if (s > 0)
            {
                s = s+1;
                var e = txtResult.indexOf(")");
                if (e < s)
                    e = txtResult.length;
                var vldStr = txtResult.substring(s,e);
                if (vldStr.substr(0,7)=="CHGTRAN" || vldStr.substr(0,4)=="DATA")
                    txtResult = txtResult.substring(0,s-1);
                getMessage("FAIL-"+(txtResult).substring(5),"");
// Test for changetran after message.
                if (vldStr.substr(0,7)=="CHGTRAN")
                {
                    try
                    {
                        document.getElementById('txtcurraction').value = vldStr;
                    }
                    catch(e)
                    {
                        document.getElementById('txtcurraction').value = "CHGTRAN:"+document.getElementById('txtTranType').value;
                    }
                    cellValidation(dataTable, 0);
                    return false;
                }
                else if(vldStr.substr(0,4)=="DATA")
                {
                    refreshData(table, vldStr.substr(5));
                    return false;
                }
                else
                {
                    getMessage("FAIL-"+(txtResult).substring(5),"");
                }
            }
            else
            {
                getMessage("FAIL-"+(txtResult).substring(5),"");
            }
// Reset Current Row
            if (id > 0)
            {
                row = id;
                currentRow = id;
            }
//            changeCurrentRow(dataTable,row,"0");
            try
            {
                document.getElementById(''+row).focus();
            }
            catch(e)
            {
            }
            try
            {
                document.getElementById(''+id).value = "";
            }
            catch(e)
            {
            }
            cellFail = true;
            idx = 999;
            return false;
        }
        else if ((txtResult.substr(0,2) == "FA") || (txtResult.substr(0,8) == "DATA:EOD"))
        {
    // Reset Current Row
            if (id > 0)
            {
                row = id;
                currentRow = id;
            }
//            changeCurrentRow(dataTable,row,"0");
            try
            {
                document.getElementById(''+row).focus();
            }
            catch(e)
            {
            }
    // End Of Pick
            if ((txtResult.substr(0,8) == "FAIL-EOD") || (txtResult.substr(0,18) == "FAIL-No More Picks") || (txtResult.substr(0,8) == "DATA:EOD"))
            {
                if (txtResult.split(";") [1] != undefined)
                {
                    mData = txtResult.split(";") [1];
                    txtResult = txtResult.split(";") [0];
                }
                else
                {
                    mData = txtResult;
                }
                if (txtResult == "DATA:EOD" || txtResult == "FAIL-EOD")
                    txtResult = "DATA:EOD-No Picks Available";
    // Pick To Pallet - Force Box Count
                if ((document.getElementById("txtTranType").value == "PBTP") || (document.getElementById("txtTranType").value == "TEST"))
                {
    //                          alert("No More Picks");
                    if (cs==0)
                        getMessage(txtResult.substr(9),"alert");
                    else
                        getMessage(txtResult.substr(9),"alert");

                    for (var i = 1; i < table.rows.length; i++)
                    {
                        if (trnName[i] == "toPlt")
                        {
                        }
                        if (trnName[i] == "aisleCode")
                        {
                            if(trnValue[i] == "ALL")
                            {
                                changeTran("PBTP?DATA:aisleCode:ALL");
                                break;
                            }
                            else if(txtResult.substr(9,17)=="customerReference")
                            {
                                changeTran("PAISLE?DATA:customerReference:"+mData+"::skip2")
                                break;
                            }
                            else
                            {
                                changeTran(document.getElementById("txtTranType").value);
                                break;
                            }
                        }
                    }
                }
    // Pick To Marshall - Check for Line or Aisle
                else if ((document.getElementById("txtTranType").value == "PBTM") || (document.getElementById("txtTranType").value == "PBAISLE"))
                {
                    if (cs==0)
                        getMessage("No Orders for this Reference","alert");
                    else
                        getMessage(txtResult.substr(9),"alert");
                    
                    if (document.getElementById("txtTranType").value == "PBTM")
                    {
                        for (var i = 1; i < table.rows.length; i++)
                        {
                            if (trnName[i] == "aisleCode")
                            {
                                if(trnValue[i] == "ALL")
                                {
                                    changeTran("PBTM?DATA:aisleCode:ALL");
                                    break;
                                }
                                else if(txtResult.substr(9,17)=="customerReference")
                                {
                                    changeTran("PBAISLE?DATA:customerReference:"+mData+"?5")
                                    break;
                                }
                                else
                                {
                                    changeTran(document.getElementById("txtTranType").value);
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    changeTran(document.getElementById('txtTranType').value);
                }
                try
                {
    //                          document.getElementById(''+id).setAttribute('tabindex', 0); 
                    document.getElementById(''+id).focus();
                }
                catch(e)
                {
    //                          document.getElementById(''+firstRow).setAttribute('tabindex', 0);
                    try
                    {
                        document.getElementById(''+firstRow).focus();
                    }
                    catch(e)
                    {
                    }
                }
                cellFail = true;
                idx = 999;
    //                      return false;
    //                      continue;
                break;
            }
    // Image Upload Failure
            if (txtResult.substr(2,2) == "IM")
            {
                getMessage("OKMS-"+txtResult.substr(5),"");
                changeTran(document.getElementById('txtTranType').value);
    //                      return;
    //                      continue;
                break;
            }
        
            try
            {
                document.getElementById(''+id).value = "";
            }
            catch(e)
            {
            }
    // Clear 'Content' if required
            if (txtResult.substr(2,2) == "CC")
                document.getElementById(''+row).placeholder = "";
    // Clear All Screen Content
            if (txtResult.substr(2,2) == "CS")
            for (var i = id; i < table.rows.length; i++)
            {
                document.getElementById(''+row).placeholder = "";
            }
    // Display Error Message
            if (txtResult.substr(5) == "")
            {
                txtResult = "FAIL-Invalid "+table.rows[id].cells[0].innerHTML;
            }
            getMessage(txtResult,"");
            try
            {
                document.getElementById(''+id).focus();
            }
            catch(e)
            {
                document.getElementById("menuOption").focus();
            }
            cellFail = true;
            idx = 999;              
    //                  return;
    //                  continue;
            break;
        }
// Hard-Coding for - Stillage Confirm Complete
        else if (txtResult == "OK  - Confirm Complete")
        {
    // Reset validation index               
            idx=0;
            errorMsg = txtResult;
            getMessage(errorMsg,"");
    // Build server command string for 'print stillage'
            vldType = "printstillage";
            vldStr="printstillage?";
            for (var i = 1; i < table.rows.length; i++)
            {
                if(i>0)
                    vldStr=vldStr+"&";
                vldStr=vldStr+trnName[i]+"="+trnValue[i].toUpperCase();
            }
            url = ajaxPath+"rdtphp/postStillage.php"+
                    "?function="+vldType+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
                    "&table="+
                    "&returnfields="+
                    "&filter="+vldStr;
                cellFail = true;
//              ajaxGet(url, rowValidated);
                get(url).then(function(response) 
                {
                    rowValidated(response,screenData,transactionType);
                }, 
                function(error) 
                {
                    getMessage("FAIL-"+error);
                })
    //                      return;
                break;
        }
// Validation OKCC- Confirm Prompt
        else if ((txtResult).substr(0,4) == "OKCC")
        {
            var yesActionTxt = "";
            var noActionTxt = "";
            var txtMsg = "";
            var yesBtnTxt = "YES";
            var noBtnTxt = "NO";
            var txtContent = (txtResult).substring(5);
            txtContent = txtContent.split("|COMMA|").join(",");
            txtContent = txtContent.split("|COLON|").join(":");
            s = 0;
            var e = txtContent.indexOf(":");
            if (e < s)
                e = txtContent.length;
            var txtMsg = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(":",s);
            if (e < s)
                e = txtContent.length;
            var yesBtnTxt = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(":",s);
            if (e < s)
                e = txtContent.length;
            var noBtnTxt = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(";",s);
            if (e < s)
                e = txtContent.length;
            yesActionTxt = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(";",s);
            if (e < s)
                e = txtContent.length;
            noActionTxt = txtContent.substring(s,e);
            
            document.getElementById('txtyesaction').value = yesActionTxt;
            document.getElementById('txtnoaction').value = noActionTxt;
            
            if (txtMsg != "")
            {
//              row = parseInt(id)+1;
                showConfirm(txtMsg,row,yesBtnTxt,noBtnTxt);
            }
            break;
        }
// Validation OKCI- Confirm Input Prompt
        else if ((txtResult).substr(0,4) == "OKCI")
        {
            var yesActionTxt = "";
            var noActionTxt = "";
            var txtMsg = "";
            var yesBtnTxt = "YES";
            var noBtnTxt = "NO";
            var txtContent = (txtResult).substring(5);
            txtContent = txtContent.split("|COMMA|").join(",");
            txtContent = txtContent.split("|COLON|").join(":");
            s = 0;
            var e = txtContent.indexOf(":");
            if (e < s)
                e = txtContent.length;
            var txtMsg = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(":",s);
            if (e < s)
                e = txtContent.length;
            var yesBtnTxt = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(":",s);
            if (e < s)
                e = txtContent.length;
            var noBtnTxt = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(";",s);
            if (e < s)
                e = txtContent.length;
            yesActionTxt = txtContent.substring(s,e);
            s = e+1;
            var e = txtContent.indexOf(";",s);
            if (e < s)
                e = txtContent.length;
            noActionTxt = txtContent.substring(s,e);
            
            document.getElementById('txtyesaction').value = yesActionTxt;
            document.getElementById('txtnoaction').value = noActionTxt;
            
            if (txtMsg != "")
            {
                showConfirmInput(txtMsg,id+1,yesBtnTxt,noBtnTxt);
            }
            break;
        }
// Image Uploaded Ok.
        else if (txtResult.substr(0,4) == "OKIM")
        {
//            changeTran(document.getElementById('txtTranType').value);
            getMessage("OKMS-Image Uploaded","");
//                  return;
            break;
        }
// If validation Response is "OKCM" - display Transaction-Completion Message & reset transaction screen
        else if ((txtResult).substr(0,4) == "OKCM")
        {
            var s = txtResult.indexOf(",");
            if (s > 0)
            {
                s = s+1;
                var e = txtResult.indexOf(")");
                if (e < s)
                    e = txtResult.length;
                var vldStr = txtResult.substring(s,e);
                txtResult = txtResult.substring(0,s-1);
                getMessage("OK  -"+(txtResult).substring(5),"");
                try
                {
                    changeTran(vldStr);
                }
                catch(e)
                {
                    changeTran(document.getElementById('txtTranType').value);
                }
            }
            else
            {
                getMessage("OK  -"+(txtResult).substring(5),"");
                changeTran(document.getElementById('txtTranType').value);
            }
            break;
        }
// If validation Response is "OKMS" - display Return Message then continue
        else if ((txtResult.substr(0,4) == "OKMS") || (txtResult.substr(0,4) == "OKAL"))
        {
            var s = txtResult.indexOf(",");
            if (s > 0)
            {
                s = s+1;
                var e = txtResult.indexOf(")");
                if (e < s)
                    e = txtResult.length;
                var vldStr = txtResult.substring(s,e);
                txtResult = txtResult.substring(0,s-1);
                getMessage("OK  -"+(txtResult).substring(5),"");
    // Test for changetran after message.
                if (vldStr.substr(0,7)=="CHGTRAN")
                {
                    idx = 0;
                    try
                    {
                        document.getElementById('txtcurraction').value = vldStr;
                    }
                    catch(e)
                    {
                        document.getElementById('txtcurraction').value = "CHGTRAN:"+document.getElementById('txtTranType').value;
                    }
                    cellValidation(dataTable, 0);
                    break;
                }
                else if(vldStr.substr(0,4)=="DATA")
                {
                    refreshData(table, vldStr.substr(5));
                    break;
                }
                else
                {
                    try
                    {
                        changeTran(vldStr);
                    }
                    catch(e)
                    {
                        changeTran(document.getElementById('txtTranType').value);
                    }
                    break;
                }
            }
            else
            {
                getMessage("OK  -"+(txtResult).substring(5),"");
            }
    // Recursive Call to perform next Cell Validation instruction
            if (txtRow != "ROW")
            {
                idx = idx+1;
                var validate = trnValidation[id];
                try
                {
                    if (document.getElementById("txtcurraction").value != "")
                    {
                        cellValidation(dataTable,id);
                    }
                    else if(document.getElementById('txtcurraction').value != "")
                    {
                        cellValidation(dataTable,id);
                    }
                }
                catch(e)
                {
                    validate = "";
                    idx = 999;
                }
                break;
            }
            else
            {
                if (cellFail == true)
                    break;
                else
                    break;
            }
            break;
        }
// Show Document
        else if ((txtResult).substr(0,4) == "OKGD")
        {
            try
            {
                vldStr = txtResult.substr(5);
                showDocument(vldStr);
            }
            catch(e)
            {
            }
            break;
        }
// Validation OK - Store Result in 'formattedinput' cell - ONLY FOR SPECIFIC FIELDS
        else if ((txtResult).substr(0,2) == "OK")
        {
            var txtContent = (txtResult).substring(5);
            var s = txtResult.indexOf("CHGTRAN")
            if (s >= 0)
            {
                txtResult = txtResult.substring(s);
                try
                {
                    changeTran(txtResult.substr(8));
                }
                catch(e)
                {
                    changeTran(document.getElementById('txtTranType').value);
                }
                break;
            }
            var s = txtResult.indexOf("DATA");
            if (s >= 0)
            {
                txtResult = txtResult.substring(s);
            }
            if (s == -1)
            {
                try
                {
                    s = txtData.indexOf("DATA");
                }
                catch(e)
                {
                    s = -1
                    txtResult = "OK  -";
                }                       
                if (s >= 0)
                {
                    txtResult = txtData.substring(s);
                }
            }
    // test if result is a JSON string
            if (txtResult.substr(0,6) == "OK  -{")
            {
                txtContent = (txtResult).substring(6,txtResult.length-1);
                for (var i = 1; i < table.rows.length; i++)
                {
                    try
                    {
                        for (var c = 0; c < txtContent.split(",").length; c++)
                        {
                            var subStr = (txtContent.split(",") [c]);
                            if ((subStr.split(":") [0]) == "")
                                break;
                            if ((subStr.split(":") [0]) == (trnName[i]))
                            {
    // Test if Server Result 'Name' = Table Row Name
                                if (trnName[i] == "fromLocationCode")
                                {
                                    trnValue[i] = (subStr.split(":") [1]);
                                    document.getElementById(''+row).placeholder = (subStr.split(":") [1]);
                                }
                            }
                        }
                    } 
                    catch(e)
                    {
                    }
                }
            }
            if (txtResult.substr(0,6) == "TOGGLE" || txtResult.substr(0,6)=="toggle")
            {
                var button = txtResult.split(":")[1];
                var onoff = txtResult.split(":")[2];
                togglebutton(button,onoff);
                break;
            }

// Update Screen with Server Response
            errorMsg = "";
    // Get Current Validation Type
            if (trnValidation[id] == undefined)
			{
                vldStr = "";
			}
            else
			{
                vldStr = (trnValidation[id].split(":") [idx]);
			}
    // Put Returned Value into current row Screen Fields
            if ((txtResult.substr(2,2) == "  ") || (txtResult.substr(2,2) == "MS"))
            {
                if (vldStr == "replace")
                {
                    trnValue[id] = txtContent.toUpperCase();
                    document.getElementById(''+row).placeholder = txtContent;
                }
            }
    // Put returned value into specified row on screen.
            if ((txtResult.substr(2,2) >= "00") && (txtResult.substr(2,2) <= "99"))
            {
                currentRow = parseInt((txtResult).substr(2,2), 10)
                trnValue[currentRow] = (txtResult).substring(5,txtResult.length).toUpperCase();
                document.getElementById(''+row).placeholder = (txtResult).substring(5,txtResult.length);
            }
            if (idx < 0)
            {
                cellFail = true;
    //                      return;
                break;
            }
    // Recursive Call to perform next Cell Validation instruction
            if (txtRow != "ROW")
            {
                idx = idx+1;
                var validate = trnValidation[id];
                try
                {
                    if (document.getElementById("txtcurraction").value != "")
                    {
                        cellValidation(dataTable,id);
                    }
                    else if(document.getElementById('txtcurraction').value != "")
                    {
                        cellValidation(dataTable,id);
                    }
                }
                catch(e)
                {
                    validate = "";
                    idx = 999;
                }
                break;
            }
            else
            {
                if (cellFail == true)
                    break;
                else
                    break;
            }
        }
    // Change Transaction
        else if ((txtResult).substr(0,7) == "CHGTRAN")
        {
            idx = 999;
            changeTran(txtResult.substr(8));
            break;
        }
// Build Selection Screen
        else if (txtResult.substr(0,6) == "SELECT" || txtResult.substr(0,8) == "DOCUMENT")
        {
            idx = 0;
//          deleteRow(dataTable);
            var pageNum = 1;
            cs = pageNum-1;
            document.getElementById("txtPageNum").value = pageNum;
            document.getElementById('txtTranType').value = "SELECT";
            buildScreen(txtResult.substr(7),'','SELECT');
            try
            {
                <!-- document.getElementById("menuOption").focus(); -->
            }
            catch(e)
            {
                document.getElementById("txtPageNum").focus();
            }
            try
            {
                document.getElementById("popupMessageContainer").style.display = "none";
            }
            catch(e)
            {
            }
            cs = 0;
//          cellFail = false;
    //                  return false;
            break;
        }
// Refresh Screen Contents with Server Response
        else if (((txtResult).substr(0,2) == "DA") || ((txtResult).substr(0,18) == "FAIL-No More Picks"))
        {
    // Return Data for end-of-Stillage Processing (registerworkstation)
            if ((txtResult).substr(0,8) == "DATA:EOD" || (txtResult).substr(0,8) == "FAIL-EOD" || (txtResult).substr(0,18) == "FAIL-No More Picks")
            {
                if (cs==0)
                    getMessage(txtResult.substr(9),"alert");
                changeTran(document.getElementById('txtTranType').value);
                idx = 999;
                cellFail = true;
    //                      return;
                continue;
            }               
    // Return Data for end-of-Stillage Processing (registerworkstation)
            if ((txtResult).substr(0,13) == "DATA:NO STOCK")
            {
                getMessage("FAIL-"+txtResult.substr(5));
                changeTran(document.getElementById('txtTranType').value);
                idx = 999;
                cellFail = true;
    //                      return;
    //                      continue;
                break;
            }
// Refresh Screen Contents with Server Response Data (remove 'DATA' from start of text)
            refreshData(table, txtResult.substr(5));
    // Test for More Validation on this entry / row
            if (txtRow != "ROW")
            {
                idx = idx+1;
                var validate = trnValidation[id];
                try
                {
                    if (document.getElementById("txtcurraction").value != "")
                    {
                        cellValidation(dataTable,id);
                    }
                }
                catch(e)
                {
                }
				cellFail = true;
                break;
            }
            
            if (cellFail == true)
            {
                break;
            }
            else
            {
                continue;
            }
        }
        else if ((txtResult).substr(0,4) == "TEXT")
        {
            popupTextShow(txtResult.substr(5));
            idx = idx+1;
            var validate = trnValidation[id];
            try
            {
                if (document.getElementById("txtcurraction").value != "")
                {
                    cellValidation(dataTable,id);
                }
            }
            catch(e)
            {
                validate = "";
                idx = 999;
            }
            cellFail = true;
			break;
        }
        else if ((txtResult).substr(0,4) == "POST")
        {
    // Recursive Call to Cell Validation routine
            idx = idx+1;
            var validate = trnValidation[id];
            try
            {
                if (document.getElementById("txtcurraction").value != "")
                {
                    cellValidation(dataTable,id);
                }
                else if(document.getElementById('txtcurraction').value != "")
                {
                    cellValidation(dataTable,id);
                }
            }
            catch(e)
            {
            }
            cellFail = true;
			break;
        }
        if ((txtResult).substr(0,6) == "IFRAME")
        {
            try
            {
                var vldStr = txtResult.substr(7);
                if (vldStr.split(",") [1] != undefined)
                {
                    document.getElementById('txtstoredvalue').value = vldStr.split(",") [1];
                    printIframe(vldStr.split(",") [0],vldStr.split(",") [1]);
                }
                else
                {
                    document.getElementById('txtstoredvalue').value = vldStr;
                    printIframe('printIframe',vldStr);
                }
            }
            catch(e)
            {
            }
            cellFail = true;
			break;
        }       
// Hard-Coded Pallet Box-Count Failure
        else if (txtResult.indexOf("Wrong Box Count") > -1)
        {
            for (var i = 1; i < table.rows.length; i++)
            {
                try
                {
                    if (trnName[i] == "boxCountQty")
                    {
                        document.getElementById(''+i).value = "";
                        document.getElementById(''+i).setAttribute('tabindex', 0); 
                        document.getElementById(''+1).focus();
                    }
// reduce no. of 'wrong answer' count
                    if (trnName[i] == "comment")
                    {
                        if (document.getElementById(''+i).value == 3)
                            document.getElementById(''+i).value = 2;
                        else if(document.getElementById(''+i).value == 2)
                            document.getElementById(''+i).value = 1;
                        else if(document.getElementById(''+i).value == 1)
                            document.getElementById(''+i).value = 0;
                        trys = document.getElementById(''+i).value
                    }
                }
                catch(e)
                {
                }
            }
            if ((trys != "") && (trys != 0))
            {
                if (trys != 1)
                    txtResult = "FAIL-wrong count - "+trys+" Attempts Left.";

                else
                    txtResult="FAIL-last chance";
                gotoHere();
            }
            else
            {
                getMessage("FAIL-wrong count","Please see Supervisor");
                trys = 3;
                gotoPrev();
                gotoPrev();
                gotoPrev();
            }
//              return false;
//                  continue;
            cellFail = true;
			break;
        }
        else
        {
            document.getElementById('rdtMessage').value = "FAIL-Unexpected Error -"+txtResult; 
            popupMessageShow();
        }
    }
//          if (r >= txtArray.length-1)
//              loading("off");
    if (idx >= 998)
	{
        cellFail = true;
	}
	if (eol==1)
	{
        lockScreen = false;
        loading('off');
		changeCurrentRow(dataTable,this.id,1);
	}
/*
    if (cellFail != undefined && cellFail == false)
    {
		var validate = document.getElementById('txtcurraction').value.split(",")[idx+1];
		console.log("curr"+document.getElementById('txtcurraction').value+" "+idx+" "+validate);
		if(validate==undefined)
		{
			changeCurrentRow(dataTable,this.id,1);
		}
    }
*/
    return false;
}

// Server Response User-Settings
function userLoggedIn(xmlDoc,inputTran="")
{
    try
    {
        var strJSON = xmlDoc.responseText;
    }
    catch(e)
    {
        var strJSON = xmlDoc;
    }
    if (strJSON == undefined)
        var strJSON = xmlDoc;
    if (strJSON != undefined && strJSON.substr(0,2) == "OK")
    {
        var userData = strJSON.substr(6,strJSON.length-1);
        userStatus = userData.split(",")[1].split(":")[1];
        var userId = userData.split(",")[0].split(":")[1];
        if (userData.split(",")[2])
        {
            userBlocked = userData.split(",")[2].split(":")[1];
        }
        if (userData.split(",")[3])
        {
            userLevel = userData.split(",")[3].split(":")[1];
        }
        var url = ajaxPath+"rdtphp/getcolumns.php?function=usersettings&connection=&trantype="+userId;
        get(url).then(function(response)
        {
            userSettingsLoaded(response,inputTran);
        }, 
        function(error) 
        {
            getMessage("FAIL-"+error);
        })
        if ((messageType == "speak") || (messageType == "speech"))
        {
            let timeVar = setInterval(userTimer, 30000);
        }
    }
    else
    {
//              getMessage("Wrong Username or Password","");
        try
        {
            var strJSON = xmlDoc.responseText;
        }
        catch(e)
        {
            var strJSON = xmlDoc;
        }
        if (strJSON == undefined)
            var strJSON = xmlDoc;
        getMessage(strJSON,"");
        document.getElementById("txtUser").value = "";
        changeTran("LOGON");
//              return;
    }
    return;
}


// Event Called when User Settings have been loaded
function userSettingsLoaded(xmlDoc,inputTran="")
{
//          alert("Test:"+xmlDoc.responseText);
// Create Transaction JSON Object
    try
    {
        var strJSON = xmlDoc.responseText;
    }
    catch(e)
    {
        var strJSON = xmlDoc;
    }
    if (strJSON == undefined)
        var strJSON = xmlDoc;
    if (xmlDoc.substr(0,2)=="FA")
    {
        getMessage(xmlDoc,"");
        changeTran("LOGON");
        return false;
    }
//    userSettings = eval("(function(){return " + strJSON + ";})()");
    userSettings = JSON.parse(strJSON);
// Set User Menu Access
    userSettings[0].status = userStatus;
// Check for Expired User
    if (userSettings[0].status == "X")
    {
//              alert("FAIL-User Id has Expired");
        getMessage("OKMS-User Id has Expired");
        changeTran("LOGON");
        document.getElementById("txtUser").value = "";
        return;
    }
// Populate Screen Values
    document.getElementById("txtConnect").value = userSettings[0].path;
    document.getElementById("txtConnectTrn").value = userSettings[0].path;
    document.getElementById("txtSystem").value = inputRdt;
    document.getElementById("txtCompany").innerHTML = userSettings[0].company;
    document.getElementById("txtMqServer").value = userSettings[0].mqserver;
    document.getElementById("txtMainMenu").value = userSettings[0].menu;
//          ajaxBuildSelect();
    if (inputTran != "")
    {
        changeTran(inputTran);
    }
    else
    {
        changeTran(userSettings[0].menu);
    }
    tabAdd (document.getElementById("txtUser").value);
//    document.getElementById("txtUser").value=document.getElementById("txtUser").value+document.getElementById("txtTab").value;
    return;
}

// Testing Key Press
function verifyKey(table,e)
{
    alert("row" + table.parentNode.parentNode.rowIndex + 
                " - column" + table.parentNode.cellIndex);
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    keyCode = keycode;
    if((keycode>=48 && keycode<=57))
    {
        alert("Number")
        return true;
    }
    else if((keycode == 188)||(keycode == 190))
    {
        alert("other");
        return true;
    }
    else
    {
        alert("letter")
        return false;
    }
    return true;
}

// Dynamic Button Action
function buttonClick(btnId)
{
//  console.log("buttonClick");
    disableBlur = true;
	try
	{
		saveCurrentRow(row);
	}
	catch(e)
	{
	}
    if (document.getElementById(btnId).disabled == true)
        return;
    for(var i = 0; i < buttons.length; i++)
    {
        if (buttons[i].name == btnId)
        {
            if (buttons[i].action != "")
            {
                var $cmd="";
                var $parm="";
                var $cmd = buttons[i].action.split('"').join('');
                var s = $cmd.indexOf("(");
                if (s > 0)
                {
                    s = s+1;
                    var e = $cmd.indexOf(")");
                    if (e < s)
                        e = $cmd.length;
                    $parm = $cmd.substring(s,e);
                    $cmd = $cmd.substring(0,s-1);
                }
                if ($parm != "")
                {
                    vldStr = validationFormat($parm);
                }
                else
                {
                    vldStr = "";
                }
                if (btnId.substr(0,5).toLowerCase() == "popup")
                {
                    e = $parm.indexOf("=");
                    
                    popupOpen($cmd,vldStr);
                }
                else if ($cmd.substr(0,4).toLowerCase() == "http")
                    window.open($cmd,"_self");
                else
                    window[$cmd] ($parm);
                break;
            }
            else if(buttons[i].validation != undefined && buttons[i].validation != "")
            {
//              console.log("button-"+buttons[i].validation);
                cellFail = false;
                idx = 0;
                id = 99;
                document.getElementById("txtcurraction").value = buttons[i].validation;
                cellValidation(dataTable,id);
//              console.log("button-"+document.getElementById("txtcurraction").value);
                break;
            }
            break;
        }
    }
}

// Read through Screen Table        
function getCellValues(tableId) 
{}

// Check Mandatory Rows
function checkMandatory() 
{
    var table = document.getElementById('dataTable');
    for (var r = 0; r < table.rows.length; r++) 
    {
        cellFail = false;
        if (trnMand[r] == "M")
        {
            var vldStr = document.getElementById(''+r).value;
            if ( vldStr == "")
            {
                s = trnScreenOption[r].indexOf("I");
                if (s == -1)
                    s = trnScreenOption[r].indexOf("*");
                if (s != -1)
                    document.getElementById("txtPageNum").value = s+1;
                pageNum = parseInt(document.getElementById("txtPageNum").value, 10);
                if (pageNum < 1)
                    pageNum = 1;
                cs = pageNum-1;
                refreshScreen(dataTable,cs);
                document.getElementById("txtPageNum").value = pageNum;
                cellFail = true;
                break;
            }
        }
    }
    return cellFail;
}

// Display "Updating"
function loading(onoff) 
{
    const dialogElement = document.getElementById('loadingDialog');

    if (onoff === "on")
    {
        if (lockScreen !== false) 
        {
            document.getElementById('loadingContainer').style.display = 'block';
        }

        // Use manageTimeout to set a timeout for hiding the loading dialog
        manageTimeout("set", "loadingTimeout", () => 
        {
            document.getElementById('loadingContainer').style.display = 'none';
        }, 120000);

    } 
    else 
    {
        if (lockScreen !== true) 
        {
            document.getElementById('loadingContainer').style.display = 'none';
        }
        manageTimeout("clear", "loadingTimeout");
    }
}

// Get Message text from message table
function getMessage(messageCode,messageText)
{
//  loading("off");
    
    if (messageText == undefined)
        var messageText = "";
    
    if ((messageType == "alert") || (messageText == "alert"))
    {
        if (messageCode.substr(0,2) == "FA")
            messageCode = messageCode.substr(5);
            
// hard-coding for Pick Messages
        if (messageCode.indexOf("Complete") >= 0)
        {
            customAlert(messageCode,'ok.mp3','green');
        }
        if (messageCode.indexOf("complete") >= 0)
        {
            customAlert(messageCode,'ok.mp3','green');
        }
        else if (messageCode.indexOf("No Stock") >= 0)
        {
            customAlert(messageCode,'ok.mp3','red');
        }
        else if (messageCode.indexOf("No Inventory") >= 0)
        {
            customAlert(messageCode,'','red');
        }
        else if (messageCode.indexOf("No Pick Tasks") >= 0)
        {
            customAlert(messageCode,'ok.mp3','green');
        }
        else if (messageCode.indexOf("Short") >= 0)
        {
            customAlert(messageCode,'','red');
        }
        else if ((messageCode.indexOf("No Picks") >= 0) || (messageCode.indexOf("No More Picks") >= 0))
        {
            customAlert(messageCode,'','red');
        }
        else
        {
            customAlert(messageCode,'',backgroundColour);
        }
    }
    else if ((messageCode == "alert") && (messageText != ""))
    {
        customAlert(messageText,'',backgroundColour);
    }
    else
    {
        try
        {
            url = ajaxPath+"rdtphp/validaterdt.php"+
                    "?function=getmessage"+
/*
                    "&connection="+
                    "&host="+userSettings[0].dbhost+
                    "&user="+userSettings[0].dbuser+
                    "&pword="+userSettings[0].dbpwd+
                    "&dbase="+userSettings[0].dbase+
*/
                    "&mqserver="+userSettings[0].mqserver+
                    "&filter=messagecode="+messageCode+"|AND|messagetext="+messageText;
        }
        catch(e)
        {
            url = ajaxPath+"rdtphp/validaterdt.php"+
                "?function=getmessage"+
/*
                "&connection="+
                "&host="+
                "&user="+
                "&pword="+
                "&dbase="+
                "&mqserver="+
*/
                "&filter=messagecode="+messageCode+"|AND|messagetext="+messageText;
        }
        get(url).then(function(response) 
        {
            mapMessage(response);
        }, 
        function(error) 
        {
            getMessage("FAIL-"+error);
        })
    }
    
    // Resets Opacity for DataTable hide
    lockScreen = false;
    loading("off");
    return false;
}

// Alert Box
function customAlert(errMsg, errSound, errColour="silver")
{
    if ((errMsg == "off") || (errMsg == "") || (errMsg == undefined))
    {
        document.getElementById("dataTable").disabled=false;
        document.getElementById('alertbox').style.display = "none";
        document.getElementById('alertoverlay').style.display = "none";
        try
        {
            document.getElementById(''+row).focus();
        }
        catch(e)
        {
            document.getElementById(''+firstRow).focus();
        }
        cellFail = true;
        idx = 999;
        return false;
    }
    else
    {
        try
        {
            document.getElementById("dataTable").disabled=true;
        }
        catch(e)
        {
            document.getElementById("dataTable").disabled=false;
        }
        document.getElementById('alertbox').style.left = 10+"px";
        document.getElementById('alertbox').style.top = 10+"px";
        document.getElementById('alertboxhead').style.backgroundColor = errColour;
        document.getElementById('alertboxfoot').style.backgroundColor = errColour;
        document.getElementById('alertboxhead').innerHTML = "Alert";
        document.getElementById('alertboxbody').innerHTML = errMsg;
        document.getElementById('alertboxfoot').innerHTML = "<button style='height:50px;width:50px' onclick='customAlert()'>OK</button>";
        document.getElementById('alertoverlay').style.display = "block";
        document.getElementById('alertbox').style.display = "block";
        if ((errSound=="speak") || (errSound=="speech") || (errSound == "speech"))
        {
            playSound(errSound);
            var msg = new SpeechSynthesisUtterance(errMsg);
            window.speechSynthesis.speak(msg);
        }
        else if(errSound != "")
        {
            playSound(errSound);
        }
    }
}

// Map Returned Message to Actual Message Text using message table
function mapMessage(xmlDoc)
{
//  loading("off");
    var errorMsg = "";
// Loop through returned server data
    try
    {
        var strJSON = xmlDoc.responseText;
    }
    catch(e)
    {
        var strJSON = xmlDoc;
    }
    if (strJSON == undefined)
    {
        var strJSON = xmlDoc;
    }
    let msgData = "";
    if (strJSON != undefined)
        msgData = (strJSON.substr(5));
    var msgCode = "";
    var msgSeverity = "";
    var audioMsg = "";
    var colourMsg = "";
    var errorMsg = msgData;
    for (var c = 0; c < msgData.split(",").length; c++)
    {
// Split-out validation string
        var vldStr = (msgData.split(",") [c]);
// Split-out returned values
        if ((vldStr.split(":") [0]) == "")
            break;
        if ((vldStr.split(":") [0]) == "MESS-severity")
            msgSeverity=vldStr.split(":") [1];
        if ((vldStr.split(":") [0]) == "severity")
            msgSeverity=vldStr.split(":") [1];
        if ((vldStr.split(":") [0]) == "short_text")
            msgCode=vldStr.split(":") [1];
        if ((vldStr.split(":") [0]) == "long_text")
            errorMsg=vldStr.split(":") [1];
//        if ((vldStr.split(":") [0]) == "file_text")
//            errorMsg += " "+vldStr.split(":") [1];
        if ((vldStr.split(":") [0]) == "audio")
            audioMsg = vldStr.split(":") [1];
        if ((vldStr.split(":") [0]) == "colour")
            colourMsg = vldStr.split(":") [1];
    }
    if (colourMsg=="" || colourMsg==undefined || colourMsg==null || colourMsg=='null')
        colourMsg = 'red';
    if (audioMsg=="" || audioMsg==undefined || audioMsg==null || audioMsg=='null')
        audioMsg = 'buzzer.mp3';
    if (errorMsg != "")
    {
        var table = document.getElementById(dataTable);
        refreshData(table, msgCode);
        if (msgSeverity.substr(0,2) == "OK")
        {
            colourMsg = 'green';
            audioMsg = 'ok.mp3';
        }
        if (msgSeverity.substr(0,2) == "FA")
            msgCode = "FAIL-"+msgCode;
        if (msgSeverity.substr(0,4) == "OKAL")
        {
            alert(errMsg);
        }
        if (msgSeverity == "ALERT")
        {
            customAlert(errorMsg,audioMsg,colourMsg);
        }    
        else if (msgSeverity == "ALERTOK")
        {
            customAlert(errorMsg,audioMsg,'green');
        }
        else if (msgSeverity == "ALERTFAIL")
        {
            customAlert(errorMsg,audioMsg,'red');
        }
        else if (errorMsg != "")
        {
            var messageCode = errorMsg;
            if (messageCode.indexOf("Complete") >= 0)
            {
                customAlert(messageCode,'ok.mp3','green');
            }
            else if (messageCode.indexOf("complete") >= 0)
            {
                customAlert(messageCode,'ok.mp3','green');
            }
            else if (messageCode.indexOf("No Stock") >= 0)
            {
                customAlert(messageCode,'ok.mp3','red');
            }
            else if (messageCode.indexOf("No Inventory") >= 0)
            {
                customAlert(messageCode,'','red');
            }
            else if (messageCode.indexOf("No Pick Tasks") >= 0)
            {
                customAlert(messageCode,'ok.mp3','green');
            }
            else if (messageCode.indexOf("Short") >= 0)
            {
                customAlert(messageCode,'','red');
            }
            else if ((messageCode.indexOf("No Picks") >= 0) || (messageCode.indexOf("No More Picks") >= 0))
            {
                customAlert(messageCode,'','red');
            }
            else
            {
                try
                {
                    var a = document.getElementById("alert");
                    a.style.position = 'absolute';
                    if (errorMsg.length > 50)
                        a.style.top = '65%';
                    else
                        a.style.top = '70%';
                    setTimeout(function(){ a.className = a.className.replace("show", ""); }, 5000);
                    a.style.backgroundColor = colourMsg;
                    a.innerHTML=errorMsg;
                    a.className = "show";
                    if ((messageType=="speak") || (messageType=="speech") || (audioMsg == "speech"))
                    {
                        playSound(audioMsg);
                        var msg = new SpeechSynthesisUtterance(errorMsg);
                        window.speechSynthesis.speak(msg);
                    }
                    else if(audioMsg != "")
                    {
                        playSound(audioMsg);
                    }
                }
                catch(e)
                {
                }
            }
        }   
//        document.getElementById("popupMessageContainer").style.display = "none";
    }
    return false;
}


function playSound(errSound,errVolume)
{
    if (errSound == "" || errSound == undefined || errSound == null || errSound == 'null')
    {
        errSound = 'buzzer.mp3';
    }
    
    var audio = new Audio('audio/'+errSound);

    audio.addEventListener('canplaythrough', function() 
    {
//      console.log('Audio has finished loading and is ready to play.'+errSound);
        audio.play();
        setTimeout(()=> 
        {
            audio.pause();
        }, 5000);
    });

// Start loading the audio
    audio.load();
}

// Build Dynamic Table From JSON
function CreateTableFromJSON(vldStr,tableName,autoDelete="")
{
    if (tableName == undefined || tableName == "")
	{
        tableName = "jsonTable";
	}
	
	let table = document.getElementById(tableName); // Use the ID you want for your table
	if (!table) 
	{
// Create the table element if it doesn't exist
		table = document.createElement('table');
		table.id = 'jsonTable';
		mainPanel.appendChild(table);
	}
	
    var vldFunction="";
    var vldTable = "";
    var vldFilter = "";
    var dir = "row";
	
    var i = vldStr.indexOf(":");
    if (i > 0 && i < 20)
    {
        vldTable = vldStr.substr(0,i);
        if ((vldTable.substr(0,6) == "TABLEC"))
        {
            vldTable = vldTable.substr(6);
            dir = "col";
        }
        else if ((vldTable.substr(0,6) == "TABLER"))
        {
            vldTable = vldTable.substr(6);
            var dir = "row";
        }
		else if ((vldTable.substr(0,6) == "TABLEP"))
        {
            vldTable = vldTable.substr(6);
            var dir = "row";
        }
        else if (vldTable.substr(0,5) == "TABLE")
        {
            vldTable = vldTable.substr(5);
            var dir = "row";
        }
        vldStr = vldStr.substr(i+1);
    }
    var i = vldStr.indexOf(":");
    if (i > 0)
    {
        vldFilter = vldStr.substr(0,i);
        vldStr = vldStr.substr(i+1);
    }
    var i = vldFilter.indexOf("&");
    if (i > 0)
    {
        vldFunction = vldFilter.substr(0,i);
        vldFilter = vldFilter.substr(i);
    }
    else
    {
        vldFunction = vldFilter;
        vldFilter = "";
    }
//    dir = "col";
// Create Array of Column Headings
    var col = [];
    xmlDoc = JSON.parse(vldStr);
    for (var i = 0; i < xmlDoc.length; i++)
    {
        for (var key in xmlDoc[i])
        {
            if (col.indexOf(key) === -1)
            {
                col.push(key);
            }
        }
    }
// Create Dynamic Table   
//    var table = document.getElementById(tableName);
    table.classList.add("div-table");
    table.innerHTML = "";
    if (dir == "row")
    {
// Create Table Headings.
        var tr = document.createElement("div");
        tr.classList.add("div-table-row");
        
        for (var i = 0; i < col.length; i++) 
        {
            var th = document.createElement("div");
            th.classList.add("div-table-header");
            th.innerHTML = col[i];
            th.id = 'TH'+i;
            th.onclick = function(e)
            {
//            getMessage(this.id+" "+this.innerHTML,"");
            }
            tr.appendChild(th);
        }
        table.appendChild(tr);
// Add Table Rows
        for (var i = 0; i < xmlDoc.length; i++) 
        {
            var tr = document.createElement("div");
            tr.classList.add("div-table-row");
            tr.id = 'TR'+i;
            for (var j = 0; j < col.length; j++) 
            {
                var td = document.createElement("div");
                td.classList.add("div-table-cell");
                try
				{
					var fileName = xmlDoc[i][col[j]].split('/').pop();
				}
				catch(e)
				{
					var fileName = "";
				}
                td.innerHTML = fileName;
                td.value = xmlDoc[i][col[j]];
                if (j == 0)
                {
                    td.id = xmlDoc[i][col[j]];
                }
                tr.appendChild(td); 
            }
            tr.onclick = function(e)
            {
                var rows = table.getElementsByClassName("div-table-row");
                for (var j = 0; j < rows.length; j++) 
                {
                    rows[j].firstElementChild.classList.remove("selected"); // Remove highlight from all rows
                }
                this.firstElementChild.classList.add('selected');
//              alert("Row:"+this.id);
                tableSelect(vldTable,this.id);
            }
            table.appendChild(tr);
        }        
    }
    else if (dir == "col")
    {
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
        for (var i = 0; i < col.length; i++) 
        {
            var tr = document.createElement("div");
            tr.classList.add("div-table-row");
            tr.id = 'TR'+i;
            var th = document.createElement("div");
            th.classList.add("div-table-header");
            th.innerHTML = col[i];
            th.id = 'TH'+i;
            tr.appendChild(th);
            table.appendChild(tr);
        }
        for (var i = 0; i < xmlDoc.length; i++) 
        {
            for (var j = 0; j < col.length; j++) 
            {
                tr = document.getElementById("TR"+j);
                var td = document.createElement("div");
                td.classList.add("div-table-cell");
                td.innerHTML = xmlDoc[i][col[j]];
                tr.appendChild(td);
            }
        }
//        table.appendChild(tr);
    }
	if (autoDelete.toUpperCase() == "Y")
	{
		table.addEventListener('mouseleave', function() 
		{
//			deleteRow(tableName);
			table.remove();
			gotoHere();
		});
	}
}

function tableSelect(table,row)
{
//    alert("Row"+table+" "+row)
    if (table == "picklabel")
    {
        document.getElementById('confirmtext').value = "Printer";
        document.getElementById('confirmpanel').style.display = "block";
        document.getElementById('confirmpanel').style.position = "absolute";
        document.getElementById('confirmpanel').style.left = '20px';
        document.getElementById('confirmpanel').style.top = '50px';
        document.getElementById('confirminput').style.display = "block";
        document.getElementById('alertoverlay').style.display = "block";
        document.getElementById('yesbtn').innerHTML="Print";
        document.getElementById('nobtn').innerHTML="Cancel";
        document.getElementById('txtcurraction').value = "";
        document.getElementById('confirminput').focus();
        currentRow = row;
        cellFail = true;            
        document.getElementById('yesbtn').onclick = function()
        {
            var printer = "ZEBK01";
            printer = document.getElementById('confirminput').value;
            id=row;
            vldStr = "pickdetailid="+id+"|AND|printer="+printer;
//            var url = "/KUK/action/printLabels.php";
            var url = "/KUKtest/action/printLabels.php";
            url +=
            "?function=picklabelzebra"+
            "&host="+userSettings[0].dbhost+
            "&user="+userSettings[0].dbuser+
            "&pword="+userSettings[0].dbpwd+
            "&dbase="+userSettings[0].dbase+
            "&filter="+vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
//            ajaxGet(url, rowValidated);
            get(url).then(function(response) 
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            document.getElementById('confirmpanel').style.display = "none";
        };
        document.getElementById('nobtn').onclick = function()
        {
            document.getElementById('confirmpanel').style.display = "none";
        };                      
        idx = 999;
        return false;
    }
    else if(table=="pdfFiles")
    {
//      alert("pdfFiles");
        const iframe = document.getElementById('printIframe');
        const modal = document.getElementById('iframeModal');
        const currRow = document.getElementById(row);
        const url = currRow.children[0].value;
		const urlType = currRow.children[1].value;
		
		if (urlType == "DIR")
		{
			idx = 0;
			cellFail = false;
			const i = url.lastIndexOf('//');
			const path = url.substr(i);
			document.getElementById("txtcurraction").value = "tables:pdftable?folder=/"+path+"/";
			cellValidation(dataTable,this.id);
			return;
		}

// URL Link
        const linkContainer = document.getElementById('file-link-container');
// Create an anchor element
        const link = document.createElement('a');
        link.href = url;
        link.textContent = 'View File';
        link.target = '_blank';
// Append the link to the container
        linkContainer.appendChild(link);
        linkContainer.style.position = 'absolute';
        const posElement = document.querySelector('footer');
        linkContainer.style.bottom = posElement.offsetHeight + 'px'; // Position above the footer
        linkContainer.style.left = posElement.offsetLeft + 'px';
        linkContainer.style.width = posElement.offsetWidth + 'px';
        linkContainer.style.display = 'flex';
        manageTimeout("set", "linkTimeout", () =>
        {
            linkContainer.style.display = 'none';
            linkContainer.innerHTML = '';
        }, 10000);
/*
// diplay in iFrame
        iframe.src = url;
        iframe.style.display = 'flex';
        iframe.style.maxWidth = '100%';
        iframe.style.maxHeight = '100%';
        iframe.style.objectFit = 'contain';
        modal.style.display = 'block';
*/
    }
}

// Display document object
function showDocument(url)
{
    if (url.substr(-3) == "pdf")
    {
//        var _window = window.open(url, '_blank');
        document.getElementById("docPanel").innerHTML = '<object id="document" width="95%" height="100px" data="'+url+'"></object>';
    }
    else if (url.substr(-4) == "xlsx")
    {
        var _window = window.open(url, '_blank');
    }
    else if (url.substr(-3) == "xml")
    {
 //       document.getElementById("docPanel").innerHTML = '<object id="document" width="95%" height="95%" data="'+url+'"></object>';
 //       ajaxGet(url, showXml);
        get(url).then(function(response) 
        {
            showXml(response);
        }, 
        function(error) 
        {
            getMessage("FAIL-"+error);
        })
    }
    else
    {
        try
        {
            document.getElementById("docPanel").innerHTML = '<object id="document" width="95%" data="'+url+'"></object>';
        }
        catch(e)
        {
            var _window = window.open(url, '_blank');
        }
    }
}

function showXml(xml) 
{
    document.getElementById("docPanel").innerHTML = '<pre id="document" width="95%" height="95%">'+xml.response+'</pre>';
}


// Create Hidden iFrame for PDF Report - NON-IE only
printPdf = function() 
{
    printIframe('printIframe');
}

function printIframe(iFrameId) 
{
    document.getElementById(iframeModal).style.display = "block";
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf ("MSIE ");
    var iframe = document.getElementById(iFrameId);
    iframe.src = document.getElementById("txtstoredvalue").value;
    if (msie !== -1) {
        iframe.contentWindow.document.execCommand('print', false, null);
    } else {
        iframe.onload = function() 
        {
            manageTimeout("set", "iframeTimeout", () => 
            {
//                var elmnt = iframe.contentWindow.document.getElementsByTagName(iframe.src)[0];
//                if (elmnt != undefined)
//                {
                    iframe.focus();
                    iframe.contentWindow.print();
                    iframe.style.display = "none";
//                }
            }, 1000);
        };
    }
//    document.getElementById(iFrameId).style.display = "none";
}

async function showPDF(response) 
{
    try 
    {
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);
        document.getElementById('printIframe').src = url;
        document.getElementById('iframeModal').style.display = "block";
    } 
    catch (error) 
    {
        alert("FAIL-"+error);
    }
}

// post Audit
function postAudit(vldFunction)
{
    if ((vldFunction == "postpick") || (vldFunction == "posttransaction") || (vldFunction == "postcts") || (vldFunction == "postrcts") || (vldFunction == "inventoryserial"))
    {
        var table = document.getElementById(dataTable);
        var screenData = "";
// populate string with field names & values
        for (var i = 1; i < table.rows.length; i++)
        {
// format URL string for post
            if (screenData != "")
                screenData = screenData+",";
                
            screenData = screenData+table.rows[i].cells[0].innerHTML+":"+document.getElementById(''+i).value+":"+document.getElementById(''+row).placeholder;
        }
// add UserId to string
        screenData = screenData+",currentUser:"+document.getElementById("txtUser").value;

//  alert("TEST1-"+screenData);
    
        if (screenData != "")
        {
            var url = ajaxPath+"rdtphp/transaction.php"+
            "?function=postaudit"+
            "&host="+userSettings[0].dbhost+
            "&user="+userSettings[0].dbuser+
            "&pword="+userSettings[0].dbpwd+
            "&dbase="+userSettings[0].dbase+
            "&connection="+userSettings[0].path+
            "&table="+document.getElementById("txtTranType").value+
            "&returnfields="+
            "&filter="+screenData;
//          ajaxGet(url, rowValidated);
            get(url).then(function(response) 
            {
                rowValidated(response);
            }, 
            function(error) 
            {
                getMessage("FAIL-"+error);
            })
            return;
        }
    }
}

function userTimer()
{
//    getMessage("Hello","");
}

function linebreak(s)
{
    return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}

function capitalize(s) 
{
    return s.replace(first_char, function(m) { return m.toUpperCase(); });
}

function detectIE() 
{
  var ua = window.navigator.userAgent;
  var msie = ua.indexOf('MSIE ');
  if (msie > 0) 
  {
// IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }
  var trident = ua.indexOf('Trident/');
  if (trident > 0) 
  {
// IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }
  var edge = ua.indexOf('Edge/');
  if (edge > 0) 
  {
// Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  }
// other browser
  return false;
}

function toggleScreen(onoff)
{
    if (onoff != undefined)
    {
        if(onoff.toLowerCase() == "on")
            openFullscreen();
        else if(onoff.toLowerCase() == "off")
            closeFullscreen();
    }
    else
    {
        if (fullScr == false)
            openFullscreen();
        else
            closeFullscreen();
        fullScr = fullScr ? false : true;
    }
}

function saveCurrentRow(row)
{
    var table = document.getElementById('dataTable');
    for (var r = 0; r < table.rows.length; r++) 
    {
        if (trnName[r] == "sequence")
        {
            trnValue[r] = trnName[row];
        }
    }
}

function getCurrentRow()
{
    var table = document.getElementById('dataTable');
    for (var r = 0; r < table.rows.length; r++) 
    {
        if (trnName[r] == "sequence")
        {
            return trnValue[r];
        }
    }
}

function openFullscreen() 
{
    try
    {
      if (elem.requestFullscreen) 
      {
        elem.requestFullscreen();
      } 
      else if (elem.webkitRequestFullscreen) { /* Safari */
        elem.webkitRequestFullscreen();
      } 
      else if (elem.msRequestFullscreen) { /* IE11 */
        elem.msRequestFullscreen();
      }
    }
    catch(e)
    {
    }
}

function closeFullscreen() 
{
    try
    {
        if (document.fullscreenElement) 
        {
            manageTimeout("set", "fullscreenTimeout", () => 
            {
                document.exitFullscreen()
            }, timeOut);
        }
        else if (document.fullscreen) 
        {
            try
            {
                document.exitFullscreen();
            }
            catch(e)
            {
                return;
            }
        } 
        else if (document.webkitExitFullscreen) 
        { /* Safari */
            document.webkitExitFullscreen();
        } 
        else if (document.msExitFullscreen) 
        { /* IE11 */
            document.msExitFullscreen();
        }
    }
    catch(e)
    {
    }
}

function iframeClose()
{
    const modal = document.getElementById('iframeModal');
    modal.style.display = 'none';
    rowValidated("OK  -iframeClose");
    return false;
}
function iframePrint(printer)
{
//  alert("FAIL-TEST-"+jsonObject.file);
    const iframe = document.getElementById('printIframe');
    vldProgram = "/rrmcreports/common/reporttrigger.php";
    vldType = jsonObject.type;
    vldStr = "file="+jsonObject.file;
    vldStr = vldStr+"|AND|pdf="+jsonObject.pdf;
// add UserId to string
    vldStr = vldStr+"|AND|currentUser="+document.getElementById("txtUser").value;
    vldStr = vldStr+"|AND|rdtstart="+rdtStart+"|AND|rdtend="+rdtEnd;
    
    url = vldProgram+
            "?function="+vldType+
            "&table="+
            "&returnfields=";
    id = row;
    vldStr = vldStr.split("|AND|").join(",");
    vldStr = vldStr.split(":").join("|COLON|");
    vldStr = vldStr.split("=").join(":");
    var dataArray = vldStr.split(",");
    dataObj = {};
    for (let i = 0; i < dataArray.length; i++) 
    {
        dataField = dataArray[i].split(":")[0];
        dataValue = dataArray[i].split(":")[1];
        dataObj[dataField]=dataValue;
    }
    post(url,JSON.stringify(dataObj)).then(function(response)
    {
        rowValidated(response);
    }, 
    function(error) 
    {
        getMessage("FAIL-"+error);
    })
    
    return false;
}

</script>
</html>
