/* 
 * Arrays to handle adding blanks and their attachments on the page.
 * 
 * Dependencies:
 *      ./javascript/general.js
 */
var newToolNumbersToAdd = new Array();

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

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

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

// Create a function to create a select list off of the comma delimited array provided
function createSelectListOfNumberedSlots(selectName, amount, style, selected=-1){
    // Get the options first
    var returnHTML = createSelectListOptionsOfNumberedSlots(amount, selected);

    // Add the select tag
    returnHTML = '<select class="ToolPositionChild" style="' + style + '" id="' + selectName + '" name="' + selectName + '">' + returnHTML + '</select>';
    
    // Return what we created
    return returnHTML;
}

// Create a function to create the select list options off of the comma delimited array provided
function createSelectListOptionsOfNumberedSlots(amount, selected=-1){
    // Create and init a return
    var returnHTML = '';
    
    // Determine if we have an amount
    if (!isNaN(amount)){
        // Get the loop variable as a number
        var loopAmount = parseInt(amount);
        
        // Loop through the list
        for (var i = 1; i <= loopAmount; i++) {
            // Determine if we are on the one passed in that is selected
            if (selected === i){
                // Add the selected option to the select
                returnHTML += '<option value="' + i + '" selected>Slot ' + i + '</option>';
            }
            else{
                // Add the non selected option to the select
                returnHTML += '<option value="' + i + '">Slot ' + i + '</option>';
            }
        }
        
        // Add the non selected option to the select
        returnHTML = '<option value="0">Slot Not Set</option>' + returnHTML;
    }
    else {
        // Return something to let them know the machine is not set
        returnHTML += '<option value="-1">Machine Not Set</option>';
    }
    
    // Return what we created
    return returnHTML;
};

