<?php
    function getToolSearchOptions($db, $userRow, $inSearchPhrase, $type, $category){
        // Initialize the return
        $result = '';

        try {
            // Start the return with the beginning of the select
            $result=
                '   <div style="text-align:center; margin-top: 8px;font-size: 90%; font-weight: normal; border: 1px solid black; padding: 0px 7px 10px 7px;">' .
                '       <br>' .
                '          Type: ' .
                getToolTypeHTML($db, $userRow, 'typeForAll', $type, $category, 'CreateAndGotoSearchOptions();',1) .
                '       <br><br>' .
                '       <label for="searchPhrase">Search Phrase: </label>' . 
                '       <input name="searchPhrase" id="searchPhrase" type="text" style="width: 70%;" value="' . htmlentities($inSearchPhrase, ENT_QUOTES) . '"/>' . 
                '       <input name="submitButton" id="submitButton" type="button" value="Search" title="Search the tools for a phrase." onclick="CreateAndGotoSearchOptions()" style="text-align:right;"/> ' .
                '   </div>';
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function retrieveToolsAsList($db, $userRow, $toolType, $inCategory, $inSortNumber, $inSearchPhrase){
        $editPrivilegesTableHTML = '';
        $editPrivilegesRowHTML = '';
        $sort = ' t.Diameter, t.CuttingLength, t.FluteNumber, t.Brand';
        
        // Determine if the current type of tool is set to all
        if ($toolType != null && 
            $toolType != "ALL TYPES" && 
            $toolType != -1 ){
            // Update the category
            $type = $toolType;
            
            // Add a category in the where
            $whereHTML = $whereHTML . "AND tt.ToolTypeID='" . $type . "' ";
        }
        else {
            // Determine if we are looking at machining tools or miscellaneous
            if ($inCategory==1){
                // Add a category in the where
                $whereHTML = $whereHTML . "AND tt.Name IN ('THREAD MILL'," .  
                        "'TAPER MILL','TAP','SPOT DRILL','REAMER','FACE MILL'," . 
                        "'END MILL','DRILL','CHAMFER DRILL','BALL NOSE MILL'," . 
                        "'BULL NOSE MILL') ";
            }
            elseif ($inCategory==2){
                // Add a category in the where
                $whereHTML = $whereHTML . "AND tt.Name IN ('SET SCREW','O-RING'," . 
                        "'HELICOIL INSERT','DOWEL PIN','ASSEMBLY HARDWARE') ";
            }
        }
        
        // Determine if we have a search phrase
        if ($inSearchPhrase != null && 
            $inSearchPhrase != ""){
            // Update the search
            $searchPhrase = strtoupper(htmlspecialchars($inSearchPhrase));
            
            // Add a search in the where
            $whereHTML = $whereHTML . "AND (UPPER(t.Name) LIKE '%" . $searchPhrase . "%' " .
                                      "     OR UPPER(t.PartNumber) LIKE '%" . $searchPhrase . "%' ) ";
        }

        // Determine if there is a search term
        if ($inSortNumber!=""){
            // Determine which sort the person wants
            switch ($inSortNumber) {
                case "Name":
                    // Sort as name the most high
                    $sort = ' LOWER(t.Name), t.Diameter, t.CuttingLength, t.Radius, t.Angle, t.FluteNumber, t.Brand';

                    break;
                case "Diameter":
                    // Sort as Diameter the most high
                    $sort = ' t.Diameter, LOWER(t.Name), t.CuttingLength, t.Radius, t.Angle, t.FluteNumber, t.Brand';

                    break;
                case "CutLength":
                    // Sort as Cutting Length the most high
                    $sort = ' t.CuttingLength, LOWER(t.Name), t.Diameter, t.Radius, t.Angle, t.FluteNumber, t.Brand';

                    break;
                case "Radius":
                    // Sort as Corner Radius the most high
                    $sort = ' t.Radius, LOWER(t.Name), t.Diameter, t.CuttingLength, t.Angle, t.FluteNumber, t.Brand';

                    break;
                case "Angle":
                    // Sort as Angle the most high
                    $sort = ' t.Angle, LOWER(t.Name), t.Diameter, t.CuttingLength, t.Radius, t.FluteNumber, t.Brand';

                    break;
                case "FluteNum":
                    // Sort as Flute Number the most high
                    $sort = ' t.FluteNumber, LOWER(t.Name), t.Diameter, t.CuttingLength, t.Radius, t.Angle, t.Brand';

                    break;
                default:
                    break;
            }
        }

        // determine if this user has update privileges
        if ($userRow["UserLevel"] == "SU" ||
            $userRow["UserLevel"] == "EXECUTIVE" ||
            $userRow["UserLevel"] == "MANAGEMENT" ||
            $userRow["UserLevel"] == "MID-MANAGEMENT" ||
            $userRow["UserLevel"] == "TYPICAL"){
            // They have edit privileges
            $editPrivilegesTableHTML =
                    '<div class="cell updateCell">
                        <p><b>Edit</b></p>
                    </div>';
        }     

        // Initialize the return
        $result = 
            getToolSearchOptions($db, $userRow, $inSearchPhrase, $type, $inCategory) . '
            <br>
            <input type="hidden" id="category" name="category" value="' . $inCategory . '"/>
            <input type="hidden" id="sortNumber" name="sortNumber" value="' . $inSortNumber . '"/>
            <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell toolsNameCell hoverHand" onclick="document.getElementById(\'sortNumber\').value=\'Name\'; CreateAndGotoSearchOptions();">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell toolsDiameterCell hoverHand" onclick="document.getElementById(\'sortNumber\').value=\'Diameter\'; CreateAndGotoSearchOptions();" >
                        <p><b>Diameter</b></p>
                    </div>
                    <div class="cell toolsCuttingLengthCell hoverHand" onclick="document.getElementById(\'sortNumber\').value=\'CutLength\'; CreateAndGotoSearchOptions();">
                        <p><b>Cutting Length</b></p>
                    </div>
                    <div class="cell toolsCornerRadiusCell hoverHand" onclick="document.getElementById(\'sortNumber\').value=\'Radius\'; CreateAndGotoSearchOptions();">
                        <p><b>Corner Radius</b></p>
                    </div>
                    <div class="cell toolsAngleCell hoverHand" onclick="document.getElementById(\'sortNumber\').value=\'Angle\'; CreateAndGotoSearchOptions();">
                        <p><b>Angle</b></p>
                    </div>
                    <div class="cell toolsFluteNumberCell hoverHand" onclick="document.getElementById(\'sortNumber\').value=\'FluteNum\'; CreateAndGotoSearchOptions();">
                        <p><b>Flute #</b></p>
                    </div>
                    <div class="cell toolsTypeCell" hoverHand>
                        <p><b>Type</b></p>
                    </div>'
                    .
                    $editPrivilegesTableHTML 
                    .
                '</div>
            </li>';

        try {
            // Setup the query to get all tools available
            $sql='SELECT t.*, ct.*, tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, ' . 
                    'tt.CategoryName FROM tools t LEFT OUTER JOIN ' . 
                 '( SELECT count(*) AS AmountAssignedTo, CurrentToolID FROM assignedtools ' .
                    'GROUP BY CurrentToolID ) ct ON t.ToolID = ct.CurrentToolID ' .
                    'LEFT OUTER JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID Where 1=1 ' .
                    $whereHTML . 
                    'ORDER BY ToolTypeName ASC,' . $sort . ';';
            
            // Query the database for the tools 
            $rows = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 4");

            // Set the order to start with 1
            $order=1;

            // Loop through the returned results
            while ($row=mysqli_fetch_array($rows)){
                // Setup a return string
                $toolDescTextarea = "\n   Amount in Stock: " . $row["Amount"] . 
                                    "\n   Brand: " . str_replace("\"","",(str_replace("'","",$row["Brand"]==null?'':$row["Brand"]))) . 
                                    "\n   Part Number: " . str_replace("\"","",(str_replace("'","",$row["PartNumber"]==null?'':$row["PartNumber"]))) . 
                                    "\n   Diameter: " . $row["Diameter"] . 
                                    "\n   Cutting Length: " . $row["CuttingLength"] . 
                                    "\n   Corner Radius: " . $row["Radius"] . 
                                    "\n   Angle: " . $row["Angle"] . 
                                    "\n   Flute Number: " . $row["FluteNumber"] . 
                                    "\n   Type: " . str_replace("\"","",(str_replace("'","",$row["ToolTypeName"]==null?'':$row["ToolTypeName"]))) . 
                                    "\n   Exposed Length: " . $row["ExposedLength"] . 
                                    "\n   Shank Length: " . $row["ShankLength"] . 
                                    "\n   Total Length: " . $row["TotalLength"] . 
                                    "\n   Shoulder Length: " . $row["ShoulderLength"] . 
                                    "\n   Taper Angle: " . $row["TaperAngle"] . 
                                    "\n   Shank Diameter: " . $row["ShankDiameter"] . 
                                    "\n   Assigned Notes: " . preg_replace( "/\r|\n/", " ", str_replace("\"","",(str_replace("'","",$row["Notes"]==null?'':$row["Notes"]))));

                // Assign the delete button attributes as though deletion is an option
                $deleteButtonTextColor = 'LIMEGREEN';
                $deleteButtonTitle = 'Remove this tool.';
                $deleteButtonOnClick = 'onclick="javascript:if (confirm(\'Are you sure you want to delete this tool?\')) ' .
                                       '{window.location=\'redirectors/delete_tool.php?deleteToolID=' . $row["ToolID"] . '\';}"';

                // Determine if this tool is assigned to any machines
                if ($row["AmountAssignedTo"]!=null){
                    // Assign the delete buttons attributes such that deletion will not happen
                    $deleteButtonTextColor = 'RED';
                    $deleteButtonTitle = 'Check what machines this tool may be assigned to.';
                    $deleteButtonOnClick = 'onclick="javascript:alert(\'This tool is assigned to '. $row["AmountAssignedTo"] .
                                           ' machine(s).\n\nCheck what machines this tool may be assigned to before attempting to delete again.\');"';
                }

                // determine if this user has update privileges
                if ($userRow["UserLevel"] == "SU" ||
                    $userRow["UserLevel"] == "EXECUTIVE" ||
                    $userRow["UserLevel"] == "MANAGEMENT" ||
                    $userRow["UserLevel"] == "MID-MANAGEMENT" ||
                    $userRow["UserLevel"] == "TYPICAL"){
                    // Determine if it is an expedite part
                    $lowQuantityRowHTML='';
                    $lowQuantityTitle='';
                    if ($row["Amount"]<=0){
                        // This one is common
                        $lowQuantityRowHTML=' lowQuantityBackground';

                        // Setup the title
                        $lowQuantityTitle='This tool has a zero quantity in the database.  Please check to ensure this is in stock before issuing a job.';
                    }

                    // They have edit privileges
                    $editPrivilegesRowHTML = 
                            '        <div class="cell updateCell' . $lowQuantityRowHTML . '" title="' . $lowQuantityTitle . '">
                                        <span>
                                            <table>
                                                <tr>
                                                    <td>
                                                        <input type="button" style="font-size:9px; color:' . $deleteButtonTextColor . ';" value="X" title="' . 
                                                        $deleteButtonTitle . '" ' . $deleteButtonOnClick . '/>
                                                    </td>
                                                    <td>
                                                        <input type="button" style="font-size:9px;" value="..." title="Edit this tool.' . $toolDescTextarea . '" ' . 
                                                        'onclick="javascript:window.location=\'updateTool.php?c=' . $inCategory . '&toid=' . $row["ToolID"] . '\';"/>
                                                    </td>
                                                </tr>
                                            </table>
                                        </span>
                                    </div>';
                }

                // Setup the result to send back to the user
                $result = $result .
                            '<li id="Tool_' . $order . '" class="ui-state-default Table">
                                <div class="Row" style="background-color: '. $row["ToolTypeRowColor"] . '; vertical-align: middle;">
                            <div class="cell toolsNameCell">
                                <span>
                                    <p>' . $row["Name"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsDiameterCell">
                                <span>
                                    <p>' . $row["Diameter"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsCuttingLengthCell">
                                <span>
                                    <p>' . $row["CuttingLength"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsCornerRadiusCell">
                                <span>
                                    <p>' . $row["Radius"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsAngleCell">
                                <span>
                                    <p>' . $row["Angle"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsFluteNumberCell">
                                <span>
                                    <p>' . $row["FluteNumber"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsTypeCell">
                                <span>
                                    <p>' . $row["ToolTypeName"] . '</p>
                                </span>
                            </div>'
                            .
                            $editPrivilegesRowHTML 
                            .
                        '</div>
                    </li>';

                // Increment the order
                $order=$order+1;
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function retrieveAssignedToolsAsList($db, $userRow, $machineID){
        $editPrivilegesTableHTML = '';
        $editPrivilegesRowHTML = '';
        $machineName = '';
        $result='';

        try {
            // Setup the query to get all tools available
            $sql = 'SELECT asst.*, t.*, m.Name as MachineName, tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, tt.CategoryName ' . 
                   'FROM assignedtools asst ' . 
                   'LEFT JOIN tools t ON asst.CurrentToolID = t.ToolID ' .
                   'LEFT JOIN machines m ON asst.MachineID = m.MachineID ' .
                   'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                   'WHERE asst.MachineID=' . $machineID . ' ' .
                   'ORDER BY asst.Position ASC;';

            // Query the database for the tools 
            $topLevelRows = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 1");

            // Set the order to start with 1
            $order=1;

            // Determine if there were rows returned
            if (mysqli_num_rows($topLevelRows)!=0) {
                // Loop through the returned results
                while ($topLevelRow=mysqli_fetch_array($topLevelRows)){
                    // Assign the machine name.  It does not matter if it is assigned 
                    // multiple times. It should be the same every time.
                    $machineName=$topLevelRow["MachineName"];
                    
                    // Create a query to determine if there multiple slots with the same tool
                    $sql='SELECT COUNT(t2.ToolID) AS SameToolsAmount, ' . 
                         'GROUP_CONCAT(asst2.Position ORDER BY asst2.Position ASC SEPARATOR ", ") AS Positions ' .
                         'FROM assignedtools asst2 ' .
                         'LEFT JOIN tools t2 ON asst2.CurrentToolID = t2.ToolID ' .
                         'LEFT JOIN machines m2 ON asst2.MachineID = m2.MachineID ' .
                         'WHERE asst2.MachineID=' . $topLevelRow["MachineID"] . ' ' .
                         'AND asst2.ExposedLength=' . $topLevelRow["ExposedLength"] . ' ' .
                         'AND asst2.CurrentToolID=' . $topLevelRow["ToolID"] . ' ' .
                         'GROUP BY t2.ToolID';
                    
                    // Query the database for the tools 
                    $amountOfSameToolsRow = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 2");

                    // Determine if the query returned a result
                    $numberOfSameToolsInMachineHTML='';
                    if ($amountOfSameToolsRow!=null && mysqli_num_rows($amountOfSameToolsRow)==1){
                        // Get the current task row to work with as the assoc style
                        $amountOfSameToolsAssRow = $amountOfSameToolsRow->fetch_assoc();
                        
                        // Determine if there are more than one tool in the machine of the same name
                        if ($amountOfSameToolsAssRow["SameToolsAmount"]>1){
                            // Create a label informing them of multiple tools
                            $numberOfSameToolsInMachineHTML='<br><strong><label style="color:Yellow;">Duplicate Positions (' . $amountOfSameToolsAssRow["Positions"] . ')</label></strong>';
                        }
                    }
                    
                    // init loop variables
                    $acceptButtonRowHTML = '';
                    $titlePopupText = '';
                    $acceptButtonPopupText = '';
                    $ifNotEmptyHTML='';
                    $exposedLengthHTML = '';
                    $removeAfterCSS = '';
                    $useNewToolCSS = '';
                    $removeAfterTitleHTML = 'Click to clear this assigned tool slot.';

                    // Determine if this will have a suggested ANG Hold class or not
                    $rowClass='';

                    // Determine if there is an exposed length
                    if ($topLevelRow["ExposedLength"]!=0) {
                        // Color the exposed length
                        $exposedLengthHTML = 'style="background-color: Yellow;"';
                    }

                    // Determine if We are supposed to remove after use
                    if ($topLevelRow["RemoveAfterUse"]!=0) {
                        // Color the button
                        $removeAfterCSS = 'style="background-color: Yellow;"';

                        // Change the text
                        $removeAfterTitleHTML = 'This tool should be removed after use. ' .
                                                'Click to clear this assigned tool slot.';
                    }

                    // Determine if We are supposed to use a brand new tool
                    $newToolPopupText = '';
                    $newToolButtonText = '';
                    if ($topLevelRow["SuggestedUseNewTool"]!=0) {
                        // Color the button
                        $useNewToolCSS = 'background-color: Yellow;';

                        // Add text to the informational on hover and clicks
                        $newToolPopupText = '*** A brand new tool should be used ***&#013;&#013;';
                        $newToolButtonText = '*** A brand new tool should be used ***\n\n';
                    }
                    
                    // Determine if We have a suggested note
                    $suggestedNotePopupText = '';
                    $suggestedNoteButtonPopupText = '';
                    if ($topLevelRow["SuggestedNote"]!=null && $topLevelRow["SuggestedNote"]!='') {
                        // Add text to the informational on hover and clicks
                        $suggestedNotePopupText = '*** Important Notes: ' . str_replace("\r\n", '&#013;&#013;', $topLevelRow["SuggestedNote"]) . ' ***&#013;&#013;';
                        $suggestedNoteButtonPopupText = '*** Important Notes: ' . str_replace("\r\n", '\n', $topLevelRow["SuggestedNote"]) . ' ***\n\n';
                    }
                    
                    // Determine if the exposed length needs to be called out to them
                    $suggestedExposedPopupText = '';
                    $suggestedExposedButtonPopupText = '';
                    if ($topLevelRow["SuggestedExposedLength"]!=null && $topLevelRow["SuggestedExposedLength"]>0) {
                        // Add text to the informational on hover and clicks
                        $suggestedExposedPopupText = '*** REQUIRED EXPOSED LENGTH: ' . $topLevelRow["SuggestedExposedLength"] . ' ***&#013;&#013;';
                        $suggestedExposedButtonPopupText = '*** REQUIRED EXPOSED LENGTH: ' . $topLevelRow["SuggestedExposedLength"] . ' ***\n\n';
                    }
                    
                    // Determine if there is any important information
                    $importantInfoPopupText='';
                    $importantInfoButtonText='';
                    if ($newToolPopupText!='' || $suggestedNotePopupText!='' || $suggestedExposedPopupText!=''){
                        // set the iportant info as the culmination of the three
                        $importantInfoPopupText = $newToolPopupText . $suggestedNotePopupText . $suggestedExposedPopupText;
                        $importantInfoButtonText = $newToolButtonText . $suggestedNoteButtonPopupText . $suggestedExposedButtonPopupText;
                    }
                    
                    // Determine if this slot is NOT empty
                    if ($topLevelRow["CurrentToolID"]!=-1){
                        // Add the buttons that should be there if not empty
                        $ifNotEmptyHTML='
                                        <td>
                                            <button type="button" title="This will replace the tool currently in this slot with a new one to keep track of time in the machine."
                                             style="font-size:14px;"
                                             onclick="alert(\'Be sure to place a new tool of the same type in this slot.\'); 
                                             window.location = \'redirectors/replace_assignedtool.php?replaceAssignedToolPosition=' .
                                             $topLevelRow["Position"] . '&replaceAssignedToolMachineID=' . $topLevelRow["MachineID"] . '\';"/>↺</button> 
                                        </td>
                                        <td>
                                            <button type="button" title="This will clear this assigned tool from this slot on this machine."
                                             style="font-size:14px;"
                                             onclick="if (confirm(\'Are you sure you want to clear this assigned tool?.\')){ 
                                             window.location = \'redirectors/clear_assignedtool.php?clearAssignedToolPosition=' .
                                             $topLevelRow["Position"] . '&clearAssignedToolMachineID=' . $topLevelRow["MachineID"] . '\';}"/>X</button> 
                                        </td>
                                        ';

                    }

                    // Determine if this will have a suggested class or not
                    if ($topLevelRow["SuggestedChangeNewToolID"]>0 || 
                        $topLevelRow["SuggestedUseNewTool"]!=0){
                        // This one is suggested only
                        $rowClass=' suggestedBackground';

                        // Create a second level row to requery the database on
                        $sql = 'SELECT t.*, tt.Name AS ToolTypeName ' .
                               'FROM tools t ' . 
                               'LEFT OUTER JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                               'WHERE t.ToolID = ' . $topLevelRow["SuggestedChangeNewToolID"];

                        // Query the database for the tools 
                        $secondLevelRow = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 2");

                        // Determine if the query returned a result
                        if ($secondLevelRow!=null){
                            // Get the current task row to work with as the assoc style
                            $secondLevelAssRow = $secondLevelRow->fetch_assoc();

                            // Create the popup texts
                            $titlePopupText = "Important Information!! &#013;&#013;" . 
                                            $importantInfoPopupText .
                                            "Clicking this will place a NEW tool with characteristics &#013;&#013;" .
                                            " Amount: " . $secondLevelAssRow["Amount"] . "&#013;" . 
                                            " Brand: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["Brand"]==null?'':$secondLevelAssRow["Brand"]))) . "&#013;" . 
                                            " Part Number: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["PartNumber"]==null?'':$secondLevelAssRow["PartNumber"]))) . "&#013;" . 
                                            " Diameter: " . $secondLevelAssRow["Diameter"] . "&#013;" . 
                                            " Cutting Length: " . $secondLevelAssRow["CuttingLength"] . "&#013;" . 
                                            " Total Length: " . $secondLevelAssRow["TotalLength"] . "&#013;" . 
                                            " Corner Radius: " . $secondLevelAssRow["Radius"] . "&#013;" . 
                                            " Angle: " . $secondLevelAssRow["Angle"] . "&#013;" . 
                                            " Flute Number: " . $secondLevelAssRow["FluteNumber"] . "&#013;" . 
                                            " Type: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["ToolTypeName"]==null?'':$secondLevelAssRow["ToolTypeName"]))) . "&#013;" . 
                                            " Name: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["Name"]==null?'':$secondLevelAssRow["Name"]))) . "&#013;" . 
                                            " into this position of this machine in the database.";
                            $acceptButtonPopupText = "Clicking this will place a NEW tool with characteristics \\n\\n" .
                                            $importantInfoButtonText . 
                                            " Amount in Stock: " . $secondLevelAssRow["Amount"] . "\\n" . 
                                            " Brand: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["Brand"]==null?'':$secondLevelAssRow["Brand"]))) . "\\n" . 
                                            " Part Number: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["PartNumber"]==null?'':$secondLevelAssRow["PartNumber"]))) . "\\n" . 
                                            " Diameter: " . $secondLevelAssRow["Diameter"] . "\\n" . 
                                            " Cutting Length: " . $secondLevelAssRow["CuttingLength"] . "\\n" . 
                                            " Total Length: " . $secondLevelAssRow["TotalLength"] . "\\n" . 
                                            " Corner Radius: " . $secondLevelAssRow["Radius"] . "\\n" . 
                                            " Angle: " . $secondLevelAssRow["Angle"] . "\\n" . 
                                            " Flute Number: " . $secondLevelAssRow["FluteNumber"] . "\\n" . 
                                            " Type: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["ToolTypeName"]==null?'':$secondLevelAssRow["ToolTypeName"]))) . "\\n" . 
                                            " Name: " . str_replace("\"","",(str_replace("'","",$secondLevelAssRow["Name"]==null?'':$secondLevelAssRow["Name"]))) . "\\n" . 
                                            " into this position of this machine in the database.";
                        }

                        // Create the accept button HTML
                        $acceptButtonRowHTML = '<tr style="text-align: center; vertical-align: middle;">
                                                    <td colspan=3 style="text-align: center; vertical-align: middle;">
                                                        <button type="button" title="' . $titlePopupText . '" style="font-size:14px; background-color: red;"
                                                         onclick="window.location = \'redirectors/accept_suggestedtool.php?acceptAssignedToolPosition=' .
                                                         $topLevelRow["Position"] . '&acceptAssignedToolMachineID=' . $topLevelRow["MachineID"] .  
                                                         '&acceptAssignedToolMachineName=' . $topLevelRow["MachineName"] . '&acceptSuggestedChangeNewToolID=' . 
                                                         $topLevelRow["SuggestedChangeNewToolID"] . '\';"/>✔</button> 
                                                             
                                                        <button type="button" name="acceptQuery" id="acceptQuery" style="font-size:14px;" title="What will happen if I accept.." onclick="javascript:alert(\'' . $acceptButtonPopupText . '\');">?</button>                                            
                                                    </td>
                                                </tr>';
                    }

                    // Determine if this is a common tool
                    if ($topLevelRow["CommonTool"]==1){
                        // This one is common
                        $rowClass=' commonToolBackground';
                    }

                    // Set the color of the main row
                    $color = $topLevelRow["ToolTypeRowColor"];
                    
                    // assume the update cell is meant to be the same color as the main row
                    $updateCellColor = $color;

                    // Determine if we have things that need to change the update cell background to white
                    if ($rowClass!=""){
                        // White is a good color
                        $updateCellColor = 'white';
                    }

                    // determine if this user has update privileges
                    if ($userRow["UserLevel"] == "SU" ||
                        $userRow["UserLevel"] == "EXECUTIVE" ||
                        $userRow["UserLevel"] == "MANAGEMENT" ||
                        $userRow["UserLevel"] == "MID-MANAGEMENT" ||
                        $userRow["UserLevel"] == "TYPICAL"){
                        // They have edit privileges and this is for the tools list
                        $editPrivilegesRowHTML = 
                                '        <div class="cell updateCell' . $rowClass . '" style="background-color: ' . $updateCellColor . ';">
                                            <span>
                                                <table>
                                                    <tr>
                                                    ' .
                                                    $ifNotEmptyHTML
                                                    . '
                                                        <td>
                                                            <button type="button" title="Edit this assigned tool." style="font-size:14px;"
                                                             onclick="window.location = \'updateAssignedTool.php?updateAssignedToolPosition=' .
                                                             $topLevelRow["Position"] . '&updateAssignedToolMachineID=' . $topLevelRow["MachineID"] . 
                                                             '\';"/>...</button> 
                                                        </td>
                                                    </tr>'
                                                    .
                                                    $acceptButtonRowHTML
                                                    .
                                                '</table>
                                            </span>
                                        </div>';
                    }

                    // Setup the result to send back to the user
                    $result = $result .
                        '<li id="Tool_' . $order . '" class="ui-state-default Table">
                            <div class="Row" style="background-color: '. $color . ';">
                                <div class="cell assignedToolsPositionCell">
                                    <span>
                                        <p>' . $topLevelRow["Position"] . '</p>
                                    </span>
                                </div>
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . trim($topLevelRow["Name"]) . $numberOfSameToolsInMachineHTML . '</p>
                                    </span>
                                </div>
                                <div class="cell brandCell">
                                    <span>
                                        <p>' . trim($topLevelRow["Brand"]) . '</p>
                                    </span>
                                </div>
                                <div class="cell pnCell">
                                    <span>
                                        <p>' . $topLevelRow["PartNumber"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsDiameterCell">
                                    <span>
                                        <p>' . $topLevelRow["Diameter"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsCuttingLengthCell">
                                    <span>
                                        <p>' . $topLevelRow["CuttingLength"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsCornerRadiusCell">
                                    <span>
                                        <p>' . $topLevelRow["Radius"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsAngleCell">
                                    <span>
                                        <p>' . $topLevelRow["Angle"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsFluteNumberCell">
                                    <span>
                                        <p>' . $topLevelRow["FluteNumber"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsTypeCell">
                                    <span>
                                        <p>' . $topLevelRow["ToolTypeName"] . '</p>
                                    </span>
                                </div>
                                <div class="cell assignedToolsExposedLengthCell" ' . $exposedLengthHTML . '>
                                    <span>
                                        <p>' . $topLevelRow["ExposedLength"] . '</p>
                                    </span>
                                </div>'
                                .
                                $editPrivilegesRowHTML 
                                .
                            '</div>
                        </li>';

                        // Increment the order
                        $order=$order+1;
                }
            }
            else {
                // Inform the user that there are no tools for this 
                echo '<script type="text/javascript">alert("There are no tools for this machine.  Closing tool page.");</script>';

                // Close the page
                echo '<script type="text/javascript">window.close();</script>';
            }
            
            // determine if this use has update privileges
            if ($userRow["UserLevel"] == "SU" ||
                $userRow["UserLevel"] == "EXECUTIVE" ||
                $userRow["UserLevel"] == "MANAGEMENT" || 
                $userRow["UserLevel"] == "MID-MANAGEMENT" ||
                $userRow["UserLevel"] == "TYPICAL"){
                // They have edit privileges
                $editPrivilegesTableHTML =
                        '<div class="cell updateCell">
                            <p><b>Edit</b></p>
                        </div>';
            }

            // Initialize the return
            $result =   
                  '
                  Machine Name: ' . $machineName . '
                  <li class="ui-state-default ui-state-disabled Table"> 
                       <div class="Heading">
                        <div class="cell assignedToolsPositionCell">
                            <p><b>#</b></p>
                        </div>
                        <div class="cell nameCell">
                            <p><b>Name</b></p>
                        </div>
                        <div class="cell brandCell">
                            <p><b>Brand</b></p>
                        </div>
                        <div class="cell pnCell">
                            <p><b>Part Number</b></p>
                        </div>
                        <div class="cell assignedToolsDiameterCell">
                            <p><b>Diameter</b></p>
                        </div>
                        <div class="cell assignedToolsCuttingLengthCell">
                            <p><b>Cutting Length</b></p>
                        </div>
                        <div class="cell assignedToolsCornerRadiusCell">
                            <p><b>Corner Radius</b></p>
                        </div>
                        <div class="cell assignedToolsAngleCell">
                            <p><b>Angle</b></p>
                        </div>
                        <div class="cell assignedToolsFluteNumberCell">
                            <p><b>Flute #</b></p>
                        </div>
                        <div class="cell assignedToolsTypeCell">
                            <p><b>Type</b></p>
                        </div>
                        <div class="cell assignedToolsExposedLengthCell">
                            <p><b>Exposed Length</b></p>
                        </div>'
                        .
                        $editPrivilegesTableHTML 
                        .
                    '</div>
                </li>' . $result;
            
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function retrieveToolsAsListForAssigned($db, $userRow){
        $editPrivilegesTableHTML = '';
        $editPrivilegesRowHTML = '';
        $pageToReturnTo = '';
        $sort = ' t.Diameter, t.CuttingLength, t.FluteNumber, t.Brand';
        
        // determine if this use has update privileges
        if ($userRow["UserLevel"] == "SU" ||
            $userRow["UserLevel"] == "EXECUTIVE" ||
            $userRow["UserLevel"] == "MANAGEMENT" ||
            $userRow["UserLevel"] == "MID-MANAGEMENT" ||
            $userRow["UserLevel"] == "TYPICAL"){
            // They have edit privileges
            $editPrivilegesTableHTML =
                    '<div class="cell updateCell">
                        <p><b>Select</b></p>
                    </div>';
        }

        // Initialize the return
        $result = 
            'Type: ' .
            getToolTypeHTML($db, $userRow, 'typeForAll', $type, 1, 'javascript:displayCorrectTypesAll();', 1) .
            '<br><br>
            <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell nameCell">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell brandCell">
                        <p><b>Brand</b></p>
                    </div>
                    <div class="cell pnCell">
                        <p><b>Part Number</b></p>
                    </div>
                    <div class="cell toolsDiameterCell">
                        <p><b>Diameter</b></p>
                    </div>
                    <div class="cell toolsCuttingLengthCell">
                        <p><b>Cutting Length</b></p>
                    </div>
                    <div class="cell toolsCornerRadiusCell">
                        <p><b>Corner Radius</b></p>
                    </div>
                    <div class="cell toolsAngleCell">
                        <p><b>Angle</b></p>
                    </div>
                    <div class="cell toolsFluteNumberCell">
                        <p><b>Flute #</b></p>
                    </div>
                    <div class="cell toolsTypeCell">
                        <p><b>Type</b></p>
                    </div>'
                    .
                    $editPrivilegesTableHTML 
                    .
                '</div>
            </li>';

        try {
            // Setup the query to get all tools available
            $sql='SELECT t.* , tt.Name AS ToolTypeName, tt.RowColor AS ToolTypeRowColor, tt.CategoryName ' . 
                 'FROM tools t ' . 
                 'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
                 'LEFT OUTER JOIN ' . 
                 '( SELECT count(*) AS AmountAssignedTo, CurrentToolID FROM assignedtools ' . 
                    'GROUP BY CurrentToolID ) ct ON t.ToolID = ct.CurrentToolID ' . 
                    'WHERE tt.CategoryName="TOOL"' .
                    'ORDER BY ToolTypeName ASC,' . $sort . ';';
            
            // Query the database for the tools 
            $rows = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 4");

            // Set the order to start with 1
            $order=1;

            //Set the current type to nothing
            $loopToolType='';

            // Loop through the returned results
            while ($row=mysqli_fetch_array($rows)){
                // Setup a return string
                $toolDescTextarea = "Amount in Stock: " . $row["Amount"] . 
                                    "||Brand: " . str_replace("\"","",(str_replace("'","",$row["Brand"]==null?'':$row["Brand"]))) . 
                                    "||Part Number: " . str_replace("\"","",(str_replace("'","",$row["PartNumber"]==null?'':$row["PartNumber"]))) . 
                                    "||Diameter: " . $row["Diameter"] . 
                                    "||Cutting Length: " . $row["CuttingLength"] . 
                                    "||Corner Radius: " . $row["Radius"] . 
                                    "||Angle: " . $row["Angle"] . 
                                    "||Flute Number: " . $row["FluteNumber"] . 
                                    "||Type: " . str_replace("\"","",(str_replace("'","",$row["ToolTypeName"]==null?'':$row["ToolTypeName"]))) . 
                                    "||Exposed Length: " . $row["ExposedLength"] . 
                                    "||Shank Length: " . $row["ShankLength"] . 
                                    "||Total Length: " . $row["TotalLength"] . 
                                    "||Shoulder Length: " . $row["ShoulderLength"] . 
                                    "||Taper Angle: " . $row["TaperAngle"] . 
                                    "||Shank Diameter: " . $row["ShankDiameter"] . 
                                    "||Assigned Notes: " . preg_replace( "/\r|\n/", " ", str_replace("\"","",(str_replace("'","",$row["Notes"]==null?'':$row["Notes"]))));

                // Assign the delete button attributes as though deletion is an option
                $deleteButtonTextColor = 'LIMEGREEN';
                $deleteButtonTitle = 'Remove this tool.';
                $deleteButtonOnClick = 'onclick="return confirm(\'Are you sure you want to delete this tool?\');"';

                // Determine if this tool is assigned to any machines
                if ($row["AmountAssignedTo"]!=null){
                    // Assign the delete buttons attributes such that deletion will not happen
                    $deleteButtonTextColor = 'RED';
                    $deleteButtonTitle = 'Check what machines this tool may be assigned to.';
                    $deleteButtonOnClick = '';
                }

                // Set the color to be whatever is set for this particular type of tool
                $color=$row["ToolTypeRowColor"];
                
                // determine if this user has update privileges
                if ($userRow["UserLevel"] == "SU" ||
                    $userRow["UserLevel"] == "EXECUTIVE" ||
                    $userRow["UserLevel"] == "MANAGEMENT" ||
                    $userRow["UserLevel"] == "MID-MANAGEMENT" ||
                    $userRow["UserLevel"] == "TYPICAL"){
                    // They have edit privileges and this is for the selecting
                    $editPrivilegesRowHTML = 
                            '        <div class="cell updateCell">
                                        <span>
                                            <table>
                                                <tr>
                                                    <td>
                                                        <button type=button onclick="javascript:selectionResultDesc=\'' . $toolDescTextarea . '\'; selectionResultID=\'' . $row["ToolID"] . '\'; newToolSelected();" title="Choose a this tool as the selected tool for the position.">Select</button>
                                                    </td>
                                                </tr>
                                            </table>
                                        </span>
                                    </div>';
                }

                // Determine if the loop type is different than the last one
                if ($loopToolType!=$row["ToolTypeID"]){
                    // Determine if this is NOT the first type
                    if ($loopToolType!=''){
                        // Finish the last type div
                        $result = $result . '</DIV>';
                    }

                    // Set the type we are keeping track of as the new type
                    $loopToolType=$row["ToolTypeID"];

                    // set the ID to have underscores where spaces are
                    $id = str_replace(" ", "_", $loopToolType);

                    // Set the name of the new type as the ID
                    $result = $result . '<DIV id="' . $id . '">';
                }

                // Setup the result to send back to the user
                $result = $result .
                            '<li id="Tool_' . $order . '" class="ui-state-default Table">
                                <div class="Row" style="background-color: '. $color . ';">
                            <div class="cell nameCell">
                                <span>
                                    <p>' . $row["Name"] . '</p>
                                </span>
                            </div>
                            <div class="cell brandCell">
                                <span>
                                    <p>' . $row["Brand"] . '</p>
                                </span>
                            </div>
                            <div class="cell pnCell">
                                <span>
                                    <p>' . $row["PartNumber"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsDiameterCell">
                                <span>
                                    <p>' . $row["Diameter"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsCuttingLengthCell">
                                <span>
                                    <p>' . $row["CuttingLength"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsCornerRadiusCell">
                                <span>
                                    <p>' . $row["Radius"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsAngleCell">
                                <span>
                                    <p>' . $row["Angle"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsFluteNumberCell">
                                <span>
                                    <p>' . $row["FluteNumber"] . '</p>
                                </span>
                            </div>
                            <div class="cell toolsTypeCell">
                                <span>
                                    <p>' . $row["ToolTypeName"] . '</p>
                                </span>
                            </div>'
                            .
                            $editPrivilegesRowHTML 
                            .
                        '</div>
                    </li>';

                // Determine if the loop type is different than the last one
                if ($loopToolType!=$row["ToolTypeID"]){
                    // End the DIV Set the name of the type as the ID
                    $result = $result . '<DIV id="' . $loopToolType . '"';
                }

                // Increment the order
                $order=$order+1;
            }

            // Determine if the loop did the loopty loop
            if ($loopToolType!=''){
                // Finish the last type div
                $result = $result . '</DIV>';
            }


        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getToolFullDescription($db, $userRow, $toolID, $suggested){
        // Determine if the user editing is in the super company and of correct privileges
        if (
                $userRow["CompanyID"]!=1 &&
                ($userRow["UselLevel"]=="SU" ||
                 $userRow["UselLevel"]=="EXECUTIVE" ||
                 $userRow["UselLevel"]=="MANAGEMENT"
                )
           ){
            // We should not even be in here if we are not a SU
            return;
        }

        // Determine if this is a suggested tool
        $suggestedHTML='';
        if ($suggested){
            // Set something to let them know that this tool is suggested and new to be setup
            $suggestedHTML = "\nINFO: NEW suggested tool to be setup.";
        }

        // Create the query to get the the assigned tool
        $sql = 'SELECT t.*, tt.Name AS ToolTypeName ' .
               'FROM tools t ' . 
               'LEFT JOIN tooltype tt ON t.ToolTypeID = tt.ToolTypeID ' .
               'WHERE t.ToolID = ' . $toolID . ';';

        // Attempt to get the assigned tool row
        $toolRow = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 5");

        // Attempt to get the assigned tool ass row
        $toolAssocRow = $toolRow->fetch_assoc();

        // Setup a return string
        $returnString = $suggestedHTML . 
                        "\nAmount: " . $toolAssocRow["Amount"] . 
                        "\nType: " . $toolAssocRow["ToolTypeName"] . 
                        "\nBrand: " . $toolAssocRow["Brand"] . 
                        "\nPart Number: " . $toolAssocRow["PartNumber"] . 
                        "\nFluteNumber: " . $toolAssocRow["FluteNumber"] . 
                        "\nCutting Length: " . $toolAssocRow["CuttingLength"] . 
                        "\nShank Length: " . $toolAssocRow["ShankLength"] . 
                        "\nDiameter: " . $toolAssocRow["Diameter"] . 
                        "\nTotal Length: " . $toolAssocRow["TotalLength"] . 
                        "\nShoulder Length: " . $toolAssocRow["ShoulderLength"] . 
                        "\nAngle: " . $toolAssocRow["Angle"] . 
                        "\nRadius: " . $toolAssocRow["Radius"] . 
                        "\nTaper Angle: " . $toolAssocRow["TaperAngle"] . 
                        "\nShank Diameter: " . $toolAssocRow["ShankDiameter"];

        return $returnString;
    }

    function getAssignedTool($db, $userRow, $machineNumber, $positionNumber){
        // Determine if the user editing is in the super company and of correct privileges
        if (
                $userRow["CompanyID"]!=1 &&
                ($userRow["UselLevel"]=="SU" ||
                 $userRow["UselLevel"]=="EXECUTIVE" ||
                 $userRow["UselLevel"]=="MANAGEMENT"
                )
           ){
            // We should not even be in here if we are not a SU
            return;
        }

        // Create the query to get the the assigned tool
        $sql = 'SELECT asst.*, m.Name AS MachineName ' .
               'FROM assignedtools as asst ' . 
               'INNER JOIN machines m ON asst.MachineID = m.MachineID ' .
               'WHERE asst.MachineID = ' . $machineNumber . ' ' .
               'AND asst.Position = ' . $positionNumber . ';';

        // Attempt to get the assigned tool row
        $assignedToolRow = $db->queryDB($sql, $userRow, "toollists_presentation Form occurance 7");

        // Attempt to get the assigned tool ass row
        $assignedToolAssocRow = $assignedToolRow->fetch_assoc();

        $currentToolID = $assignedToolAssocRow["CurrentToolID"];
        $machineName = $assignedToolAssocRow["MachineName"];
        $suggestedChangeNewToolID = $assignedToolAssocRow["SuggestedChangeNewToolID"];
        $notes = $assignedToolAssocRow["Notes"];
        $exposedLength = $assignedToolAssocRow["ExposedLength"];
        $loadedOn = $assignedToolAssocRow["LoadedOn"];
        $commonTool = $assignedToolAssocRow["CommonTool"];
        $removeAfter = $assignedToolAssocRow["RemoveAfterUse"];
        $removeSuggestedAfter = $assignedToolAssocRow["SuggestedRemoveToolAfterUse"];
        $suggestedExposedLength = $assignedToolAssocRow["SuggestedExposedLength"];
        $suggestedNote = $assignedToolAssocRow["SuggestedNote"];
        $suggestedUseNewTool = $assignedToolAssocRow["SuggestedUseNewTool"];
        

        $toolHTML = '';
        $suggestedToolHTML = '';
        $commonToolHTML = '';
        $removeAfterHTML = '';
        $suggestedUseNewToolHTML = '';

        // Determine if they want this as a common tool
        if ($commonTool==1){
            // Assign it as checked
            $commonToolHTML='checked';
        }

        // Determine if we are to remove after use
        if ($removeAfter==1){
            // Assign it as checked
            $removeAfterHTML='checked';
        }

        // Determine if we are suggested to remove after use
        if ($removeSuggestedAfter==1){
            // Assign it as checked
            $removeSuggestedAfterHTML='checked';
        }

        // Determine if we are suggested to use a new tool
        if ($suggestedUseNewTool==1){
            // Assign it as checked
            $suggestedUseNewToolHTML='checked';
        }

        // Determine if there is a suggested tool
        If ($currentToolID != null &&
            $currentToolID > 0){
            // Get the tool info as not setup
            $toolHTML = getToolFullDescription($db, $userRow, $currentToolID, false);
        }

        // Determine if there is a suggested tool
        If ($suggestedChangeNewToolID != null &&
            $suggestedChangeNewToolID > 0){
            // Get the tool info as not setup
            $suggestedToolHTML = getToolFullDescription($db, $userRow, $suggestedChangeNewToolID, true);
        }

        return '
            <form action="updateAssignedTool.php?updateAssignedToolPosition=' . $positionNumber . 
                '&updateAssignedToolMachineID=' . $machineNumber . '" method="post" name="updateAssignedTool" enctype="multipart/form-data">  
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr align="left" valign="top">
                        <td width="58%">
                            <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                <tr>
                                  <td colspan=1 height="30" align="right" valign="middle">
                                        <strong>Machine Name: </strong>&nbsp; &nbsp; 
                                  </td>
                                  <td colspan=2 height="30" align="left" valign="middle">
                                        <input name="machineName" type="text" class="intext" maxlength="30" style="width: 100%; height: 19px" value="' . $machineName . '" disabled>
                                        <input type="hidden" name="updateAssignedToolMachineID" value="' . $machineNumber . '">
                                  </td>
                                </tr>
                                <tr>
                                  <td colspan=1 height="30" align="right" valign="middle">
                                        <strong>Position: </strong>&nbsp; &nbsp; 
                                  </td>
                                  <td colspan=2 height="30" align="left" valign="middle">
                                        <input name="updateAssignedToolPosition" type="text" maxlength="4" class="intext" style="width: 100%; height: 19px" value="' . $positionNumber . '" disabled>
                                  </td>
                                </tr>
                                <tr>
                                  <td colspan=1 height="30" align="right" valign="middle">
                                        <strong>Loaded On: </strong>&nbsp; &nbsp; 
                                  </td>
                                  <td colspan=2 height="30" align="left" valign="middle">
                                        <input name="LoadedOn" id="LoadedOn" type="date" class="intext" style="width: 100%;" value="' . $loadedOn . '" disabled>
                                        <input name="LoadedOnOriginal" id="LoadedOnOriginal" type="hidden" value="' . $loadedOn . '">
                                  </td>
                                </tr>
                                <tr>
                                  <td colspan=1 height="30" align="right" valign="middle">
                                        <strong>Exposed Length: </strong>&nbsp; &nbsp; 
                                  </td>
                                  <td colspan=2 height="30" align="left" valign="middle">
                                        <input name="ExposedLength" id="ExposedLength" type="text" maxlength="15" class="intext" style="width: 100%; height: 19px" value="' . $exposedLength . '">
                                        <input name="ExposedLengthOriginal" id="ExposedLengthOriginal" type="hidden" value="' . $exposedLength . '">
                                  </td>
                                </tr>
                                <tr> 
                                  <td colspan=1 width="45%" height="30" align="left" valign="middle">
                                        <strong>Remove After Use: </strong>
                                        <input name="RemoveAfter" id="RemoveAfter" type="checkbox" ' . $removeAfterHTML . '></input>
                                        <input name="RemoveAfterOriginal" id="RemoveAfterOriginal" type="hidden" value="' . $removeAfter . '">
                                  </td>
                                  <td colspan=1 width="10%" height="30" align="center" valign="middle">
                                  </td>
                                  <td colspan=1 width="45%" height="30" align="left" valign="middle">
                                        <strong>Common Tool: </strong>
                                        <input name="CommonTool" id="CommonTool" type="checkbox" ' . $commonToolHTML . '></input>
                                        <input name="CommonToolOriginal" id="CommonToolOriginal" type="hidden" value="' . $commonTool . '">
                                  </td>
                                </tr>
                            </table>
                        </td>
                        <td width="4%">&nbsp;</td>
                        <td width="38%">
                            <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                <tr>
                                    <td width="100%"><strong>Assigned Tool Notes (1000 characters)</strong><br> 
                                        <textarea name="Notes" id="Notes" maxlength="1000" class="intext" style="resize:vertical; width: 100%; height: 140px; overflow: auto;">' .
                                        $notes .
                                        '</textarea>
                                    </td>
                                    <input name="NotesOriginal" id="NotesOriginal" type="hidden" value="' . $notes . '">
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                      <td colspan=3 align="center" style="width:100%">
                        <table style="width:100%">
                            <tr style="width:100%">
                                <td style="width:50%">
                                    <strong>Current Tool</strong>
                                </td>
                                <td style="width:50%">
                                    <strong>Suggested Change Tool</strong>
                                </td>
                            </tr>
                            <tr style="width:100%">
                                <td style="width:50%">
                                    <textarea name="CurrentToolDescription" id="CurrentToolDescription" class="intext" style="width: 100%; height: 230px; overflow: auto; resize:none; border: 1px solid black;" disabled>'
                                        . 
                                        $toolHTML
                                        .
                                    '</textarea>
                                    <input type="hidden" name="CurrentToolID" id="CurrentToolID" value="' . $currentToolID . '">
                                    <textarea name="CurrentToolDescriptionOriginal" id="CurrentToolDescriptionOriginal" class="intext" style="display:none; width: 100%; height: 230px; overflow: auto; resize:none" disabled>'
                                        . 
                                        $toolHTML
                                        .
                                    '</textarea>
                                    <input type="hidden" name="CurrentToolIDOriginal" id="CurrentToolIDOriginal" value="' . $currentToolID . '">
                                </td>
                                <td style="width:50%">
                                    <textarea name="SuggestedChangeDescription" id="SuggestedChangeDescription" class="intext" style="width: 100%; height: 230px; overflow: auto; resize:none; border: 1px solid black;" disabled>'
                                        . 
                                        $suggestedToolHTML
                                        .
                                    '</textarea>
                                    <input type="hidden" name="SuggestedChangeNewToolID" id="SuggestedChangeNewToolID" value="' . $suggestedChangeNewToolID . '">
                                    <textarea name="SuggestedChangeDescriptionOriginal" id="SuggestedChangeDescriptionOriginal" class="intext" style="display:none; width: 100%; height: 230px; overflow: auto; resize:none" disabled>'
                                        . 
                                        $suggestedToolHTML
                                        .
                                    '</textarea>
                                    <input type="hidden" name="SuggestedChangeNewToolIDOriginal" id="SuggestedChangeNewToolIDOriginal" value="' . $suggestedChangeNewToolID . '">
                                </td>
                            </tr>
                            <tr style="width:100%">
                                <td colspan=1 height="30" align="left" valign="center" style="width:50%">
                                    <strong>Change: </strong>
                                    <button type="button" style="font-size: 10px;" onClick="javascript:suggestedNewTool=false; div_showAllTools();" align="right" title="Choose a different current tool.">New</button>
                                    <button type="button" style="font-size: 10px;" onClick="javascript:resetCurrentTool();" align="right" title="Clicking this will place current tool fields back to the last saved state.">Back</button>
                                    <button type="button" style="font-size: 10px;" onClick="javascript:clearCurrentTool();" align="right" title="Clicking this will clear all current tool fields.">X</button>
                                </td>
                                <td colspan=1 height="30" align="left" valign="center" style="width:50%">
                                    <strong>Change: </strong>
                                    <button type=button style="font-size: 10px;" onclick="javascript:suggestedNewTool=true; div_showAllTools();" title="Choose a different suggested tool that needs setup.">New</button>
                                    <button type="button" style="font-size: 10px;" onClick="javascript:resetSuggestedTool();" align="right" title="Clicking this will place thie suggested tool fields back to the last saved state.">Back</button>
                                    <button type="button" style="font-size: 10px;" onClick="javascript:clearSuggestedTool();" align="right" title="Clicking this will clear all suggested tool fields.">X</button>
                                </td>
                            </tr>
                            <tr style="width:100%">
                                <td colspan=1 height="30" align="left" valign="center" style="width:50%">
                                </td>
                                <td colspan=1 height="30" align="left" valign="center" style="width:50%">
                                    <div id="suggestedChangeAttributes" style="margin: 5 auto; width: 100%; display: none;">
                                        <table>
                                            <tr>
                                              <td colspan=1 width="45%" height="30" align="left" valign="middle">
                                                    <strong>Remove After Use: </strong>
                                                    <input name="RemoveSuggestedToolAfter" id="RemoveSuggestedToolAfter" type="checkbox" ' . $removeSuggestedAfterHTML . '></input>
                                                    <input name="RemoveSuggestedToolAfterOriginal" id="RemoveSuggestedToolAfterOriginal" type="hidden" value="' . $removeSuggestedAfter . '">
                                              </td>
                                              <td colspan=1 width="10%" height="30" align="left" valign="middle">
                                              </td>
                                              <td colspan=1 width="45%" height="30" align="left" valign="middle">
                                                    <strong>Use New Tool: </strong>
                                                    <input name="SuggestedUseNewTool" id="SuggestedUseNewTool" type="checkbox" ' . $suggestedUseNewToolHTML . '></input>
                                                    <input name="SuggestedUseNewToolOriginal" id="SuggestedUseNewToolOriginal" type="hidden" value="' . $suggestedUseNewTool . '">
                                              </td>
                                            </tr>
                                            <tr>
                                              <td colspan=2 width="45%" height="30" align="left" valign="bottom">
                                                    <strong><label>Required Exposed Length:</label></strong>
                                              </td>
                                              <td colspan=1 width="45%" height="30" align="left" valign="bottom">
                                                    <input name="RequiredExposedLength" id="RequiredExposedLength" type="text" maxlength="15" class="intext" style="width: 100%; height: 19px" value="' . $suggestedExposedLength . '">
                                                    <input name="RequiredExposedLengthOriginal" id="RequiredExposedLengthOriginal" type="hidden" value="' . $suggestedExposedLength . '">
                                              </td>
                                            </tr>
                                            <tr>
                                              <td colspan=3 height="30" align="left" valign="bottom">
                                                    <label><strong>Tool Note: </strong></label>
                                              </td>
                                            </tr>
                                            <tr>
                                              <td colspan=3 height="30" align="left" valign="bottom">
                                                <textarea name="SuggestedToolNote" id="SuggestedToolNote" maxlength="1000" class="intext" style="width: 100%; height: 70px; overflow: auto; resize:vertical;">' .
                                                $suggestedNote .
                                                '</textarea>
                                                <input name="SuggestedToolNoteOriginal" id="SuggestedToolNoteOriginal" type="hidden" value="' . $suggestedNote . '">
                                              </td>
                                            </tr>
                                        </table>
                                    </div>
                                </td>
                            </tr>
                        </table>
                      </td>
                    </tr>
                </table>
                <p align="right">
                    <input type="hidden" id="formSubmitted" name="formSubmitted" value="TRUE">
                    <input id="formSubmit" type="submit" style="cursor: hand; cursor: pointer;" value="Update"/>
                </p>
            </form>
            <script language="JavaScript">
                // Code for validating the form
                // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                // for details
                var frmvalidator = new Validator("updateAssignedTool", "formSubmit");
                frmvalidator.addValidation("ExposedLength",
                                           "dec",
                                           "Please enter the Exposed Length of this machine as a number.");
                frmvalidator.addValidation("ExposedLength",
                                           "greaterthan=-1",
                                           "The Exposed Length should be greater than or equal to zero.");
                frmvalidator.addValidation("RequiredExposedLength",
                                           "dec",
                                           "Please enter the Required Exposed Length of this machine as a number.");
                frmvalidator.addValidation("RequiredExposedLength",
                                           "greaterthan=-1",
                                           "The Required Exposed Length should be greater than or equal to zero.");
            </script>';
    }
    
    function copyTaskTools($db, $userRow, &$currentSuccess, $newTaskID, $taskIDToCopy=null){
        try {
            // Determine if they are currently successful as well as the proper variables are passed in
            if ($currentSuccess && 
                $taskIDToCopy!= null && $taskIDToCopy>0 && 
                $newTaskID!= null && $newTaskID>0){
                    // Create the query as if there is a parent
                    $sql='INSERT INTO tooltotasklinker (TaskID, ToolPosition, ToolID, ' . 
                            'ExposedLength, Notes, RemoveAfterUse, UseNewTool) ' . 
                          'SELECT ' . $newTaskID . ', ToolPosition, ToolID, ' . 
                            'ExposedLength, Notes, RemoveAfterUse, UseNewTool ' . 
                            'FROM tooltotasklinker ' . 
                            'WHERE TaskID=' . $taskIDToCopy . ';';

                // Attempt to update the task
                if (!$db->queryDB($sql, $userRow, "toolLists_presentation Form occurance 8")){
                    // Set all as a fail
                    $currentSuccess=false;
                }
            }
        } 
        catch (Exception $ex) {
            // Assign the output string as to what happened
            return $currentSuccess;
        } 
        finally {
            // Return the result
            return $currentSuccess;
        }
    }
?>
