/* 
 * Arrays to handle adding setups and their attachments on the page.
 * 
 * Dependencies:
 *      ./javascript/general.js
 */
// The new numbers of the setups that they are creating
var newSetupNumbersToAdd = new Array();

function getNewMaxSetupNumber(){
    // Set the result to zero for now
    var result = 0;
    
   // Loop through the result numbers to get the highest
   for (var loopSetupNumber in newSetupNumbersToAdd){
       // Determine if the number is higher than the current number
       if (newSetupNumbersToAdd[loopSetupNumber]>result){
           // make this the new high
           result = newSetupNumbersToAdd[loopSetupNumber];
       }
   }
   
    // Return the highest result
    return result;
}

function createNewSetupNumbersString(){
    // Set the result to zero for now
    var result = '';
    
   // Loop through the result numbers
   for (var loopSetupNumber in newSetupNumbersToAdd){
       // Add it to the string
       result = result+newSetupNumbersToAdd[loopSetupNumber].toString()+'|';
   }

    // Remove the last comma
    result=result.slice(0, (result.length-1));
    
    // Return the highest result
    return result;
}

function removeNewSetupNumber(setupNumberToRemove){
    // Set the removal item to zero for now
    var setupLocationToRemove = -1;
    
    // Loop through the result numbers to get the highest
    for (var loopSetupNumber in newSetupNumbersToAdd){
        // Determine if the number is higher than the current number
        if (newSetupNumbersToAdd[loopSetupNumber]===setupNumberToRemove){
            // set this as the one to remove
            setupLocationToRemove = loopSetupNumber;

            // Break out of the list
            break;
        }
    }

    // Remove it from the list
    newSetupNumbersToAdd.splice(setupLocationToRemove,1);
}

function CheckSetupFilesize(fileElementName, surroundDivName, number, maxSetupsFileSize=4294967296){
    // Init and get variables from the page
    var fileElement = document.getElementById(fileElementName + number);
    var sizeinbytes = 0;
    var returnValue = 0; // Put as a false that there will NOT be an alert

    // Get the file size of what they want to upload
    sizeinbytes = fileElement.files[0].size;

    // Determine if the size is ok
    if (sizeinbytes>maxSetupsFileSize){
        // Let the user know that the file is not going to be taken
        alert( 'The file chosen is approximately ' + getHumanReadableFileSize(sizeinbytes) + 
               '. That is larger than the alloted size of approximately ' + getHumanReadableFileSize(maxSetupsFileSize) +
               '. This file will not be uploaded and the value will be set to nothing.');
       
        // Set the background to something showing it is GTG
        document.getElementById(surroundDivName + number).style.backgroundColor = 'Transparent';
        
        // Remove the file
        fileElement.files[0] = null;
        
        // reset the value to nothing for speeds sake
        fileElement.value='';
        
        // Put as true that there is an alert
        returnValue = 1; 
    }
    else {
        // Set the background to something showing it is GTG
        document.getElementById(surroundDivName + number).style.backgroundColor = 'Green';
    }
    
    // Return the alert
    return returnValue;
}

function setupAttachmentElementCurrentSetupOnChange(number){
    // Get the check element to modify
    var removeAttachmentCheckbox=document.getElementById('removeAttachment' + number);
    var removeAttachmentLabel=document.getElementById('removeAttachmentLabel' + number);
    
    // Check that we ARE NOT clearing out the old file
    removeAttachmentCheckbox.checked=false;

    // Let them check the file and check if it is a good file
    if (CheckSetupFilesize('newToolStartAttachment', 'newToolStartRow', number)===1){
        // Show the checkbox to remove the old file again
        removeAttachmentCheckbox.style="";
        removeAttachmentLabel.style="";
    }
    else {
        // Check that we ARE clearing out the old file
        removeAttachmentCheckbox.checked=true;

        // Show the checkbox to remove the old file again
        removeAttachmentCheckbox.style="display:none;";
        removeAttachmentLabel.style="display:none;";
    }
    
    // Toggle the image cell
    div_toggleVisibilityOnCheckbox('removeAttachment' + number, 'imageCell' + number, 'OPPOSITE');
}

function addEmployeesToCurrentSetups () {
    // Get the elements that are setup IDs
    var setupByIDElements = document.getElementsByClassName("SetupByID");
    
    // Loop through them to get the value of the element
    for (var loopNumber = 0; loopNumber < setupByIDElements.length; loopNumber++) {
        // Set the position ID to the final numbers
        var position = setupByIDElements[loopNumber].id.replace("oldSetupBy", "");

        // Create the select and add it to the parent
        document.getElementById('setupByDiv' + position).innerHTML = getSUCompanyEmployeesAsSelectOptions('setupBy' + position, setupByIDElements[loopNumber].value, style="");
    }
    
    // Get the elements that are setup IDs
    var setupCheckedByIDElements = document.getElementsByClassName("SetupCheckedByID");
    
    // Loop through them to get the value of the element
    for (var loopNumber = 0; loopNumber < setupCheckedByIDElements.length; loopNumber++) {
        // Set the position ID to the final numbers
        var position = setupCheckedByIDElements[loopNumber].id.replace("oldCheckedBy", "");

        // Create the select and add it to the parent
        document.getElementById('checkedByDiv' + position).innerHTML = getSUCompanyEmployeesAsSelectOptions('checkedBy' + position, setupCheckedByIDElements[loopNumber].value, style="");
    }
}

function getToolAdded(queriedToolID){
    // Set the default return to false
    var taskToolIDFound = null;
    
    // Get the elements that are considered tools for this task
    var taskToolIDElements = document.getElementsByClassName("taskToolID");
    
    // Loop through them to get the value of the element
    for (var loopNumber = 0; loopNumber < taskToolIDElements.length; loopNumber++) {
        // Determine if the Tool ID equals the one passed in
        if (queriedToolID === parseInt(taskToolIDElements[loopNumber].value)){
            // Set the return to the task tool ID element
            taskToolIDFound = taskToolIDElements[loopNumber];
            
            // No need to continue to loop, so break out
            break;
        }
    }

    // Return what was found out
    return taskToolIDFound;
}