function checkUniqueToolPositions()
{
    try {
        // Get all of the controls that contain tool position combo boxes as children
        var positionChildren = document.getElementsByClassName('ToolPositionChild');        

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

        // Loop through all of the elements
        for (var i=0, len=positionChildren.length|0; i<len; i=i+1|0) {
            // Determine if the control has even been filled with anything first
            if (positionChildren[i].options.length===0){
                // Just fill it
                positionChildren[i].innerHTML = createSelectListOptionsOfNumberedSlots(maxTools);
            }
            // Determine if the old max value is not equal to the new machines max value
            else {
                // Determine if this is an already existing tool and if it is marked for deletion
                if (!positionChildren[i].name.includes('new') && 
                    document.getElementById('removeTool' + positionChildren[i].name.replace('toolPosition', '')).checked){
                    // Ignore this one, since it is marked for deletion.
                    continue;
                }
                
                // Get the current position
                var currentPosition = positionChildren[i].value;
                
                // Determine if the value is greater than zero
                if (currentPosition>0){
                    // Determine if this one is already seen
                    if (alreadySeen["" + currentPosition]){
                        // Let them know there are duplicate values
                        alert("There are positions that are set that would result in tools in the same position.\n\nEither unset them or correct to be unique.");

                        // Found duplicate, so return false
                        return false;
                    }
                    else{
                        // Add to checked array
                        alreadySeen["" + currentPosition] = true;
                    }
                }
            }
        }
    } catch (e) {
        // Let them know there are duplicate values
        alert("There was an error validation positions of tools.\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 hasUniqueTools(){
    try {
        // 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 an array of already seen values to help check for duplicity
            var alreadySeen = [];
            
            // Set a variable to hold tool to task linker ID, tool ID and it's exposed length
            var toolToTaskLinkerID = -1;
            var toolID=-1;
            var exposedLength = 0;

            // Loop through the elements
            var toolsAmount = toolTableElements.length;
            for (var currentToolTableLoopNum = toolsAmount-1; currentToolTableLoopNum > -1; currentToolTableLoopNum--) {
                // Determine if this is a new tool or not
                if (toolTableElements[currentToolTableLoopNum].id.includes("newTool")){
                    // Get the tool to task linker ID
                    toolToTaskLinkerID=toolTableElements[currentToolTableLoopNum].id.replace("newTool","");
                    
                    // Get the tool ID and exposed length
                    toolID=document.getElementById("newToolChosenID"+toolToTaskLinkerID).value;
                    exposedLength=isNaN(parseFloat(document.getElementById("newRequiredExposedLength"+toolToTaskLinkerID).value).toFixed(3))?0:parseFloat(document.getElementById("newRequiredExposedLength"+toolToTaskLinkerID).value).toFixed(3);
                }
                // This is an current tool
                else if (toolTableElements[currentToolTableLoopNum].id.includes("currentTool")){
                    // Get the to task linker ID 
                    toolToTaskLinkerID = toolTableElements[currentToolTableLoopNum].id.replace("currentTool", "");

                    // Ensure that this one is not being removed before applying the check
                    if (document.getElementById("removeTool"+toolToTaskLinkerID).checked){
                        // Just move onto the next one
                        continue;
                    }
                    
                    // Get the tool ID and exposed length
                    toolID=document.getElementById("toolChosenID"+toolToTaskLinkerID).value;
                    exposedLength=isNaN(parseFloat(document.getElementById("requiredExposedLength"+toolToTaskLinkerID).value).toFixed(3))?0:parseFloat(document.getElementById("requiredExposedLength"+toolToTaskLinkerID).value).toFixed(3);
                }

                // Determine if we can add it is there yet ot not
                if (alreadySeen[toolID + '-' + exposedLength]){
                    // It cannot be added, therefore it is duplicate. Return a fail
                    alert ("There are duplicate tools in your list of tools that could be used. Please either remove duplicates or make them unique (exposed length, rougher, finisher, etc). Aborting.");

                    // Invalidate check
                    return false;
                }
                else{
                    // Add a true flag for this element with this name to be compared with on next tool
                    alreadySeen[toolID + '-' + exposedLength] = true;           
                }
            }
        }
    } catch (e) {
        // Let them know there are duplicate values
        alert("There was an error validation duplicate tools.\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 checkAndChangeToolPositions(whichMachineIndex){
    // create a variable for the message
    var message = '';
        
    // Determine if we have a value for this variable
    if (typeof machineToolSlotMaxes === 'string'){
        // Create  comma delimited list from the list passed in, hopefully
        var commaList = machineToolSlotMaxes.split(',');

        // Get the selected max tool amount from the array list
        var maxTools = parseInt(commaList[whichMachineIndex]);

        // Get all of the controls that contain tool position combo boxes as children
        var positionChildren = document.getElementsByClassName('ToolPositionChild');        

        // Loop through all of the elements
        for (var i=0, len=positionChildren.length|0; i<len; i=i+1|0) {
            // Get the number of the elements we are on
            var numberOn = positionChildren[i].id.replace('toolPosition','');
            
            // Determine if the control has even been filled with anything first
            if ((positionChildren[i].options.length-1)<=0){
                // Get any previous values that it might have had
                var toolID = document.getElementById('toolChosenID' + numberOn);
                var previousToolID = document.getElementById('previousToolChosenID' + numberOn);
                var previousToolPositionID = document.getElementById('previousToolPosition' + numberOn);
                
                // Determine if we have anything for both
                if (previousToolID !== null && previousToolPositionID !== null && toolID !== null &&
                    parseInt(previousToolID.value) >= 1 && previousToolID.value === toolID.value){
                    // Just fill it
                    positionChildren[i].innerHTML = createSelectListOptionsOfNumberedSlots(maxTools, parseInt(previousToolPositionID.value));
                }
                else {
                    // Just fill it
                    positionChildren[i].innerHTML = createSelectListOptionsOfNumberedSlots(maxTools);
                }
            }
            // Determine if the old max value is not equal to the new machines max value
            else if (maxTools !== parseInt(positionChildren[i].options[positionChildren[i].options.length - 1].value)){
                // Get the current value
                var position = parseInt(positionChildren[i].value);

                // We will need to fix the option amounts, so might as well do it now
                positionChildren[i].innerHTML = createSelectListOptionsOfNumberedSlots(maxTools, position);
                
                // Determine if the position is valid for this new machine
                if (position > maxTools) {
                    // Check to see if we started the message yet
                    if (message === ''){
                        // make a message to let them know that some positions have been changed
                        message = 'NEW Tool position(s) are out of the range of the machine max tool position. Old position(s) ' + position + ',';
                    }
                    else {
                        // make a message to let them know that some positions have been changed
                        message = message + position + ',';
                    }
                }
            }
        }
        
        // Determine if there are messages to display
        if (message !== ''){
            // Remove the last comma
            message = message.substring(0, message.length-1);
            
            // Add the final remarks
            message = message + ' have been set to unassigned position 0.\n\nPlease review ' + 
                    'the tools to ensure they are set back to the appropriate positions.';
            
            // Inform them of the changes
            alert(message);
        }
    }
}

function removeNewToolNumber(toolNumberToRemove){
    // Set the removal item to zero for now
    var toolLocationToRemove = -1;
    
    // Loop through the result numbers to get the highest
    for (var loopToolNumber in newToolNumbersToAdd){
        // Determine if the number is higher than the current number
        if (newToolNumbersToAdd[loopToolNumber]===toolNumberToRemove){
            // set this as the one to remove
            toolLocationToRemove = loopToolNumber;

            // Break out of the list
            break;
        }
    }

    // Remove it from the list
    newToolNumbersToAdd.splice(toolLocationToRemove,1);
}

function removeNewTool(toolToRemove){
    console.log("in removeNewTool");

    // Get the element to remove
    var tool = document.getElementById('newTool'+toolToRemove);

    // Remove it
    tool.parentNode.removeChild(tool);    
    
    // Remove this from the list
    removeNewToolNumber(toolToRemove);
    
    // Reset the tool number string
    var toolAmount = document.getElementById("newToolNumbers");
    toolAmount.value=createNewToolNumberString();
}

function addNewTool(position=-1, notes='', removeAfter=false, useNewTool=false, requiredExposed=0) {
    console.log("in addNewTool");

    // Increment the amount that is currently in the array
    var newToolAmountID=getNewMaxToolNumber()+1;
    
// *** Table 1
    
    // Create the dynamic tool table
    var toolDiv = document.createElement("table");
    toolDiv.style = 'margin: 5px; width: 100%; border-top-style:dashed; border-width: 1px; display: inline-block; text-align: center;';
    toolDiv.id = 'newTool' + newToolAmountID;
    toolDiv.name = 'newTool' + newToolAmountID;
    toolDiv.classList.add("toolTable");
    
 // *** Row 1 
    
    // Create the row to hold the dynamic attributes of the chosen tool
    var toolDynamicAttributesRowHeader = document.createElement("tr");
    toolDynamicAttributesRowHeader.style = 'width: 100%; margin: 5px; vertical-align: middle; font-weight: bold;';

    // Add the row to hold the dynamic attributes of the chosen tool to the tool table
    toolDiv.appendChild(toolDynamicAttributesRowHeader);

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

// *** Row 1 Cell 1 

    // Create the tool position header cell to add to the dynamic attributes header row
    var toolPositionHeader = document.createElement("td");
    toolPositionHeader.style = 'width: 10%; align: center;';

    // Create the tool position header cell to add to the dynamic attributes header row
    toolDynamicAttributesRowHeader.appendChild(toolPositionHeader);

    // Create the tool position label
    var toolPositionLabel = document.createElement("label");
    toolPositionLabel.textContent="Position";

    // Add the tool position label to the cell
    toolPositionHeader.appendChild(toolPositionLabel);
    
// *** Row 1 Cell 2 
    
    // Create the Remove After header cell to add to the dynamic attributes header row
    var toolRemoveAfterCellHeader = document.createElement("td");
    toolRemoveAfterCellHeader.id = 'toolRemoveAfterCell' + newToolAmountID;
    toolRemoveAfterCellHeader.name = 'toolRemoveAfterCell' + newToolAmountID;
    toolRemoveAfterCellHeader.style = 'width: 14%; align: center;';

    // Add the Remove After header Cell to the dynamic attributes header row
    toolDynamicAttributesRowHeader.appendChild(toolRemoveAfterCellHeader);

    // Create the Remove After label
    var toolRemoveAfterLabel = document.createElement("label");
    toolRemoveAfterLabel.textContent="Remove After";

    // Add the Remove After label to the cell
    toolRemoveAfterCellHeader.appendChild(toolRemoveAfterLabel);

// *** Row 1 Cell 3 
    
    // Create the Use New header cell to add to the dynamic attributes header row
    var toolUseNewCellHeader = document.createElement("td");
    toolUseNewCellHeader.id = 'toolUseNewCell' + newToolAmountID;
    toolUseNewCellHeader.name = 'toolUseNewCell' + newToolAmountID;
    toolUseNewCellHeader.style = 'width: 10%; align: center;';

    // Add the Use New header Cell to the dynamic attributes header row
    toolDynamicAttributesRowHeader.appendChild(toolUseNewCellHeader);

    // Create the Use New label
    var toolUseNewLabel = document.createElement("label");
    toolUseNewLabel.textContent="Use New";

    // Add the Remove After label to the cell
    toolUseNewCellHeader.appendChild(toolUseNewLabel);

// *** Row 1 Cell 4 

    // Create the required exposed length header cell to add to the dynamic attributes header row
    var toolRequiredExposedLengthCellHeader = document.createElement("td");
    toolRequiredExposedLengthCellHeader.id = 'toolRequiredExposedLengthCell' + newToolAmountID;
    toolRequiredExposedLengthCellHeader.name = 'toolRequiredExposedLengthCell' + newToolAmountID;
    toolRequiredExposedLengthCellHeader.style = 'width: 14%; align: center;';

    // Add the requred exposed length header cell to the dynamic attributes header row
    toolDynamicAttributesRowHeader.appendChild(toolRequiredExposedLengthCellHeader);

    // Create the required exposed length label
    var toolRequiredExposedLengthLabel = document.createElement("label");
    toolRequiredExposedLengthLabel.textContent="Req Exposed";

    // Add the Remove After label to the cell
    toolRequiredExposedLengthCellHeader.appendChild(toolRequiredExposedLengthLabel);
    
// *** Row 1 Cell 5 
    
    // Create the note header cell to add to the dynamic attributes header row
    var toolNoteCellHeader = document.createElement("td");
    toolNoteCellHeader.id = 'toolNoteCell' + newToolAmountID;
    toolNoteCellHeader.name = 'toolNoteCell' + newToolAmountID;
    toolNoteCellHeader.style = 'align: center;';

    // Create the note header cell to add to the dynamic attributes header row
    toolDynamicAttributesRowHeader.appendChild(toolNoteCellHeader);

    // Create the note label
    var toolNoteLabel = document.createElement("label");
    toolNoteLabel.textContent="Note";

    // Add the note label to the cell
    toolNoteCellHeader.appendChild(toolNoteLabel);
    
// *** Row 1 Cell 6

    // Create the required edit row header cell to add to the dynamic attributes header row
    var toolEditRowHeaderCellHeader = document.createElement("td");
    toolEditRowHeaderCellHeader.id = 'toolEditRowHeaderCell' + newToolAmountID;
    toolEditRowHeaderCellHeader.name = 'toolEditRowHeaderCell' + newToolAmountID;
    toolEditRowHeaderCellHeader.style = 'width: 10%; align: center;';

    // Add the required edit row cell to the dynamic attributes row
    toolDynamicAttributesRowHeader.appendChild(toolEditRowHeaderCellHeader);

    // Create the required edit row label
    var toolRequiredExposedLengthLabel = document.createElement("label");
    toolRequiredExposedLengthLabel.textContent="Actions";

    // Add the edit row label to the cell
    toolEditRowHeaderCellHeader.appendChild(toolRequiredExposedLengthLabel);
    
 // *** Row 2 *** //
    
    // Create the row to hold the dynamic attributes of the chosen tool
    var toolDynamicAttributesRow = document.createElement("tr");
    toolDynamicAttributesRow.id = 'toolDynamicAttributesRow' + newToolAmountID;
    toolDynamicAttributesRow.name = 'toolDynamicAttributesRow' + newToolAmountID;
    toolDynamicAttributesRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row to hold the dynamic attributes of the chosen tool to the tool table
    toolDiv.appendChild(toolDynamicAttributesRow);

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

// *** Row 2 Cell 1 

    // Create the position cell to add to the dynamic attributes row
    var toolPositionCell = document.createElement("td");
    toolPositionCell.id = 'toolPositionCell' + newToolAmountID;
    toolPositionCell.name = 'toolPositionCell' + newToolAmountID;
    toolPositionCell.style = 'align: center;';

    // Create the position cell to add to the dynamic attributes row
    toolDynamicAttributesRow.appendChild(toolPositionCell);

    // Determine if we have a value for this variable
    if (typeof machineToolSlotMaxes === 'string'){
        // Create  comma delimited list from the list passed in, hopefully
        var commaList = machineToolSlotMaxes.split(',');

        // Create the material category
        var toolPositionDiv=  document.createElement("div");
        toolPositionDiv.class = 'ToolPositionParent';
        toolPositionDiv.title = newToolAmountID;
        toolPositionDiv.innerHTML = createSelectListOfNumberedSlots('newToolPosition' + newToolAmountID, commaList[document.getElementById('machineID').selectedIndex], "", position);

        // Add the tool position combobox control to the cell
        toolPositionCell.appendChild(toolPositionDiv);
    }

// *** Row 2 Cell 2 

    // Create the Remove After cell to add to the dynamic attributes row
    var toolRemoveAfterCell = document.createElement("td");
    toolRemoveAfterCell.id = 'toolRemoveAfterCell' + newToolAmountID;
    toolRemoveAfterCell.name = 'toolRemoveAfterCell' + newToolAmountID;
    toolRemoveAfterCell.style = 'align: center;';

    // Add the Remove After Cell to the dynamic attributes row
    toolDynamicAttributesRow.appendChild(toolRemoveAfterCell);

    // Create the remove after checkbox
    var toolRemoveAfterCheck=  document.createElement("input");
    toolRemoveAfterCheck.type = "checkbox";
    toolRemoveAfterCheck.id = 'newRemoveToolAfter' + newToolAmountID;    
    toolRemoveAfterCheck.name = 'newRemoveToolAfter' + newToolAmountID; 
    toolRemoveAfterCheck.checked = removeAfter;
    
    // Add the remove after checkbox control to the cell
    toolRemoveAfterCell.appendChild(toolRemoveAfterCheck);

// *** Row 2 Cell 3 

    // Create the Use New cell to add to the dynamic attributes row
    var toolUseNewCell = document.createElement("td");
    toolUseNewCell.id = 'toolUseNewCell' + newToolAmountID;
    toolUseNewCell.name = 'toolUseNewCell' + newToolAmountID;
    toolUseNewCell.style = 'align: center;';

    // Add the Remove After Cell to the dynamic attributes row
    toolDynamicAttributesRow.appendChild(toolUseNewCell);

    // Create the use new checkbox
    var toolUseNewCheck=  document.createElement("input");
    toolUseNewCheck.type = "checkbox";
    toolUseNewCheck.id = 'newUseNewTool' + newToolAmountID;    
    toolUseNewCheck.name = 'newUseNewTool' + newToolAmountID; 
    toolUseNewCheck.checked = useNewTool;
    
    // Add the remove after checkbox control to the cell
    toolUseNewCell.appendChild(toolUseNewCheck);

// *** Row 2 Cell 4 

    // Create the required exposed length cell to add to the dynamic attributes row
    var toolRequiredExposedLengthCell = document.createElement("td");
    toolRequiredExposedLengthCell.id = 'toolRequiredExposedLengthCell' + newToolAmountID;
    toolRequiredExposedLengthCell.name = 'toolRequiredExposedLengthCell' + newToolAmountID;
    toolRequiredExposedLengthCell.style = 'align: center;';

    // Add the requred exposed length cell to the dynamic attributes row
    toolDynamicAttributesRow.appendChild(toolRequiredExposedLengthCell);

    // Create the required exposed length text
    var toolRequiredExposedLength = document.createElement("input");
    toolRequiredExposedLength.rows = '1';
    toolRequiredExposedLength.id = 'newRequiredExposedLength' + newToolAmountID;    
    toolRequiredExposedLength.name = 'newRequiredExposedLength' + newToolAmountID;  
    toolRequiredExposedLength.style = 'width: 50px; text-align: center; resize: none;';
    toolRequiredExposedLength.type = 'text';
    toolRequiredExposedLength.value = requiredExposed;

    // Add the Exposed Length text control to the cell
    toolRequiredExposedLengthCell.appendChild(toolRequiredExposedLength);

// *** Row 2 Cell 5 

    // Create the note cell to add to the dynamic attributes row
    var toolNoteCell = document.createElement("td");
    toolNoteCell.id = 'toolNoteCell' + newToolAmountID;
    toolNoteCell.name = 'toolNoteCell' + newToolAmountID;
    toolNoteCell.style = 'align: center;';

    // Create the note cell to add to the dynamic attributes row
    toolDynamicAttributesRow.appendChild(toolNoteCell);

    // Create the note text
    var toolNote=  document.createElement("textarea");
    toolNote.rows = 1;
    toolNote.id = 'newToolNote' + newToolAmountID;    
    toolNote.name = 'newToolNote' + newToolAmountID;  
    toolNote.style = 'resize: vertical; max-width: 100%; max-height: 100%;';
    toolNote.value = notes;
    toolNote.maxLength = 1000;
    
    // Add the tool note checkbox control to the cell
    toolNoteCell.appendChild(toolNote);

// *** Row 2 Cell 6

    // Create the buttons cell to add to the dynamic attributes row
    var toolButtonsCell = document.createElement("td");
    toolButtonsCell.id = 'toolButtonsCell' + newToolAmountID;
    toolButtonsCell.name = 'toolButtonsCell' + newToolAmountID;
    toolButtonsCell.style = 'align: center;';

    // Add the buttons cell to the dynamic attributes row
    toolDynamicAttributesRow.appendChild(toolButtonsCell);

    // Create the button that will get the tool from the new tool table
    var toolChosenAsNewToolButton = document.createElement("button");
    toolChosenAsNewToolButton.textContent="New";
    toolChosenAsNewToolButton.id = 'newChooseToolAsNewBtn' + newToolAmountID;    
    toolChosenAsNewToolButton.style = 'margin-left: %90;';
    toolChosenAsNewToolButton.type = 'button';
    toolChosenAsNewToolButton.onclick = function(i) {  
        return function() {
            // Set the tool slot row to modify
            toolSlotIDToModifyRow = newToolAmountID;
            
            // We are not updating a tool. We are adding one.
            updatingtool=false;
            
            // Get all tools in the database
            chooseTool(true);
        };
    }(newToolAmountID);

    // Add the button to choose tool as new tool to the buttons cell
    toolButtonsCell.appendChild(toolChosenAsNewToolButton);

    // Create the button that will get the tool from the new tool table
    var toolRemoveButton = document.createElement("button");
    toolRemoveButton.textContent="X";
    toolRemoveButton.id = 'newRemoveToolButton' + newToolAmountID;    
    toolRemoveButton.style = 'margin-left: %90;';
    toolRemoveButton.type = 'button';
    toolRemoveButton.onclick = function(i) {  
        return function() {
            removeNewTool(i);
        };
    }(newToolAmountID);

    // Add the button to choose tool as new tool to the buttons cell
    toolButtonsCell.appendChild(toolRemoveButton);

 // *** Row 3 - The contents of the toolChoiceCell should be dynamically populated from the buttons and AJAX *** //
    
    // Create the row to hold the chosen tool
    var toolChoiceRow = document.createElement("tr");
    toolChoiceRow.id = 'newToolChoiceRow' + newToolAmountID;
    toolChoiceRow.name = 'newToolChoiceRow' + newToolAmountID;
    toolChoiceRow.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the row to hold the chosen tool
    toolDiv.appendChild(toolChoiceRow);

// *** Row 3 Cell 1 

    // Create the chosen tool cell to add to the chosen tool row
    var toolChoiceCell = document.createElement("td");
    toolChoiceCell.id = 'newToolChoiceCell' + newToolAmountID;
    toolChoiceCell.name = 'newToolChoiceCell' + newToolAmountID;
    toolChoiceCell.style = 'width: 100%; margin: 5px; vertical-align: center;';
    toolChoiceCell.colSpan = 6;

    // Add the chosen tool cell to the chosen tool row to the tool table
    toolChoiceRow.appendChild(toolChoiceCell);

    // Create the hidden value for the tool ID selected for this slot and start with a non tool number
    var toolChosen = document.createElement("input");
    toolChosen.id = 'newToolChosenID' + newToolAmountID;    
    toolChosen.name = 'newToolChosenID' + newToolAmountID;  
    toolChosen.type = 'hidden';
    toolChosen.classList.add('taskToolID');
    toolChosen.value = '-1';

    // Add the choice to the div
    toolChoiceRow.appendChild(toolChosen);
    
// *** Add newly created div to the main container

    // Get the main div container to add the new div tag to and hidden choice to it 
    var container = document.getElementById("newTools");
    container.appendChild(toolDiv);
    
    // Add this ID to the list
    newToolNumbersToAdd.push(newToolAmountID);
    
    // Get the element and change the amount of tools
    var toolAmountDiv = document.getElementById("newToolNumbers");
    toolAmountDiv.value=newToolNumbersToAdd.join('|');
    
    // Add any validation that we have
    addToolValidation(newToolAmountID);
    
    // Return the position of the new tool div
    return newToolAmountID;
}

function addToolValidation(toolToAddValidation){
    console.log("in addToolValidation");

    // Ensure that the validator object is available
    if (typeof frmvalidator !== 'undefined'){
        // Add the validators
        frmvalidator.addValidation("newRequiredExposedLength" +  toolToAddValidation,
                                   "req",
                                   "Please enter an exposed length for all tools.");
        frmvalidator.addValidation("newRequiredExposedLength" +  toolToAddValidation,
                                   "num",
                                   "Please enter an exposed length for all tools as a number.");
        frmvalidator.addValidation("newRequiredExposedLength" +  toolToAddValidation,
                                   "greaterthan=-.0000000001",
                                   "The required exposed length for all tools should be greater than 0.");
        frmvalidator.addValidation("newToolChosenID" +  toolToAddValidation,
                                   "req",
                                   "There should be a tool chosen for all slots added.");
        frmvalidator.addValidation("newToolChosenID" +  toolToAddValidation,
                                   "greaterthan=-1",
                                   "There should be a tool chosen for all slots added.");
    }
}

// Function to handle AJax
function chooseTool(isNewTool){
    try {
        // Set a variable to hold the div that will be holding the appropriate tools
        var appropriateToolsListedDiv = null;

        // Get the machine ID
        var machineID=document.getElementById("machineID").value;

        // Determine if this wants new tools or assigned
        if (isNewTool){
            // Get the div to hold the list of new tools after the query
            appropriateToolsListedDiv = document.getElementById('toolsListed');
        }
        else {
            // Determine if there is a machine selected
            if (machineID<=0){
                // Let the user know
                alert ("There must be a machine selected in order to select tools that are already in a machine for the job.\n\nSelect a machine first.");

                // Exit this function
                return false;
            }
            // Get the div to hold the list of assigned tools after the query
            appropriateToolsListedDiv = document.getElementById('assignedToolsListed');

            // Reset the list
            appropriateToolsListedDiv.innerHTML="";                
        }

        // Determine if the query has already been run
        if (appropriateToolsListedDiv.innerHTML.trim() === ''){
            // Set a message at the center of the div to inform them we are querying
            appropriateToolsListedDiv.innerHTML = '<label style="color:Red; font-size: 44px;">Please Wait. Loading Data.</label>';
            
            // Determine if it is new.
            if (isNewTool){
                // Show the newly populated list of new tools
                div_showAllTools();
            }
            else {
                // Show the newly populated list of assigned tools
                div_showAllAssignedTools();
            }
            
            // Setup the parameters to pass to PHP
            var params = {
                "sessionID" : sessionID
            };

            // Setup the error string variable.  Assume new at first.
            var toolTypeStringForError = 'tools';

            // Create the string containing the PHP file to use. Assume new at first
            var url = "php_only_scripts/jquery_only/all_toollist.php";

            // Determine if it it NOT new.
            if (!isNewTool){
                // Setup the parameters to pass to PHP
                var params = {
                    "sessionID" : sessionID,
                    "machineID" : machineID
                };
                
                // use the assigned tools
                url = "php_only_scripts/jquery_only/assigned_toollist.php";
                toolTypeStringForError = 'assigned tools';
            }

            // 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")){
                        // Split the string on the double colon
                        var errorStrings=data.trim().split("::");

                        // Give an alert popup of the problem
                        alert(errorStrings[1]);
                    }
                    else {
                        // Populate the contents of the returned query into the DIV
                        appropriateToolsListedDiv.innerHTML = data.trim();
                    }

                    // Log any errors to the console
                    console.log(data.trim());
                }
                else {
                    // Give an alert informational popup
                    alert('There were no ' + toolTypeStringForError + ' returned from the query.');
                }
            })
            .fail(function(data){   
                // Log any errors to the console
                console.log(data);

                // Give an alert informational popup
                alert('There was a problem communicating with the server to get the ' + toolTypeStringForError + '.');
            }); 
        }
        else {
            // Determine if it is new.
            if (isNewTool){
                // Show the newly populated list of new tools
                div_showAllTools();
            }
            else {
                // Show the newly populated list of assigned tools
                div_showAllAssignedTools();
            }
        }
    } 
    catch (e) {
        // Log the error
        console.error(e);
        
        // Give an alert informational popup
        alert('There was a problem attempting to get the tools.\n\nPlease inform tech admin.');
    }
}

function addChosenTools() {
    try {
        // Get all elements that are of the tool row class
        var elements = document.getElementsByClassName("selectTool");

        // Loop through them to get the child select checkbox and check it
        for (var displayPosition = 1; displayPosition <= elements.length; displayPosition++) {
            // Get the chosen tool header
            var clonedChosenToolRowHeader = document.getElementById("Assigned_Tool_Header").cloneNode(true);

            // Get the checked value
            var isSelectedTool = elements[displayPosition-1].checked;

            // Determine if it is checked
            if (isSelectedTool){
                // Get the relevant hidden variables
                var displayedToolID = parseInt(document.getElementById("displayedToolID" + displayPosition).value);
                var machinePosition = parseInt(document.getElementById("displayedAssignedToolMachinePosition" + displayPosition).value);
                var notes = document.getElementById("displayedAssignedToolNotes" + displayPosition).value;
                var removeAfter = parseInt(document.getElementById("displayedAssignedToolRemoveAfter" + displayPosition).value);
                var useNewTool = parseInt(document.getElementById("displayedUseNewTool" + displayPosition).value);
                var exposedLength = document.getElementById("displayedAssignedToolExposedLength" + displayPosition).value;
                
                // get the row element
                var clonedChosenToolRowElement = document.getElementById("Assigned_Tool_" + displayPosition).cloneNode(true);
                
                // Create the new div for this tool and get the position of the new div
                var divPosition = addNewTool(machinePosition, notes, removeAfter, useNewTool, exposedLength);                
                
                // 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 = displayedToolID;

                // 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);
                }

                // Change the ID of the newly copied rows
                clonedChosenToolRowHeader.id = displayRowHeaderID;
                clonedChosenToolRowElement.id = displayRowID;

                // 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++){
                        // Determine if this is a cell class to remove
                        if (updateCellHeaderElements[i].classList.contains("removeForTask")){
                            // Remove the edit cell   
                            updateCellHeaderElements[i].parentNode.removeChild (updateCellHeaderElements[i]);
                        }
                        else {
                            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++){
                        // Determine if this is a cell class to remove
                        if (updateCellElements[i].classList.contains("removeForTask")){
                            // Remove the edit cell   
                            updateCellElements[i].parentNode.removeChild (updateCellElements[i]);
                        }
                        else {
                            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;
                                }
                            }
                        }
                    }
                }

                // Set the HTML that is the chosen tool row into the visual area
                toolChosenDisplayCell.appendChild (clonedChosenToolRowHeader);
                toolChosenDisplayCell.appendChild (clonedChosenToolRowElement);
            }
        }
    }
    catch (e) {
        // Log the error
        console.error(e);
        
        // Show the user in their face
        alert(e.Message);
    }
    finally {
        // Hide the assigned tools div that should still be shown
        div_hide('showAllAssignedTools');
    }
}