function addGCodeTools(queriedToolIDs, inNumberOfToolsExpected, inToolsNotInDatabase) {
    try {
        // Open the tools tab while populating it
        openChildPage('ToolsInfo', document.getElementById('toolsTabButton'));

        // Get the tools that were queried as an array
        var queriedTools = queriedToolIDs.split(",");
                
        // Set default of no tools actually found
        var queriedToolCount=0;
        
        // Loop through the queried rows
        for (var arrayPosition = 0; arrayPosition < queriedTools.length; arrayPosition++) {
            // Get the relevant variables
            var relevantVariables = queriedTools[arrayPosition].split(":");
            
            // Get the position element
            var theTaskToolIDElement = getToolAdded(parseInt(relevantVariables[0]));
            
            // Determine if this is a new tool or old
            var thePosition = -1;
            if (theTaskToolIDElement!==null && theTaskToolIDElement!=='undefined' && 
                theTaskToolIDElement.id.includes("newToolChosenID")){
                // Set the position ID to the final numbers
                thePosition = theTaskToolIDElement.id.replace("newToolChosenID", "");
            }
            else if (theTaskToolIDElement!==null && theTaskToolIDElement!=='undefined' && 
                     theTaskToolIDElement.id.includes("toolChosenID")){
                // Set the position ID to the final numbers
                thePosition = theTaskToolIDElement.id.replace("toolChosenID", "");
                
                // Get the check control and set it as not to be removed in case it was checked 
                document.getElementById("removeTool" + thePosition).checked=false;
            }
            
            // Determine if this tool is already added
            if (thePosition !== -1){
                // This is already in the list, so it should be counted
                queriedToolCount++;
                
                // Skip this one
                continue;
            }
            
            // Get the tool row to work with 
            var divToolRow = document.getElementById("GCode_Tool_" + parseInt(relevantVariables[0]));
            
            // Get the chosen tool header
            var clonedChosenToolRowHeader = document.getElementById("GCode_Tool_Header").cloneNode(true);

            // clone the tool row element
            var clonedChosenToolRowElement = divToolRow.cloneNode(true);

            // Create the new div for this tool and get the position of the new div
            var divPosition = addNewTool(parseInt(relevantVariables[1]));                

            // Get the elements of the new row
            var toolChosenDisplayCell=  document.getElementById("newToolChoiceCell" + divPosition);
            var toolChosenID = document.getElementById("newToolChosenID" + divPosition);
            var displayRowHeaderID = "newEditCellIDForHeader" + divPosition;
            var displayRowID = "newEditCellIDFor" + divPosition;

            // Set the ID(s)
            toolChosenID.value = parseInt(relevantVariables[0]);

            // Get any old children for this position
            var oldHeader = document.getElementById(displayRowHeaderID);
            var oldChild = document.getElementById(displayRowID);

            // Determine if the parent has this child really
            if (oldChild !== null){
                // Remove any old children
                toolChosenDisplayCell.removeChild (oldHeader);
                toolChosenDisplayCell.removeChild (oldChild);
            }

            // Attempt to get the update cell element
            var updateCellHeaderElements = clonedChosenToolRowHeader.querySelectorAll(".cell");

            // Determine if we got the update cell
            if (updateCellHeaderElements!==null){
                // Loop through the elements found
                for (var i=0; i<updateCellHeaderElements.length; i++){
                    var classList = updateCellHeaderElements[i].classList;
                    // Loop through the classes found
                    for (var j=classList.length-1; j>=0; j--){
                        switch (classList[j]) {
                            case "nameCell":
                                // Change the width for machines
                                updateCellHeaderElements[i].style.width = "30%";
                                break;
                            case "assignedToolsTypeCell":
                                // Change the width for machines
                                updateCellHeaderElements[i].style.width = "20%";
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            // Attempt to get the update cell element
            var updateCellElements = clonedChosenToolRowElement.querySelectorAll(".cell");

            // Determine if we got the update cell
            if (updateCellElements!==null){
                // Loop through the elements found
                for (var i=0; i<updateCellElements.length; i++){
                    var classList = updateCellElements[i].classList;
                    // Loop through the classes found
                    for (var j=classList.length-1; j>=0; j--){
                        // Set the height to skinnier
                        updateCellElements[i].style.height = "5px";

                        // Check for the class
                        switch (classList[j]) {
                            case "nameCell":
                                // Change the width for machines
                                updateCellElements[i].style.width = "30%";
                                break;
                            case "assignedToolsTypeCell":
                                // Change the width for machines
                                updateCellElements[i].style.width = "20%";
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            
            // Change the ID of the newly copied rows
            clonedChosenToolRowHeader.id = displayRowHeaderID;
            clonedChosenToolRowElement.id = displayRowID;
            
            // Set the HTML that is the chosen tool row into the visual area
            toolChosenDisplayCell.appendChild (clonedChosenToolRowHeader);
            toolChosenDisplayCell.appendChild (clonedChosenToolRowElement);
            
            // Increase the amount of tools found
            queriedToolCount++;
            
            // Remove the row element
            divToolRow.parentNode.removeChild(divToolRow);
        }
        
        // Determine if the query returned the amount that they had in the GCode
        if (queriedToolCount !== inNumberOfToolsExpected){
            // If the two do not match, then let the user know
            alert('There were ' + queriedToolCount + ' tools that were added to the task, ' + 
                  'but expected there to be ' + inNumberOfToolsExpected + ' tools. The tool(s) ' +
                  'that is/are not in the database is/are "' + inToolsNotInDatabase + '".');
        }
    }
    catch (e) {
        // Show the user in their face
        alert(e.message);
    }
    finally {
        // ReOpen the setups tab
        openChildPage('SetupsInfo', document.getElementById('setupsTabButton'));
    }
}

// Query the database for the tools that are in the GCode file
function queryForToolsInGCode(inSessionID, inToolNames, inNumberOfToolsExpected, showMessages=true, theGCodeElement=null, theNumber=-1, isNewSetup=false){
    // Reset the array
    newestQueriedToolIDs = null;
    
    // Setup the parameters to pass to PHP
    var params = {
        "sessionID" : inSessionID,
        "specificToolNames" : inToolNames
    };

    // use the assigned tools
    url = "php_only_scripts/jquery_only/tools_in_gcode.php";

    // Setup AJAX for communication
    $.ajax({
        context : this,
        type    : "GET", 
        url     : url, 
        data    : params, 
        dataType: "html", 
        encode  : true, 
        cache   : false
    })
    .done(function(data){
        // Determine if it was NOT success
        if (data.trim() !== ""){
            // Check to see if there is a reason NOT to allow list population
            if (data.includes("ABORT ASSIGN") && showMessages){
                // Split the string on the double colon
                var errorStrings=data.trim().split("::");

                // Give an alert popup of the problem
                alert(errorStrings[1]);
                
//                // determine if there was a choose file element passed in
//                if (theGCodeElement!==null){
//                    // Remove the file
//                    theGCodeElement.files[0]=null;
//                    theGCodeElement.value='';
//                }
                
                removeGCode(theNumber, isNewSetup);
                
                // Return a failed result
                return false;
            }
            else {
                // Attempt to separate the data returned
                var dataArray = data.split("~~||***||~~");
                
                // Determine if the length is two
                if (dataArray.length>=2){
                    // Determine if there were tools that were not added to the database
                    var toolsNotInDatabase="";
                    if (dataArray.length===3){
                        // Let the user know that there were tools that were NOT in the database and what they were
                        toolsNotInDatabase = dataArray[2].trim();
                    }

                    // Set a variable to hold the div that will be holding the appropriate tools
                    var appropriateToolsListedDiv = document.getElementById('gCodeTools');

                    // Populate the contents of the returned query into the DIV
                    appropriateToolsListedDiv.innerHTML = dataArray[1].trim();

                    // Add the populated tools to the task
                    addGCodeTools(dataArray[0].trim(), inNumberOfToolsExpected, toolsNotInDatabase);
                }
                
                // Cleanup the div
                appropriateToolsListedDiv.innerHTML = "";
                
                // Return a successful result
                return true;
            }

            // Log any errors to the console
            console.log(data.trim());
        }
        else if (showMessages) {
            // Give an alert informational popup
            alert('There were no tools returned from the query.');
                
            // Return a failed result
            return false;
        }
    })
    .fail(function(data){   
        // Log any errors to the console
        console.log(data);

        // Determine if they want to show messages
        if (showMessages){
            // Give an alert informational popup
            alert('There was a problem communicating with the server to get the tools that are in your GCode.');
        }
                
        // Return a failed result
        return false;
    }); 
}

function handlerGCodeFileLoad(number, isNewSetup=false, inSessionID=null, theGCodeElement, event) {
    // Get the value of the result
    var gcode = event.target.result;
    
    // Determine if we have a name for the file 
    var fileName='Unknown';
    if (theGCodeElement.files[0].name != null && theGCodeElement.files[0].name != ""){
        // Set the name to the filename of this particular file
        fileName=theGCodeElement.files[0].name;
    }
    
    // Determine if there was a problem parsing GCode
    !parseGCodeContent(number, isNewSetup, gcode, inSessionID, fileName, theGCodeElement);
}

// Method to handle the loading of a GCode
function parseCurrentToolContent(number, inSessionID) {
    // Create variables for elements used
    var numberOfToolsExpected = 0;
    var amountOfLinesElement = document.getElementById('amountProgramLines'+number);
    var toolsUsedName = 'toolDetails';
    
    // Get the tools used control 
    var toolsUsedCtrl = document.getElementById(toolsUsedName+number);

    // Split the string on end line characters
    var lines = toolsUsedCtrl.value.split("\n");
    
    // Loop through the control
    var currentTools = "";
    for (var i = 0; i < lines.length; i++) {
        var currentLine=lines[i];
        
        // Add this line to the string
        currentTools += currentLine + "\n";
            
        // Increase the number of tools expected
        numberOfToolsExpected++;
    }
    
    // Set the amount of lines calculated
    amountOfLinesElement.value = lines.length;
    
    // Query for the tools requested
    queryForToolsInGCode(inSessionID, currentTools, numberOfToolsExpected, false);
}

// Method to handle the loading of a GCode
function parseGCodeContent(number, isNewSetup=false, gcode, inSessionID=null, fileName='Unknown', theGCodeElement=null) {
    var amountOfLinesElement = null;
    var programName = null;
    var runTime = null;
    var coordinateSystemName = null;
    var m00Name = null;
    var originalToolsUsedName = null;
    var moddedToolsUsedName = null;
    var numberOfToolsExpected = 0;
    var removeGCodeName = null;
    var moddedToolsUsedCtrl = null;
    
    // Determine if this is from the new file section
    if (isNewSetup){
        // Get the amount of lines element from the new section
        amountOfLinesElement = document.getElementById('newAmountProgramLines'+number);
        programName = 'newProgramName';
        runTime = 'newProgramRunTime';
        coordinateSystemName = 'newCoordinateID';
        m00Name = 'newM00';
        originalToolsUsedName = 'newToolDetails';
        removeGCodeName = 'newRemoveGCode';
    }
    else{
        // Get the amount of lines element from the old section
        amountOfLinesElement = document.getElementById('amountProgramLines'+number);
        programName = 'programName';
        runTime = 'programRunTime';
        coordinateSystemName = 'coordinateID';
        m00Name = 'm00';
        originalToolsUsedName = 'toolDetails';
        moddedToolsUsedName = 'moddedToolDetails';
        removeGCodeName = 'removeGCode';
        
        // Get the control that has info on modded tools
        moddedToolsUsedCtrl = document.getElementById(moddedToolsUsedName+number);
    }
    
    // Show the remove button
    document.getElementById(removeGCodeName+number).style.display='block';

    // Set M00 to false for now until proven otherwise
    document.getElementById(m00Name+number).checked=false;

    // Set the filename to the passed in filename until it is found in the GCode
    document.getElementById(programName+number).value=fileName;
    
    // Set the runtime to Unknown until found in the GCode
    document.getElementById(runTime+number).value='Unknown';
    
    // Split the string on end line characters
    var lines = gcode.split("\r");
    
    // Loop through the file looking for end line characters
    var currentTools = "";
    for (var i = 0; i < lines.length; i++) {
        var currentLine=lines[i];
        
        // Check to see if this is a variable line that we care about
        if (currentLine.includes("(//)")) {
            // Remove the end and beginning
            currentLine = currentLine.replace("(//)(", "");
            currentLine = currentLine.replace(")(//)", "");

            // Determine if this is the file name field
            if (currentLine.includes("FILE NAME")) {
                // Set the name of the file in the appropriate control
                document.getElementById(programName+number).value=currentLine.split('-').pop().trim();
            } 
            // Check to see if this is a tool line
            else if (currentLine.includes("CYCLE TIME")){
                // Set the runtime in the appropriate control
                document.getElementById(runTime+number).value=currentLine.split('=').pop().trim();
            }
            else {
                // Set the coordinate System in the appropriate control
                document.getElementById(coordinateSystemName+number).value=currentLine.trim();
            }
        } 
        // Check to see if this is a tool line
        else if (currentLine.includes("(/-/)")){
            // Remove the end and beginning
            currentLine = currentLine.replace("(/-/)(","");
            currentLine = currentLine.replace(")(/-/)", "");

            // Split the tooline into toolnumber and tool name
            const myArray = currentLine.split("-");
            
            // Determine if we have more than one variable
            if (myArray.length > 1){
                // Take the first value and determine if that tool number is already in the tools
                if (currentTools.includes(myArray[0])){
                    // Remove the gcode info on this one uploaded
                    removeGCode(number, isNewSetup);
                    
                    // Let them know there are duplicate values
                    alert("There was an error validating the setups.\n\nError was: There is more than one tool for the " + 
                           myArray[0].trim() + " slot. This is not allowed to happen in the G-Codes uploaded to the TMS.\n\n" + 
                           "Please uniquely assign tools to tool slots.");
                   
                   // Leave method
                   return false;
                }
            }

            // Add this line to the string
            currentTools += currentLine;
            
            // Increase the number of tools expected
            numberOfToolsExpected++;
        }
        // Check to see if this is a mandatory stop
        else if (currentLine.includes("M00")){
            // There is an M00, so check it
            document.getElementById(m00Name+number).checked=true;
        }
    }
    
    // Get the control that has info on current tools
    var toolsUsedCtrl = document.getElementById(originalToolsUsedName+number);

    // Determine if the tools that are currently in the tool details control are currently in any others
    cleanupTools(toolsUsedCtrl, true, moddedToolsUsedCtrl);

    // Set the tools in the appropriate control
    toolsUsedCtrl.value=currentTools.trim();
    toolsUsedCtrl.style.height = (toolsUsedCtrl.scrollHeight+5)+'px';

    // Determine if this is a setup that was already existing
    if (!isNewSetup){
        // Set the tools in the appropriate control
        moddedToolsUsedCtrl.value=currentTools.trim();
        moddedToolsUsedCtrl.style.height = (moddedToolsUsedCtrl.scrollHeight+5)+'px';
    }
    
    // Set the amount of lines calculated
    amountOfLinesElement.value = lines.length;
    
    // Get the type of the current selected machine
    var machineType = document.getElementById("machineID").options[document.getElementById("machineID").selectedIndex].title;

    // Determine if this is one we currently handle parsing of GCode. 
    // TODO: Modify this as we parse more and more machine types.
    if (machineType === "MILL"){
        // Query for the tools requested
        return queryForToolsInGCode(inSessionID, currentTools, numberOfToolsExpected, true, theGCodeElement, number, isNewSetup);
    }
}

function savedSetupMarkedForRemoval(setupNumber, inSessionID){
    // Get the check box control
    var chkbxRemoveSetup = document.getElementById('removeSetup' + setupNumber);
    
    // Determine if it is checked or not checked
    if (chkbxRemoveSetup.checked){
        // Get the tool details control of the one marked for removal
        var txtToolDetails = document.getElementById('toolDetails' + setupNumber);
        
        // Set the modded control to null for now
        var moddedToolsUsedCtrl = document.getElementById('moddedToolDetails' + setupNumber);

        // Do the cleanup as though it is being removed
        cleanupTools(txtToolDetails, false, moddedToolsUsedCtrl);
    }
    else {
        // Parse this setup as if it already had tools in it
        parseCurrentToolContent(setupNumber, inSessionID);
    }
}

function getCurrentNotToDeleteTools(){
    // create a variable for all tools
    var returnCurrentToolsInDetails=new Array();

    // Get all elements that have current tool details
    var toolDetailsElements = document.getElementsByClassName("setupToolDetails");

    // Loop through the elements
    for (var currentToolistLoopNumber = 0; currentToolistLoopNumber < toolDetailsElements.length; currentToolistLoopNumber++) {
        // Determine if this setup is NOT a new setup
        if (!toolDetailsElements[currentToolistLoopNumber].id.includes("new")){
            // Get the current ID
            var currentSetupToCheckID = toolDetailsElements[currentToolistLoopNumber].id.replace("moddedToolDetails", "");

            // Determine if this one is slated for removal
            if (document.getElementById("removeSetup" + currentSetupToCheckID).checked){
                // Ignore this one by continuing on to the next one
                continue;
            }
        }

        // Split the current toollist string on end line characters
        var currentTools = toolDetailsElements[currentToolistLoopNumber].value.split("\n");

        // Loop through the tools in this control
        for (var currentToolArrayPosition = 0; currentToolArrayPosition < currentTools.length; currentToolArrayPosition++) {
            // Attempt to separate the data returned in order to get the tool name
            var currentTool = currentTools[currentToolArrayPosition].substring(currentTools[currentToolArrayPosition].indexOf("-") + 1).trim();

            // Determine if this tool is NOT empty and it has not been added
            if(currentTool!=='' && returnCurrentToolsInDetails.indexOf(currentTool) === -1) {
                // Add it to the current tool list
                returnCurrentToolsInDetails.push(currentTool);
            }
        }
    }
    
    // Return the unique tools that are not in a setup that is marked for delete
    return returnCurrentToolsInDetails;
}

function cleanupTools(toolsUsedCtrl, removeValue=true, moddedToolsUsedCtrl=null){
    // Open the tools tab while cleaning up
    openChildPage('ToolsInfo', document.getElementById('toolsTabButton'));
    
    // Create the return variable and set it to success
    var returnSuccess=true;
    
    // Get a value to hold the old value(s) of the control(s)
    var oldDetails = toolsUsedCtrl.value;
    var oldModdedDetails = "";
        
    // Now remove the tools from this control
    toolsUsedCtrl.value = "";
    
    // Determine if the modded control is available
    if (moddedToolsUsedCtrl!==null){
        // Get the value
        oldModdedDetails = moddedToolsUsedCtrl.value;
        
        // Now remove the tools from this control
        moddedToolsUsedCtrl.value = "";
    }
        
    // Get all of the tool tables in the document
    var toolTableElements = document.getElementsByClassName("toolTable");

    // Determine if there are any to compare against
    if (toolTableElements.length>0){
        // create a variable for all tools in the  and get them
        var allCurrentToolsInDetails=getCurrentNotToDeleteTools();

        // Loop through the elements
        var toolsAmount = toolTableElements.length;
        for (var currentToolTableLoopNum = toolsAmount-1; currentToolTableLoopNum > -1; currentToolTableLoopNum--) {
            // Set the tool as NOT being used at first
            var toolIsUsed=false;

            // get the tool name
            var loopToolName = toolTableElements[currentToolTableLoopNum].getElementsByClassName("nameCell")[1].innerText;

            // Loop through all of the unique tools in the details
            for (var currentDetailsToolistLoopNumber = 0; currentDetailsToolistLoopNumber < allCurrentToolsInDetails.length; currentDetailsToolistLoopNumber++) {
                // Determine if this tool is the same as the tool we are checking on
                if (loopToolName === allCurrentToolsInDetails[currentDetailsToolistLoopNumber]){
                    // Set the tool is used to true
                    toolIsUsed = true;

                    // Jump out of the loop
                    break;
                }
            }
            
            // Determine if this tool is NOT used
            if (!toolIsUsed){
                // Determine if this is a new tool or not
                if (toolTableElements[currentToolTableLoopNum].id.includes("newTool")){
                    // Remove the tool
                    removeNewTool(toolTableElements[currentToolTableLoopNum].id.replace("newTool",""));
                }
                // This is an current tool
                else if (toolTableElements[currentToolTableLoopNum].id.includes("currentTool")){
                    // Get the ID we will be messing with
                    var toolID = toolTableElements[currentToolTableLoopNum].id.replace("currentTool", "");

                    // Get the check control and set it as ready for removal
                    document.getElementById("removeTool" + toolID).checked=true;
                }
            }
        }
    }
                
    // Determine if we were supposed to remove the value or not
    if (!removeValue){
        // Return the value back
        toolsUsedCtrl.value=oldDetails;
        
        // Determine if the modded control is available
        if (moddedToolsUsedCtrl!==null){
            // Now remove the tools from this control
            moddedToolsUsedCtrl.value = oldModdedDetails;
        }
    }

    // ReOpen the setups tab
    openChildPage('SetupsInfo', document.getElementById('setupsTabButton'));
    
    // Return the result
    return returnSuccess;
}

// Method called once a file is chosen
function onGoodGCodeFile(event, onLoadFileHandler) {
    // Check for browser specific problems
    if (typeof window.FileReader !== 'function'){
        throw ("The file API isn't supported on this browser.");
    }
    let input = event.target;
    if (!input){
        throw ("The browser does not properly implement the event object");
    }
    if (!input.files){
        throw ("This browser does not support the `files` property of the file input.");
    }
    if (!input.files[0]){
        return undefined;
    }
    
    // Get the file
    let file = input.files[0];
    
    // Read the file
    let fr = new FileReader();
    
    // Set the onload of the reading to the passed in handler
    fr.onload = onLoadFileHandler;
    
    // Read the file so we can fire the onload method
    fr.readAsText(file);
}    

function onToolStartFileChange(theNumber, isNewSetup=false) {
    // Create element variables and set as null for now
    var toolStartAttachmentName = null;
    var toolStartRowName = null;
    var removeImageBtnName = null;
    var toolStartImageName = null;
    
    // Determine if this is a new setup
    if (isNewSetup){
        // Set what we can based on this is a new setup
        toolStartAttachmentName = 'newToolStartAttachment';
        toolStartRowName = 'newToolStartRow';
        removeImageBtnName = 'newRemoveImage';
        toolStartImageName = 'newToolStartImage';
    }
    else {
        // Set what we can based on this is a new setup
        toolStartAttachmentName = 'toolStartAttachment';
        toolStartRowName = 'toolStartRow';
        removeImageBtnName = 'removeImage';
        toolStartImageName = 'toolStartImage';
    }
    
    // Get the Tool Start File element
    var theToolStartAttachmentElement = document.getElementById(toolStartAttachmentName+theNumber);

    // Check to see that the name is good or not
    if (doesFileNameHaveBadChars(theToolStartAttachmentElement.value)){
        // Give an alert that the file name has bad characters
        alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");

        // Remove the file
        theToolStartAttachmentElement.files[0]=null;
        theToolStartAttachmentElement.value='';

        // Fail the load
        return false;
    }
            
    // Get the extension of this file they chose
    var ext = theToolStartAttachmentElement.files[0].name.split('.').pop().toLowerCase();

    // Determine if it is NOT the correct extension
    if(ext !== 'tif' && ext !== 'tiff' && 
       ext !== 'bmp' && 
       ext !== 'jpg' && ext !== 'jpeg' && 
       ext !== 'gif' && 
       ext !== 'png') {
        // Let the user know
        alert('File is not of an appropriate image file.\n\nTry again.');

        // Remove the file
        theToolStartAttachmentElement.files[0]=null;
        theToolStartAttachmentElement.value='';

        // Fail the load
        return false;
    }            

    // Check the file size
    var isError = CheckSetupFilesize(toolStartAttachmentName, toolStartRowName, theNumber);

    // Determine if the file was sized well
    if (isError === 0){
        // Attempt to preview the file
        PreviewImage(toolStartAttachmentName + theNumber, toolStartImageName + theNumber);

        // Show the button control
        document.getElementById(removeImageBtnName + theNumber).style.display='block';
    }
    else {
        // Remove any stray images
        document.getElementById(toolStartImageName + theNumber).value='';
        document.getElementById(toolStartImageName + theNumber).style.display='none';

        // Hide the button control
        document.getElementById(removeImageBtnName + theNumber).style.display='none';
    }
    
    // Return the inverse of the isError flag
    return !isError;
};

function onNewGCodeSelected(theNumber, isNewSetup=false, inSessionID=null) {
    try {
        // Create element variables and set as null for now
        var gCodeAttachmentName = null;
        var gCodeRowName = null;
        var programName = null;

        // Determine if this is a new setup
        if (isNewSetup){
            // Set what we can based on this is a new setup
            gCodeAttachmentName = 'newGCodeAttachment';
            gCodeRowName = 'newGCodeRow';
            programName = 'newProgramName';
        }
        else {
            // Set what we can based on this is a new setup
            gCodeAttachmentName = 'gCodeAttachment';
            gCodeRowName = 'gCodeRow';
            programName = 'programName';

            // Reset the cell contents containing the info on any current file
            document.getElementById('gCodeDescCell' + theNumber).innerHTML="";

            // Hide the label
            document.getElementById('removeGCodeLabel' + theNumber).style.display='block';
        }

        // Get the GCode element
        var theGCodeElement = document.getElementById(gCodeAttachmentName+theNumber);

        // Above anything, check to see if they verified the GCode
        if (confirm("Have you verified the GCode before uploading this file?")){
            // Check to see that the name is good or not
            if (doesFileNameHaveBadChars(theGCodeElement.value)){
                // Let them know why we are failing
                alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.\n\nThis file has NOT been uploaded.");

                // Remove the file
                theGCodeElement.files[0]=null;
                theGCodeElement.value='';

                // Fail the load
                return false;
            }

            // Get the extension of this file they chose
            var ext = theGCodeElement.files[0].name.split('.').pop().toLowerCase();

            // Determine if it is NOT the correct extension
            if(ext !== 'nc' && ext !== 'tap') {
                // Let them know why we are failing
                alert("File is not of the appropriate type of .nc or .tap.\n\nTry again.\n\nThis file has NOT been uploaded.");

                // Remove the file
                theGCodeElement.files[0]=null;
                theGCodeElement.value='';

                // Fail the load
                return false;
            }            

            // Check the file size
            if (CheckSetupFilesize(gCodeAttachmentName, gCodeRowName, theNumber) === 1){
                // Fail the load
                return false;
            }

            // Create a way to handle the file load
            onGoodGCodeFile(event, handlerGCodeFileLoad.bind(this, theNumber, isNewSetup, inSessionID, theGCodeElement));

            // Determine if there was a file that stayed associated with this control
            if (theGCodeElement.files[0]===null){
                // Return failed
                return false;
            }

            // Return the inverse of the isError flag
            return true;
        }
        else {
            // Let them know why we are failing
            alert("This file has NOT been uploaded.\n\nPlease verify the code before uploading the GCode.");

            // Remove the file
            theGCodeElement.files[0]=null;
            theGCodeElement.value='';

            // Fail the load
            return false;
        }
    }
    catch (e) {
        // Let them know there are duplicate values
        alert("There was an error validating the setups.\n\nError was: " + e + "\n\n");

        // Remove the file
        theGCodeElement.files[0]=null;
        theGCodeElement.value='';

        // Fail the load
        return false;
    }
        
};

function removeImage(theNumber, isNewSetup=false){
    // Create element variables and set as null for now
    var toolStartAttachmentName = null;
    var toolStartRowName = null;
    var removeImageBtnName = null;
    var toolStartImageName = null;
    
    // Determine if this is a new setup
    if (isNewSetup){
        // Set what we can based on this is a new setup
        toolStartAttachmentName = 'newToolStartAttachment';
        toolStartRowName = 'newToolStartRow';
        removeImageBtnName = 'newRemoveImage';
        toolStartImageName = 'newToolStartImage';
    }
    else {
        // Set what we can based on this is a new setup
        toolStartAttachmentName = 'toolStartAttachment';
        toolStartRowName = 'toolStartRow';
        removeImageBtnName = 'removeImage';
        toolStartImageName = 'toolStartImage';
        
        // Get the is remove tool hidden element and set it to yes
        document.getElementById("isRemoveTool" + theNumber).value='1';
    }
    
    // Remove any stray display image
    document.getElementById(toolStartImageName + theNumber).value='';
    document.getElementById(toolStartImageName + theNumber).style.display='none';

    // get rid of any image that might already be in the control
    document.getElementById(toolStartAttachmentName + theNumber).value=null;

    // Set the row background to transparent
    document.getElementById(toolStartRowName + theNumber).style.backgroundColor = 'Transparent';

    // Hide the button control 
    document.getElementById(removeImageBtnName + theNumber).style.display='none';
}

function removeGCode(theNumber, isNewSetup=false){
    // Create element variables and set as null for now
    var gCodeAttachmentName = null;
    var gCodeRowName = null;
    var programName = null;
    var removeGCodeBtnName = null;
    var amountProgramLinesName = null;
    var programRunTimeName = null;
    var toolDetailsName = null;
    var moddedToolDetailsName = null;

    // Determine if this is a new setup
    if (isNewSetup){
        // Set what we can based on this is a new setup
        gCodeRowName = 'newGCodeRow';
        
        gCodeAttachmentName = 'newGCodeAttachment';
        removeGCodeBtnName = 'newRemoveGCode';
        programName = 'newProgramName';
        amountProgramLinesName = 'newAmountProgramLines';
        programRunTimeName = 'newProgramRunTime';
        toolDetailsName = 'newToolDetails';
    }
    else {
        // Set what we can based on this is a new setup
        gCodeRowName = 'gCodeRow';
        
        gCodeAttachmentName = 'gCodeAttachment';
        removeGCodeBtnName = 'removeGCode';
        programName = 'programName';
        amountProgramLinesName = 'amountProgramLines';
        programRunTimeName = 'programRunTime';
        toolDetailsName = 'toolDetails';
        moddedToolDetailsName = 'moddedToolDetails';
        
        // Reset the cell contents containing the info on any current file
        document.getElementById('gCodeDescCell' + theNumber).innerHTML="";

        // Hide the label
        document.getElementById('removeGCodeLabel' + theNumber).style.display='none';
    }

    // Open the tools tab while cleaning up
    openChildPage('ToolsInfo', document.getElementById('toolsTabButton'));
    
    // Get the tool details element
    var toolDetailsElement = document.getElementById(toolDetailsName + theNumber);
    
    // Set the modded control to null for now
    var moddedToolDetailsElement = document.getElementById('moddedToolDetails' + theNumber);
    
    // Cleanup any tools used that are no longer used
    cleanupTools(toolDetailsElement, true, moddedToolDetailsElement);

    // Cleanup the G-Code Element
    var theGCodeElement = document.getElementById(gCodeAttachmentName + theNumber);
    theGCodeElement.files[0]=null;
    theGCodeElement.value='';
    
    // Cleanup the fields that had old gcod info
    document.getElementById(programName + theNumber).value="";
    document.getElementById(amountProgramLinesName + theNumber).value="";
    document.getElementById(programRunTimeName + theNumber).value="";
    toolDetailsElement.value="";
    
    // Hide the button
    document.getElementById(removeGCodeBtnName + theNumber).style.display='none';
    
    // Turn the row color back to nothing
    document.getElementById(gCodeRowName + theNumber).style.backgroundColor = 'Transparent';
    
    // ReOpen the setups tab
    openChildPage('SetupsInfo', document.getElementById('setupsTabButton'));
}

function modifySize(element){
    // Determine what size we currently are
    if (element.style.width==='150px'){
        // Set it to larger
        element.style.width='450px';
    }
    else {
        // set it to smaller
        element.style.width='150px';
    }
}
    
function removeNewSetup(setupToRemove){
    console.log("in removeNewSetup");

    // Get the details of the tools that were supposed to be used for this setup
    var newToolDetails = document.getElementById('newToolDetails'+setupToRemove);

    // Cleanup any tools used that are no longer
    cleanupTools(newToolDetails);

    // Get the element to remove
    var setup = document.getElementById('newSetupDiv'+setupToRemove);

    // Remove it
    setup.parentNode.removeChild(setup);    
    
    // Remove this from the list
    removeNewSetupNumber(setupToRemove);
    
    // Reset the setup number string
    var setupAmount = document.getElementById("newSetupNumbers");
    setupAmount.value=createNewSetupNumbersString();
}

function addNewSetup() {
    console.log("in addNewSetup");

    // Increment the amount that is currently in the array
    var newSetupAmountID=getNewMaxSetupNumber()+1;
    
// *** Table 1
    
    // Create the dynamic setup table
    var setupDiv = document.createElement("table");
    setupDiv.style = 'margin: 5px; width: 100%; border-bottom-style:dashed; border-width: 1px; display: inline-block; text-align: center;';
    setupDiv.id = 'newSetupDiv' + newSetupAmountID;
    setupDiv.name = 'newSetupDiv' + newSetupAmountID;
    
// *** Row 1 *** //
    
    // Create the row
    var firstRow = document.createElement("tr");
    firstRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(firstRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 1 Cell 1-6 

    // Create the cell to add to the row
    var generalHeaderCell = document.createElement("td");
    generalHeaderCell.style = 'text-align: center;';
    generalHeaderCell.colSpan = 6;

    // Add the cell to the row
    firstRow.appendChild(generalHeaderCell);

    // Create the label
    var generalHeaderLabel = document.createElement("Label");
    generalHeaderLabel.textContent="General";
    generalHeaderLabel.style.fontWeight="bold";

    // Add the label to the cell
    generalHeaderCell.appendChild(generalHeaderLabel);
    
// *** Row 2 *** //
    
    // Create the row
    var secondRow = document.createElement("tr");
    secondRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(secondRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 2 Cell 1 

    // Create the cell to add to the row
    var orderLabelCell = document.createElement("td");
    orderLabelCell.style = 'text-align: right;';
    orderLabelCell.colSpan = 1;

    // Add the cell to the row
    secondRow.appendChild(orderLabelCell);

    // Create the label
    var orderLabel = document.createElement("Label");
    orderLabel.textContent="Order:";

    // Add the label to the cell
    orderLabelCell.appendChild(orderLabel);
    
// *** Row 2 Cell 2 

    // Create the cell to add to the row
    var orderCell = document.createElement("td");
    orderCell.style = 'text-align: left;';
    orderCell.colSpan = 1;

    // Add the cell to the row
    secondRow.appendChild(orderCell);

    // Create the Side text
    var orderCtrl = document.createElement("input");
    orderCtrl.rows = '1';
    orderCtrl.id = 'newOrder' + newSetupAmountID;    
    orderCtrl.name = 'newOrder' + newSetupAmountID;  
    orderCtrl.style = 'resize: none; width:90px;';
    orderCtrl.classList.add('ASetupOrder');
    orderCtrl.type = 'text';
    orderCtrl.value = 1;

    // Add the ctrl to the cell
    orderCell.appendChild(orderCtrl);

// *** Row 2 Cell 3 

    // Create the cell to add to the row
    var setupByLabelCell = document.createElement("td");
    setupByLabelCell.style = 'text-align: right;';
    setupByLabelCell.colSpan = 1;

    // Add the cell to the row
    secondRow.appendChild(setupByLabelCell);

    // Create the label
    var setupByLabel = document.createElement("Label");
    setupByLabel.textContent="Setup By:";

    // Add the label to the cell
    setupByLabelCell.appendChild(setupByLabel);
    
// *** Row 2 Cell 4 

    // Create the cell to add to the row
    var setupByCell = document.createElement("td");
    setupByCell.style = 'text-align: left;';
    setupByCell.colSpan = 1;

    // Add the cell to the row
    secondRow.appendChild(setupByCell);

    // Create the combo box
    var setupByDiv =  document.createElement("div");
    setupByDiv.title = newSetupAmountID;
    setupByDiv.innerHTML = getSUCompanyEmployeesAsSelectOptions("newSetupBy" + newSetupAmountID, -1, "");

    // Add the div to the cell
    setupByCell.appendChild(setupByDiv);

// *** Row 2 Cell 5 

    // Create the cell to add to the row
    var checkedByLabelCell = document.createElement("td");
    checkedByLabelCell.style = 'text-align: right;';
    checkedByLabelCell.colSpan = 1;

    // Add the cell to the row
    secondRow.appendChild(checkedByLabelCell);

    // Create the label
    var checkedByLabel = document.createElement("Label");
    checkedByLabel.textContent="Checked By:";

    // Add the label to the cell
    checkedByLabelCell.appendChild(checkedByLabel);
    
// *** Row 2 Cell 6 

    // Create the cell to add to the row
    var checkedByCell = document.createElement("td");
    checkedByCell.style = 'text-align: left;';
    checkedByCell.colSpan = 1;

    // Add the cell to the row
    secondRow.appendChild(checkedByCell);

    // Create the combo box
    var checkedByDiv =  document.createElement("div");
    checkedByDiv.title = newSetupAmountID;
    checkedByDiv.innerHTML = getSUCompanyEmployeesAsSelectOptions("newSetupCheckedBy" + newSetupAmountID, -1, "");

    // Add the div control to the cell
    checkedByCell.appendChild(checkedByDiv);

// *** Row 3 *** //
    
    // Create the row
    var thirdRow = document.createElement("tr");
    thirdRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(thirdRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 3 Cell 1 

    // Create the cell to add to the row
    var sideLabelCell = document.createElement("td");
    sideLabelCell.style = 'resize: none;';
    sideLabelCell.colSpan = 1;

    // Add the cell to the row
    thirdRow.appendChild(sideLabelCell);

    // Create the label
    var sideLabel = document.createElement("Label");
    sideLabel.textContent="Side:";

    // Add the label to the cell
    sideLabelCell.appendChild(sideLabel);
    
// *** Row 3 Cell 2 

    // Create the cell to add to the row
    var sideCell = document.createElement("td");
    sideCell.style = 'text-align: left;';
    sideCell.colSpan = 1;

    // Add the cell to the row
    thirdRow.appendChild(sideCell);

    // Create the Side text
    var sideCtrl = document.createElement("input");
    sideCtrl.rows = '1';
    sideCtrl.id = 'newSide' + newSetupAmountID;    
    sideCtrl.name = 'newSide' + newSetupAmountID;  
    sideCtrl.style = 'resize: none; width:90px;';
    sideCtrl.type = 'text';
    sideCtrl.value = 1;

    // Add the ctrl to the cell
    sideCell.appendChild(sideCtrl);

// *** Row 3 Cell 3 

    // Create the cell to add to the row
    var coordinateIDLabelCell = document.createElement("td");
    coordinateIDLabelCell.style = 'text-align: right;';
    coordinateIDLabelCell.colSpan = 1;

    // Add the cell to the row
    thirdRow.appendChild(coordinateIDLabelCell);

    // Create the label
    var coordinateIDLabel = document.createElement("Label");
    coordinateIDLabel.textContent="Coordinate ID:";

    // Add the label to the cell
    coordinateIDLabelCell.appendChild(coordinateIDLabel);
    
// *** Row 3 Cell 4 

    // Create the cell to add to the row
    var coordinateIDCell = document.createElement("td");
    coordinateIDCell.style = 'text-align: left;';
    coordinateIDCell.colSpan = 1;

    // Add the cell to the row
    thirdRow.appendChild(coordinateIDCell);

    // Create the Coordinate ID text
    var coordinateIDCtrl = document.createElement("input");
    coordinateIDCtrl.rows = '1';
    coordinateIDCtrl.id = 'newCoordinateID' + newSetupAmountID;    
    coordinateIDCtrl.name = 'newCoordinateID' + newSetupAmountID;  
    coordinateIDCtrl.style = 'resize: none; width:90px;';
    coordinateIDCtrl.type = 'text';
    coordinateIDCtrl.value = "";

    // Add the ctrl to the cell
    coordinateIDCell.appendChild(coordinateIDCtrl);

// *** Row 3 Cell 5 

    // Create the cell to add to the row
    var m00LabelCell = document.createElement("td");
    m00LabelCell.style = 'text-align: right;';
    m00LabelCell.colSpan = 1;

    // Add the cell to the first row
    thirdRow.appendChild(m00LabelCell);

    // Create the label
    var m00Label = document.createElement("Label");
    m00Label.style = 'text-align: right; margin-left: %10;';
    m00Label.textContent="M00:";

    // Add the label to the cell
    m00LabelCell.appendChild(m00Label);
    
    // *** Making cells to add to the row and controls to fill the cells below *** //
    
// *** Row 3 Cell 6 

    // Create the cell to add to the row
    var m00Cell = document.createElement("td");
    m00Cell.style = 'text-align: left;';
    m00Cell.colSpan = 1;

    // Add the cell to the row
    thirdRow.appendChild(m00Cell);

    // Create the blank submit checkbox
    var m00Ctrl = document.createElement("input");
    m00Ctrl.type = "checkbox";
    m00Ctrl.id = 'newM00' + newSetupAmountID;    
    m00Ctrl.name = 'newM00' + newSetupAmountID;  

    // Add the ctrl to the cell
    m00Cell.appendChild(m00Ctrl);

// *** Row 4 *** //
    
    // Create the row
    var forthRow = document.createElement("tr");
    forthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(forthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 4 Cell 1 

    // Create the cell to add to the second row
    var holdByLabelCell = document.createElement("td");
    holdByLabelCell.style = 'text-align: right;';
    holdByLabelCell.colSpan = 1;

    // Add the cell to the row
    forthRow.appendChild(holdByLabelCell);

    // Create the label
    var holdByLabel = document.createElement("Label");
    holdByLabel.textContent="Hold By:";

    // Add the label to the cell
    holdByLabelCell.appendChild(holdByLabel);
    
// *** Row 4 Cell 2-6 

    // Create the cell to add to the row
    var holdByCell = document.createElement("td");
    holdByCell.style = 'text-align: left;';
    holdByCell.colSpan = 5;

    // Add the cell to the row
    forthRow.appendChild(holdByCell);

    // Create the Hold By text
    var holdByCtrl = document.createElement("textarea");
    holdByCtrl.rows = '1';
    holdByCtrl.id = 'newHoldBy' + newSetupAmountID;    
    holdByCtrl.name = 'newHoldBy' + newSetupAmountID;  
    holdByCtrl.style = 'width: 100%; overflow: auto; resize: vertical;';
    holdByCtrl.value = '';
    holdByCtrl.maxLength = 150;

    // Add the ctrl to the cell
    holdByCell.appendChild(holdByCtrl);

// *** Row 5 *** //
    
    // Create the row
    var fifthRow = document.createElement("tr");
    fifthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(fifthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 5 Cell 1 

    // Create the cell to add to the second row
    var orientationLabelCell = document.createElement("td");
    orientationLabelCell.style = 'text-align: right;';
    orientationLabelCell.colSpan = 1;

    // Add the cell to the row
    fifthRow.appendChild(orientationLabelCell);

    // Create the label
    var orientationLabel = document.createElement("Label");
    orientationLabel.textContent="Orientation:";

    // Add the label to the cell
    orientationLabelCell.appendChild(orientationLabel);
    
// *** Row 5 Cell 2-6 

    // Create the cell to add to the row
    var orientationCell = document.createElement("td");
    orientationCell.style = 'text-align: left;';
    orientationCell.colSpan = 5;

    // Add the cell to the row
    fifthRow.appendChild(orientationCell);

    // Create the orientation text
    var orientationCtrl = document.createElement("textarea");
    orientationCtrl.rows = '1';
    orientationCtrl.id = 'newOrientation' + newSetupAmountID;    
    orientationCtrl.name = 'newOrientation' + newSetupAmountID;  
    orientationCtrl.style = 'width: 100%; resize: vertical;';
    orientationCtrl.value = '';
    orientationCtrl.maxLength = 150;

    // Add the ctrl to the cell
    orientationCell.appendChild(orientationCtrl);

// *** Row 6 *** //
    
    // Create the row
    var sixthRow = document.createElement("tr");
    sixthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';
    sixthRow.id = 'newToolStartRow' + newSetupAmountID;    
    sixthRow.name = 'newToolStartRow' + newSetupAmountID;    

    // Add the row 
    setupDiv.appendChild(sixthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 6 Cell 1 

    // Create the cell to add to the second row
    var toolStartLabelCell = document.createElement("td");
    toolStartLabelCell.style = 'text-align: right;';
    toolStartLabelCell.colSpan = 1;

    // Add the cell to the row
    sixthRow.appendChild(toolStartLabelCell);

    // Create the label
    var toolStartLabel = document.createElement("Label");
    toolStartLabel.textContent="Tool Start:";

    // Add the label to the cell
    toolStartLabelCell.appendChild(toolStartLabel);
    
// *** Row 6 Cell 2-4 

    // Create the cell to add to the row
    var toolStartCell = document.createElement("td");
    toolStartCell.style = 'text-align: left;';
    toolStartCell.colSpan = 3;

    // Add the cell to the row
    sixthRow.appendChild(toolStartCell);

    var toolStartText = document.createElement("input");
    toolStartText.type="file";
    toolStartText.disabled = false;
    toolStartText.accept='image/gif, image/jpeg, image/png, image/tiff, image/bmp';
    toolStartText.id = 'newToolStartAttachment' + newSetupAmountID;    
    toolStartText.name = 'newToolStartAttachment' + newSetupAmountID;    
    toolStartText.style = 'width:90px;';
    toolStartText.onselect = '';
    toolStartText.onchange = function(a) {  
        return function() {
            // Get the file element
            var fileElement = document.getElementById('newToolStartAttachment' + a);
            
            // Check to see that the name is good or not
            if (doesFileNameHaveBadChars(fileElement.value)){
                // Give an alert that the file name has bad characters
                alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");
                
                // Remove the file
                fileElement.files[0]=null;
                fileElement.value='';
            }
            else {
                // Return the results of the file change method
                return onToolStartFileChange(a, true);
            }
        };
    }(newSetupAmountID);

    // Add the attachment to the attachment line div
    toolStartCell.appendChild(toolStartText);
    
    // Create the remove image checkbox
    var removeImageCtrl = document.createElement("button");
    removeImageCtrl.type = "button";
    removeImageCtrl.id = 'newRemoveImage' + newSetupAmountID;    
    removeImageCtrl.name = 'newRemoveImage' + newSetupAmountID;  
    removeImageCtrl.style.display='none';
    removeImageCtrl.textContent="Remove";
    removeImageCtrl.onclick = function(a) { 
        return function() {
            // Remove the image appropriately
            removeImage(a, true);
        };
    }(newSetupAmountID);

    // Add the ctrl to the cell
    toolStartCell.appendChild(removeImageCtrl);

// *** Row 6 Cell 5-6 

    // Create the cell to add to the row
    var toolStartImageCell = document.createElement("td");
    toolStartImageCell.style = 'text-align: center;';
    toolStartImageCell.colSpan = 2;

    // Add the cell to the row
    sixthRow.appendChild(toolStartImageCell);

    var toolStartImg = document.createElement("img");
    toolStartImg.id = 'newToolStartImage' + newSetupAmountID;    
    toolStartImg.name = 'newToolStartImage' + newSetupAmountID;    
    toolStartImg.style.width = '150px';
    toolStartImg.onclick = function() { 
        // Modify the size appropriately
        modifySize(this);
    };

    // Add the attachment to the attachment line div
    toolStartImageCell.appendChild(toolStartImg);

// *** Row 7 *** //
    
    // Create the row
    var seventhRow = document.createElement("tr");
    seventhRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(seventhRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 7 Cell 1-6 

    // Create the cell to add to the second row
    var toolZeroLocationsCell = document.createElement("td");
    toolZeroLocationsCell.style = 'text-align: center;';
    toolZeroLocationsCell.colSpan = 6;

    // Add the cell to the row
    seventhRow.appendChild(toolZeroLocationsCell);

    // Create the label
    var toolZeroLocationsLabel = document.createElement("Label");
    toolZeroLocationsLabel.textContent="Zero Locations";
    toolZeroLocationsLabel.style.fontWeight="bold";

    // Add the label to the cell
    toolZeroLocationsCell.appendChild(toolZeroLocationsLabel);
    
// *** Row 8 *** //
    
    // Create the row
    var eighthRow = document.createElement("tr");
    eighthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(eighthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 8 Cell 1 

    // Create the cell to add to the row
    var xLocationLabelCell = document.createElement("td");
    xLocationLabelCell.style = 'text-align: right;';
    xLocationLabelCell.colSpan = 1;

    // Add the cell to the row
    eighthRow.appendChild(xLocationLabelCell);

    // Create the label
    var xLocationLabel = document.createElement("Label");
    xLocationLabel.textContent="X Zero:";

    // Add the label to the cell
    xLocationLabelCell.appendChild(xLocationLabel);
    
// *** Row 8 Cell 2 

    // Create the cell to add to the row
    var xLocationCell = document.createElement("td");
    xLocationCell.style = 'text-align: left;';
    xLocationCell.colSpan = 1;

    // Add the cell to the row
    eighthRow.appendChild(xLocationCell);

    // Create the Side text
    var xLocationCtrl = document.createElement("input");
    xLocationCtrl.rows = '1';
    xLocationCtrl.id = 'newXLocation' + newSetupAmountID;    
    xLocationCtrl.name = 'newXLocation' + newSetupAmountID;  
    xLocationCtrl.style = 'resize: none; width:130px;';
    xLocationCtrl.type = 'text';
    xLocationCtrl.value = '';

    // Add the ctrl to the cell
    xLocationCell.appendChild(xLocationCtrl);

// *** Row 8 Cell 3 

    // Create the cell to add to the row
    var yLocationLabelCell = document.createElement("td");
    yLocationLabelCell.style = 'text-align: right;';
    yLocationLabelCell.colSpan = 1;

    // Add the cell to the row
    eighthRow.appendChild(yLocationLabelCell);

    // Create the label
    var yLocationLabel = document.createElement("Label");
    yLocationLabel.textContent="Y Zero:";

    // Add the label to the cell
    yLocationLabelCell.appendChild(yLocationLabel);
    
// *** Row 8 Cell 4 

    // Create the cell to add to the row
    var yLocationCell = document.createElement("td");
    yLocationCell.style = 'text-align: left;';
    yLocationCell.colSpan = 1;

    // Add the cell to the row
    eighthRow.appendChild(yLocationCell);

    // Create the Side text
    var yLocationCtrl = document.createElement("input");
    yLocationCtrl.rows = '1';
    yLocationCtrl.id = 'newYLocation' + newSetupAmountID;    
    yLocationCtrl.name = 'newYLocation' + newSetupAmountID;  
    yLocationCtrl.style = 'resize: none; width:130px;';
    yLocationCtrl.type = 'text';
    yLocationCtrl.value = '';

    // Add the ctrl to the cell
    yLocationCell.appendChild(yLocationCtrl);

// *** Row 8 Cell 5 

    // Create the cell to add to the row
    var zLocationLabelCell = document.createElement("td");
    zLocationLabelCell.style = 'text-align: right;';
    zLocationLabelCell.colSpan = 1;

    // Add the cell to the row
    eighthRow.appendChild(zLocationLabelCell);

    // Create the label
    var zLocationLabel = document.createElement("Label");
    zLocationLabel.textContent="Z Zero:";

    // Add the label to the cell
    zLocationLabelCell.appendChild(zLocationLabel);
    
// *** Row 8 Cell 6 

    // Create the cell to add to the row
    var zLocationCell = document.createElement("td");
    zLocationCell.style = 'text-align: left;';
    zLocationCell.colSpan = 1;

    // Add the cell to the row
    eighthRow.appendChild(zLocationCell);

    // Create the Side text
    var zLocationCtrl = document.createElement("input");
    zLocationCtrl.rows = '1';
    zLocationCtrl.id = 'newZLocation' + newSetupAmountID;    
    zLocationCtrl.name = 'newZLocation' + newSetupAmountID;  
    zLocationCtrl.style = 'resize: none; width:130px;';
    zLocationCtrl.type = 'text';
    zLocationCtrl.value = '';

    // Add the ctrl to the cell
    zLocationCell.appendChild(zLocationCtrl);

// *** Row 9 *** //
    
    // Create the row
    var ninthRow = document.createElement("tr");
    ninthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(ninthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 9 Cell 1-6 

    // Create the cell to add to the second row
    var programInfoHeaderCell = document.createElement("td");
    programInfoHeaderCell.style = 'text-align: center;';
    programInfoHeaderCell.colSpan = 6;

    // Add the cell to the row
    ninthRow.appendChild(programInfoHeaderCell);

    // Create the label
    var programInfoHeaderLabel = document.createElement("Label");
    programInfoHeaderLabel.textContent="Program Info";
    programInfoHeaderLabel.style.fontWeight="bold";

    // Add the label to the cell
    programInfoHeaderCell.appendChild(programInfoHeaderLabel);
    
// *** Row 10 *** //
    
    // Create the row
    var tenthRow = document.createElement("tr");
    tenthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';
    tenthRow.id = 'newGCodeRow' + newSetupAmountID;    
    tenthRow.name = 'newGCodeRow' + newSetupAmountID;    

    // Add the row 
    setupDiv.appendChild(tenthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 10 Cell 1 

    // Create the cell to add to the second row
    var gCodeLabelCell = document.createElement("td");
    gCodeLabelCell.style = 'text-align: right;';
    gCodeLabelCell.colSpan = 1;

    // Add the cell to the row
    tenthRow.appendChild(gCodeLabelCell);

    // Create the label
    var gCodeLabel = document.createElement("Label");
    gCodeLabel.textContent="G-Code File:";

    // Add the label to the cell
    gCodeLabelCell.appendChild(gCodeLabel);
    
// *** Row 10 Cell 2-6 

    // Create the cell to add to the row
    var gCodeCell = document.createElement("td");
    gCodeCell.style = 'text-align: left;';
    gCodeCell.colSpan = 5;

    // Add the cell to the row
    tenthRow.appendChild(gCodeCell);

    var gCodeAttachment = document.createElement("input");
    gCodeAttachment.type="file";
    gCodeAttachment.disabled = false;
    gCodeAttachment.id = 'newGCodeAttachment' + newSetupAmountID;    
    gCodeAttachment.name = 'newGCodeAttachment' + newSetupAmountID;   
    gCodeAttachment.accept='.nc,.NC,.tap,.TAP';
    gCodeAttachment.style = 'width:90px;';
    gCodeAttachment.onselect = '';
    gCodeAttachment.onchange = function(a, inSessionID) {  
        return function() {
            // Get the file element
            var fileElement = document.getElementById('newGCodeAttachment' + a);
            
            // Check to see that the name is good or not
            if (doesFileNameHaveBadChars(fileElement.value)){
                // Give an alert that the file name has bad characters
                alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");
                
                // Remove the file
                fileElement.files[0]=null;
                fileElement.value='';
            }
            else {
                // Return the results of the file change method 
                return onNewGCodeSelected(a, true, inSessionID);
            }
        };
    }(newSetupAmountID, sessionID);

    // Add the attachment to the attachment line div
    gCodeCell.appendChild(gCodeAttachment);
    
    // Create the remove image checkbox
    var removeGCodeCtrl = document.createElement("button");
    removeGCodeCtrl.type = "button";
    removeGCodeCtrl.id = 'newRemoveGCode' + newSetupAmountID;    
    removeGCodeCtrl.name = 'newRemoveGCode' + newSetupAmountID;  
    removeGCodeCtrl.style.display='none';
    removeGCodeCtrl.textContent="Remove";
    removeGCodeCtrl.onclick = function(a) { 
        return function() {
            // Remove the image appropriately
            removeGCode(a, true);
        };
    }(newSetupAmountID);

    // Add the ctrl to the cell
    gCodeCell.appendChild(removeGCodeCtrl);

// *** Row 11 *** //
    
    // Create the row
    var eleventhRow = document.createElement("tr");
    eleventhRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(eleventhRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 11 Cell 1 

    // Create the cell to add to the row
    var programNameLabelCell = document.createElement("td");
    programNameLabelCell.style = 'text-align: right;';
    programNameLabelCell.colSpan = 1;

    // Add the cell to the row
    eleventhRow.appendChild(programNameLabelCell);

    // Create the label
    var programNameLabel = document.createElement("Label");
    programNameLabel.textContent="Name:";

    // Add the label to the cell
    programNameLabelCell.appendChild(programNameLabel);
    
// *** Row 11 Cell 2 

    // Create the cell to add to the row
    var programNameCell = document.createElement("td");
    programNameCell.style = 'text-align: left;';
    programNameCell.colSpan = 1;

    // Add the cell to the row
    eleventhRow.appendChild(programNameCell);

    // Create the Side text
    var newProgramNameCtrl = document.createElement("input");
    newProgramNameCtrl.rows = '1';
    newProgramNameCtrl.id = 'newProgramName' + newSetupAmountID;    
    newProgramNameCtrl.name = 'newProgramName' + newSetupAmountID;  
    newProgramNameCtrl.type = 'text';
    newProgramNameCtrl.value = 'Unknown';
    newProgramNameCtrl.classList.add('disableaslabel');

    // Add the ctrl to the cell
    programNameCell.appendChild(newProgramNameCtrl);

// *** Row 11 Cell 3 

    // Create the cell to add to the row
    var amountProgramLinesLabelCell = document.createElement("td");
    amountProgramLinesLabelCell.style = 'text-align: right;';
    amountProgramLinesLabelCell.colSpan = 1;

    // Add the cell to the row
    eleventhRow.appendChild(amountProgramLinesLabelCell);

    // Create the label
    var amountProgramLinesLabel = document.createElement("Label");
    amountProgramLinesLabel.textContent="Lines:";

    // Add the label to the cell
    amountProgramLinesLabelCell.appendChild(amountProgramLinesLabel);
    
// *** Row 11 Cell 4 

    // Create the cell to add to the row
    var amountProgramLinesCell = document.createElement("td");
    amountProgramLinesCell.style = 'text-align: left;';
    amountProgramLinesCell.colSpan = 1;

    // Add the cell to the row
    eleventhRow.appendChild(amountProgramLinesCell);

    // Create the Side text
    var amountProgramLinesCtrl = document.createElement("input");
    amountProgramLinesCtrl.rows = '1';
    amountProgramLinesCtrl.id = 'newAmountProgramLines' + newSetupAmountID;    
    amountProgramLinesCtrl.name = 'newAmountProgramLines' + newSetupAmountID;  
    amountProgramLinesCtrl.type = 'text';
    amountProgramLinesCtrl.value = '0';
    amountProgramLinesCtrl.classList.add('disableaslabel');

    // Add the ctrl to the cell
    amountProgramLinesCell.appendChild(amountProgramLinesCtrl);

// *** Row 11 Cell 5 

    // Create the cell to add to the row
    var programRunTimeLabelCell = document.createElement("td");
    programRunTimeLabelCell.style = 'text-align: right;';
    programRunTimeLabelCell.colSpan = 1;

    // Add the cell to the row
    eleventhRow.appendChild(programRunTimeLabelCell);

    // Create the label
    var programRunTimeLabel = document.createElement("Label");
    programRunTimeLabel.textContent="Run Time:";

    // Add the label to the cell
    programRunTimeLabelCell.appendChild(programRunTimeLabel);
    
// *** Row 11 Cell 6 

    // Create the cell to add to the row
    var programRunTimeCell = document.createElement("td");
    programRunTimeCell.style = 'text-align: left;';
    programRunTimeCell.colSpan = 1;

    // Add the cell to the row
    eleventhRow.appendChild(programRunTimeCell);

    // Create the Side text
    var programRunTimeCtrl = document.createElement("input");
    programRunTimeCtrl.rows = '1';
    programRunTimeCtrl.id = 'newProgramRunTime' + newSetupAmountID;    
    programRunTimeCtrl.name = 'newProgramRunTime' + newSetupAmountID;  
    programRunTimeCtrl.type = 'text';
    programRunTimeCtrl.value = 'None';
    programRunTimeCtrl.classList.add('disableaslabel');

    // Add the ctrl to the cell
    programRunTimeCell.appendChild(programRunTimeCtrl);

// *** Row 12 *** //
    
    // Create the row
    var twelfthRow = document.createElement("tr");
    twelfthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(twelfthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 12 Cell 1 

    // Create the cell to add to the row
    var toolDetailsHeaderLabelCell = document.createElement("td");
    toolDetailsHeaderLabelCell.style = 'text-align: center;';
    toolDetailsHeaderLabelCell.colSpan = 6;

    // Add the cell to the row
    twelfthRow.appendChild(toolDetailsHeaderLabelCell);

    // Create the label
    var toolDetailsHeaderLabel = document.createElement("Label");
    toolDetailsHeaderLabel.style.fontWeight="bold";
    toolDetailsHeaderLabel.textContent="Tool Details";

    // Add the label to the cell
    toolDetailsHeaderLabelCell.appendChild(toolDetailsHeaderLabel);
    
// *** Row 13 *** //
    
    // Create the row
    var thirteenthRow = document.createElement("tr");
    thirteenthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(thirteenthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 13 Cell 1 

    // Create the cell to add to the row
    var toolDetailsCell = document.createElement("td");
    toolDetailsCell.style = 'text-align: center;';
    toolDetailsCell.colSpan = 6;

    // Add the cell to the row
    thirteenthRow.appendChild(toolDetailsCell);

    // Create the label
    var toolDetailsCtrl = document.createElement("textarea");
    toolDetailsCtrl.classList.add('setupToolDetails');
    toolDetailsCtrl.rows = '1';
    toolDetailsCtrl.id = 'newToolDetails' + newSetupAmountID;    
    toolDetailsCtrl.name = 'newToolDetails' + newSetupAmountID;  
    toolDetailsCtrl.style.height = 'auto';
    toolDetailsCtrl.style = 'width: 100%; resize: vertical; text-align: center;';
    toolDetailsCtrl.value = '';
    toolDetailsCtrl.classList.add('setupToolDetails');
    toolDetailsCtrl.readOnly=true;

    // Add the label to the cell
    toolDetailsCell.appendChild(toolDetailsCtrl);
    
// *** Row 14 *** //
    
    // Create the row
    var forteenthRow = document.createElement("tr");
    forteenthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(forteenthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 14 Cell 1 

    // Create the cell to add to the row
    var setupM00InstructionsCell = document.createElement("td");
    setupM00InstructionsCell.style = 'text-align: center;';
    setupM00InstructionsCell.colSpan = 6;

    // Add the cell to the row
    forteenthRow.appendChild(setupM00InstructionsCell);

    // Create the M00 Checkbox
    var m00InstructionsHideChkBx=  document.createElement("input");
    m00InstructionsHideChkBx.type = 'checkbox';
    m00InstructionsHideChkBx.id = 'newHideSETUP_M00' + newSetupAmountID + 'NEWNotes';
    m00InstructionsHideChkBx.name = 'newHideSETUP_M00' + newSetupAmountID + 'NEWNotes';
    m00InstructionsHideChkBx.onclick = function(inNewSetupAmountID) {  
        return function() {
           div_toggleVisibilityOnCheckbox('newHideSETUP_M00' + inNewSetupAmountID + 'NEWNotes', 'newSETUP_M00' + inNewSetupAmountID + 'NEWNotes', 'NORMAL');
        };
    }(newSetupAmountID);

    // Add the ctrl to the cell
    setupM00InstructionsCell.appendChild(m00InstructionsHideChkBx);

    // Create the label
    var m00InstructionsHideChkBxLbl = document.createElement("Label");
    m00InstructionsHideChkBxLbl.style.fontWeight="bold";
    m00InstructionsHideChkBxLbl.textContent="M00 Instructions";
    m00InstructionsHideChkBxLbl.for='newHideSETUP_M00' + newSetupAmountID + 'NEWNotes';

    // Add the label to the cell
    setupM00InstructionsCell.appendChild(m00InstructionsHideChkBxLbl);

    // Create the div
    var setupM00InstructionsDiv = document.createElement("div");
    setupM00InstructionsDiv.id = 'newSETUP_M00' + newSetupAmountID + 'NEWNotes';    
    setupM00InstructionsDiv.name = 'newSETUP_M00' + newSetupAmountID + 'NEWNotes';
    setupM00InstructionsDiv.title = newSetupAmountID;
    setupM00InstructionsDiv.style="text-align:center; font-weight: bold; font-size: 12px;";
    setupM00InstructionsDiv.style.display='none';
    setupM00InstructionsDiv.innerHTML = '<label style="font-size: 20px;"><strong>New M00 Instructions: </strong></label>'+
                                        '<p align="right" style="border-top-style:dashed; border-width: 1px; font-weight: bold;font-size: 12px;">' +
                                        '    <input type="hidden" id="newSETUP_M00' + newSetupAmountID + 'NEWNoteNumbers" name="newSETUP_M00' + newSetupAmountID + 'NEWNoteNumbers" value="0"></input>' +
                                        '    <button type="button" onClick="addNewChild(\'SETUP_M00\', ' + newSetupAmountID + ', \'NEW\');" align="right">Add New</button>' +
                                        '</p>';
                        
    // Add the div to the cell
    setupM00InstructionsCell.appendChild(setupM00InstructionsDiv);
    
// *** Row 15 *** //
    
    // Create the row
    var fifthteenthRow = document.createElement("tr");
    fifthteenthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(fifthteenthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 15 Cell 1 

    // Create the cell to add to the row
    var setupNotesCell = document.createElement("td");
    setupNotesCell.style = 'text-align: center;';
    setupNotesCell.colSpan = 6;

    // Add the cell to the row
    fifthteenthRow.appendChild(setupNotesCell);

    // Create the M00 Checkbox
    var setupNotesHideChkBx=  document.createElement("input");
    setupNotesHideChkBx.type = 'checkbox';
    setupNotesHideChkBx.id = 'newHideSETUP_NOTE' + newSetupAmountID + 'NEWNotes';
    setupNotesHideChkBx.name = 'newHideSETUP_NOTE' + newSetupAmountID + 'NEWNotes';
    setupNotesHideChkBx.onclick = function(inNewSetupAmountID) {  
        return function() {
           div_toggleVisibilityOnCheckbox('newHideSETUP_NOTE' + inNewSetupAmountID + 'NEWNotes', 'newSETUP_NOTE' + inNewSetupAmountID + 'NEWNotes', 'NORMAL');
        };
    }(newSetupAmountID);

    // Add the ctrl to the cell
    setupNotesCell.appendChild(setupNotesHideChkBx);

    // Create the label
    var setupNotesHideChkBxLbl = document.createElement("Label");
    setupNotesHideChkBxLbl.style.fontWeight="bold";
    setupNotesHideChkBxLbl.textContent="Setup Notes";
    setupNotesHideChkBxLbl.for='newHideSETUP_NOTE' + newSetupAmountID + 'NEWNotes';

    // Add the label to the cell
    setupNotesCell.appendChild(setupNotesHideChkBxLbl);





// TODO: Redo this is I want to be perfect
//    // Create the label
//    var setupNotesNewLbl = document.createElement("Label");
//    setupNotesNewLbl.style="font-size: 20px;";
//    setupNotesNewLbl.textContent="New Setup Notes:";
//
//    // Add the label to the cell
//    setupNotesCell.appendChild(setupNotesNewLbl);
//    
//    var setupNotesParagraph = document.createElement("p");
//    setupNotesParagraph.style.textAlign = "right";
//
//    // Add the p to the cell
//    setupNotesCell.appendChild(setupNotesParagraph);
//    
//    // Create the hidden numbers
//    var setupNotesHiddenNumbers=  document.createElement("input");
//    setupNotesHiddenNumbers.type = 'hidden';
//    setupNotesHiddenNumbers.id = 'newSETUP_M00' + newSetupAmountID + 'NEWNoteNumbers';
//    setupNotesHiddenNumbers.name = 'newSETUP_M00' + newSetupAmountID + 'NEWNoteNumbers';
//    setupNotesHiddenNumbers.value = '';
//
//    // Add the ctrl to the cell
//    setupNotesParagraph.appendChild(setupNotesHiddenNumbers);
//    
//    // Create the remove image checkbox
//    var newNoteBtn = document.createElement("button");
//    newNoteBtn.type = "button";
//    newNoteBtn.textContent="Add New";
//    newNoteBtn.onclick = function(inNewSetupAmountID) { 
//        return function() {
//            // Add a new child
//            addNewChild('SETUP_NOTE', inNewSetupAmountID , 'NEW');
//        };
//    }(newSetupAmountID);
//
//    // Add the ctrl to the cell
//    setupNotesParagraph.appendChild(newNoteBtn);
    
    
    



    // Create the div
    var setupNotesDiv = document.createElement("div");
    setupNotesDiv.id = 'newSETUP_NOTE' + newSetupAmountID + 'NEWNotes';    
    setupNotesDiv.name = 'newSETUP_NOTE' + newSetupAmountID + 'NEWNotes';
    setupNotesDiv.title = newSetupAmountID;
    setupNotesDiv.style="text-align:center; font-weight: bold; font-size: 12px;";
    setupNotesDiv.style.display='none';
    setupNotesDiv.innerHTML = '<label style="font-size: 20px;"><strong>New Setup Notes: </strong></label>'+
                              '<p align="right" style="">' +
                              '    <input type="hidden" id="newSETUP_NOTE' + newSetupAmountID + 'NEWNoteNumbers" name="newSETUP_NOTE' + newSetupAmountID + 'NEWNoteNumbers" value="0"></input>' +
                              '    <button type="button" onClick="addNewChild(\'SETUP_NOTE\', ' + newSetupAmountID + ', \'NEW\');" align="right">Add New</button>' +
                              '</p>';
                        
    // Add the div to the cell
    setupNotesCell.appendChild(setupNotesDiv);
    
// *** Row 16 *** //
    
    // Create the row
    var sixteenthRow = document.createElement("tr");
    sixteenthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(sixteenthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 16 Cell 1 

    // Create the cell to add to the row
    var operatorFeedbackCell = document.createElement("td");
    operatorFeedbackCell.style = 'text-align: center;';
    operatorFeedbackCell.colSpan = 6;

    // Add the cell to the row
    sixteenthRow.appendChild(operatorFeedbackCell);

    // Create the M00 Checkbox
    var operatorFeedbackCellHideChkBx=  document.createElement("input");
    operatorFeedbackCellHideChkBx.type = 'checkbox';
    operatorFeedbackCellHideChkBx.id = 'newHideOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNotes';
    operatorFeedbackCellHideChkBx.name = 'newHideOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNotes';
    operatorFeedbackCellHideChkBx.onclick = function(inNewSetupAmountID) {  
        return function() {
           div_toggleVisibilityOnCheckbox('newHideOPERATOR_FEEDBACK_NOTE' + inNewSetupAmountID + 'NEWNotes', 'newOPERATOR_FEEDBACK_NOTE' + inNewSetupAmountID + 'NEWNotes', 'NORMAL');
        };
    }(newSetupAmountID);

    // Add the ctrl to the cell
    operatorFeedbackCell.appendChild(operatorFeedbackCellHideChkBx);

    // Create the label
    var operatorFeedbackCellHideChkBxLbl = document.createElement("Label");
    operatorFeedbackCellHideChkBxLbl.style.fontWeight="bold";
    operatorFeedbackCellHideChkBxLbl.textContent="Operator Feedback Notes";
    operatorFeedbackCellHideChkBxLbl.for='newHideOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNotes';

    // Add the label to the cell
    operatorFeedbackCell.appendChild(operatorFeedbackCellHideChkBxLbl);

    // Create the div
    var operatorFeedbackCellDiv = document.createElement("div");
    operatorFeedbackCellDiv.id = 'newOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNotes';    
    operatorFeedbackCellDiv.name = 'newOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNotes';
    operatorFeedbackCellDiv.title = newSetupAmountID;
    operatorFeedbackCellDiv.style="text-align:center; font-weight: bold; font-size: 12px;";
    operatorFeedbackCellDiv.style.display='none';
    operatorFeedbackCellDiv.innerHTML = '<label style="font-size: 20px;"><strong>New Operator Feedback: </strong></label>'+
                                        '<p align="right" style="border-top-style:dashed; border-width: 1px; font-weight: bold;font-size: 12px;">' +
                                        '    <input type="hidden" id="newOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNoteNumbers" name="newOPERATOR_FEEDBACK_NOTE' + newSetupAmountID + 'NEWNoteNumbers" value="0"></input>' +
                                        '    <button type="button" onClick="addNewChild(\'OPERATOR_FEEDBACK_NOTE\', ' + newSetupAmountID + ', \'NEW\');" align="right">Add New</button>' +
                                        '</p>';
                        
    // Add the div to the cell
    operatorFeedbackCell.appendChild(operatorFeedbackCellDiv);
    
// *** Row 17 *** //
    
    // Create the row
    var seventeenthRow = document.createElement("tr");
    seventeenthRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row 
    setupDiv.appendChild(seventeenthRow);

    // *** Making cells to add to the row and controls to fill the cells below *** //

// *** Row 17 Cell 1 

    // Create the cell to add to the row
    var m00InstructionsCell = document.createElement("td");
    m00InstructionsCell.style = 'text-align: right;';
    m00InstructionsCell.colSpan = 6;

    // Add the cell to the row
    seventeenthRow.appendChild(m00InstructionsCell);

    // Create the remove setup button
    var removeBtn = document.createElement("button");
    removeBtn.textContent="Remove Setup";
    removeBtn.id = 'outRemoveBtn' + newSetupAmountID;    
    removeBtn.style = 'margin-left: %95;';
    removeBtn.type = 'button';
    removeBtn.onclick = function(i) {  
        return function() {
           removeNewSetup(i);
        };
    }(newSetupAmountID);

    // Add elements to the newly created DIV tags
    m00InstructionsCell.appendChild(removeBtn);

    // Get the main div container to add the new div tag to and hidden choice to it 
    var container = document.getElementById("newSetups");
    container.appendChild(setupDiv);
    
    // Add this ID to the list
    newSetupNumbersToAdd.push(newSetupAmountID);
    
    // Get the element and change the amount of setups
    var setupAmountDiv = document.getElementById("newSetupNumbers");
    setupAmountDiv.value=newSetupNumbersToAdd.join('|');
    
    // Add any validation that we have
    addSetupValidation(newSetupAmountID);
    
    // Return the position of the new setup div
    return newSetupAmountID;
}

function checkUniqueSetupOrder()
{
    try {
        // Get all of the controls that contain setup order
        var orderChildren = document.getElementsByClassName('ASetupOrder');        

        // Create an array of already seen positions
        var alreadySeen = [];

        // Loop through all of the elements
        for (var i=0, len=orderChildren.length|0; i<len; i=i+1|0) {
            // Determine if this is an already existing tool and if it is marked for deletion
            if (!orderChildren[i].name.includes('new') && 
                document.getElementById('removeSetup' + orderChildren[i].id.replace('order', '')).checked){
                // Ignore this one, since it is marked for deletion.
                continue;
            }

            // Get the current order
            var currentOrder = orderChildren[i].value;

            // Determine if the value is greater than zero
            if (currentOrder>0){
                // Determine if this one is already seen
                if (alreadySeen["" + currentOrder]){
                    // Let them know there are duplicate values
                    alert("The order of the setups is such that it would allow for duplicate setups.  The setup orders need to be unique.\n\nPlease correct to be unique.");

                    // Found duplicate, so return false
                    return false;
                }
                else{
                    // Add to checked array
                    alreadySeen["" + currentOrder] = true;
                }
            }
        }
    } catch (e) {
        // Let them know there are duplicate values
        alert("There was an error validating the order of setups.\n\nError was: " + e + "\n\nPlease inform tech support.");

        // If error, then invalidate check
        return false;
    }
    
    // Now we can go on with our normal submission
    return true;
}    

function addSetupValidation(setupToAddNumber){
    console.log("in addSetupValidation");

    // Ensure that the validator object is available
    if (typeof frmvalidator !== 'undefined'){
        // Add the validators
        frmvalidator.addValidation("newOrder" +  setupToAddNumber,
                                   "req",
                                   "Please enter an order of operations for all setups.");
        frmvalidator.addValidation("newOrder" +  setupToAddNumber,
                                   "num",
                                   "Please enter an order of operations for all setups as a number.");
        frmvalidator.addValidation("newOrder" +  setupToAddNumber,
                                   "greaterthan=-.0000000001",
                                   "The order of operations for all setups should be greater than 0.");
        frmvalidator.addValidation("newSide" +  setupToAddNumber,
                                   "req",
                                   "Please enter which side for all setups.");
        frmvalidator.addValidation("newSide" +  setupToAddNumber,
                                   "num",
                                   "Please enter which side for all setups as a number.");
        frmvalidator.addValidation("newSide" +  setupToAddNumber,
                                   "greaterthan=-.0000000001",
                                   "The which side for all setups should be greater than 0.");
        frmvalidator.addValidation("newCoordinateID" +  setupToAddNumber,
                                   "req",
                                   "Please enter a coordinate system for all setups.");
        frmvalidator.addValidation("newXLocation" +  setupToAddNumber,
                                   "req",
                                   "Please enter the X zero for all setups.");
        frmvalidator.addValidation("newYLocation" +  setupToAddNumber,
                                   "req",
                                   "Please enter the Y zero for all setups.");
        frmvalidator.addValidation("newZLocation" +  setupToAddNumber,
                                   "req",
                                   "Please enter the Z zero for all setups.");
    }
}