var toolSlotIDToModifyRow = -1;
var updatingtool = false;
function newToolSelectedForTask(toolRowNumber, toolID=-1){
    try {
        // We are not updating a tool. We are adding one.
        updatingtool=false;
        
        // Start setting up the new tool and get the toolSlotID picked
        toolSlotIDToModifyRow=addNewTool(); 
        
        // Create variables for the rows we will be modifying
        var clonedChosenToolRowHeader = document.getElementById("New_Tool_Header").cloneNode(true);
        var clonedChosenToolRowElement = document.getElementById("New_Tool_" + toolRowNumber).cloneNode(true);
        var toolChosenDisplayCell = document.getElementById("newToolChoiceCell" + toolSlotIDToModifyRow);
        var toolChosenID = document.getElementById("newToolChosenID" + toolSlotIDToModifyRow);
        var displayRowHeaderID = "newEditCellIDForHeader" + toolSlotIDToModifyRow;
        var displayRowID = "newEditCellIDFor" + toolSlotIDToModifyRow;
        
        // Set the ID(s)
        toolChosenID.value = toolID;

        // 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);
        }
        
        // Change the ID of the newly copied rows
        clonedChosenToolRowHeader.id = displayRowHeaderID;
        clonedChosenToolRowElement.id = displayRowID;

        // 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++){
                // Determine if this is a cell class to remove
                if (updateCellHeaderElements[i].classList.contains("removeForTask")){
                    // Remove the edit cell   
                    updateCellHeaderElements[i].parentNode.removeChild (updateCellHeaderElements[i]);
                }
                else {
                    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 "toolsTypeCell":
                                // 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++){
                // Determine if this is a cell class to remove
                if (updateCellElements[i].classList.contains("removeForTask")){
                    // Remove the edit cell   
                    updateCellElements[i].parentNode.removeChild (updateCellElements[i]);
                }
                else {
                    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 "toolsTypeCell":
                                // Change the width for machines
                                updateCellElements[i].style.width = "20%";
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
        
        // Set the HTML that is the chosen tool row into the visual area
        toolChosenDisplayCell.appendChild (clonedChosenToolRowHeader);
        toolChosenDisplayCell.appendChild (clonedChosenToolRowElement);
    } 
    catch (e) {
        // Log the error
        console.error(e);
        
        // Show the user in their face
        alert(e.Message);
    }
    finally {
        // Hide the new tools div that should still be shown
        div_hide('showAllTools');
    }
}


function displayCorrectTypesAssignedByClass() {
    // get the type combo now by ID
    var cmbTypes = document.getElementById('typeForAssigned');

    // Get all elements that are of the tool row class
    var elements = document.getElementsByClassName("toolrow");
    
    // Loop through them to hide or show them as selected
    for (var i = 0, len = elements.length; i < len; i++) {
        // Check to see if they selected all or the correct secondary type this row is
        if (cmbTypes[cmbTypes.selectedIndex].value === "-1" ||
            elements[i].classList.contains('type_'+cmbTypes[cmbTypes.selectedIndex].value)){
            // Show this row
            elements[i].style.display = 'table';
        }
        else {
            // Hide this row
            elements[i].style.display = 'none';            
        }
    }
} 

function displayCorrectTypesAssigned() {
    // get the type combo now by ID
    var cmbTypes = document.getElementById('typeForAssigned');

    // Loop through the values in the combo box
    for(i = 0; i < cmbTypes.length; i++) {
        // Go onto next index if we are on the ALL TYPES one
        if (cmbTypes[i].value === "ALL TYPES"){
            // Move to the next element
            continue;
        }

        // assume that the type will become invisible
        var visible = false;

        // get value with spaces changed to underscores
        var loopTypeID = cmbTypes[i].value.split(" ").join("_") + '_assigned';

        // Determine if it is the selected one to be visible or all visible
        if (cmbTypes[i].selected ||
            cmbTypes[0].selected) {
            // This is the one to be visible
            var visible = true;
        }

        // Call the function to set visibility
        setDivVisibility(loopTypeID, visible);
    }
} 

function displayCorrectTypesAll() {
    // get the type combo now by ID
    var cmbTypes = document.getElementById('typeForAll');

    // Loop through the values in the combo box
    for(i = 0; i < cmbTypes.length; i++) {
        // Go onto next index if we are on the ALL TYPES one
        if (cmbTypes[i].value === "ALL TYPES"){
            // Move to the next element
            continue;
        }

        // assume that the type will become invisible
        var visible = false;

        // get value with spaces changed to underscores
        var loopTypeID = cmbTypes[i].value.split(" ").join("_");

        // Determine if it is the selected one to be visible or all visible
        if (cmbTypes[i].selected ||
            cmbTypes[0].selected) {
            // This is the one to be visible
            var visible = true;
        }

        // Call the function to set visibility
        setDivVisibility(loopTypeID, visible);
    }
} 

function setDivVisibility(){
    // Set the div to hide as the ID passed in.  Assume good ID.
    var divToHide = document.getElementById(arguments[0]);

    // Determine if the DIV Exists
    if (typeof(divToHide) !== 'undefined' && divToHide !== null){
        // Determine if it is to be visible
        if (arguments[1]) {
            // show it
            divToHide.style.display = 'block';
        } else {
            // Hide it
            divToHide.style.display = 'none';
        }
    }
}

//Function To Display Assigned Tools Popup
function div_showAllAssignedTools() {
    // Get the outer div and show it
    div_show('showAllAssignedTools');

    // Get the show all tools div
    var showAllAssignedToolsBackgroundDiv = document.getElementById('showAllAssignedToolsBackground');

    // Scroll back to the top of the DIV
    showAllAssignedToolsBackgroundDiv.scrollTop = 0;
}

//Function To Display Tools Popup
function div_showAllTools() {
    // Get the outer div and show it
    div_show('showAllTools');

    // Get the show all tools div
    var showAllToolsBackgroundDiv = document.getElementById('showAllToolsBackground');

    // Scroll back to the top of the DIV
    showAllToolsBackgroundDiv.scrollTop = 0;
}
