<?php
    function getCCFutureYears(){
        // Get the current year
        $currentYear = date("Y");

        // Start the return with the beginning of the select
        $result='<select id=expDateYear name=expDateYear>';

        // Loop through 10 times to get tem future years in the select
        $currentLoopYear = $currentYear;
        for ($loopYear = 0 ; $loopYear < 10; $loopYear++){ 
            // Create the year to add to the drop down
            $currentLoopYear = $currentYear + $loopYear;

            // Add this option to the select
            $result = $result . '<option value=' . $currentLoopYear . '>' . $currentLoopYear . '</option>';
        }

        // End the select
        $result=$result . '</select>';

        // Return the result
        return $result;
    }

    function retrieveCompanyAndPersonalAddresses($db, $userRow){
        try {
            // Initialize variables
            $result = 
                    '<div class="Table" id="currentAddress" name="currentAddress">
                       <div class="Row">
                            <div class="cell cell1"></div>
                            <div class="cell addressCell">Address</div>
                            <div class="cell cityCell">City</div>
                            <div class="cell stateCell">State</div>
                            <div class="cell zipCell">Zip</div>
                            <div class="cell phoneCell">Phone</div>
                            <div class="cell checkCell">Remove</div>
                        </div>';
            $addressIDArray = '';

            // Setup the query to be where they only get adresses of their company
            $sql='SELECT * FROM addresses a, addresslinker al ' .
                 'WHERE a.AddressID = al.AddressID ' .
                 'AND al.CompanyID=' . $userRow["CompanyID"] . ' ' .
                 'ORDER BY a.Address1;';

            // Query the database for the addresses 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 1");

            // Loop through the returned company results
            $rowNumber = 0;                
            while ($row=mysqli_fetch_array($rows)){
                // Increment the row number
                $rowNumber++;

                // Add the attachment to the table
                $result = $result .
                    '   <div class="Row">
                            <div class="cell cell1">' . $rowNumber . '</div>
                            <div class="cell addressCell">
                                1-<input name="currentAddress1' . $row["AddressID"] . '" type="text" maxlength="150" class="intext" style="border: 0px solid; background-color: transparent; width: 220px;" value="' . $row["Address1"] . '"></input>
                                <br>
                                2-<input name="currentAddress2' . $row["AddressID"] . '" type="text" maxlength="150" class="intext" style="border: 0px solid; background-color: transparent; width: 220px;" value="' . $row["Address2"] . '"></input>
                            </div>
                            <div class="cell cityCell">
                                <input name="currentCity' . $row["AddressID"] . '" type="text" maxlength="75" class="intext" style="border: 0px solid; background-color: transparent; width: 90px;" value="' . $row["City"] . '"></input>
                            </div>
                            <div class="cell stateCell">
                                <input name="currentState' . $row["AddressID"] . '" type="text" maxlength="2" class="intext" style="border: 0px solid; background-color: transparent; width: 22px;" value="' . $row["State"] . '"></input>
                            </div>
                            <div class="cell zipCell">
                                <input name="currentZip' . $row["AddressID"] . '" type="text" maxlength="5" class="intext" style="border: 0px solid; background-color: transparent; width: 40px;" value="' . $row["Zip"] . '"></input>
                            </div>
                            <div class="cell phoneCell">
                                1-<input name="currentPhone1' . $row["AddressID"] . '" type="text" maxlength="12" class="intext" style="border: 0px solid; background-color: transparent; width: 100px;" value="' . $row["PhoneNumber1"] . '"></input>
                                <br>
                                2-<input name="currentPhone2' . $row["AddressID"] . '" type="text" maxlength="12" class="intext" style="border: 0px solid; background-color: transparent; width: 100px;" value="' . $row["PhoneNumber2"] . '"></input>
                            </div>
                            <div class="cell checkCell">
                                <input type="radio" name="addressChosenRow" onclick="handleChooseAddressClick(currentAddressesArray);" value="' . $rowNumber . '"> select
                            </div>
                        </div>';

                // Add something to the array list
                $addressIDArray = $addressIDArray . $row["AddressID"] . '|';
            }

            // Setup the query to be where they only get adresses of their company
            $sql='SELECT * FROM addresses a, addresslinker al ' .
                 'WHERE a.AddressID = al.AddressID ' .
                 'AND al.UserID=' . $userRow["UserID"] . ' ' .
                 'ORDER BY a.Address1;';

            // Query the database for the addresses 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 2");

            // Loop through the returned User results
            while ($row=mysqli_fetch_array($rows)){
                // Increment the row number
                $rowNumber++;

                // Add the attachment to the table
                $result = $result .
                    '   <div class="Row">
                            <div class="cell cell1">' . $rowNumber . '</div>
                            <div class="cell addressCell">
                                1-<input name="currentAddress1' . $row["AddressID"] . '" type="text" maxlength="150" class="intext" style="border: 0px solid; background-color: transparent; width: 220px;" value="' . $row["Address1"] . '"></input>
                                <br>
                                2-<input name="currentAddress2' . $row["AddressID"] . '" type="text" maxlength="150" class="intext" style="border: 0px solid; background-color: transparent; width: 220px;" value="' . $row["Address2"] . '"></input>
                            </div>
                            <div class="cell cityCell">
                                <input name="currentCity' . $row["AddressID"] . '" type="text" maxlength="75" class="intext" style="border: 0px solid; background-color: transparent; width: 90px;" value="' . $row["City"] . '"></input>
                            </div>
                            <div class="cell stateCell">
                                <input name="currentState' . $row["AddressID"] . '" type="text" maxlength="2" class="intext" style="border: 0px solid; background-color: transparent; width: 22px;" value="' . $row["State"] . '"></input>
                            </div>
                            <div class="cell zipCell">
                                <input name="currentZip' . $row["AddressID"] . '" type="text" maxlength="5" class="intext" style="border: 0px solid; background-color: transparent; width: 40px;" value="' . $row["Zip"] . '"></input>
                            </div>
                            <div class="cell phoneCell">
                                1-<input name="currentPhone1' . $row["AddressID"] . '" type="text" maxlength="12" class="intext" style="border: 0px solid; background-color: transparent; width: 100px;" value="' . $row["PhoneNumber1"] . '"></input>
                                <br>
                                2-<input name="currentPhone2' . $row["AddressID"] . '" type="text" maxlength="12" class="intext" style="border: 0px solid; background-color: transparent; width: 100px;" value="' . $row["PhoneNumber2"] . '"></input>
                            </div>
                            <div class="cell checkCell">
                                <input type="radio" name="addressChosenRow" onclick="handleChooseAddressClick(currentAddressesArray);" value="' . $rowNumber . '"> select
                            </div>
                        </div>';

                // Add something to the array list
                $addressIDArray = $addressIDArray . $row["AddressID"] . '|';
            }

            // Add the hidden field to the form
            $result = 
                    '<strong>Choose Billing Address: </strong>
                    <div id="currentAddresses" style="margin: 5 auto; width: 100%; ">
                        <input type="hidden" name="currentAddressesArray" id="currentAddressesArray" value="' . $addressIDArray . '"></input>
                        <input type="hidden" name="deleteCurrentAddresses" id="deleteCurrentAddresses" value=""></input>' .
                        $result .
                    '</div></div>';
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return the created HTML
        return $result;
    }
    
    function getCompanyCreditInfo($db, $userRow, $taskNumber, $disabled){
        // Initialize the return
        $result = '';

        // Init all of the settings to the appropriate values
        $taskPrice = 'TBD';
        $allowCreditPayment = true;

        // Determine if this is an update or not
        $assocTask = null;
        if ($taskNumber){
            // Create the query to get the the task and the user that created the task
            $sql = 'SELECT t.*, u.FirstName, u.LastName, c.AllowCredit ' .
                        'FROM tasks t ' . 
                        'LEFT JOIN users u ON t.CreatedByID = u.UserID ' .
                        'LEFT JOIN companies c ON c.CompanyID = u.CompanyID ' .
                        'WHERE t.TaskID=' . $taskNumber . ';';

            // Attempt to change all of the rows that need to be changed
            $row = $db->queryDB($sql, $userRow, "task_presentation Form occurance 3");

            // Attempt to get the user row
            $assocTask = $row->fetch_assoc();

            // Set the things we can
            $taskPrice = $assocTask["TaskPrice"];
            $allowCreditPayment = $assocTask["AllowCredit"];

            // Determine if the task price is null
            if ($taskPrice == null){
                // Set the task price to be showing TBD
                $taskPrice = 'TBD';
            }
        }


        // Initialize the checkbox html values
        $allowCreditHTML = false;
        $disabledHTML='';

        // Determine if we have values for the allow credit flag
        if ($allowCreditPayment != null and $allowCreditPayment==true){
            // Set it to what we got in
            $allowCreditHTML = 'checked';
        }

        // Determine if we have values for the disabled flag
        if ($disabled != null and $disabled==true){
            // Set it to what we got in
            $disabledHTML='disabled';
        }

        try {
            // If this is the executive, then allow them the option to pay with card or not
            if (($userRow["UserLevel"]=="EXECUTIVE" or $userRow["UserLevel"]=="SU") and 
                (is_numeric($taskPrice) and $taskPrice>0)){
                // Set the money format to US
                setlocale(LC_MONETARY, 'en_US');

                // Get the moneys as US dollar format
                $fee = $taskPrice*.04;
                $total = $taskPrice + $fee;
                $result='
                    <form method="POST" action="DoDirectPaymentReceipt.php" name="DoDirectPaymentForm">
                    <!--Payment type is <?=$paymentType?><br> -->
                    <input type=hidden name=paymentType value="<?php echo $paymentType?>" />
                    <table width=600>
                            <tr>
                                    <td align=right>First Name:</td>
                                    <td align=left><input type=text size=30 maxlength=32 name=firstName value=' . $userRow["FirstName"] . '></td>
                            </tr>
                            <tr>
                                    <td align=right>Last Name:</td>
                                    <td align=left><input type=text size=30 maxlength=32 name=lastName value=' . $userRow["LastName"] . '></td>
                            </tr>
                            <tr>
                                    <td align=right>Card Type:</td>
                                    <td align=left>
                                            <select name=creditCardType onChange="javascript:generateCC(); return false;">
                                                    <option value=Visa selected>Visa</option>
                                                    <option value=MasterCard>MasterCard</option>
                                                    <option value=Discover>Discover</option>
                                                    <option value=Amex>American Express</option>
                                            </select>
                                    </td>
                            </tr>
                            <tr>
                                    <td align=right>Card Number:</td>
                                    <td align=left><input type=text size=19 maxlength=19 name=creditCardNumber></td>
                            </tr>
                            <tr>
                                    <td align=right>Expiration Date:</td>
                                    <td align=left><p>
                                            <select name=expDateMonth>
                                                    <option value=1>01</option>
                                                    <option value=2>02</option>
                                                    <option value=3>03</option>
                                                    <option value=4>04</option>
                                                    <option value=5>05</option>
                                                    <option value=6>06</option>
                                                    <option value=7>07</option>
                                                    <option value=8>08</option>
                                                    <option value=9>09</option>
                                                    <option value=10>10</option>
                                                    <option value=11>11</option>
                                                    <option value=12>12</option>
                                            </select>' .
                                            getCCFutureYears() .
                                    '</p></td>
                            </tr>
                            <tr>
                                    <td align=right>Card Verification Number:</td>
                                    <td align=left><input type=text size=3 maxlength=4 name=cvv2Number></td>
                            </tr>
                            <tr>
                                    <td align=right><br><b>Billing Address:</b></td>
                            </tr>
                            <tr>
                                    <td align=right>Address 1:</td>
                                    <td align=left><input type=text size=25 maxlength=100 name=address1></td>
                            </tr>
                            <tr>
                                    <td align=right>Address 2:</td>
                                    <td align=left><input type=text  size=25 maxlength=100 name=address2>(optional)</td>
                            </tr>
                            <tr>
                                    <td align=right>City:</td>
                                    <td align=left><input type=text size=25 maxlength=40 name=city></td>
                            </tr>
                            <tr>
                                    <td align=right>State:</td>
                                    <td align=left>' .
                                        getStatesAsSelectOptions("CO") .
                                    '</td>
                            </tr>
                            <tr>
                                    <td align=right>ZIP Code:</td>
                                    <td align=left><input type=text size=10 maxlength=10 name=zip>(5 or 9 digits)</td>
                            </tr>
                            <tr>
                                    <td align=right>Country:</td>
                                    <td align=left>United States</td>
                            </tr>
                            <tr>
                                <td colspan=3>
                                    <br>' .
                                    retrieveCompanyAndPersonalAddresses($db, $userRow) .
                                '</td>
                            </tr>
                            <tr>
                                    <td align=right><br>Total:</td>
                                    <td align=left>
                                        <br>
                                        <div class="tooltip">
                                            $<input type=text size=7 maxlength=11 name=amount disabled style="text-align:center; color: blue;" value=' . sprintf('%0.2f', $total) . '> USD
                                            <span class="tooltiptext">Calculated as -->  ' . money_format('%.2n', $taskPrice) . ' (Task Price) + ' . money_format('%.2n', $fee)  . ' (4% Transaction Fee) = ' . money_format('%.2n', $total) . ' (Total)</span>
                                        </div>
                                    </td>
                                    <td align="center">
                                        <br><br>
                                        <input type=Submit value="Pay Bill">
                                    </td>
                            </tr>
                            <tr>
                                    <td colspan=3 align=center><b>(Supporting ONLY USD at this time)</b></td>
                            </tr>
                    </table>
                    </form>
                    </center>';
            }
            else {
                $result='
                        <tr>
                            <td>
                                <br>
                                <font size="3">There is not valid information to calculate a price.</font>
                                <br>
                            </td>
                        </tr>';

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

        // Return whatever we got
        return $result;
    }
    
    function getTaskBlanksInfo($db, $userRow, $taskNumber){
        // Initialize the return
        $result = '';

        // Determine if this is an update or not
        $assocTask = null;
        if ($taskNumber){
            // Create the query to all job blanks for this task number
            $sql = 'SELECT *
                    FROM jobblanks  
                    WHERE t.TaskID=' . $taskNumber . ';';

            // Attempt to change all of the rows that need to be changed
            $row = $db->queryDB($sql, $userRow, "task_presentation Form occurance 4");

            // If this is the executive, then allow them the option to pay with card or not
            if (($userRow["UserLevel"]=="EXECUTIVE" or $userRow["UserLevel"]=="SU") and 
                (is_numeric($taskPrice) and $taskPrice>0)){
                // Set the money format to US
                setlocale(LC_MONETARY, 'en_US');

                // Get the moneys as US dollar format
                $fee = $taskPrice*.04;
                $total = $taskPrice + $fee;
                $result='
                    <form method="POST" action="DoDirectPaymentReceipt.php" name="DoDirectPaymentForm">
                    <!--Payment type is <?=$paymentType?><br> -->
                    <input type=hidden name=paymentType value="<?php echo $paymentType?>" />
                    <table width=600>
                            <tr>
                                    <td align=right>First Name:</td>
                                    <td align=left><input type=text size=30 maxlength=32 name=firstName value=' . $userRow["FirstName"] . '></td>
                            </tr>
                            <tr>
                                    <td align=right>Last Name:</td>
                                    <td align=left><input type=text size=30 maxlength=32 name=lastName value=' . $userRow["LastName"] . '></td>
                            </tr>
                            <tr>
                                    <td align=right>Card Type:</td>
                                    <td align=left>
                                            <select name=creditCardType onChange="javascript:generateCC(); return false;">
                                                    <option value=Visa selected>Visa</option>
                                                    <option value=MasterCard>MasterCard</option>
                                                    <option value=Discover>Discover</option>
                                                    <option value=Amex>American Express</option>
                                            </select>
                                    </td>
                            </tr>
                            <tr>
                                    <td align=right>Card Number:</td>
                                    <td align=left><input type=text size=19 maxlength=19 name=creditCardNumber></td>
                            </tr>
                            <tr>
                                    <td align=right>Expiration Date:</td>
                                    <td align=left><p>
                                            <select name=expDateMonth>
                                                    <option value=1>01</option>
                                                    <option value=2>02</option>
                                                    <option value=3>03</option>
                                                    <option value=4>04</option>
                                                    <option value=5>05</option>
                                                    <option value=6>06</option>
                                                    <option value=7>07</option>
                                                    <option value=8>08</option>
                                                    <option value=9>09</option>
                                                    <option value=10>10</option>
                                                    <option value=11>11</option>
                                                    <option value=12>12</option>
                                            </select>' .
                                            getCCFutureYears() .
                                    '</p></td>
                            </tr>
                            <tr>
                                    <td align=right>Card Verification Number:</td>
                                    <td align=left><input type=text size=3 maxlength=4 name=cvv2Number></td>
                            </tr>
                            <tr>
                                    <td align=right><br><b>Billing Address:</b></td>
                            </tr>
                            <tr>
                                    <td align=right>Address 1:</td>
                                    <td align=left><input type=text size=25 maxlength=100 name=address1></td>
                            </tr>
                            <tr>
                                    <td align=right>Address 2:</td>
                                    <td align=left><input type=text  size=25 maxlength=100 name=address2>(optional)</td>
                            </tr>
                            <tr>
                                    <td align=right>City:</td>
                                    <td align=left><input type=text size=25 maxlength=40 name=city></td>
                            </tr>
                            <tr>
                                    <td align=right>State:</td>
                                    <td align=left>' .
                                        getStatesAsSelectOptions("CO") .
                                    '</td>
                            </tr>
                            <tr>
                                    <td align=right>ZIP Code:</td>
                                    <td align=left><input type=text size=10 maxlength=10 name=zip>(5 or 9 digits)</td>
                            </tr>
                            <tr>
                                    <td align=right>Country:</td>
                                    <td align=left>United States</td>
                            </tr>
                            <tr>
                                <td colspan=3>
                                    <br>' .
                                    retrieveCompanyAndPersonalAddresses($db, $userRow) .
                                '</td>
                            </tr>
                            <tr>
                                    <td align=right><br>Total:</td>
                                    <td align=left>
                                        <br>
                                        <div class="tooltip">
                                            $<input type=text size=7 maxlength=11 name=amount disabled style="text-align:center; color: blue;" value=' . sprintf('%0.2f', $total) . '> USD
                                            <span class="tooltiptext">Calculated as -->  ' . money_format('%.2n', $taskPrice) . ' (Task Price) + ' . money_format('%.2n', $fee)  . ' (4% Transaction Fee) = ' . money_format('%.2n', $total) . ' (Total)</span>
                                        </div>
                                    </td>
                                    <td align="center">
                                        <br><br>
                                        <input type=Submit value="Pay Bill">
                                    </td>
                            </tr>
                            <tr>
                                    <td colspan=3 align=center><b>(Supporting ONLY USD at this time)</b></td>
                            </tr>
                    </table>
                    </form>';
            }
        }

        // Return whatever we got
        return $result;
    }
    
    function getStatusAsSelectOptions($db, $userRow, $selected, $onChangeHTML, $allFieldsAccess, $onfocusHTML="", $style=""){
        // Initialize the return
        $result = '';
        try {
            // Initialize the disabled value
            $disableHTML='';

            // Create the query to run
            $sql='SELECT * FROM status ORDER BY ProcessOrder;';

            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 5");

            // If there is only one result for a username/password combo, then they are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                // Loop through the returned results
                $rowNumber = 0;

                // Setup the selected name to be nothing for now
                $selectedStatusName="";
                
                // Assume the row is a SU level row, since they are the most
                $selectedRowLevel="SU";
                        
                // Loop through the status rows
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if this is one that is to be selected
                    $selectedText='';
                    if ($selected != null and $selected==$row["StatusID"]) {
                        // Hold onto the mod level
                        $selectedRowLevel=$row["ModifyLevel"];
                        
                        // Create the selected html
                        $selectedText='selected';

                        // Set the type name equal to the one selected
                        $selectedStatusName = $row["Name"];
                        
                        // Determine if they have access to modify it or not
                        if ($userRow["CompanyID"]!=1 &&
                            ((($userRow["UserLevel"]=='TYPICAL') && 
                              ($row["ModifyLevel"]=='MINIMAL')) ||
                             (($userRow["UserLevel"]=='TYPICAL' || $userRow["UserLevel"]=='MINIMAL') && 
                              ($row["ModifyLevel"]=='MANAGEMENT')) ||
                             (($userRow["UserLevel"]=='MANAGEMENT' || $userRow["UserLevel"]=='TYPICAL' || $userRow["UserLevel"]=='MINIMAL') && 
                              ($row["ModifyLevel"]=='SU' || $row["ModifyLevel"]=='EXECUTIVE')) ||
                             (($userRow["UserLevel"]=='EXECUTIVE' || $userRow["UserLevel"]=='MANAGEMENT' || $userRow["UserLevel"]=='TYPICAL' || $userRow["UserLevel"]=='MINIMAL') && 
                              ($row["ModifyLevel"]=='SU')))){
                            // Disable the control for this person's use
                            $disableHTML='disabled';
                        }
                    }

                    // Add this option to the select
                    $result=$result . '<option value="' . $row["StatusID"] . '" ' . $selectedText . '>' . $row["Name"] . ' </option>';
                }

                // Showing a totally different thing for non editable users on status
                if ($disableHTML==='disabled' || $allFieldsAccess==='disabled'){
                    // Only need a text box to show them their status, since they cannot change their own company
                    $result='<input type="hidden" name="status" id="status" value="' . $selected . '"></input>
                             <input class="intext" name="statusName" id="statusName" type="text" style="width: 100%;" value="' . $selectedStatusName . '" ' . $disableHTML . '><br><br>';
                }
                else {
                    // Determine if this is a customer
                    if ($userRow["CompanyID"]!=1){
                        // Reset the result
                        $result="";
                        
                        // Query the database for the user 
                        $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 6");

                        // Loop through the status rows again
                        while ($row=mysqli_fetch_array($rows)){
                            // Reset the old selected text
                            $selectedText = ""; 
                            
                            // Need to find the new selected
                            if ($selected != null and $selected==$row["StatusID"]) {
                                // Create the selected html
                                $selectedText='selected';
                            }

                            // Determine the row compatibility
                            if ((($userRow["UserLevel"]=='EXECUTIVE') && 
                                 ($row["ModifyLevel"]=='EXECUTIVE' || $row["ModifyLevel"]=='MANAGEMENT' || $row["ModifyLevel"]=='TYPICAL' || $row["ModifyLevel"]=='MINIMAL')) ||
                                (($userRow["UserLevel"]=='MANAGEMENT') && 
                                 ($row["ModifyLevel"]=='MANAGEMENT' || $row["ModifyLevel"]=='TYPICAL' || $row["ModifyLevel"]=='MINIMAL')) ||
                                (($userRow["UserLevel"]=='TYPICAL') && 
                                 ($row["ModifyLevel"]=='TYPICAL' || $row["ModifyLevel"]=='MINIMAL')) ||
                                (($userRow["UserLevel"]=='MINIMAL') && 
                                 ($row["ModifyLevel"]=='MINIMAL'))){
                                // Add this option to the select
                                $result=$result . '<option value="' . $row["StatusID"] . '" ' . $selectedText . '>' . $row["Name"] . ' </option>';
                            }
                        }
                    }
                    
                    // Start the return with the beginning of the select
                    $result='<select name="status" id="status" onchange="' . 
                            $onChangeHTML . '" onfocus="' . $onfocusHTML . '" ' . 
                            $disableHTML . ' style="' . $style . '">' . $result . 
                            '</select>';
                }
                
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getMachineAsSelectOptions($db, $userRow, $selected, $onChangeHTML, $allFieldsAccess="", $variableNameToolSlotAmount=''){
        // Initialize the return
        $result = '';
        try {
            // Set there to be no variable to match tool slots to machines yet
            $toolSlotCSV='0,';
            
            // Set disabled to be whatever was passed in
            $disableHTML=$allFieldsAccess;

            // Create the query to run
            $sql = 'SELECT *, 
                           If((MachineID in (SELECT i_m.MachineID 
                                             FROM machines i_m 
                                             LEFT JOIN tasktomachinelinker i_tml ON i_m.MachineID = i_tml.MachineID 
                                             LEFT JOIN tasks i_t ON i_tml.TaskID = i_t.TaskID 
                                             LEFT JOIN status i_s ON i_t.StatusID = i_s.StatusID 
                                             WHERE i_s.Name="Machining")),"*","") AS HasMachiningTask 
                    FROM machines
                    ORDER BY Type ASC, Name;';
            
            // Query the database for the machines 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 7");

            // If there are rows then they are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                // Setup the selected name to be nothing for now
                $selectedMachineName="";
                
                // Setup a group variable to group the types of machines
                $type="";
                        
                // Loop throught eh results
                $oneSelected = false;
                while ($row=mysqli_fetch_array($rows)){
                    // determing if the group has changed
                    if ($type!=$row["Type"]){
                        // reset the type
                        $type=$row["Type"];

                        // Add the group
                        $result=$result . '<optgroup label="' . $type . '">';
                    }
                    
                    // Determine if this is one that is to be selected
                    $selectedText='';
                    if ($selected != null and $selected==$row["MachineID"]) {
                        // Create the selected html
                        $selectedText='selected';

                        // Set the type name equal to the one selected
                        $selectedMachineName = $row["Name"];
                        
                        // Set it that we selected something
                        $oneSelected=true;
                    }

                    // Add this option to the select
                    $result=$result . '<option title="' . $row["Type"] . '" value="' . $row["MachineID"] . '" ' . $selectedText . '>' . $row["Name"] . ' ' . $row["HasMachiningTask"] .'</option>';

                    // Determine if there is a variable name passed in
                    if ($variableNameToolSlotAmount!=""){
                        // Setup the variable as it would be in javascript
                        $toolSlotCSV = $toolSlotCSV . $row["MaxTools"] . ',';
                    }
                }
                
                // Determine if any were selected.  If not, then the NONE option should be
                if (!$oneSelected){
                    // Add a none option as selected
                    $result='<option value="-1" selected>NONE</option>' . $result;
                }
                else {
                    // Add a none option NOT selected
                    $result='<option value="-1">NONE</option>' . $result;
                }
                
                // Showing a totally different thing for non editable users on status
                if ($allFieldsAccess==='disabled'){
                    // Only need a text box to show them their company, since they cannot change their own company
                    $result='<input type="hidden" name="machineID" id="machineID" value="' . $selected . '"></input>
                             <input class="intext" name="machineName" id="machineName" type="text" maxlength="30" style="width: 100%;" value="' . $selectedMachineName . '" ' . $allFieldsAccess . '><br><br>';
                }
                else {
                    // Determine if there is a variable name passed in
                    if ($variableNameToolSlotAmount!="" && 
                        $toolSlotCSV!=""){
                        // Remove the last comma
                        $toolSlotCSV = substr($toolSlotCSV, 0, -1);
                        
                        // Setup the variable as it would be in javascript
                        $toolSlotCSV = '<script>var ' . $variableNameToolSlotAmount . '="' . $toolSlotCSV . '";</script>';
                    }
                    
                    // Start the return with the beginning of the select
                    $result='<select name="machineID" id="machineID" onchange="' . 
                            $onChangeHTML . '"' . $disableHTML . '>' . $result . 
                            '</select>
                            ' . $toolSlotCSV;
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getFixturesAsSelectOptions($db, $userRow, $selected, $onChangeHTML, $allFieldsAccess=""){
        $result="";
        
        try {
            // Set disabled to be whatever was passed in
            $disableHTML=$allFieldsAccess;

            // Initialize the return with a non result
            $result='<select name="fixture" id="fixture" onchange="' . 
                    $onChangeHTML . '"' . $disableHTML . '>' . 
                    '<option value="-1" selected>NONE</option>' .
                    '</select>';
            
            // Create the query to run
            $sql = 'SELECT * FROM tasks t 
                    LEFT JOIN companies c ON t.CompanyID = c.CompanyID
                    WHERE c.CompanyName="EES Fixtures" 
                    ORDER BY t.Title;';
            
            // Query the database for the machines 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 8");

            // If there are rows then they are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                // Re initialize the result
                $result = "";
                
                // Setup the selected name to be nothing for now
                $selectedFixtureName="";
                
                // Loop throught eh results
                $oneSelected = false;
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if this is one that is to be selected
                    $selectedText='';
                    if ($selected != null and $selected==$row["TaskID"]) {
                        // Create the selected html
                        $selectedText='selected';

                        // Set the type name equal to the one selected
                        $selectedFixtureName = $row["Title"];
                        
                        // Set it that we selected something
                        $oneSelected=true;
                    }

                    // Add this option to the select
                    $result=$result . '<option value="' . $row["TaskID"] . '" ' . $selectedText . '>' . $row["Title"] . '</option>';
                }
                
                // Determine if any were selected.  If not, then the NONE option should be
                if (!$oneSelected){
                    // Add a none option as selected
                    $result='<option value="-1" selected>NONE</option>' . $result;
                }
                else {
                    // Add a none option NOT selected
                    $result='<option value="-1">NONE</option>' . $result;
                }
                
                // Showing a totally different thing for non editable users on status
                if ($allFieldsAccess==='disabled'){
                    // Only need a text box to show them their company, since they cannot change their own company
                    $result='<input type="hidden" name="fixture" id="fixture" value="' . $selected . '"></input>
                             <input class="intext" name="fixtureName" id="fixtureName" type="text" maxlength="100" style="width: 100%;" value="' . $selectedFixtureName . '" ' . $allFieldsAccess . '><br><br>';
                }
                else {
                    // Start the return with the beginning of the select
                    $result='<select name="fixture" id="fixture" onchange="' . 
                            $onChangeHTML . '"' . $disableHTML . '>' . $result . 
                            '</select>';
                }
                
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function createCompanyEmployeesAsJSON($db, $userRow, $taskAssignedToID){
        // Initialize the return
        $result = '';

        try {
            // Setup the query to be where they only get users in their company
            $sql='SELECT * FROM users ' .
                 'WHERE (CompanyID=' . $userRow["CompanyID"] . ' OR CompanyID=1) ' .
                 'AND (AccountStatus="ACTIVE" OR UserID=' . $taskAssignedToID . ') ' . 
                 'AND UserTemplateOnly=0 ' .
                 'ORDER BY CompanyID, LastName, FirstName;';

            // If the SU has signed in, then they can assign it to anyone
            if ($userRow["CompanyID"]==1){
                // Create the query to run
                $sql='SELECT * FROM users WHERE AccountStatus="ACTIVE" OR UserID=' . 
                     $taskAssignedToID . ' AND UserTemplateOnly=0 ORDER BY CompanyID, LastName, FirstName;';
            }

            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 9");

            // If there is only one result for a username/password combo, then they are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                // Initialize the variable to be used
                $localCompanyID='';
                $companies=array();

                // Loop through the returned results
                $counter = 0;
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if the company ID has changed
                    if ($localCompanyID!=$row["CompanyID"]){
                        // Reset the employee number
                        $employeeCount = 0;

                        // Create the new company
                        $companies[$row["CompanyID"]] = array(
                            'CompanyID' => $row["CompanyID"],
                            'employees' => array ()
                        );

                        // Set the current company to what is in the loop now
                        $localCompanyID=$row["CompanyID"];

                    }

                    // Add the employee to the company's employee array
                    $companies[$row["CompanyID"]]['employees'][$employeeCount]=array(
                        'UserID' => $row["UserID"],
                        'UserName' => $row["UserName"],
                        'FirstName' => $row["FirstName"],
                        'LastName' => $row["LastName"]
                    );

                    // Increment the counters
                    ++$counter;
                    ++$employeeCount;
                }

                // Encode the array for javascript
                $encoded_companies = json_encode($companies, JSON_PRETTY_PRINT);

                // Create the javascript code to create the array to be used to repopulate the employees
                $result=$result . '
                    <script type="text/javascript">
                        // using JSON.parse with json_encode
                        var companies = ' . $encoded_companies . ';
                        var originalTaskAssignedToID = ' . $taskAssignedToID . ';
                    </script>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function getTaskTypesAsSelectOptions($db, $userRow, $selected, $allFieldsAccess){
        // Initialize the return
        $result = '';

        try {
            // Create the query to run
            $sql='SELECT * FROM type;';

            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 10");

            // If there is only one result for a username/password combo, then they are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                // Set a type to possibly be added later
                $selectedTaskName = '';
                
                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if this is one that is to be selected
                    $selectedText='';
                    if ($selected != null and $selected==$row["TypeID"]) {
                        // Create the selected html
                        $selectedText='selected';
                        
                        // Set the type ID equal to the one selected
                        $typeID = $row["TypeID"];

                        // Set the type name equal to the one selected
                        $selectedTaskName = $row["Name"];
                    }

                    // Add this option to the select
                    $result=$result . '<option value="' . $row["TypeID"] . '" ' . $selectedText . '>' . $row["Name"] . '</option>';
                }

                // End the select
                $result=$result . '</select>';
                
                // Showing a totally different thing for non editable users on company
                if ($allFieldsAccess==='disabled'){
                    // Only need a text box to show them their company, since they cannot change their own company
                    $result='<input type="hidden" name="taskType" id="taskType" value="' . $selected . '"></input>
                             <input class="intext" name="taskName" id="taskName" type="text" maxlength="50" style="width: 100%;" value="' . $selectedTaskName . '" ' . $allFieldsAccess . '><br><br>';
                }
                else {
                    // Start the return with the beginning of the select
                    $result= '<select name="taskType" id="taskType" ' . $allFieldsAccess . '>' . $result;
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function getTaskCheckboxes($userRow, $invoiced, $completed, $closed, $cleanUp, $isParent){
        // Initialize the return
        $result = '';

        // Assume a null is a false value
        $invoicedValue = ($invoiced == null || $invoiced == ''?0:$invoiced);
        $completedValue = ($completed == null || $completed == ''?0:$completed);
        $closedValue = ($closed == null || $closed == ''?0:$closed);
        $cleanUpValue = ($cleanUp == null || $cleanUp == ''?0:$cleanUp);
                
        try {
            // If the SU has signed in, then they can assign it to anyone
            if ($userRow["UserLevel"]=="SU" && $isParent==1){
                // Initialize the checkbox html values
                $invoicedHTML = '';
                $completedHTML = '';
                $closedHTML = '';
                $cleanUpHTML = '';

                // Determine if we have values for the invoiced flag
                if ($invoicedValue){
                    // Set it to what we got in
                    $invoicedHTML = 'checked';
                }

                // Determine if we have values for the completed flag
                if ($completedValue){
                    // Set it to what we got in
                    $completedHTML = 'checked';
                }

                // Determine if we have values for the closed flag
                if ($closedValue){
                    // Set it to what we got in
                    $closedHTML = 'checked';
                }

                // Determine if we have values for the closed flag
                if ($cleanUpValue){
                    // Set it to what we got in
                    $cleanUpHTML = 'checked';
                }

                $result='
                        <tr>
                            <td height="39" align="left" valign="top" colspan=2>
                                <input name="cleanUp" id="cleanUp" type="checkbox" ' . $cleanUpHTML . '>
                                <strong><label for="cleanUp">Allow task to have data (attachments, etc) purged.</label></strong>
                            </td>
                        </tr>
                        <tr>
                            <td height="39" align="left" valign="top" colspan=2>
                                <input name="invoiced" id="invoiced" type="checkbox" ' . $invoicedHTML . '>
                                <strong><label for="invoiced">Invoiced</label></strong>
                                <input name="completed" id="completed" type="checkbox" ' . $completedHTML . '>
                                <strong><label for="completed">Completed</label></strong>
                                <input name="closed" id="closed" type="checkbox" ' . $closedHTML . '>
                                <strong><label for="closed">Closed</label></strong>
                            </td>
                        </tr>';
            }
            else {
                $result='
                        <tr>
                            <td height="39" align="left" valign="top" colspan=2>
                                <input name="hiddenCleanUp" id="hiddenCleanUp" type="hidden" value=' . $cleanUpValue . '>
                                <input name="hiddenInvoiced" id="hiddenInvoiced" type="hidden" value=' . $invoicedValue . '>
                                <input name="hiddenCompleted" id="hiddenCompleted" type="hidden" value=' . $completedValue . '>
                                <input name="hiddenClosed" id="hiddenClosed" type="hidden" value=' . $closedValue . '>
                            </td>
                        </tr>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function getSecondaryStatusCheckboxes($isWaitingToBeReviewed,
                                          $isPendingTools, $isPendingApproval){
        // Initialize the return
        $result = '';

        try {
            // Initialize the checkbox html values
            $isWaitingToBeReviewedHTML = '';
            $isPendingToolHTML = '';
            $IsPendingApprovalHTML = '';

            // Determine if we have values for the waiting to be reviewed flag
            if ($isWaitingToBeReviewed){
                // Set it to what we got in
                $isWaitingToBeReviewedHTML = 'checked';
            }

            // Determine if we have values for the pending tool flag
            if ($isPendingTools){
                // Set it to what we got in
                $isPendingToolHTML = 'checked';
            }

            // Determine if we have values for the pending approval flag
            if ($isPendingApproval){
                // Set it to what we got in
                $IsPendingApprovalHTML = 'checked';
            }

            $result='
                    <input name="isPendingApproval" id="isPendingApproval" type="checkbox" ' . $IsPendingApprovalHTML . ' disabled>
                    <strong><label for="cleanUp">Approval</label></strong>&nbsp;&nbsp;
                    <input name="isWaitingToBeReviewed" id="isWaitingToBeReviewed" type="checkbox" ' . $isWaitingToBeReviewedHTML . ' disabled>
                    <strong><label for="invoiced">Review</label></strong>
                    <br>
                    <input name="isPendingTools" id="isPendingTools" type="checkbox" ' . $isPendingToolHTML . ' disabled>
                    <strong><label for="closed">Tool</label></strong>';
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function createPostMachiningInformation($isVacuumClean, $isWashForAnodize,
                                            $hasAllowableCosmeticDamage,
                                            $isTappedPostMachining, $postMachiningTappingInstructions,
                                            $isSandblasted, $sandBlastingInstructions,
                                            $postMachiningNotes, $postMachiningFeedback){
        // Initialize the return
        $result = '';

        try {
            // Initialize the checkbox html values
            $isVacuumCleanHTML = '';
            $isWashForAnodizeHTML = '';
            $hasAllowableCosmeticDamageHTML = '';
            $isTappedPostMachiningHTML='';
            $isSandblastedHTML = '';

            // Determine if we have a value for vacuum cleaning flag
            if ($isVacuumClean){
                // Set it to what we got in
                $isVacuumCleanHTML = 'checked';
            }

            // Determine if we have a value for wash before anodize flag
            if ($isWashForAnodize){
                // Set it to what we got in
                $isWashForAnodizeHTML = 'checked';
            }

            // Determine if we have a value for allowance of minor damage flag
            if (!$hasAllowableCosmeticDamage){
                // Set it to what we got in
                $hasAllowableCosmeticDamageHTML = 'checked';
            }

            // Determine if we have a value for post machining tapping flag
            if ($isTappedPostMachining){
                // Set it to what we got in
                $isTappedPostMachiningHTML = 'checked';
            }

            // Determine if we have a value for sandblasting flag
            if ($isSandblasted){
                // Set it to what we got in
                $isSandblastedHTML = 'checked';
            }

            $result='
                    <table width="100%" border="0" cellspacing="0" cellpadding="7px">
                        <tr width="100%" >
                            <td align="right" width="33%">
                                <input name="isVacuumClean" id="isVacuumClean" type="checkbox" ' . $isVacuumCleanHTML . '>
                                <strong><label for="isVacuumClean">Vacuum Clean</label></strong>&nbsp;&nbsp;
                            </td>
                            <td align="center" width="33%">
                                <input name="isWashForAnodize" id="isWashForAnodize" type="checkbox" ' . $isWashForAnodizeHTML . '>
                                <strong><label for="isWashForAnodize">Wash for Anodize</label></strong>
                            </td>
                            <td align="left" width="33%">
                                <input name="hasAllowableCosmeticDamage" id="hasAllowableCosmeticDamage" type="checkbox" ' . $hasAllowableCosmeticDamageHTML . '>
                                <strong><label for="hasAllowableCosmeticDamage">No Cosmetic Damage</label></strong>
                            </td>
                        <tr>
                        <tr>
                            <td align="right">
                                <input name="isTappedPostMachining" id="isTappedPostMachining" type="checkbox" ' . $isTappedPostMachiningHTML . ' onchange="document.getElementById(\'postMachiningTappingInstructions\').disabled=!this.checked">
                                <strong><label for="isTappedPostMachining">Post Tapping</label></strong>&nbsp;&nbsp;
                            </td>
                            <td colspan=2>
                                <textarea name="postMachiningTappingInstructions" id="postMachiningTappingInstructions" maxlength="500" class="intext" style="width: 100%; height: 70px; overflow: vertical; resize:vertical"' . ($isTappedPostMachining?'':'disabled')  . '>' .
                                $postMachiningTappingInstructions .
                                '</textarea>
                            </td>
                        <tr>
                        <tr>
                            <td align="right">
                                <input name="isSandblasted" id="isSandblasted" type="checkbox" ' . $isSandblastedHTML . ' onchange="document.getElementById(\'sandBlastingInstructions\').disabled=!this.checked">
                                <strong><label for="isSandblasted">Sandblasting</label></strong>&nbsp;&nbsp;
                            </td>
                            <td colspan=2>
                                <textarea name="sandBlastingInstructions" id="sandBlastingInstructions" maxlength="500" class="intext" style="width: 100%; height: 70px; overflow: vertical; resize:vertical" ' . ($isSandblasted?'':'disabled')  . '>' .
                                $sandBlastingInstructions .
                                '</textarea>
                            </td>
                        <tr>
                        <tr>
                            <td align="right">
                                <strong><label>Post Machining Notes</label></strong>
                            </td>
                            <td colspan=2>
                                <textarea name="postMachiningNotes" id="postMachiningNotes" maxlength="500" class="intext" style="width: 100%; height: 70px; overflow: vertical; resize:vertical">' .
                                $postMachiningNotes .
                                '</textarea>
                            </td>
                        <tr>
                        <tr>
                            <td align="right">
                                <strong><label>Post Machining Feedback</label></strong>
                            </td>
                            <td colspan=2>
                                <textarea name="postMachiningFeedback" id="postMachiningFeedback" maxlength="500" class="intext" style="width: 100%; height: 70px; overflow: vertical; resize:vertical">' .
                                $postMachiningFeedback .
                                '</textarea>
                            </td>
                        <tr>
                    </table>';
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function retrieveTaskAttachments($db, $userRow, $taskNumber, $mainSubCompany){
        // Set the return result to nothing in case nothing is passed in for task number
        $result='';

        try {
            // Determine if a task number was provided
            if (isset($taskNumber)){
                // Setup the query to be where they only get users in their company
                $sql='SELECT AttachmentID, Title, FileType, ByteSize FROM attachments ' .
                     'WHERE TaskID=' . $taskNumber . ' ORDER BY SubmitDate;';

                // Query the database for the companies 
                $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 11");

                // Start the return
                $result = '';

                // Loop through the returned results
                $rowNumber = 0;                
                while ($row=mysqli_fetch_array($rows)){
                    // Increment the row number
                    $rowNumber++;

                    // Determine if this is an image type or not
                    $viewtag = '';
                    if ($row["FileType"] !== null && strpos($row["FileType"], 'image') !== false){
                        // setup the view tag to show this image
                        $viewtag = '<a href="view_image.php?id=' . $row["AttachmentID"] . '" target="_blank">
                                        View <img src="php_only_scripts/show_blob.php?id=' . $row["AttachmentID"] . '&tbl=attachments&idf=AttachmentID&bf=Datum&tyf=FileType&nmf=Title&szf=ByteSize" height=45 style="vertical-align: middle;">
                                    </a>&nbsp;';
                    }

                    // Add the attachment to the table
                    $result = $result .
                        '<div class="Table" id="currentAttachment' . $row["AttachmentID"] . '" name="currentAttachment' . $row["AttachmentID"] . '">
                            <div class="Row">
                                <div class="cell numberCell">' . $rowNumber . '</div>
                                <div class="cell nameCell">' . 
                                        $row["Title"] . ' &nbsp;
                                    <a href="php_only_scripts/show_blob.php?id=' . $row["AttachmentID"] . '&tbl=attachments&idf=AttachmentID&bf=Datum&tyf=FileType&nmf=Title&szf=ByteSize">Download</a>&nbsp;' .
                                    $viewtag . '
                                </div>
                                <div class="cell typeCell">Type=' . $row["FileType"] . '</div>
                                <div class="cell sizeCell">Size=' . $row["ByteSize"] . ' KB</div>';

                    // Determine if the user is an executive or not
                    if ($userRow["UserLevel"]=='SU' ||
                        ($userRow["CompanyID"]==1 && ($userRow["UserLevel"]=='EXECUTIVE' || $userRow["UserLevel"]=='MANAGEMENT'))){
                        $result = $result . 
                                    '<div class="cell checkCell">
                                        <input type="checkbox" class="notinput" onclick="handleAttachmentClick(this);" value="' . $row["AttachmentID"] . '">Remove Attachment Upon Update</input>
                                    </div>';
                    }

                    // Finish the tags
                    $result = $result . 
                            '</div>
                         </div>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return the created HTML
        return $result;
    }

    function checkThenGetNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, &$validationHTML=""){
        // Init all of the settings to the appropriate values
        $noteDiv = '';
        
        // Determine if the user editing this is part of the SU company
        if ($userRow["CompanyID"]==1)
        {
            // get the div
            $noteDiv = retrieveNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, false, $validationHTML, true);
        }

        // Return the result
        return $noteDiv;
    }

    function checkThenGetBlanksDiv($db, $userRow, $inTaskID, &$validationHTML=""){
        // Init all of the settings to the appropriate values
        $blanksDiv = '';
        
        // Determine if the user editing this is part of the SU company
        if ($userRow["CompanyID"]==1)
        {
            // get the div
            $blanksDiv = '<div id="BlanksInfo" class="childtabcontent" style="display:none;">
                         ' . retrieveBlanksDiv($db, $userRow, $inTaskID, $validationHTML) . '
                         </div>';
        }

        // Return the result
        return $blanksDiv;
    }

    function checkThenGetToolsDiv($db, $userRow, $inTaskID, &$validationHTML=""){
        // Init all of the settings to the appropriate values
        $toolsDiv = '';
        
        // Determine if the user editing this is part of the SU company
        if ($userRow["CompanyID"]==1)
        {
            // get the div
            $toolsDiv = '<div id="ToolsInfo" class="childtabcontent" style="display:none;">
                        ' . retrieveToolsDiv($db, $userRow, $inTaskID, $validationHTML) . '
                        </div>';
        }

        // Return the result
        return $toolsDiv;
    }

    function checkThenGetSetupsDiv($db, $userRow, $inTaskID, &$validationHTML=""){
        
        // Init all of the settings to the appropriate values
        $setupsDiv = '';
        
        // Determine if the user editing this is part of the SU company
        if ($userRow["CompanyID"]==1)
        {
            // get the div
            $setupsDiv = '<div id="SetupsInfo" class="childtabcontent" style="display:none;">
                         ' . retrieveSetupsDiv($db, $userRow, $inTaskID, $validationHTML) . '
                         </div>';
        }

        // Return the result
        return $setupsDiv;
    }

    function getParentTask($db, $userRow, $taskNumber, $selectedCompany, $selectedType, $fromWhatBaseURL){
        // Init all of the settings to the appropriate values
        $title = '';
        $description = '';
        $priority = 99998;
        $idealDate = '';
        $dueDate = '';
        $highLevelFieldsAccess = '';
        $taskPrice = 'TBD';
        $deliverableQuantity = 0;
        $totalQuantity = 0;
        $createdByID = $userRow["UserID"];
        $createdByFirstName =  $userRow["FirstName"];
        $createdByLastName =  $userRow["LastName"];
        $createdDate = "Unknown";
        $statusID = null;
        $assignedToID = -1;
        $childrenAssignedToID = -1;
        $taskTypeID = null;
        $companyID = -1;
        $invoiced = false;
        $completed = false;
        $closed = false;
        $isWaitingToBeReviewed = false;
        $isPendingTools = false;
        $isPendingApproval = false;
        $machineID = -1;
        $fixtureID = -1;
        $theOrder = 99998;
        $allowCreditPayment = true;
        $expedite = 0;
        $expediteHTML = '';
        $isVacuumClean = 0;
        $isWashForAnodize = 0;
        $hasAllowableCosmeticDamage = 0;
        $isTappedPostMachining = 0;
        $postMachiningTappingInstructions = '';
        $isSandblasted = 0;
        $sandBlastingInstructions = '';
        $postMachiningNotes = '';
        $postMachiningFeedback = '';
        $programmerID = -1;
        $programCheckedByID = -1;
        $partHardware='';
        $secondaryStatusID = -1;
        $outsideServiceVendorID = -1;

        $cleanUp = false;
        $hasChildren = 0;
        
        $modifyType = 'add';
        
        // Setup the on clicks 
        $onClickHTML = 'onclick="javascript:reenableCmbBoxes(); populateCurrentDateTime(\'localTime\',\'yyyy-MM-dd hh:mm\'); document.getElementById(\'hiddenMachineTaskOrder\').value=document.getElementById(\'machineTaskOrder\').value;"';

        // Setup the button for setup sheets and making the packetas nothing at first
        $ssButtonHTML = '';
        $makePacketButtonHTML = '';
            
        // setup the sticky not div
        $stickyNoteDivHTML='';

        // Set the blanks validation script to nothing at first
        $toolsValidationHTML="";
        $setupsValidationHTML="";
        $blankValidationHTML="";
        $noteValidationHTML="";
        $stickyNoteValidationHTML="";
                
        // Determine if the user editing this is NOT a SU or not
        if ($userRow["UserLevel"]!="SU"){
            // Disable price and due date editing except for SU's
            $highLevelFieldsAccess = 'disabled';
        }
        
        // Dummy variable to hold task number or real task number
        $dummyTaskNumber = $taskNumber;

        // Levels Management and above can see this so set as default
        $allFieldsAccess = '';
        $addNewAttachmentsVisibilityHTML = 'display:none;';
        $updateTaskVisibilityHTML = 'display:none;';
        $suManagementLevelFieldsHTML = 'display:none;';
        $makePacketVisibility = "display:none;";
        
        // Set the status field to disabled for now
        $statusFieldAccess = 'disabled';

        // Set the tab to be hidden for now
        $machiningButtonStyling = 'display:none;';
        $stickyNotesButtonStyling = 'display:none;';
        $historyButtonStyling = 'display:none;';

        // Determine if they are of the SU Company to change status access
        if ($userRow["CompanyID"]==1){
            // Give them access to the status
            $statusFieldAccess = '';
            $updateTaskVisibilityHTML = '';
            
            // Determine if this is an update or not
            if ($taskNumber){
                // Set them as visible
                $machiningButtonStyling = 'display:block;';
                $stickyNotesButtonStyling = 'display:block;';
                $historyButtonStyling = 'display:block;';
            }
        }
        
        // Children assigned to combo box is not shown if it is an add so make a hidden element
        $childrenAssignedToHTML = ' <tr>
                                        <td></td>
                                        <td>
                                            <input type="hidden" id="childrenAssignedTo" name="childrenAssignedTo" value=-1>
                                        </td>
                                    </tr>
                                   ';
            
        // Determine if this is an update or not
        $assocTask = null;
        if ($taskNumber){
            // Create the query to get the the task and the user that created the task
            $sql = 'SELECT t.*, u.FirstName, u.LastName, ' . 
                   'u2.FirstName AS LastUpdatedUserFirstName, u2.LastName AS LastUpdatedUserLastName, ' . 
                   'c.AllowCredit, c.MainSubCompany, c.Store, ' . 
                   's.ProcessOrder, s.Name AS StatusName, m.MachineID, m.Name as MachineName, ' . 
                   'tm.TheOrder, tm.IsWaitingToBeReviewed, ' . 
                   'tm.IsPendingTools, tm.IsPendingApproval, ' .
                   'ss.Description as SSDescription, ss.RowColor AS SSRowColor, ' .
                   'IF(ctl.CopiedFromTaskID IS NULL,"null",ctl.CopiedFromTaskID) AS CopiedFromTaskID , ctl.DateCopied AS CopiedDate, ctl.CopyingUserID, IF(ctl.CopiedFromHasFeedback IS NULL,0,ctl.CopiedFromHasFeedback) AS CopiedFromHasFeedback ' .
                   'FROM tasks t ' . 
                   'LEFT JOIN users u ON t.CreatedByID = u.UserID ' .
                   'LEFT JOIN users u2 ON t.LastUpdatedByID = u2.UserID ' .
                   'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                   'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                   'LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID ' .
                   'LEFT JOIN tasktomachinelinker tm ON t.TaskID = tm.TaskID ' .
                   'LEFT JOIN machines m ON tm.MachineID = m.MachineID ' .
                   'LEFT JOIN copiedtaskslinker ctl ON t.TaskID = ctl.CopiedToTaskID ' .
                   'WHERE t.TaskID=' . $taskNumber . ';';

            // Attempt to change all of the rows that need to be changed
            $row = $db->queryDB($sql, $userRow, "task_presentation Form occurance 12");

            // Attempt to get the user row
            $assocTask = $row->fetch_assoc();

            // Determine if this person is of appropriate level and company
            if ($userRow["CompanyID"] != 1 && 
                $userRow["CompanyID"] != $assocTask["CompanyID"]){
                    // redirect to the invalid access page
                    echo ('<script>window.location = "invalid_access.php";</script>');

                    exit;
            }
            
            // Set the things we can
            $title = $assocTask["Title"];
            $description = $assocTask["Entry"];
            $priority = $assocTask["Priority"];
            $dueDate = $assocTask["DueDate"];
            $idealDate = $assocTask["IdealDate"];
            $createdByID = $assocTask["CreatedByID"];
            $createdByFirstName = $assocTask["FirstName"];
            $createdByLastName = $assocTask["LastName"];
            $createdDate = date("Y-m-d H:i:s", strtotime("-1 hour", strtotime($assocTask["CreatedDate"])));
            $lastUpdatedDate = date("Y-m-d H:i:s", strtotime("-1 hour", strtotime($assocTask["LastUpdated"])));
            $lastUpdatedByFirstName = $assocTask["LastUpdatedUserFirstName"];
            $lastUpdatedByLastName = $assocTask["LastUpdatedUserLastName"];
            $statusID = $assocTask["StatusID"];
            $assignedToID = $assocTask["UserID"];
            $taskTypeID = $assocTask["TypeID"];
            $companyID = $assocTask["CompanyID"];
            $mainSubCompany = $assocTask["MainSubCompany"];
            $invoiced = $assocTask["Invoiced"];
            $completed = $assocTask["Completed"];
            $closed = $assocTask["Closed"];
            $isWaitingToBeReviewed = $assocTask["IsWaitingToBeReviewed"];
            $isPendingTools = $assocTask["IsPendingTools"];
            $isPendingApproval = $assocTask["IsPendingApproval"];
            $allowCreditPayment = $assocTask["AllowCredit"];
            $modifyType = 'update';
            $taskPrice = $assocTask["TaskPrice"];
            $deliverableQuantity = $assocTask["DeliverableQuantity"];
            $totalQuantity = $assocTask["TotalQuantity"];
            $processOrder = $assocTask["ProcessOrder"];
            $machineID = $assocTask["MachineID"];
            $fixtureID = $assocTask["FixtureToUseID"];
            $statusName = $assocTask["StatusName"]; 
            $expedite = $assocTask["Expedite"];
            $expediteHTML = ($assocTask["Expedite"]==1)?'checked':'';
            $isVacuumClean = $assocTask["IsVacuumClean"];
            $isWashForAnodize = $assocTask["IsWashForAnodize"];
            $hasAllowableCosmeticDamage = $assocTask["HasAllowableCosmeticDamage"];
            $isTappedPostMachining = $assocTask["IsTappedPostMachining"];
            $postMachiningTappingInstructions = $assocTask["PostMachiningTappingInstructions"];
            $isSandblasted = $assocTask["IsSandblasted"];
            $sandBlastingInstructions = $assocTask["SandBlastingInstructions"];
            $postMachiningNotes = $assocTask["PostMachiningNotes"];
            $postMachiningFeedback = $assocTask["PostMachiningFeedback"];
            $programmerID=$assocTask["ProgrammerID"]!=null?$assocTask["ProgrammerID"]:-1;
            $programCheckedByID=$assocTask["ProgramCheckedByID"]!=null?$assocTask["ProgramCheckedByID"]:-1;
            $partHardware=$assocTask["PartHardware"];
            $secondaryStatusID = $assocTask["SecondaryStatusID"];
            $secondaryStatusColor = $assocTask["SSRowColor"];
            $secondaryStatusDescription = $assocTask["SSDescription"];
            $cleanUp = $assocTask["CleanUp"];
            $rollupPrice = 0;
            $hasChildren = $assocTask["HasChildren"];
            $outsideServiceVendorID = $assocTask["OutsideServiceVendorID"];
            
            // Setup the onchange for the status
            $onStatusChangeHTML='prefillOrderControl(this.options[this.selectedIndex].text); outsideServiceCheck(this.options[this.selectedIndex].text); intoProgrammingServiceCheck(this.options[this.selectedIndex].text, ' . $assocTask["CopiedFromHasFeedback"] . ', ' . $assocTask["CopiedFromTaskID"] . ');';

            // Determine if this parent has children
            if ($hasChildren==1){
                // set it to inform the user about changing parents with children
                $onStatusChangeHTML="onChangeStatus(this, " . $statusID . ");";
            }

            // create a variable to hold HTML that will show there is operator feedback
            $operatorFeedbackNotificationHTML='';
            
            // Determine if there is an issued date and setup the html value if so
            $issuedToMachineDateHTML='';
            if ($assocTask["IssuedToMachineDate"]!=null){
                // Set the HTML
                $issuedToMachineDateHTML='
                            <tr>
                              <td height="39" align="left" valign="top" colspan=5>
                                    <br>
                                    <strong>Sent to machining on </strong>' . date("Y-m-d H:i:s", strtotime("-1 hour", strtotime($assocTask["IssuedToMachineDate"]))) . '. 
                              </td>
                            </tr>
                            ';
            }

            // Determine if there is a machine yet
            $orderDisabledHTML="disabled";
            if ($machineID!=null){
                // Now we can set the order to something other than 99998
                $theOrder = $assocTask["TheOrder"];
                
                // Machining tasks cannot be changed from the first slot
                if ($statusName != "Machining"){
                    // Order will not be disabled now
                    $orderDisabledHTML="";
                }
                
                // Determine if the order is one or two and then allow for the packet to be created
                if ($theOrder < 3 || $statusName == "Manual Machining"){
                    $makePacketVisibility = "";
                }
            }

            // Determine if this task is one of the main companies and if the user is allowed to modify it
            if ($mainSubCompany==1 && $userRow["CompanyID"]==1){
                    // For this combination, it is ok for this user to edit
                    $highLevelFieldsAccess = '';
            }
            
            // Determine if this task has children
            $children = '';
            if ($hasChildren == 1){
                // Get the children
                $children = retrieveChildTasksAsList($db, $userRow, $taskNumber, true, $selectedCompany, $selectedType);
                
                // Create the query to get the sum of all sub tasks
                $sql = 'SELECT Sum(TaskPrice*DeliverableQuantity) AS RollupPrice FROM tasks ' . 
                       'WHERE ParentID = ' . $taskNumber . ' ' .
                       'AND TaskPrice IS NOT NULL;';
//echo '<script>alert("' . $sql. '");</script>';

                // Run the query
                $rollupPriceRow = $db->queryDB($sql, $userRow, "task_presentation Form occurance 13");

                // Determine if we have one row to look at
                if (mysqli_num_rows($rollupPriceRow)==1){
                    // Get the Row returned
                    $rollupPriceAssocRow = $rollupPriceRow->fetch_assoc();

                    // Determine if we have a null value
                    if (is_numeric($rollupPriceAssocRow["RollupPrice"]) &&
                        $rollupPriceAssocRow["RollupPrice"] > 0){
                        // Set the price to be the rollup price
                        $taskPrice=$rollupPriceAssocRow["RollupPrice"];
                        $rollupPrice=$rollupPriceAssocRow["RollupPrice"];
                    }
                }
                
                // Make a visible combo box since this one has children
                $childrenAssignedToHTML = '
                                            <tr>
                                                <td height="39" align="right" valign="top">
                                                    <strong>ALL Children Assigned To: </strong> &nbsp; &nbsp; 
                                                </td>
                                                <td height="39" align="left" valign="top" width="45%">
                                                    <select name="childrenAssignedTo" id="childrenAssignedTo" ' . $statusFieldAccess . ' title="This will assign the children to this user upon changing status of the parent."></select>
                                                </td>
                                            </tr>
                                           ';
            }
            else {
                // Determine if this user is a SU company user
                if ($userRow["CompanyID"]==1){
                    // Make the setup sheet button 
                    $ssButtonHTML='<input name="createModifiedSetupSheet" id="createModifiedSetupSheet" type="button" style="pointer-events: auto; cursor: hand; ' . $makePacketVisibility . '" value="Create SS" title="This will modify the database to match tools as closely as possible and then create a PDF setup sheep for this task." onclick="javascript:if (_isDirty && !confirm(\'The form has new data.\n\nAre you sure you want to create the setup sheet without saving?\')) {return false;};  if (modifyTaskForThePresent(' . $taskNumber . ', ' . (($machineID==null) ? ('null') : ($machineID)) . ', 1, sessionID)){window.open(\'pdf_templates/setup_sheet.php?tid=' . $taskNumber . '\', \'_blank\'); location.reload(); return true;}"/>';

                    // Determine if this task is in the machining state
                    if ($statusName=="Machining"){
                        // Make the create packet button 
                        $makePacketButtonHTML='<input name="gcodePacketModified" id="gcodePacketModified" type="button" style="pointer-events: auto; cursor: hand; ' . $makePacketVisibility . '" value="Remake Packet" title="This will modify the database to match tools as closely as possible and then modify the GCodes to add M00 image links and set tools to match appropriate tools in the machine. A zip file will be made after that with the package contents." onclick="javascript:if (_isDirty && !confirm(\'The form has new data.\n\nAre you sure you want to modify the GCode?\')) {return false;}; if (modifyTaskForThePresent(' . $taskNumber . ', ' . (($machineID==null) ? ('null') : ($machineID)) . ', 0, sessionID)){if (recalculateToolsForTask(' . $taskNumber . ', ' . (($machineID==null) ? ('null') : ($machineID)) . ', sessionID)) {window.open(\'pdf_templates/setup_sheet_with_downloads.php?tid=' . $taskNumber . '\', \'_blank\'); location.reload(); return true;}}"/>';
                    } 
                    
                    // Create query to determine if this one has feedback notes from the operators
                    $sql='SELECT COUNT(*) AS CountFeedback ' .
                         'FROM machiningsetups ms ' .
                         'LEFT JOIN notes n ON ms.MachiningSetupID = n.AssociatedCategoryID ' .
                         'WHERE n.Category="OPERATOR_FEEDBACK_NOTE" ' . 
                         'AND n.IsSticky=0 ' .
                         'AND ms.TaskID=' . $taskNumber . ';';            

                    // Attempt to get the amount of operator feedback for this task
                    $countFeedbackRow = $db->queryDB($sql, $userRow, "task_presentation Form occurance 14");

                    // set it as easily readable
                    $assocCountFeedbackRow = $countFeedbackRow->fetch_assoc();

                    // Check how much feedback there is
                    if ($assocCountFeedbackRow["CountFeedback"]>0){
                        // Create some HTML to visually notify of operator feedback
                        $operatorFeedbackNotificationHTML='&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<label style="width:100%; color:red; align: right;" title="There are ' . $assocCountFeedbackRow["CountFeedback"] . ' operator feedback notes."><strong>Has Operator Feedback</strong></label>';
                    }
                }
            }

            // Determine if the task price is null
            if ($taskPrice == null){
                // Set the task price to be showing TBD
                $taskPrice = 'TBD';
            }
            
            // Get something for sticky notes
            $stickyNoteDivHTML=checkThenGetStickyNotesDiv($db, $userRow, $taskNumber, 'TASK', $stickyNoteValidationHTML);
        }
        else {
            // Set a dummy task name to be replaced
            $dummyTaskNumber = 'TaskIDToReplace';
            
            // Enable due date editing for adding tasks for everyone
            $highLevelFieldsAccess = '';
                    
            // Pretend this is a main user company in this case
            $mainSubCompany=1;
        }

        // Add a section for price for executive and above
        $priceHTML = '';
        if (($userRow["CompanyID"]==$companyID) && 
            ($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT") &&
            ($userRow["CompanyID"]!=1)){
            // add a price to let the customer see to order
            $priceHTML = '<tr>
                            <td colspan=4>
                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;"><strong>Price:</strong></label></div>
                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;">
                                    <input name="taskPrice" type="text" maxlength="15" class="intext" style="width: 100%; height: 19px" value="' . $taskPrice . '" ' . $highLevelFieldsAccess . '>
                                    <input type="hidden" name="rollupTaskPrice" id="rollupTaskPrice" value="' . $rollupPrice . '">
                                </div>
                                <br>
                            </td>
                          </tr>
                         ';
        }
        // Determine if it is a SU or Exec from the main company
        else if (($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE") &&
            ($userRow["CompanyID"]==1)){
            // add a price to let the SU see to order
            $priceHTML = '<tr>
                              <td colspan=4 height="39" align="left" valign="top">
                                <input name="hidePrice" id="hidePrice" class="notinput" type="checkbox" onclick="javascript:div_toggleVisibilityOnCheckbox(\'hidePrice\',\'priceDiv\', \'NORMAL\');"/>
                                <strong><label for="hidePrice">Price</label></strong>
                                <div id="priceDiv" style="display: none; font-weight: bold; font-size: 12px; width: 100%;">
                                    <input name="taskPrice" type="text" maxlength="15" class="intext" style="width: 100%; height: 19px" value="' . $taskPrice . '" ' . $highLevelFieldsAccess . '>
                                    <input type="hidden" name="rollupTaskPrice" id="rollupTaskPrice" value="' . $rollupPrice . '">
                                </div>
                              </td>
                          </tr>
                         ';
        }

        // Determine if it is a SU or Exec from the main company and can modify children
        $addSubtaskButtonHTML='';
        if (($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT" || $userRow["UserLevel"]=="MID-MANAGEMENT") &&
            (($userRow["UserLevel"]=="SU") || ($userRow["CompanyID"]==1 && $userRow["CompanyID"]==$companyID)  || ($userRow["CompanyID"]==1 && $userRow["CanModifyChildren"]==1))){
            // Determine if this task has children or not
            if ($hasChildren==1){
                // Add the option for these user to have children as setup like a current task
                $addSubtaskButtonHTML='
                            <td colspan=1>
                                <input type="button" value="Add SubTask" title="Add a SubTask to this parent." onclick="javascript:document.getElementById(\'redirectTo\').value=\'addTask.php?parentTaskId=' . $dummyTaskNumber . '&updateTaskID=-1&cs=' . $selectedCompany . '&ts=' . $selectedType . '\'; this.form.submit();"/>
                                <br><br>
                            </td>
                            ';
            }
            else{
//                                <input type="button" value="Add SubTask" title="Add a SubTask to this parent." onclick="javascript:document.getElementById(\'redirectTo\').value=\'addTask.php?parentTaskId=' . $dummyTaskNumber . '&updateTaskID=-1&cs=' . $selectedCompany . '&ts=' . $selectedType . '\'; getAddChildDialog();"/>
                // Add the option for these user to have children as setup like a current task
                $addSubtaskButtonHTML='
                            <td colspan=1>
                                <input type="button" value="Add SubTask" title="Add a SubTask to this parent." onclick="getAddChildDialog();"/>
                                <br><br>
                            </td>
                        ';
            }
        }
            
        // Determine if it is a SU or Exec from the main company and can copy tasks
        $addCopyTaskElementsHTML='';
        if (($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT" || $userRow["UserLevel"]=="MID-MANAGEMENT") &&
            (($userRow["UserLevel"]=="SU") || ($userRow["CompanyID"]==1 && $userRow["CompanyID"]==$companyID)  || ($userRow["CompanyID"]==1 && $userRow["CanCopyTasks"]==1))){
            // Add the option for these user to have children as setup like a current task
            $addCopyTaskElementsHTML='
                        <td colspan=1 align="left">
                            <strong><label for="copyTaskID" title="Use the last four of the hyphenated TID (ex:1111-2222 is 2222).">Copy Machining Tasks From TID:</label></strong>
                            <input type="text" name="copyTaskID" id="copyTaskID" maxlength="4" class="intext" title="Use the last four of the hyphenated TID (ex:1111-2222 is 2222)." style="width:40px;">
                            <input type="button" name="copyTaskButton" id="copyTaskButton" value="Copy" title="Add a all machining tasks from or of the task ID that is in the text box. Use the last four of the hyphenated TID (ex:1111-2222 is 2222)." onclick="javascript:if (isNaN(document.getElementById(\'copyTaskID\').value)){alert (\'The TID to copy is not valid.  Please try again.\');} else{getWaitDialog();}"/>
                            <br><br>
                        </td>
                    ';
        }
        
        // Determine if either element has something
        $addTasksHTML='';
        if ($addSubtaskButtonHTML!='' ||
            $addCopyTaskElementsHTML!=''){
            
            // Determine if one or the other is NOT set
            if ($addSubtaskButtonHTML!='' && $addCopyTaskElementsHTML=='') {
                // make a dummy cell
                $addCopyTaskElementsHTML='
                            <td colspan=1>
                                <br><br>
                            </td>
                        ';
            }
            else if ($addSubtaskButtonHTML=='' && $addCopyTaskElementsHTML!='') {
                // make a dummy cell
                $addSubtaskButtonHTML='
                            <td colspan=1>
                                <br><br>
                            </td>
                        ';
            }
            
            // Add the row for these extra options
            $addTasksHTML='
                    <tr align="left" valign="middle">
                        ' . $addSubtaskButtonHTML . '
                        <td colspan=1 width="4%">&nbsp;</td>
                        ' . $addCopyTaskElementsHTML . '
                    </tr>';
        }
            
        // In order to determine the level of this person's account, I need to know their type
        switch ($userRow["UserLevel"]){
            case 'MINIMAL' :
            case 'TYPICAL' :
                // Disable access to most fields
                $allFieldsAccess = 'disabled';
                $addNewAttachmentsVisibilityHTML = 'display:none;';
                
                // If they are a mid-manager and this task is of the SU subsidiary, give them access
                if ($userRow["CompanyID"]==1 &&
                    $mainSubCompany){
                    // For this combination, Get access to everything
                    $updateTaskVisibilityHTML = '';
                    $addNewAttachmentsVisibilityHTML = '';
                    $suManagementLevelFieldsHTML = '';
                    $allFieldsAccess = '';
                }
                
                // Break out of this case statement
                break;
            case 'MID-MANAGEMENT' :
                // Disable access to most fields
                $allFieldsAccess = 'disabled';
                $addNewAttachmentsVisibilityHTML = 'display:none;';
                
                // If they are a mid-manager and this task is of the SU subsidiary, give them access
                if ($userRow["CompanyID"]==1 &&
                    $mainSubCompany){
                    // For this combination, Get access to everything
                    $updateTaskVisibilityHTML = '';
                    $addNewAttachmentsVisibilityHTML = '';
                    $suManagementLevelFieldsHTML = '';
                    $allFieldsAccess = '';
                }
                else {
                    // Determine if this is one of the main company's employee
                    if ($userRow["CompanyID"]==1){
                        // Mid-Managers can add attachments
                        $addNewAttachmentsVisibilityHTML = '';
                    }
                    
                }
                
                // Break out of this case statement
                break;
            case 'MANAGEMENT':
                // Management has access to update always
                $updateTaskVisibilityHTML = '';
                
                // Disable access to most fields
                $allFieldsAccess = 'disabled';
                $addNewAttachmentsVisibilityHTML = 'display:none;';
                
                // If they are a manager and this task is of the SU subsidiary, give them access
                if ($userRow["CompanyID"]==1 &&
                    $mainSubCompany){
                    // For this combination, it is ok for this user to edit due date
                    $updateTaskVisibilityHTML = '';
                    $addNewAttachmentsVisibilityHTML = '';
                    $suManagementLevelFieldsHTML = '';
                    $allFieldsAccess = '';
                }
                else {
                    // Determine if this is one of the main company's employee
                    if ($userRow["CompanyID"]==1){
                        // Main company's manager can modify customer level items
                        $suManagementLevelFieldsHTML = '';
                        $addNewAttachmentsVisibilityHTML = '';
                    }
                    
                }
                
                // Break out of this case statement
                break;
            case 'EXECUTIVE':
            case 'SU': /* In case the SU is NOT in the super company for some reason */
                // For this combination, Get access to everything
                $updateTaskVisibilityHTML = '';
                $statusFieldAccess = '';
                $addNewAttachmentsVisibilityHTML = '';
                $suManagementLevelFieldsHTML = '';
                
                // Break out of this case statement
                break;
        }

        // Determine if this task has children
        $quantityRowHTML = '';
        if (!$hasChildren){
            // Create the quantity row
            $quantityRowHTML = '
                                    <tr>
                                        <td height="39" width="40%" align="left" valign="top">
                                            <strong><label style="height: 19px; width:40%;" >Deliverable Quantity:</label></strong>
                                        </td>
                                        <td height="39" width="10%" align="left" valign="top">
                                            <input name="deliverableQuantity" id="deliverableQuantity" type="text" maxlength="11" style="height: 19px;  width:85%;" value="' . $deliverableQuantity . '" ' . $highLevelFieldsAccess . '>
                                        </td>
                                        <td height="39" width="40%" align="right" valign="top">
                                            <strong><label style="height: 19px; width:40%;">Total Quantity:</label></strong>
                                        </td>
                                        <td height="39" width="10%" align="right" valign="top">
                                            <input name="totalQuantity" id="totalQuantity" type="text" maxlength="11" style="height: 19px; width:85%;" value="' . $totalQuantity . '" ' . $highLevelFieldsAccess . '>
                                        </td>
                                    </tr>
                                ';
        }
        
        // Create somevariables to hold info about whether we have rows for blanks, tools and notes
        $haveTools = false;
        $haveBlanks = false;
        $haveNotes = false;

        // Create the query to check the amount of tools
        $testSql = 'SELECT count(*) as toolCount FROM tooltotasklinker ' . 
                   'WHERE TaskID=' . $taskNumber . ';';

        // Attempt to get all of the tools for this category type and ID
        $testRows = $db->queryDB($testSql, $userRow, "task_presentation Form occurance 15");

        // Determine if there were rows for the tools on this task
        if ($testRows != null && 
            mysqli_num_rows($testRows)>0){
            // Get the row as an assoc row
            $testRowAssoc = $testRows->fetch_assoc();
            
            // Determine if we have more than zero
            if ($testRowAssoc["toolCount"]>0){
                // set the flag to say there are tools
                $haveTools = true;
            }
        }

        // Create the query to check the amount of blanks
        $testSql = 'SELECT count(*) as blankCount FROM jobblanks ' . 
                   'WHERE TaskID=' . $taskNumber . ';';

        // Attempt to get all of the blanks for this category type and ID
        $testRows = $db->queryDB($testSql, $userRow, "task_presentation Form occurance 16");

        // Determine if there were rows for the blanks on this task
        if ($testRows != null && 
            mysqli_num_rows($testRows)>0){
            // Get the row as an assoc row
            $testRowAssoc = $testRows->fetch_assoc();
            
            // Determine if we have more than zero
            if ($testRowAssoc["blankCount"]>0){
                // set the flag to say there are blanks
                $haveBlanks = true;
            }
        }

        // Create the query to check the amount of notes
        $testSql = 'SELECT count(*) as noteCount FROM notes ' . 
                   'WHERE AssociatedCategoryID = ' . $taskNumber . ' ' .
                   'AND   IsSticky=0 ' .
                   'AND   Category = "TASK";';

        // Attempt to get all of the blanks for this category type and ID
        $testRows = $db->queryDB($testSql, $userRow, "task_presentation Form occurance 17");

        // Determine if there were rows for the notes on this task
        if ($testRows != null && 
            mysqli_num_rows($testRows)>0){
            // Get the row as an assoc row
            $testRowAssoc = $testRows->fetch_assoc();
            
            // Determine if we have more than zero
            if ($testRowAssoc["noteCount"]>0){
                // set the flag to say there are blanks
                $haveNotes = true;
            }
        }
        
        // Determine if we have any blanks or notes for this task
        if ($machineID>0 || $haveTools || $haveBlanks || $haveNotes){
            // Setup the styling to be green text
            $machiningButtonStyling .= 'color:LimeGreen;';
        }
        
        // Setup a query to get the low/high numbers for attachments 
        $sql='SELECT ProcessOrder, Name FROM status WHERE Name in ("Waiting Assignment", "Delivered") ORDER BY ProcessOrder;';

        // Query the database for the the two statuses 
        $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 18");

        // Loop through the returned results
        $lowViewNumber = -1;                
        $highViewNumber = -1;                
        while ($row=mysqli_fetch_array($rows)){
            // Determine if we have set the low yet
            if ($lowViewNumber==-1){
                // Set the low number
                $lowViewNumber=$row["ProcessOrder"];
            }
            else {
                // Set the high number
                $highViewNumber=$row["ProcessOrder"];
            }
        }

        // Create variables for the attachments, notes and tools HTML
        $attachmentsHTML = '';

        // Determine if They are of the correct state to see extra things
        if ($userRow["UserLevel"]=='SU' || $userRow["UserLevel"]=='EXECUTIVE' ||
            $userRow["UserLevel"]=='MANAGEMENT' || in_array($processOrder, range($lowViewNumber,$highViewNumber)) ||
            $assignedToID==$userRow["UserID"] || $mainSubCompany || $companyID==1 ||
            $userRow["CompanyID"]==$companyID){
            // Get html for the notes and attachments
            $attachmentsHTML = retrieveTaskAttachments($db, $userRow, $taskNumber, $mainSubCompany);

            // If it has children, then no display of the machining tab is allowed
            if ( $hasChildren == 1){
                // Set the tab to invisible
                $machiningButtonStyling = 'display:none;';
            }
        }
        else {
            // Set the tab to invisible
            $machiningButtonStyling = 'display:none;';
        }
        
        // Get the current time of opening this task
        $micro_date = microtime();
        $date_array = explode(" ",$micro_date);
        $startServerTime = date("Y-m-d H:i:s",$date_array[1]);
        $localtime = (date("Y-m-d H:i:s", strtotime("-1 hour", $date_array[1])));

        // Determine if they are of the SU Company to change status access
        $someFieldsAccess=$allFieldsAccess;
        if (($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT" || $userRow["UserLevel"]=="MID-MANAGEMENT") &&
            ($userRow["CompanyID"]==1) &&
            ($userRow["CompanyID"]==$companyID)){
            // Allow them to see the fields marked as ones for this group
            $someFieldsAccess="";
        }

        // Setup the secondary status as though they are not from the SU company
        $secondaryStatusHTML='
                         <tr>
                             <td colspan=4 width="100%"><strong>Task Notes (2000 characters):</strong><br> 
                                 <textarea name="description" maxlength="2000" class="intext" style="width: 100%; height: 310px; overflow: auto; resize:none" ' . $someFieldsAccess . '>' .
                                 $description .
                                 '</textarea>
                             </td>
                         </tr> 
                         ';
        
        // Determine if they are in the SU company
        if (($userRow["CompanyID"]==1)){
            // Determine if the user is NOT a super user
            $addTaskNotesHTML="";
            $notesHeight="210";
            if (($userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT") && 
                $companyID!=1 && $mainSubCompany==false){
                // Create the HTML area for other user to add their notes for the task
                $addTaskNotesHTML='
                                <tr>
                                    <td colspan=4 width="100%"><br><strong>Add Task Notes:</strong><br> 
                                        <input type="hidden" name="hiddenDescription" id="hiddenDescription" value="' . $description . '"/>
                                        <textarea name="addDescription" id="addDescription" maxlength="2000" class="intext" style="width: 100%; height: 60px; overflow: auto; resize:none">
                                        </textarea>
                                    </td>
                                </tr> 
                        ';
                $notesHeight="150";
            }
            
            // Allow them to see the fields marked as ones for this group
            $secondaryStatusHTML='
                                <tr>
                                    <td colspan=4 width="100%"><strong>Task Notes (2000 characters):</strong><br> 
                                        <textarea name="description" maxlength="2000" class="intext" style="width: 100%; height: ' . $notesHeight . 'px; overflow: auto; resize:none" ' . $someFieldsAccess . '>' .
                                        $description .
                                        '</textarea>
                                    </td>
                                </tr> ' 
                                . 
                                $addTaskNotesHTML 
                                . 
                                '<tr>
                                    <td colspan=4 height="39" align="left" valign="top">
                                        <br>
                                        <strong>Secondary Status: </strong> &nbsp; &nbsp;
                                        ' 
                                        . getSecondaryStatusAsSelectOptions($db, $userRow, $secondaryStatusID) . 
                                        '
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan=4 width="100%">
                                        <textarea name="secondaryStatusDescription" id="secondaryStatusDescription" maxlength="2000" class="intext" style="width: 100%; height: 35px; overflow: auto; resize:none; background: white;" disabled>' .
                                        $secondaryStatusDescription .
                                        '</textarea>
                                    </td>
                                </tr> 
                             ';
        }
        
        // Create the HTML to show or hide the vendor cell
        $vendorCellStyle=(strpos($statusName, "Outside Services")==false || $userRow["CompanyID"]!=1)?'style="display:none; width:100%;"':'';
        
        // Determine if it is an expedite part
        $rowExpedite='';
        $expediteTitle='';
        if ($expedite==1){
            // This one is common
            $rowExpedite=' expediteTaskBackground';
                        
            // Setup the title
            $expediteTitle='This part is expedited. It takes highest priority.';
        }

        return createCompanyEmployeesAsJSON($db, $userRow, $assignedToID) .
          '<div class="' . $rowExpedite . '" title="' . $expediteTitle . '">
            <br>
            <button class="tablink" type="button" onclick="openPage(\'GeneralInfo\');" id="defaultOpen">General Info</button>
            <button class="tablink" type="button" onclick="openPage(\'StickyNotes\'); document.getElementById(\'tabsStickyNotes\').click();" style="' . $stickyNotesButtonStyling . '">Sticky Notes</button>
            <button class="tablink" type="button" onclick="openPage(\'Machining\'); document.getElementById(\'generalMachiningTabButton\').click();" style="' . $machiningButtonStyling . '">Machining</button>
            <button class="tablink" type="button" onclick="openPage(\'History\'); document.getElementById(\'taskStatusesAsListID\').click();" style="' . $historyButtonStyling . '">History</button>
            <form action="' . $modifyType . 'Task.php?updateTaskID=' . $taskNumber . '&parentTaskId=0&cs=' . $selectedCompany . '&ts=' . $selectedType . '" method="post" name="' . $modifyType . 'Task" id="' . $modifyType . 'Task" enctype="multipart/form-data">  
                <div id="updateDiv">
                    <input name="formSubmit" id="formSubmit" type="submit" onclick="this.disabled=true; if (wantsFirstPositionOnMachiningMachine(' . $machineID . ', document.getElementById(\'machineID\'), document.getElementById(\'machineTaskOrder\').value)){alert(\'The machine you are trying to move this to has a machining job and you are trying to move the task to the first position. Rectify this and try again.\'); this.disabled=false; wantsFirstPositionOnMachineWithMachiningTask=true; return false;} else{this.form.submit();}" style="pointer-events: auto; cursor: hand; ' . $updateTaskVisibilityHTML . '" value="' . $modifyType . ' task" title="' . $modifyType . ' this parent task." ' . $onClickHTML . '/>
                </div>          
                <input type="hidden" name="localTime" id="localTime" value="' . $localtime . '">
                <input type="hidden" name="redirectTo" id="redirectTo" value="' . $fromWhatBaseURL . '"/>
                <input type="hidden" name="deliverableQuantityHidden" id="deliverableQuantityHidden" value="' . $deliverableQuantity . '"/>
                <input type="hidden" name="totalQuantityHidden" id="totalQuantityHidden" value="' . $totalQuantity . '"/>
                <input type="hidden" name="outsideServiceVendorID" id="outsideServiceVendorID" value="' . $outsideServiceVendorID . '"/>
                <div id="GeneralInfo" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr align="left" valign="top">
                            <td width="48%">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Created By: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">
                                            ' . $createdByFirstName . '  ' . $createdByLastName . '
                                            <input type="hidden" name="createdBy" value="' . $createdByID . '"> 
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Created Date: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">
                                              ' . $createdDate . ' 
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>EES TID: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">
                                            <input type="hidden" id="taskID" name="taskID" value="' . $taskNumber . '">
                                              ' . $taskNumber . '
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Task Type: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">' . 
                                            getTaskTypesAsSelectOptions($db, $userRow, $taskTypeID, $allFieldsAccess) .
                                        '</td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Status: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">' .
                                            getStatusAsSelectOptions($db, $userRow, $statusID, $onStatusChangeHTML, $statusFieldAccess, "previousToOutsideServicesValue=this.options[this.selectedIndex].text;") . 
                                           '<input type="hidden" id="oldStatusID" name="oldStatusID" value="' . $statusID . '">
                                            <div id="vendorCell" ' . $vendorCellStyle . '> 
                                                <strong>To</strong>:' .
                                                getVendorAsSelectOptions($db, $userRow, $outsideServiceVendorID, "document.getElementById('outsideServiceVendorID').value=this.options[this.selectedIndex].value;", "", "", "width:128px;") .
                                                '
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Task Assigned To: </strong> &nbsp; &nbsp; 
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">
                                            <select name="assignedTo" id="assignedTo" ' . $statusFieldAccess . '></select> 
                                        </td>
                                    </tr>
                                    '
                                    .
                                    $childrenAssignedToHTML
                                    .
                                    '
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Priority Level: </strong> &nbsp; &nbsp; 
                                        </td>
                                        <td height="39" align="left" valign="top">
                                            <input name="priority" id="priority" type="text" maxlength="11" class="intext" title="99998 represents lowest priority" style="width: 100%;" ' . $suManagementLevelFieldsHTML . ' value="' . $priority . '" ' . $allFieldsAccess . '>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong><label>Due Date:</label></strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">
                                            <input name="dueDate" id="dueDate" type="date" class="intext" style="width: 100%;" value="' . $dueDate . '" ' . $highLevelFieldsAccess . '>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Ideal Date:</strong> &nbsp; &nbsp;
                                        </td>
                                        <td height="39" align="left" valign="top" width="45%">
                                            <input name="idealDate" type="date" class="intext" style="width: 100%;" ' . $suManagementLevelFieldsHTML . ' value="' . $idealDate . '">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="left" valign="top" colspan=1>
                                          <input type="hidden" name="expedite" id="expedite" value="' . $expedite . '"/>
                                          <input name="expediteVisible" id="expediteVisible" type="checkbox" ' . $expediteHTML . ' onchange="document.getElementById(\'expedite\').value=this.checked; if (this.checked==true){alert(\'This will change the priority of this parent task to number one. This can be changed before the update button is pressed, if you do not want to increase the priority.\'); document.getElementById(\'priority\').value=1;}"' . $highLevelFieldsAccess . '>
                                          <strong><label for="expedite">Expedite Task</label></strong>
                                        </td>
                                    </tr>
                                    '
                                    .   
                                        getTaskCheckboxes($userRow, $invoiced, $completed, $closed, $cleanUp, 1)
                                    . 
                                    '
                                    <tr>
                                      <td height="39" align="left" valign="top" colspan=2>
                                            <strong>Updated </strong>' . $lastUpdatedDate . ' <strong>by</strong> ' . $lastUpdatedByFirstName . ' ' . $lastUpdatedByLastName . '
                                      </td>
                                    </tr>
                                </table>
                            </td>
                            <td width="4%">&nbsp;</td>
                            <td width="48%">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                      <td colspan=4 height="39" align="left" valign="top">
                                            <strong>Company: </strong>' . getCompanyHTML($db, $userRow, $companyID, "displayCorrectCompanyEmployees();", $allFieldsAccess, true, $mainSubCompany) . '
                                            <br>
                                            <br>
                                      </td>
                                    </tr>
                                    ' .
                                    $quantityRowHTML
                                    .
                                    $priceHTML
                                    .
                                    '                        
                                </table>
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                     <tr>
                                        <td height="39" align="left" valign="top">
                                            <strong>Title:</strong><br> 
                                        </td>
                                        <td height="39" align="left" valign="top">
                                            <textarea name="title" maxlength="100" class="intext" style="width: 100%; height: 53px; overflow: auto; resize:none" ' . $someFieldsAccess . '>' .
                                            $title .
                                            '</textarea>
                                            <br><br>    
                                        </td>
                                    </tr>
                                    '
                                    .
                                    $secondaryStatusHTML
                                    .
                                    '
                                </table>
                                <br>    
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                     <tr>
                                        <td colspan=4 >
                                            <br>
                                            <p align="right">
                                                <input type="hidden" name="formSubmitted" value="TRUE">
                                                <input type="hidden" id="newAttachmentNumbers" name="newAttachmentNumbers" value="0">
                                            </p>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        ' . $addTasksHTML . '
                        <tr align="left" valign="middle">
                            <td colspan=4>
                                <div name="childrenTasks" id="childrenTasks">
                                ' . $children . '
                                </div>
                            </td>
                        </tr>
                    </table>
                    <input type="hidden" name="MAX_FILE_SIZE" id="maxFileSize" value="4294967296">
                    <div>
                        <strong>Current Attachments: </strong>
                        <div id="currentAttachments" style="margin: 5 auto; width: 100%; ">
                            <input type="hidden" name="deleteCurrentAttachments" id="deleteCurrentAttachments" value=""></input>' .
                            $attachmentsHTML .
                        '</div>
                    </div>
                    <div style="' . $addNewAttachmentsVisibilityHTML . '">
                        <strong>New Attachments: </strong>
                        <div id="newAttachments" style="margin: 5 auto; width: 100%; ">
                        </div>
                    </div>
                    <p align="right">
                        <button type="button" onClick="addNewAttachment()"  style="' . $addNewAttachmentsVisibilityHTML . '" align="right">new attachment</button>
                    </p>
                </div>
                <div id="StickyNotes" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <div id="tabsStickyNotes">
                        <br>
                        '
                        .
                        $stickyNoteDivHTML
                        .
                        '
                    </div>
                </div>
                <div id="Machining" style="background-color:' . $secondaryStatusColor . '; display: none;" class="tabcontent">
                    '
                    .
                    $ssButtonHTML . '&nbsp' . $makePacketButtonHTML . $operatorFeedbackNotificationHTML
                    .
                    '
                    <br><br>
                    <button class="childtablink" type="button" onclick="openChildPage(\'GeneralMachiningInfo\', this);" style="border-left: 2px solid forestgreen; border-right: 2px solid forestgreen; border-top: 2px solid forestgreen; border-bottom: none;" id="generalMachiningTabButton">General</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'BlanksInfo\', this);" id="blanksTabButton" title="Blanks present will only be shown if the blank has been submitted, if the user is assigned to the task or the user is a Super User.">Blanks</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'ToolsInfo\', this);" id="toolsTabButton" title="This tab will not be enabled if task is not in machining.">Tools</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'SetupsInfo\', this);" id="setupsTabButton" title="This tab will not be enabled if task is not in machining. Setups present will only be shown if task is past Machining Queue phase, if the user is assigned to the task or the user is a Super User." >Setups</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'NotesInfo\', this);" id="notesTabButton">Notes</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'PostMachiningInfo\', this);" id="postMachiningTabButton">Post Machining</button>
                    <div id="GeneralMachiningInfo" class="childtabcontent" style="display:block;">
                        <br><br>
                        <label style="font-size: 20px;"><strong>General:</strong></label>
                        <br><br>
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Machine:</label></strong>
                                </td>
                                <td width="20%" align="left">
                                    '
                                    .
                                    getMachineAsSelectOptions($db, $userRow, $machineID, "enableOrderControl(this.value); checkAndChangeToolPositions(this.selectedIndex);", $statusFieldAccess, 'machineToolSlotMaxes') 
                                    .
                                    '
                                    <input type="hidden" name="oldMachineID" id="oldMachineID" value="' . $machineID . '"></input>
                                </td>
                                <td width="10%">
                                </td>
                                <td width="30%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Order (99998 is lowest):</label></strong>
                                </td>
                                <td width="30%" align="left">
                                    <input name="machineTaskOrder" id="machineTaskOrder" title="This will only be set if there is a machine chosen." type="text" maxlength="11" style="height: 19px;  width:30%;" value="' . $theOrder . '" ' . $orderDisabledHTML . '>
                                    <input name="hiddenMachineTaskOrder" id="hiddenMachineTaskOrder" type="hidden" value="' . $theOrder . '">
                                    <input type="hidden" name="oldMachineTaskOrder" id="oldMachineTaskOrder" value="' . $theOrder . '"></input>
                                </td>
                            </tr>
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Fixture:</label></strong>
                                </td>
                                <td width="20%" align="left">
                                    '
                                    .
                                    getFixturesAsSelectOptions ($db, $userRow, $fixtureID, "", $statusFieldAccess) 
                                    .
                                    '
                                </td>
                                <td width="10%">
                                    <input name="toFixture" id="toFixture" type="button" style="pointer-events: auto; cursor: hand; ' . $updateTaskVisibilityHTML . '" value="..." title="This will open a new tab to the fixture." onclick="javascript:if (document.getElementById(\'fixture\').value>0){window.open(\'updateTask.php?updateTaskID=\' + document.getElementById(\'fixture\').value + \'\', \'_blank\');} else{alert(\'There is no fixture to go and get.\');} return false;"/>
                                </td>
                                <td width="30%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Pending Options:</label></strong>
                                </td>
                                <td width="30%" align="left">
                                    '
                                    .
                                    getSecondaryStatusCheckboxes($isWaitingToBeReviewed,$isPendingTools,$isPendingApproval)
                                    .
                                    '
                                </td>
                            </tr>
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Programmer:</label></strong>
                                </td>
                                <td width="20%" align="left">
                                    <div name="programmerDiv" id="programmerDiv"></div> 
                                </td>
                                <td width="10%">
                                </td>
                                <td width="30%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Program Checked By:</label></strong>
                                </td>
                                <td width="30%" align="left">
                                    <div name="programCheckedByDiv" id="programCheckedByDiv"></div> 
                                </td>
                            </tr>
                            '
                            .
                            $issuedToMachineDateHTML
                            .
                            '
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <br>
                                    <strong><label style="height: 19px; width:40%;" >Hardware:</label></strong>
                                </td>
                                <td width="20%" align="left" colspan=4>
                                    <br>
                                    <textarea name="partHardware" id="partHardware" maxlength="500" class="intext" style="width: 100%; height: 70px; overflow: auto; resize:vertical">' .
                                    $partHardware .
                                    '</textarea>
                                </td>
                            </tr>
                        </table>
                        <br>
                    </div>
                    '
                    .
                    checkThenGetBlanksDiv($db, $userRow, $taskNumber, $blankValidationHTML)
                    .   
                    checkThenGetToolsDiv($db, $userRow, $taskNumber, $toolsValidationHTML)
                    .   
                    checkThenGetSetupsDiv($db, $userRow, $taskNumber, $setupsValidationHTML)
                    .
                    checkThenGetNotesDiv($db, $userRow, $taskNumber, 'TASK', $noteValidationHTML)
                    .
                    '
                    <div id="PostMachiningInfo" class="childtabcontent" style="display:none;">
                        <br><br>
                        <label style="font-size: 20px;"><strong>Post Machining:</strong></label>
                        <br><br>
                        '
                        .
                        createPostMachiningInformation($isVacuumClean, $isWashForAnodize,
                                                       $hasAllowableCosmeticDamage, 
                                                       $isTappedPostMachining, $postMachiningTappingInstructions,
                                                       $isSandblasted, $sandBlastingInstructions,
                                                       $postMachiningNotes, $postMachiningFeedback)
                        .
                        '
                    </div>
                </div>
                <div id="History" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <br>
                    ' . retrieveTaskStatusesAsList($db, $userRow, $taskNumber) . '<br>
                </div>
            </form>
            <script language="JavaScript">
                var originalProgrammerID = ' . $programmerID . ';
                var originalProgramCheckedByID = ' . $programCheckedByID . ';
                var startServerTime = "' . $startServerTime . '";
                var copiedFromHasFeedback = "' . $assocTask["CopiedFromHasFeedback"] . '";
                var copiedFromTaskID = "' . $assocTask["CopiedFromTaskID"] . '";
                var wantsFirstPositionOnMachineWithMachiningTask = false;
                    
                // Code for validating the form
                // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                // for details
                var frmvalidator = new Validator("' . $modifyType . 'Task", "formSubmit");
                frmvalidator.addValidation("priority",
                                           "req",
                                           "Please enter the priority of this task.");
                frmvalidator.addValidation("priority",
                                           "posint",
                                           "Please enter the priority of this task as a number.");
                frmvalidator.addValidation("priority",
                                           "greaterthan=0",
                                           "The priority should be greater than 0.");
                frmvalidator.addValidation("priority",
                                           "lessthan=99999",
                                           "The priority should be less than 99999.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "req",
                                           "Please enter the order of this task.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "posint",
                                           "Please enter the order of this task as a number.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "greaterthan=0",
                                           "The order should be greater than 0.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "lessthan=99999",
                                           "The order should be less than 99999.");
                frmvalidator.addValidation("title",
                                           "required",
                                           "There must be a value for the title.");
                '
                .
                $toolsValidationHTML
                .
                $blankValidationHTML
                . 
                $noteValidationHTML
                . 
                $setupsValidationHTML
                .
                $stickyNoteValidationHTML
                .
                '
                frmvalidator.setAddnlValidationFunction(function() {return checkform("' . $taskNumber . '", ' . $hasChildren . ');});
                                           
                function parseCompany(stringToParse){
                    var theArray = stringToParse.split("|");

                    // determine if the array is the correct size
                    if (theArray.length > 1){
                        return theArray[1];
                    }
                }
                
                // Get a variable to hold the initial status value
                var initialStatus
                
                function onChangeStatus(statusControl, statusID){
                    if (window.confirm("Are you sure you want to change this task status? This will result in all the children tasks being changed to this status as well. This cannot be undone.") == true){
                        prefillOrderControl(statusControl.options[statusControl.selectedIndex].text); 
                        outsideServiceCheck(statusControl.options[statusControl.selectedIndex].text); 
                        return true;
                    } 
                    else{
                        //set this back to the original value when this form was refreshed
                        statusControl.value = statusID;
                        return false;
                    }
                }
                        
                // Change the back button to ensure that is keeps get variables in order to know exactly where to go
                history.pushState(null, null, \'' . $_SERVER["REQUEST_URI"] . '\');
                window.addEventListener(\'popstate\', function(event) {
                    window.location.assign("' . $fromWhatBaseURL . '");
                });
                
            </script>';
    }
    
    function getChildTask($db, $userRow, $taskNumber, $parentTaskNumber, $selectedCompany, $selectedType, $fromWhatBaseURL){
        // Init all of the settings to the appropriate values
        $title = '';
        $description = '';
        $priority = 99998;
        $idealDate = '';
        $dueDate = '';
        $highLevelFieldsAccess = '';
        $priceAccess = '';
        $taskPrice = 'TBD';
        $deliverableQuantity = 0;
        $totalQuantity = 0;
        $createdByID = $userRow["UserID"];
        $createdByFirstName =  $userRow["FirstName"];
        $createdByLastName =  $userRow["LastName"];
        $createdDate = "Unknown";
        $statusID = null;
        $assignedToID = -1;
        $taskTypeID = null;
        $companyID = -1;
        $invoiced = false;
        $completed = false;
        $closed = false;
        $isWaitingToBeReviewed = false;
        $isPendingTools = false;
        $isPendingApproval = false;
        $machineID = -1;
        $fixtureID = -1;
        $theOrder = 99998;
        $allowCreditPayment = true;
        $expedite = 0;
        $expediteHTML = '';
        $isVacuumClean = 0;
        $isWashForAnodize = 0;
        $hasAllowableCosmeticDamage = 0;
        $isTappedPostMachining = 0;
        $postMachiningTappingInstructions = '';
        $isSandblasted = 0;
        $sandBlastingInstructions = '';
        $postMachiningNotes = '';
        $postMachiningFeedback = '';
        $programmerID = -1;
        $programCheckedByID = -1;
        $partHardware='';
        $secondaryStatusID = -1;
        $secondaryStatusColor = 'ffffff';
        $secondaryStatusDescription = '';
        $outsideServiceVendorID = null;

        $subPriority = 99998;
        $parentStatusID = -1;
        $parentStatusName = null;
        $parentTitle = null;
        
        $modifyType = 'add';
        
        // Setup the on clicks 
        $onClickHTML = 'onclick="javascript:reenableCmbBoxes(); populateCurrentDateTime(\'localTime\',\'yyyy-MM-dd hh:mm\'); document.getElementById(\'hiddenMachineTaskOrder\').value=document.getElementById(\'machineTaskOrder\').value;"';

        // Setup the button for setup sheets and making the packetas nothing at first
        $ssButtonHTML = '';
        $makePacketButtonHTML = '';
            
        // setup the sticky not div
        $stickyNoteDivHTML='';

        // Set the blanks validation script to nothing at first
        $toolsValidationHTML="";
        $setupsValidationHTML="";
        $blankValidationHTML="";
        $noteValidationHTML="";
        $stickyNoteValidationHTML="";
                
        // Determine if the user editing this is NOT a SU or not
        if ($userRow["UserLevel"]!="SU"){
            // Disable price and due date editing except for SU's
            $priceAccess = 'disabled';
        }

        // Determine if the user editing this is NOT a SU or can modify children
        if ($userRow["UserLevel"]!="SU" || $userRow["CanModifyChildren"]==1){
            // Disable price and due date editing except for SU's
            $highLevelFieldsAccess = 'disabled';
        }

        // Levels Management and above can see this so set as default
        $allFieldsAccess = '';
        $addNewAttachmentsVisibilityHTML = 'display:none;';
        $updateTaskVisibilityHTML = 'display:none;';
        $suManagementLevelFieldsHTML = 'display:none;';
        $makePacketVisibility = "display:none;";
        
        // Set the status field to disabled for now
        $statusFieldAccess = 'disabled';

        // Set the tab to be hidden for now
        $machiningButtonStyling = 'display:none;';
        $routingButtonStyling = 'display:none;';
        $stickyNotesButtonStyling = 'display:none;';
        $historyButtonStyling = 'display:none;';

        // Determine if they are of the SU Company to change status access
        if ($userRow["CompanyID"]==1){
            // Give them access to the status
            $statusFieldAccess = '';
            $updateTaskVisibilityHTML = '';
            
            // Determine if this is an update or not
            if ($taskNumber!=null && $taskNumber>0){
                // Set them as visible
                $machiningButtonStyling = 'display:block;';
                $stickyNotesButtonStyling = 'display:block;';
                $historyButtonStyling = 'display:block;';
            }
        }

        // Determine if they can modify routing
        if ($userRow["CanModifyRouting"]==1){
            // Give them access to the routing tab
            $routingButtonStyling = 'display:block;';
        }

        // Determine if we have a parent to this new child task, so we can change things based on it.
        // This is the 'new child' case.  Things will change after if this is an update.
        if ($parentTaskNumber!=null &&
            $parentTaskNumber>0){
            // Create the query to get the the task and the user that created the task
            $sql = 'SELECT t.*, u.FirstName, u.LastName, c.AllowCredit, c.MainSubCompany, s.Name AS StatusName, ' . 
                          'c.Store, s.ProcessOrder, m.MachineID, m.Name as MachineName, tm.TheOrder, ' .
                          'ss.Description as SSDescription, ss.RowColor AS SSRowColor, usvl.ViewCategory ' .
                   'FROM tasks t ' . 
                   'LEFT JOIN users u ON t.CreatedByID = u.UserID ' .
                   'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                   'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                   'LEFT JOIN tasktomachinelinker tm ON t.TaskID = tm.TaskID ' .
                   'LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID ' .
                   'LEFT JOIN machines m ON tm.MachineID = m.MachineID ' .
                   'LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
                   'WHERE t.TaskID=' . $parentTaskNumber . ' ' .
                   'AND t.ParentID=0;';

            // Attempt to change all of the rows that need to be changed
            $row2 = $db->queryDB($sql, $userRow, "task_presentation Form occurance 19");

            // Attempt to get the parent row
            $assocTask2 = $row2->fetch_assoc();

            // Determine if this person is of appropriate level and company
            if ($userRow["CompanyID"] != 1 && 
                $userRow["CompanyID"] != $assocTask2["CompanyID"]){
                    // redirect to the invalid access page
                    echo ('<script>window.location = "invalid_access.php";</script>');

                    exit;
            }

            // Set the things we can
            $priority = $assocTask2["Priority"];
            $subPriority = 99998;
            $dueDate = $assocTask2["DueDate"];
            $taskTypeID = $assocTask2["TypeID"];
            $companyID = $assocTask2["CompanyID"];
            $mainSubCompany = $assocTask2["MainSubCompany"];
            $invoiced = $assocTask2["Invoiced"];
            $completed = $assocTask2["Completed"];
            $closed = $assocTask2["Closed"];
            $allowCreditPayment = $assocTask2["AllowCredit"];
            $parentStatusID = $assocTask2["StatusID"];
            $parentStatusName = $assocTask2["StatusName"];
            $parentTitle = $assocTask2["Title"];

            // Determine if we are adding a new child.
            if (!$taskNumber){
                // Set the child secondary information the same as the parent
                $secondaryStatusID = $assocTask2["SecondaryStatusID"];
                $secondaryStatusColor = $assocTask2["SSRowColor"];
                $secondaryStatusDescription = $assocTask2["SSDescription"];
            }
            
            // Determine if this task is one of the main companies and if the user is allowed to modify it
            if (($mainSubCompany==1 && $userRow["CompanyID"]==1) ||
                $userRow["CanModifyChildren"]==1){
                    // For this combination, it is ok for this user to edit
                    $highLevelFieldsAccess = '';
            }

            // Determine if the task price is null
            if ($taskPrice == null){
                // Set the task price to be showing TBD
                $taskPrice = 'TBD';
            }
        }
            
        // Determine if this is an update or not
        $assocTask = null;
        if ($taskNumber){
            // Create the query to get the the task and the user that created the task
            $sql = 'SELECT t.*, u.FirstName, u.LastName, ' . 
                   'u2.FirstName AS LastUpdatedUserFirstName, u2.LastName AS LastUpdatedUserLastName, ' . 
                   'c.AllowCredit, c.MainSubCompany, c.Store, ' . 
                   's.ProcessOrder, s.Name AS StatusName, ' . 
                   'm.MachineID, m.Name as MachineName, ' . 
                   'tm.TheOrder, tm.IsWaitingToBeReviewed, tm.IsPendingTools, tm.IsPendingApproval, ' .
                   'ss.Description as SSDescription, ss.RowColor AS SSRowColor, ' .
                   'IF(ctl.CopiedFromTaskID IS NULL,"null",ctl.CopiedFromTaskID) AS CopiedFromTaskID , ctl.DateCopied AS CopiedDate, ctl.CopyingUserID, IF(ctl.CopiedFromHasFeedback IS NULL,0,ctl.CopiedFromHasFeedback) AS CopiedFromHasFeedback, ' .
                   'tsi.MainBranchID, FLOOR(tsi.ExecutionOrder) AS TrunkExecutionOrder, ' . 
                   't2.ParentID AS CopiedFromParentID ' .
                   'FROM tasks t ' . 
                   'LEFT JOIN users u ON t.CreatedByID = u.UserID ' .
                   'LEFT JOIN users u2 ON t.LastUpdatedByID = u2.UserID ' .
                   'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                   'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                   'LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID ' .
                   'LEFT JOIN tasktomachinelinker tm ON t.TaskID = tm.TaskID ' .
                   'LEFT JOIN machines m ON tm.MachineID = m.MachineID ' .
                   'LEFT JOIN copiedtaskslinker ctl ON t.TaskID = ctl.CopiedToTaskID ' .
                   'LEFT JOIN tasks t2 ON ctl.CopiedFromTaskID = t2.TaskID ' .
                   'LEFT JOIN taskstatusinfo_current tsi ON t.CurrentTaskStatusRoutingNodeID = tsi.TaskStatusInfoID ' .
                   'WHERE t.TaskID=' . $taskNumber . ' ' .
                   'AND t.ParentID=' . $parentTaskNumber . ';';
//echo '<script>alert("' . addslashes($sql) . '");</script>';
            // Attempt to change all of the rows that need to be changed
            $row = $db->queryDB($sql, $userRow, "task_presentation Form occurance 20");

            // Attempt to get the user row
            $assocTask = $row->fetch_assoc();

            // Determine if this person is of appropriate level and company
            if ($userRow["CompanyID"] != 1 && 
                $userRow["CompanyID"] != $assocTask["CompanyID"]){
                    // redirect to the invalid access page
                    echo ('<script>window.location = "invalid_access.php";</script>');

                    exit;
            }
            
            // Set the things we can
            $title = $assocTask["Title"];
            $description = $assocTask["Entry"];
            $priority = $assocTask["Priority"];
            $dueDate = $assocTask["DueDate"];
            $idealDate = $assocTask["IdealDate"];
            $createdByID = $assocTask["CreatedByID"];
            $createdByFirstName = $assocTask["FirstName"];
            $createdByLastName = $assocTask["LastName"];
            $createdDate = date("Y-m-d H:i:s", strtotime("-1 hour", strtotime($assocTask["CreatedDate"])));
            $lastUpdatedDate = date("Y-m-d H:i:s", strtotime("-1 hour", strtotime($assocTask["LastUpdated"])));
            $lastUpdatedByFirstName = $assocTask["LastUpdatedUserFirstName"];
            $lastUpdatedByLastName = $assocTask["LastUpdatedUserLastName"];
            $statusID = $assocTask["StatusID"];
            $assignedToID = $assocTask["UserID"];
            $taskTypeID = $assocTask["TypeID"];
            $companyID = $assocTask["CompanyID"];
            $mainSubCompany = $assocTask["MainSubCompany"];
            $invoiced = $assocTask["Invoiced"];
            $completed = $assocTask["Completed"];
            $closed = $assocTask["Closed"];
            $isWaitingToBeReviewed = $assocTask["IsWaitingToBeReviewed"];
            $isPendingTools = $assocTask["IsPendingTools"];
            $isPendingApproval = $assocTask["IsPendingApproval"];
            $allowCreditPayment = $assocTask["AllowCredit"];
            $modifyType = 'update';
            $taskPrice = $assocTask["TaskPrice"];
            $deliverableQuantity = $assocTask["DeliverableQuantity"];
            $totalQuantity = $assocTask["TotalQuantity"];
            $processOrder = $assocTask["ProcessOrder"];
            $machineID = $assocTask["MachineID"];
            $fixtureID = $assocTask["FixtureToUseID"];
            $statusName = $assocTask["StatusName"]; 
            $expedite = $assocTask["Expedite"];
            $expediteHTML = ($assocTask["Expedite"]==1)?'checked':'';
            $isVacuumClean = $assocTask["IsVacuumClean"];
            $isWashForAnodize = $assocTask["IsWashForAnodize"];
            $hasAllowableCosmeticDamage = $assocTask["HasAllowableCosmeticDamage"];
            $isTappedPostMachining = $assocTask["IsTappedPostMachining"];
            $postMachiningTappingInstructions = $assocTask["PostMachiningTappingInstructions"];
            $isSandblasted = $assocTask["IsSandblasted"];
            $sandBlastingInstructions = $assocTask["SandBlastingInstructions"];
            $postMachiningNotes = $assocTask["PostMachiningNotes"];
            $postMachiningFeedback = $assocTask["PostMachiningFeedback"];
            $subPriority = $assocTask["SubPriority"];
            $programmerID=($assocTask["ProgrammerID"]==null)?-1:$assocTask["ProgrammerID"];
            $programCheckedByID=($assocTask["ProgramCheckedByID"]==null)?-1:$assocTask["ProgramCheckedByID"];
            $partHardware = $assocTask["PartHardware"];
            $secondaryStatusID = $assocTask["SecondaryStatusID"];
            $secondaryStatusColor = $assocTask["SSRowColor"];
            $secondaryStatusDescription = $assocTask["SSDescription"];
            $outsideServiceVendorID = $assocTask["OutsideServiceVendorID"];
            $templateName = $assocTask["LastAppliedRouteTitle"];
            $currentTaskStatusRoutingNodeID = $assocTask["CurrentTaskStatusRoutingNodeID"];
            $mainBranchID = $assocTask["MainBranchID"];
            
            // create a variable to hold HTML that will show there is operator feedback
            $operatorFeedbackNotificationHTML='';
            
            // Determine if there is an issued date and setup the html value if so
            $issuedToMachineDateHTML='';
            if ($assocTask["IssuedToMachineDate"]!=null){
                // Set the HTML
                $issuedToMachineDateHTML='
                            <tr>
                              <td height="39" align="left" valign="top" colspan=5>
                                    <br>
                                    <strong>Sent to machining on </strong>' . date("Y-m-d H:i:s", strtotime("-1 hour", strtotime($assocTask["IssuedToMachineDate"]))) . '. 
                              </td>
                            </tr>
                            ';
            }

            // Determine if this task was copied from another task
            $copiedFromHTML='';
            $pinkNoteTabButtonHTML='';
            $pinkNoteTabContentHTML='';
            if ($assocTask["CopiedFromTaskID"]!="null"){
                // Determine if there was feedback
                $copiedTaskHadFeedbackText='';
                $copiedTaskHadFeedbackTextBorderColorHTML='';
                if ($assocTask["CopiedFromHasFeedback"]==1){
                    // Create some text message for them to know that there was feedback from the previous task
                    $copiedTaskHadFeedbackText='There was feedback that came from the copied task.';
                    $copiedTaskHadFeedbackTextBorderColorHTML='border:3px solid #fa86c4';
                    
                    // Write a query to get the previous tasks feedback notes and post machining feedback
                    $sql='SELECT t.PostMachiningFeedback, ms.SetupOrder, ms.Side, n.* ' .
                         'FROM tasks t ' .
                         'LEFT JOIN machiningsetups ms ON t.TaskID = ms.TaskID ' .
                         'LEFT JOIN notes n on ms.MachiningSetupID = n.AssociatedCategoryID ' .
                         'WHERE t.TaskID=' . $assocTask["CopiedFromTaskID"] . ' ' .
                         'AND n.Category="OPERATOR_FEEDBACK_NOTE" ' .
                         'ORDER BY ms.SetupOrder, n.NoteOrder;';
                    
                    // Query the database for the pink notes 
                    $pinkNoteRows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 21");

                    // Loop through the returned results
                    $amount=0;
                    while ($pinkNoteRow=mysqli_fetch_array($pinkNoteRows)){
                        // Increment the amount
                        $amount++;

                        // Determine if we are on the first one and we have a value for the post machining setup feedback
                        if ($amount==1 && $pinkNoteRow["PostMachiningFeedback"]!=null && $pinkNoteRow["PostMachiningFeedback"]!=''){
                            // Determine if there is postmachining feedback notes
                            if ($pinkNoteRow["PostMachiningFeedback"]!=null && $pinkNoteRow["PostMachiningFeedback"]!=''){
                                // Add the information to the pink notes 
                                $pinkNoteTabContentHTML='
                                                    <tr>
                                                        <td colspan=1 align="left" valign="top">
                                                            <strong>Post Machining Feedback Pink Note: </strong>
                                                        </td>
                                                        <td colspan=1 align="left" valign="top" Title="Post machining pink notes entered." style="">
                                                            ' . $pinkNoteRow["PostMachiningFeedback"] . '
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan=2 align="center" valign="top">
                                                            <br>
                                                            <strong>Setups Operator Feedback Pink Note(s)</strong>
                                                        </td>
                                                    </tr>
                                            ';
                            }
                            else {
                                // Add the information to the pink notes 
                                $pinkNoteTabContentHTML='
                                                    <tr>
                                                        <td colspan=2 align="center" valign="top">
                                                            <strong>Setups Operator Feedback Pink Note(s)</strong>
                                                        </td>
                                                    </tr>
                                            ';
                            }
                        }

                        // Add any operator feedback notes
                        $pinkNoteTabContentHTML = $pinkNoteTabContentHTML . '
                                                    <tr>
                                                        <td colspan=1 align="right" valign="top">
                                                            <strong>Setup Order: </strong>
                                                        </td>
                                                        <td colspan=1 align="left" valign="top">
                                                            ' . $pinkNoteRow["SetupOrder"] . '
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan=1 align="right" valign="top">
                                                            <strong>Side: </strong>
                                                        </td>
                                                        <td colspan=1 align="left" valign="top">
                                                            ' . $pinkNoteRow["Side"] . '
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan=1 align="right" valign="top">
                                                            <strong>Note Title: </strong>
                                                        </td>
                                                        <td colspan=1 align="left" valign="top">
                                                            ' . $pinkNoteRow["Title"] . '
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan=1 align="right" valign="top">
                                                            <strong>Note: </strong>
                                                        </td>
                                                        <td colspan=1 align="left" valign="top">
                                                            ' . $pinkNoteRow["Note"] . '
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan=2 align="center" valign="top">
                                                            --------------------------------------
                                                        </td>
                                                    </tr>
                                            ';
                    }

                    // Finish the tab content
                    $pinkNoteTabContentHTML='<div id="PreviousPinkNotesInfo" class="childtabcontent" style="display:block; background-color:#fa86c4;"><br><br><table>' . $pinkNoteTabContentHTML . '</table></div>';

                    // Create the tab button
                    $pinkNoteTabButtonHTML='<button class="childtablink" type="button" onclick="openChildPage(\'PreviousPinkNotesInfo\', this);" id="previousPinkNotesTabButton">Past Pink Notes</button>';
                }
                
                // Set the HTML
                $copiedFromHTML='
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top" width="40%">
                                            <strong>Original TID: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=1 height="39" align="left" valign="top" width="50%" Title="This task was copied from TID ' . $assocTask["CopiedFromTaskID"] . '. ' . $copiedTaskHadFeedbackText . ' Click the button to see the Copied From Task." style="">
                                            ' . $assocTask["CopiedFromTaskID"] . '<br>
                                            <input type="hidden" name="copiedFromTaskNumber" id="copiedFromTaskNumber" value="' . $assocTask["CopiedFromTaskID"] . '">
                                        </td>
                                        <td colspan=1 height="39" align="left" valign="top" width="10%">
                                            <button type="button" onClick="javascript: window.open(\'updateTask.php?updateTaskID=' . $assocTask["CopiedFromTaskID"] . '&parentTaskId=' . $assocTask["CopiedFromParentID"] . '&cs=' . $companyID . '&ts=' . $selectedType . '\', \'_blank\');" align="right"  Title="This task was copied from TID ' . $assocTask["CopiedFromTaskID"] . '. ' . $copiedTaskHadFeedbackText . ' Click to see the Copied From Task." style="' . $copiedTaskHadFeedbackTextBorderColorHTML . '">Old TID</button>
                                        </td>
                                    </tr>
                            ';
            }

            // Set the copied by html to nothing for now
            $copiedByHTML='
                            <tr>
                                <td colspan=1 height="39" align="right" valign="top" width="40%">
                                    <strong>Copied By TIDs: </strong> &nbsp; &nbsp;
                                </td>
                                <td colspan=2 height="39" align="left" valign="top" width="50%" Title="Tasks that have copied this task.">
                                    NONE<br>
                                </td>
                            </tr>
                        ';

            // Create a query to determine if there are tasks that have copied this one
            $sql='SELECT *, t.ParentID, t.CompanyID, t.TypeID ' .
                 'FROM copiedtaskslinker ctl ' .
                 'LEFT JOIN tasks t ON ctl.CopiedToTaskID = t.TaskID ' .
                 'WHERE ctl.CopiedFromTaskID=' . $taskNumber . ';';
            
            // Query the database for tasks that have copied this task 
            $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 21");

            // Loop through the returned results
            $tasksCopyingThisTaskButtons='';
            while ($row=mysqli_fetch_array($rows)){
                // Add link buttons for these tasks
                $tasksCopyingThisTaskButtons .='<button type="button" onClick="javascript: window.open(\'updateTask.php?updateTaskID=' . $row["CopiedToTaskID"] . '&parentTaskId=' . $row["ParentID"] . '&cs=' . $row["CompanyID"] . '&ts=' . $row["TypeID"] . '\', \'_blank\');" align="right"  Title="This task was copied from the current task. Click to see the task that has copied this.">TID#' . $row["CopiedToTaskID"] . '</button>';
            }
            
            // Determine if we have any tasks that have copied this task
            if ($tasksCopyingThisTaskButtons!=''){
                // Create the row of buttons
                $copiedByHTML='
                                <tr>
                                    <td colspan=1 height="39" align="right" valign="top" width="40%">
                                        <strong>Copied By TIDs: </strong> &nbsp; &nbsp;
                                    </td>
                                    <td colspan=2 height="39" align="left" valign="top" width="50%" Title="Tasks that have copied this task.">
                                        ' . $tasksCopyingThisTaskButtons . '<br>
                                    </td>
                                </tr>
                            ';
            }
            
            // Determine if there is a machine yet
            $orderDisabledHTML="disabled";
            if ($machineID!=null){
                // Now we can set the order to something other than 99998
                $theOrder = $assocTask["TheOrder"];
                
                // Machining tasks cannot be changed from the first slot
                if ($statusName != "Machining"){
                    // Order will not be disabled now
                    $orderDisabledHTML="";
                }
                
                // Determine if the order is one or two and then allow for the packet to be created
                if ($theOrder < 3 || $statusName == "Manual Machining"){
                    $makePacketVisibility = "";
                }
            }

            // Determine if this task is one of the main companies and if the user is allowed to modify it
            if (($mainSubCompany==1 && $userRow["CompanyID"]==1) ||
                $userRow["CanModifyChildren"]==1){
                    // For this combination, it is ok for this user to edit
                    $highLevelFieldsAccess = '';
            }
            
            // Determine if the task price is null
            if ($taskPrice == null){
                // Set the task price to be showing TBD
                $taskPrice = 'TBD';
            }
            
            // Determine if this user is a SU company user
            if ($userRow["CompanyID"]==1){
                // Make the setup sheet button 
                $ssButtonHTML='<input name="createModifiedSetupSheet" id="createModifiedSetupSheet" type="button" style="pointer-events: auto; cursor: hand; ' . $makePacketVisibility . '" value="Create SS" title="This will modify the database to match tools as closely as possible and then create a PDF setup sheep for this task." onclick="javascript:if (_isDirty && !confirm(\'The form has new data.\n\nAre you sure you want to create the setup sheet without saving?\')) {return false;};  if (modifyTaskForThePresent(' . $taskNumber . ', ' . (($machineID==null) ? ('null') : ($machineID)) . ', 1, sessionID)){window.open(\'pdf_templates/setup_sheet.php?tid=' . $taskNumber . '\', \'_blank\'); location.reload(); return true;}"/>';

                // Determine if this task is in the machining state
                if ($statusName=="Machining"){
                    // Make the create packet button 
                    $makePacketButtonHTML='<input name="gcodePacketModified" id="gcodePacketModified" type="button" style="pointer-events: auto; cursor: hand; ' . $makePacketVisibility . '" value="Remake Packet" title="This will modify the database to match tools as closely as possible and then modify the GCodes to add M00 image links and set tools to match appropriate tools in the machine. A zip file will be made after that with the package contents." onclick="javascript:if (_isDirty && !confirm(\'The form has new data.\n\nAre you sure you want to modify the GCode?\')) {return false;}; if (modifyTaskForThePresent(' . $taskNumber . ', ' . (($machineID==null) ? ('null') : ($machineID)) . ', 0, sessionID)){if (recalculateToolsForTask(' . $taskNumber . ', ' . (($machineID==null) ? ('null') : ($machineID)) . ', sessionID)) {window.open(\'pdf_templates/setup_sheet_with_downloads.php?tid=' . $taskNumber . '\', \'_blank\'); location.reload(); return true;}}"/>';
                } 
 
                // Create query to determine if this one has feedback notes from the operators
                $sql='SELECT COUNT(*) AS CountFeedback ' .
                     'FROM machiningsetups ms ' .
                     'LEFT JOIN notes n ON ms.MachiningSetupID = n.AssociatedCategoryID ' .
                     'WHERE n.Category="OPERATOR_FEEDBACK_NOTE" ' . 
                     'AND n.IsSticky=0 ' .
                     'AND ms.TaskID=' . $taskNumber . ';';            

                // Attempt to get the amount of operator feedback for this task
                $countFeedbackRow = $db->queryDB($sql, $userRow, "task_presentation Form occurance 22");

                // set it as easily readable
                $assocCountFeedbackRow = $countFeedbackRow->fetch_assoc();

                // Check how much feedback there is
                if ($assocCountFeedbackRow["CountFeedback"]>0){
                    // Create some HTML to visually notify of operator feedback
                    $operatorFeedbackNotificationHTML='&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<label style="width:100%; color:red; align: right;" title="There are ' . $assocCountFeedbackRow["CountFeedback"] . ' operator feedback notes."><strong>Has Operator Feedback</strong></label>';
                }
            }
            
            // Get something for sticky notes
            $stickyNoteDivHTML=checkThenGetStickyNotesDiv($db, $userRow, $taskNumber, 'TASK', $stickyNoteValidationHTML);
        }
        else {
            // Enable due date editing for adding tasks for everyone
            $highLevelFieldsAccess = '';
                    
            // Pretend this is a main user company in this case
            $mainSubCompany=1;
        }

        // Add a section for price for executive and above
        $priceHTML = '';
        if (($userRow["CompanyID"]==$companyID) && 
            ($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT") &&
            ($userRow["CompanyID"]!=1)){
            // add a price to let the customer see to order
            $priceHTML = '<tr>
                            <td colspan=4>
                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;"><strong>Price:</strong></label></div>
                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;">
                                    <input name="taskPrice" type="text" maxlength="15" class="intext" style="width: 100%; height: 19px" value="' . $taskPrice . '" ' . $priceAccess . '>
                                </div>
                                <br>
                            </td>
                          </tr>
                         ';
        }
        // Determine if it is a SU or Exec from the main company
        else if (($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE") &&
            ($userRow["CompanyID"]==1)){
            // add a price to let the SU see to order
            $priceHTML = '<tr>
                              <td colspan=4 height="60" align="left" valign="top">
                                <input name="hidePrice" id="hidePrice" class="notinput" type="checkbox" onclick="javascript:div_toggleVisibilityOnCheckbox(\'hidePrice\',\'priceDiv\', \'NORMAL\');"/>
                                <strong><label for="hidePrice">Price Per Part</label></strong>
                                <div id="priceDiv" style="display: none; font-weight: bold; font-size: 12px; width: 100%;">
                                    <input name="taskPrice" type="text" maxlength="15" class="intext" style="width: 100%; height: 19px" value="' . $taskPrice . '" ' . $priceAccess . '>
                                </div>
                              </td>
                          </tr>
                         ';
        }

        // In order to determine the level of this person's account, I need to know their type
        switch ($userRow["UserLevel"]){
            case 'MINIMAL' :
            case 'TYPICAL' :
            case 'MID-MANAGEMENT' :
                // Disable access to most fields
                $allFieldsAccess = 'disabled';
                $addNewAttachmentsVisibilityHTML = 'display:none;';
                
                // If they are a mid-manager and this task is of the SU subsidiary or somebody deems it, give them access
                if ($userRow["CompanyID"]==1 ||
                    $userRow["CanModifyChildren"]==1){
                    // For this combination, Get access to everything
                    $updateTaskVisibilityHTML = '';
                    $addNewAttachmentsVisibilityHTML = '';
                    $suManagementLevelFieldsHTML = '';
                    $allFieldsAccess = '';
                }
                
                // Break out of this case statement
                break;
            case 'MANAGEMENT':
                // Management has access to update always
                $updateTaskVisibilityHTML = '';
                
                // Disable access to most fields
                $allFieldsAccess = 'disabled';
                $addNewAttachmentsVisibilityHTML = 'display:none;';
                
                // If they are a manager and this task is of the SU subsidiary or somebody deems it, give them access
                if (($userRow["CompanyID"]==1 && $mainSubCompany) ||
                    $userRow["CanModifyChildren"]==1){
                    // For this combination, it is ok for this user to edit due date
                    $updateTaskVisibilityHTML = '';
                    $addNewAttachmentsVisibilityHTML = '';
                    $suManagementLevelFieldsHTML = '';
                    $allFieldsAccess = '';
                }
                else {
                    // Determine if this is one of the main company's employee
                    if ($userRow["CompanyID"]==1){
                        // Main company's manager can modify customer level items
                        $suManagementLevelFieldsHTML = '';
                        $addNewAttachmentsVisibilityHTML = '';
                    }
                }
                
                // Break out of this case statement
                break;
            case 'EXECUTIVE':
            case 'SU': /* In case the SU is NOT in the super company for some reason */
                // For this combination, Get access to everything
                $updateTaskVisibilityHTML = '';
                $statusFieldAccess = '';
                $addNewAttachmentsVisibilityHTML = '';
                $suManagementLevelFieldsHTML = '';
                
                // Break out of this case statement
                break;
        }

        // Create some variables to hold info about whether we have rows for blanks and notes
        $haveTools = false;
        $haveBlanks = false;
        $haveNotes = false;

        // Create the query to check the amount of tools
        $testSql = 'SELECT count(*) as toolCount FROM tooltotasklinker ' . 
                   'WHERE TaskID=' . $taskNumber . ';';

        // Attempt to get all of the tools for this category type and ID
        $testRows = $db->queryDB($testSql, $userRow, "task_presentation Form occurance 23");

        // Determine if there were rows for the tools on this task
        if ($testRows != null && 
            mysqli_num_rows($testRows)>0){
            // Get the row as an assoc row
            $testRowAssoc = $testRows->fetch_assoc();
            
            // Determine if we have more than zero
            if ($testRowAssoc["toolCount"]>0){
                // set the flag to say there are tools
                $haveTools = true;
            }
        }

        // Create the query to check the amount of blanks
        $testSql = 'SELECT count(*) as blankCount FROM jobblanks ' . 
                   'WHERE TaskID=' . $taskNumber . ';';

        // Attempt to get all of the blanks for this category type and ID
        $testRows = $db->queryDB($testSql, $userRow, "task_presentation Form occurance 24");

        // Determine if there were rows for the blanks on this task
        if ($testRows != null && 
            mysqli_num_rows($testRows)>0){
            // Get the row as an assoc row
            $testRowAssoc = $testRows->fetch_assoc();
            
            // Determine if we have more than zero
            if ($testRowAssoc["blankCount"]>0){
                // set the flag to say there are blanks
                $haveBlanks = true;
            }
        }

        // Create the query to check the amount of notes
        $testSql = 'SELECT count(*) as noteCount FROM notes ' . 
                   'WHERE AssociatedCategoryID = ' . $taskNumber . ' ' .
                   'AND   IsSticky=0 ' .
                   'AND   Category = "TASK";';

        // Attempt to get all of the blanks for this category type and ID
        $testRows = $db->queryDB($testSql, $userRow, "task_presentation Form occurance 25");

        // Determine if there were rows for the notes on this task
        if ($testRows != null && 
            mysqli_num_rows($testRows)>0){
            // Get the row as an assoc row
            $testRowAssoc = $testRows->fetch_assoc();
            
            // Determine if we have more than zero
            if ($testRowAssoc["noteCount"]>0){
                // set the flag to say there are blanks
                $haveNotes = true;
            }
        }
        
        // Determine if we have any blanks or notes for this task
        if ($machineID>0 || $haveTools || $haveBlanks || $haveNotes){
            // Setup the styling to be green text
            $machiningButtonStyling .= 'color:LimeGreen;';
        }

        // Setup a query to get the low/high numbers for attachments 
        $sql='SELECT ProcessOrder, Name FROM status WHERE Name in ("Waiting Assignment", "Delivered") ORDER BY ProcessOrder;';

        // Query the database for the the two statuses 
        $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 26");

        // Loop through the returned results
        $lowViewNumber = -1;                
        $highViewNumber = -1;                
        while ($row=mysqli_fetch_array($rows)){
            // Determine if we have set the low yet
            if ($lowViewNumber==-1){
                // Set the low number
                $lowViewNumber=$row["ProcessOrder"];
            }
            else {
                // Set the high number
                $highViewNumber=$row["ProcessOrder"];
            }
        }

        // Create variables for the attachments, notes and tools HTML
        $attachmentsHTML = '';
        $notesHTML = '';

        // Determine if They are of the correct state to see extra things
        if ($userRow["UserLevel"]=='SU' || $userRow["UserLevel"]=='EXECUTIVE' ||
            $userRow["UserLevel"]=='MANAGEMENT' || in_array($processOrder, range($lowViewNumber,$highViewNumber)) ||
            $assignedToID==$userRow["UserID"] || $mainSubCompany || $companyID==1 ||
            $userRow["CompanyID"]==$companyID){
            // Get html for the notes and attachments
            $attachmentsHTML = retrieveTaskAttachments($db, $userRow, $taskNumber, $mainSubCompany);

            // Determine if this is a su company user or customer
            if ($userRow["CompanyID"]==1){
                // Allow SU users to see notes
                $notesHTML = checkThenGetNotesDiv($db, $userRow, $taskNumber, 'TASK', $noteValidationHTML);
            }
        }
        else {
            // Set the tab to invisible
            $machiningButtonStyling = 'display:none;';
        }
                
        // Get the current time of opening this task
        $micro_date = microtime();
        $date_array = explode(" ",$micro_date);
        $startServerTime = date("Y-m-d H:i:s",$date_array[1]);
        $localtime = (date("Y-m-d H:i:s", strtotime("-1 hour", $date_array[1])));

        // Determine if they are of the SU Company to change status access
        $someFieldsAccess=$allFieldsAccess;
        if (($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT" || $userRow["UserLevel"]=="MID-MANAGEMENT") &&
            ($userRow["CompanyID"]==1) &&
            ($userRow["CompanyID"]==$companyID)){
            // Allow them to see the fields marked as ones for this group
            $someFieldsAccess="";
        }
        
        // Setup the secondary status as though they are not from the SU company
        $secondaryStatusHTML='
                         <tr>
                             <td colspan=4 width="100%"><strong>Task Notes (2000 characters):</strong><br> 
                                 <textarea name="description" maxlength="2000" class="intext" style="width: 100%; height: 310px; overflow: auto; resize:none" ' . $someFieldsAccess . '>' .
                                 $description .
                                 '</textarea>
                                  <input type="hidden" name="secondaryStatus" id="secondaryStatus" value="' . $secondaryStatusID . '"/>
                             </td>
                         </tr> 
                         ';
        
        // Determine if they are in the SU company
        if (($userRow["CompanyID"]==1)){
            // Determine if the user is NOT a super user
            $addTaskNotesHTML="";
            $notesHeight="210";
            if (($userRow["UserLevel"]=="EXECUTIVE" || $userRow["UserLevel"]=="MANAGEMENT") && 
                $companyID!=1 && $mainSubCompany==false){
                // Create the HTML area for other user to add their notes for the task
                $addTaskNotesHTML='
                                <tr>
                                    <td colspan=4 width="100%"><br><strong>Add Task Notes:</strong><br> 
                                        <input type="hidden" name="hiddenDescription" id="hiddenDescription" value="' . $description . '"/>
                                        <textarea name="addDescription" id="addDescription" maxlength="2000" class="intext" style="width: 100%; height: 60px; overflow: auto; resize:none">
                                        </textarea>
                                    </td>
                                </tr> 
                        ';
                $notesHeight="150";
            }
            
            // Allow them to see the fields marked as ones for this group
            $secondaryStatusHTML='
                                <tr>
                                    <td colspan=4 width="100%"><strong>Task Notes (2000 characters):</strong><br> 
                                        <textarea name="description" maxlength="2000" class="intext" style="width: 100%; height: ' . $notesHeight . 'px; overflow: auto; resize:none" ' . $someFieldsAccess . '>' .
                                        $description .
                                        '</textarea>
                                        <input type="hidden" name="hiddenDescription" id="hiddenDescription" value="' . $description . '"/>
                                    </td>
                                </tr> ' 
                                . 
                                $addTaskNotesHTML 
                                . 
                                '<tr>
                                    <td colspan=4 height="39" align="left" valign="top">
                                        <br>
                                        <strong>Secondary Status: </strong> &nbsp; &nbsp;
                                        ' 
                                        . getSecondaryStatusAsSelectOptions($db, $userRow, $secondaryStatusID) . 
                                        '
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan=4 width="100%">
                                        <textarea name="secondaryStatusDescription" id="secondaryStatusDescription" maxlength="2000" class="intext" style="width: 100%; height: 65px; overflow: auto; resize:none; background: white;"" disabled>' .
                                        $secondaryStatusDescription .
                                        '</textarea>
                                    </td>
                                </tr> 
                             ';
        }
        
        // Create the HTML to show or hide the vendor cell
        $vendorCellStyle=(strpos($statusName, "Outside Services")==false || $userRow["CompanyID"]!=1)?'style="display:none; width:100%;"':'';

        // Determine if the parent button should be displayed based on it's state and assigned to person
        $parentButtonHTML = '<button type="button" onClick="javascript: window.location=\'updateTask.php?updateTaskID=' . $parentTaskNumber . '&parentTaskId=0&cs=' . $companyID . '&ts=' . $selectedType . '\';" align="right">Parent</button>';
        if ($assocTask2["ViewCategory"] == "NOT VIEWABLE" &&
            $assocTask2["UserID"] != $userRow["UserID"]){
            // Set the button to nothing
            $parentButtonHTML = '';
        }
        
        // Determine if it is an expedite part
        $rowExpedite='';
        $expediteTitle='';
        if ($expedite==1){
            // This one is common
            $rowExpedite=' expediteTaskBackground';
                        
            // Setup the title
            $expediteTitle='This part is expedited. It takes highest priority.';
        }
        
        // Determine if this user has the ability to update routing
        $canModifyInitialRouteButton='';
        $canModifyCurrentRouteButton = '<div style="padding:20px;"><button type="button" Title="This will update the current routing information.  It is updated separately from other information in the task, so must be used if current routing information is needing to be changed. Also, this will refresh the task, so task should be saved, if necessary." style="float: right;" onclick="javascript:if (confirm(\'This will overwrite the datum inside each current route node to the data added here.\n\nIs it OK to continue?\')!=false){updateCurrentRoutingElements(' . $taskNumber . '); location.reload();}">save</button></div>';
        $canModifyRouteTabButton='';
        $templateInfoHTML='';
        $templateRadioHTML='';
        $currentRoutingBranchesHTML='';
        $replaceInitialWithCurrentHTML='';
        if ($userRow["CanModifyRouting"]==1){
            // Allow the modify buttons to be there
            $canModifyInitialRouteButton = '<div style="padding:20px;"><button type="button" Title="This will update the initial routing setup information.  It is updated separately from other information in the task, so must be used if routing information is needing to be changed. Also, this will refresh the task, so task should be saved, if necessary." style="float: right;" onclick="javascript:if (confirm(\'This will overwrite the intial routing to be the routing displayed here.\n\nIs it OK to continue?\')!=false){updateInitialRoutingElements(' . $taskNumber . '); updateTaskTemplateName(' . $taskNumber . ', document.getElementById(\'appliedTemplateName\').value); location.reload();}">save</button></div>';

            // allow for them to update initial with current
            $replaceInitialWithCurrentHTML='<b><a id="replaceInitialWithCurrent" name="replaceInitialWithCurrent" style="float: left; cursor: copy;" onclick="if (confirm(\'This will replace the initial routing path with the current route nodes that are checked.  Are you sure you want to do this?\')){javascript:updateCurrentRoutingElements(' . $taskNumber . '); replaceInitialWithCurrent(' . $taskNumber .')}" title="Clicking this will replace the initial routing path with the current route nodes that are checked.">>>></a></b>';
            
            // create the tab button html
            $canModifyRouteTabButton = '<button class="childtablink" type="button" onclick="openChildPage(\'StatusRoutingSetup\', this);"  id="statusRoutingSetupButton" style="border-left: 2px solid forestgreen; border-right: 2px solid forestgreen; border-top: 2px solid forestgreen; border-bottom: none;">Routing Setup</button>';
            
            // Determine if there is a routing template applied to this task
            $lastTemplateLabelDiv='<div id="routingTemplateLabelDiv"></div>';
            if ($templateName!=null && $templateName != ""){
                // Add info about the template last applied
                $lastTemplateLabelDiv='<div id="routingTemplateLabelDiv">Last applied template:' . $templateName . '</div>';
            }
            
            // Setup the template info as though it has NOT had one applied
            $templateInfoHTML='
                <div name="isRoutingTemplateGroup" id="isRoutingTemplateGroup">
                    <input type="hidden" id="originalTemplateName" name="originalTemplateName" value="' . $templateName . '"/>
                    <table width="100%">
                        <tr width="100%">
                            <td colspan=2 align="left">
                                ' .
                                $lastTemplateLabelDiv
                                . '
                            </td>
                        </tr>
                        <tr width="100%">
                            <td align="right" width="65%">
                                <strong><label name="isRoutingTemplateLabel" id="isRoutingTemplateLabel" for="isRoutingTemplate"> Save As Template</label></strong>
                                <input name="isRoutingTemplate" id="isRoutingTemplate" type="checkbox" onchange="document.getElementById(\'routingTemplateName\').disabled=!this.checked;document.getElementById(\'saveTemplate\').disabled=!this.checked;"/>
                            </td>
                            <td align="left" width="35%">
                                <input name="routingTemplateName" id="routingTemplateName" type="text" class="intext" maxlength="50" style="width: 65%;"  value="' . $templateName . '" disabled/>
                                <button name="saveTemplate" id="saveTemplate" type="button" style="font-size:8px;" title="Save the current configuration as a routing template." onclick="updateRoutingTemplate(); location.reload();" disabled>✔</button>    
                            </td>
                        </tr>
                    </table>
                </div>
                ';

            // Setup the template radio button for this user
            $templateRadioHTML= '
                    <div>
                        <table width="100%">
                            <tr>
                                <td width="36%">
                                    <fieldset style="border:none;">
                                        <input type="radio" name="applyPreferencesRadio" id="applyPreferencesRadio" value="NONE" checked="checked" onchange="javacript:div_hide(\'taskIDToCopyRoute\');div_hide(\'routingTemplateToCopy\');div_show(\'isRoutingTemplateGroup\');div_hide(\'applyTemplate\'); document.getElementById(\'isRoutingTemplate\').checked=false;"><b>NONE</b>
                                        <input type="radio" name="applyPreferencesRadio" id="applyPreferencesRadio" value="TaskID" onchange="javacript:div_hide(\'routingTemplateToCopy\');div_show(\'taskIDToCopyRoute\');div_hide(\'isRoutingTemplateGroup\');div_show(\'applyTemplate\'); document.getElementById(\'isRoutingTemplate\').checked=false;"><b>TASK ID</b>
                                        <input type="radio" name="applyPreferencesRadio" id="applyPreferencesRadio" value="Template" onchange="javacript:div_hide(\'taskIDToCopyRoute\');div_show(\'routingTemplateToCopy\');div_hide(\'isRoutingTemplateGroup\');div_show(\'applyTemplate\');"><b>TEMPLATE</b>
                                    </fieldset>
                                </td>
                                <td width="33%">
                                    <input name="taskIDToCopyRoute" id="taskIDToCopyRoute" type="text" maxlength="6" class="intext" style="float:left; width: 60px; display: none;" value="">
                                    <div id="routeTemplateParent">
                                        ' 
                                        .
                                        getRoutingTemplatesToCopyAsSelectOptions($db, $userRow,'float:left; display:none; width:30%','') 
                                        . 
                                        '
                                    </div>
                                    <input type="hidden" name="appliedTemplateName" id="appliedTemplateName" value="">
                                    <input name="applyTemplate" id="applyTemplate" type="button" onClick="populateRoutingTemplate();" style="float:left; display: none;" value="Apply" title="Apply the template to the current task."\> 
                                    <input name="loadSavedTrunk" id="loadSavedTrunk" type="button" onClick="statusInfoIdsToDelete=\'\'; populateRouting(' . $taskNumber . ');" value="Reload" style="display: none;"  title="Load the most recently save trunk."\> 
                                </td>
                                <td width="31%" align="right">
                                '
                                .
                                $templateInfoHTML
                                .
                                '
                                </td>
                            </tr>
                        </table>
                    </div>
                    ';
        }
        
        // Determine if we have routing for this task
        $backButton='';
        $statusSelectorScript='javascript:prefillOrderControl(this.options[this.selectedIndex].text); outsideServiceCheck(this.options[this.selectedIndex].text); intoProgrammingServiceCheck(this.options[this.selectedIndex].text, ' . $assocTask["CopiedFromHasFeedback"] . ', ' . $assocTask["CopiedFromTaskID"] . ');';
        $forwardButton='';
        $statusStyle='';
        if (taskHasRouting($db, $userRow, $taskNumber)===true && $userRow["CompanyID"]==1){
            // Create a query to get the max and min trunk routing
            $sql='SELECT (MAX(FLOOR(ExecutionOrder))=' . $assocTask["TrunkExecutionOrder"] . ') AS IsMax, (MIN(FLOOR(ExecutionOrder))=' . $assocTask["TrunkExecutionOrder"] . ') AS IsMin FROM taskstatusinfo_current WHERE TaskID=' . $taskNumber . ';';
            
            // Get the boundaries of trunk execution
            $trunkBoundariesRows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 27");

            // Determine if there were rows for the notes on this task
            if ($trunkBoundariesRows != null && 
                mysqli_num_rows($trunkBoundariesRows)==1){
                // Get the row as an assoc row
                $trunkBoundariesRowAssoc = $trunkBoundariesRows->fetch_assoc();

                // Determine if we are NOT at the max trunk
                if ($trunkBoundariesRowAssoc["IsMax"]!=1){
                    // Create the forward button
                    $forwardButton='<button type="button" title="This will move the task forward to the next routing node." onClick="moveRouting(' . $taskNumber . ', ' . $currentTaskStatusRoutingNodeID . ', ' . $mainBranchID . ', 1, \'moveRoutingNode\', \'moveRoutingHeader\', -1);" style="float:right;"><div style="color:limegreen;";>&#8658;</div></button>';
                }
                
                // Determine if we are NOT at the min trunk
                if ($trunkBoundariesRowAssoc["IsMin"]!=1){
                    // Create the back button
                    $backButton='<button type="button" title="This will move the task back to the previous routing node." onClick="moveRouting(' . $taskNumber . ', ' . $currentTaskStatusRoutingNodeID . ', ' . $mainBranchID . ', -1, \'moveRoutingNode\', \'moveRoutingHeader\', -1);" style="float:left;"><div style="color:red;";>&#8656;</div></button>';
                }
            }
            
            // set the back and forward buttons to actually have information
            $statusSelectorScript='javascript:moveRouting(' . $taskNumber . ', ' . $currentTaskStatusRoutingNodeID . ', ' . $mainBranchID . ', 0, \'moveRoutingNode\', \'moveRoutingHeader\', this.options[this.selectedIndex].value);';

            // Set the visibility of the routing tab and make it green
            $routingButtonStyling = 'display:block; color:LimeGreen;';
            
            // Set the style for the status control to be centered
            $statusStyle.='text-align:center;';
        }
        
        // Get the current routing and any branches
        $currentRoutingTrunkHTML=getCurrentStatusRoutingList($db, $userRow, $taskNumber, $currentTaskStatusRoutingNodeID, $currentRoutingBranchesHTML);
        
        // Determine if there is any current routing
        if ($currentRoutingTrunkHTML==''){
            // Hide the update button
            $canModifyCurrentRouteButton='';
            
            // Hide the copy to initial link
            $replaceInitialWithCurrentHTML='';
            
            // Determine if this task has been copied from another
            if ($assocTask["CopiedFromTaskID"]!="null"){
                // Attempt to create a routing list from the history of the previous task
//                getCurrentStatusRoutingListFromHistory
            }
            else {
                // Hide the copy to initial link
                $replaceInitialWithCurrentHTML='';
            }
        }
        
        return createCompanyEmployeesAsJSON($db, $userRow, $assignedToID) .
          '<div class="' . $rowExpedite . '" title="' . $expediteTitle . '">
            <br>
            <button class="tablink" type="button" onclick="openPage(\'GeneralInfo\');" id="defaultOpen">General Info</button>
            <button class="tablink" type="button" onclick="openPage(\'StickyNotes\'); document.getElementById(\'tabsStickyNotes\').click();" style="' . $stickyNotesButtonStyling . '">Sticky Notes</button>
            <button class="tablink" type="button" onclick="openPage(\'Machining\'); document.getElementById(\'generalMachiningTabButton\').click();" style="' . $machiningButtonStyling . '">Machining</button>
            <button class="tablink" type="button" onclick="openPage(\'Routing\'); document.getElementById(\'statusRoutingCurrentTabButton\').click();" style="' . $routingButtonStyling . '">Routing</button>
            <button class="tablink" type="button" onclick="openPage(\'History\'); document.getElementById(\'taskStatusesAsListID\').click();" style="' . $historyButtonStyling . '">History</button>
            <form action="' . $modifyType . 'Task.php?updateTaskID=' . $taskNumber . '&parentTaskId=' . $parentTaskNumber . '&cs=' . $selectedCompany . '&ts=' . $selectedType .
                '" method="post" name="' . $modifyType . 'Task" id="' . $modifyType . 'Task" enctype="multipart/form-data">  
                <div id="updateDiv">
                    <input name="formSubmit" id="formSubmit" type="submit" onclick="this.disabled=true; if (wantsFirstPositionOnMachiningMachine(' . $machineID . ', document.getElementById(\'machineID\'), document.getElementById(\'machineTaskOrder\').value, ' . $theOrder . ')){alert(\'The machine you are trying to move this to has a machining job and you are trying to move the task to the first position. Rectify this and try again.\'); this.disabled=false; wantsFirstPositionOnMachineWithMachiningTask=true; return false;} else{this.form.submit();}" style="pointer-events: auto; cursor: hand; cursor: pointer;' . $updateTaskVisibilityHTML . '" value="' . $modifyType . ' task" title="' . $modifyType . ' this parent task." ' . $onClickHTML . '/>
                </div>        
                <input type="hidden" name="localTime" id="localTime" value="' . $localtime . '">
                <input type="hidden" name="redirectTo" id="redirectTo" value="' . $fromWhatBaseURL . '"/>
                <input type="hidden" name="parentStatusID" id="parentStatusID" value="' . $parentStatusID . '"/>
                <input type="hidden" name="parentStatusName" id="parentStatusName" value="' . $parentStatusName . '"/>
                <input type="hidden" name="parentTitle" id="parentTitle" value="' . $parentTitle . '"/>
                <input type="hidden" name="outsideServiceVendorID" id="outsideServiceVendorID" value="' . $outsideServiceVendorID . '"/>
                <div id="GeneralInfo" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <br>
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr align="left" valign="top">
                            <td width="48%">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Created By: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            ' . $createdByFirstName . '  ' . $createdByLastName . '
                                            <input type="hidden" name="createdBy" value="' . $createdByID . '">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="top">
                                            <strong>Created Date: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            ' . $createdDate . '
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top" width="40%">
                                            <strong>Parent TID: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=1 height="39" align="left" valign="top" width="50%">
                                            ' . $parentTaskNumber . '<br>
                                            <input type="hidden" name="parentTaskNumber" id="parentTaskNumber" value="' . $parentTaskNumber . '">
                                        </td>
                                        <td colspan=1 height="39" align="left" valign="top" width="10%">
                                        '
                                        .
                                        $parentButtonHTML
                                        .
                                        '
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>EES TID: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            ' . $taskNumber . '
                                        </td>
                                    </tr>
                                    ' .
                                    $copiedFromHTML . 
                                    $copiedByHTML
                                    . '
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Task Type: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            ' . getTaskTypesAsSelectOptions($db, $userRow, $taskTypeID, 'disabled') .
                                        '</td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Status: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top" style="' . $statusStyle . '">
                                            ' . $backButton . '
                                            ' . getStatusAsSelectOptions($db, $userRow, $statusID, $statusSelectorScript, $statusFieldAccess, "previousToOutsideServicesValue=this.options[this.selectedIndex].text;") . 
                                            '<input type="hidden" id="oldStatusID" name="oldStatusID" value="' . $statusID . '">
                                            ' . $forwardButton . '
                                            <div id="vendorCell" ' . $vendorCellStyle . '> 
                                                <label for="vendor"><strong>To</strong>: </label>' .
                                                getVendorAsSelectOptions($db, $userRow, $outsideServiceVendorID, "document.getElementById('outsideServiceVendorID').value=this.options[this.selectedIndex].value;", "", "", "width:128px;") .
                                                '
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Task Assigned To: </strong> &nbsp; &nbsp; 
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            <select name="assignedTo" id="assignedTo" ' . $statusFieldAccess . '></select> 
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Parent Priority: </strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            <input maxlength="11" type="text" title="99998 sets lowest priority" class="intext" style="width: 100%;" value="' . $priority . '" disabled>
                                            <input type="hidden" name="priority" id="priority" value="' . $priority . '">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Sub Priority:</strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            <input type="hidden" name="subPriorityHidden" id="subPriorityHidden" value="' . $subPriority . '">
                                            <input id="subPriority" name="subPriority" maxlength="11" type="text" title="99998 sets lowest priority" class="intext" style="width: 100%;" value="' . $subPriority . '" ' . $allFieldsAccess . '>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                          <strong>Due Date:</strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                          <input name="dueDate" type="date" class="intext" style="width: 100%;" value="' . $dueDate . '" ' . $highLevelFieldsAccess . '>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=1 height="39" align="right" valign="top">
                                            <strong>Ideal Date:</strong> &nbsp; &nbsp;
                                        </td>
                                        <td colspan=2 height="39" align="left" valign="top">
                                            <input name="idealDate" type="date" class="intext" style="width: 100%;" ' . $suManagementLevelFieldsHTML . ' value="' . $idealDate . '">
                                        </td>
                                    </tr>                    
                                    <tr>
                                        <td colspan=3 height="39" align="left" valign="top">
                                            <input type="hidden" name="expedite" id="expedite" value="' . $expedite . '"/>
                                            <input name="expediteVisible" id="expediteVisible" type="checkbox" ' . $expediteHTML . ' onchange="document.getElementById(\'expedite\').value=this.checked; if (this.checked==true){alert(\'This will change the sub-priority of this child task to number one. This can be changed before the update button is pressed, if you do not want to increase the priority.\'); document.getElementById(\'subPriority\').value=1;}" ' . $highLevelFieldsAccess . '>
                                            <strong><label for="expedite">Expedite Task</label></strong>
                                        </td>
                                    </tr>
                                    '
                                    .   
                                        getTaskCheckboxes($userRow, $invoiced, $completed, $closed, 0, 0)
                                    . 
                                    '
                                    <tr>
                                        <td height="39" align="left" valign="top" colspan=3>
                                              <strong>Updated </strong>' . $lastUpdatedDate . ' <strong>by</strong> ' . $lastUpdatedByFirstName . ' ' . $lastUpdatedByLastName . '
                                        </td>
                                    </tr>
                                </table>
                            </td>
                            <td width="4%">&nbsp;</td>
                            <td width="48%">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td colspan=4 height="39" align="left" valign="top">
                                            <strong>Company: </strong>' . getCompanyHTML($db, $userRow, $companyID, "displayCorrectCompanyEmployees();", 'disabled', true, $mainSubCompany) . '
                                            <br>
                                            <br>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" width="40%" align="left" valign="top">
                                            <strong><label style="height: 19px; width:40%;" >Deliverable Quantity:</label></strong>
                                        </td>
                                        <td height="39" width="10%" align="left" valign="top">
                                            <input name="deliverableQuantity" id="deliverableQuantity" maxlength="11" type="text" style="height: 19px;  width:85%;" value="' . $deliverableQuantity . '" ' . $highLevelFieldsAccess . '>
                                        </td>
                                        <td height="39" width="40%" align="right" valign="top">
                                            <strong><label style="height: 19px; width:40%;">Total Quantity:</label></strong>
                                        </td>
                                        <td height="39" width="10%" align="right" valign="top">
                                            <input name="totalQuantity" id="totalQuantity" maxlength="11" type="text" style="height: 19px; width:85%;" value="' . $totalQuantity . '" ' . $highLevelFieldsAccess . '>
                                        </td>
                                    </tr>
                                    '
                                    .
                                    $priceHTML
                                    .
                                    '
                                </table>
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td height="39" align="left" valign="top">
                                            <strong>Title:</strong><br> 
                                        </td>
                                        <td height="39" align="left" valign="top">
                                            <textarea name="title" maxlength="100" class="intext" style="width: 100%; height: 53px; overflow: auto; resize:none" ' . $someFieldsAccess . '>' .
                                            $title .
                                            '</textarea>
                                        <br><br>
                                        </td>
                                    </tr>
                                    '
                                    .
                                    $secondaryStatusHTML
                                    .
                                    '
                                    <tr>
                                        <td colspan=4 >
                                            <br>
                                            <p align="right">
                                                <input type="hidden" name="formSubmitted" value="TRUE">
                                                <input type="hidden" id="newAttachmentNumbers" name="newAttachmentNumbers" value="0">
                                            </p>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                    <input type="hidden" name="MAX_FILE_SIZE" id="maxFileSize" value="4294967296">
                    <div>
                        <strong>Current Attachments: </strong>
                        <div id="currentAttachments" style="margin: 5 auto; width: 100%; ">
                            <input type="hidden" name="deleteCurrentAttachments" id="deleteCurrentAttachments" value=""></input>' .
                            $attachmentsHTML .
                        '</div>
                    </div>
                    <div style="' . $addNewAttachmentsVisibilityHTML . '">
                        <strong>New Attachments: </strong>
                        <div id="newAttachments" style="margin: 5 auto; width: 100%; ">
                        </div>
                    </div>
                    <p align="right">
                        <button type="button" onClick="addNewAttachment()"  style="' . $addNewAttachmentsVisibilityHTML . '" align="right">new attachment</button>
                    </p>
                </div>
                <div id="StickyNotes" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <div id="tabsStickyNotes">
                        <br>
                        '
                        .
                        $stickyNoteDivHTML
                        .
                        '
                    </div>
                </div>
                <div id="Machining" style="background-color:' . $secondaryStatusColor . '; display: none;" class="tabcontent">
                    <br>
                    '
                    .
                    $ssButtonHTML . '&nbsp' . $makePacketButtonHTML . $operatorFeedbackNotificationHTML
                    .
                    '
                    <br><br>
                    <button class="childtablink" type="button" onclick="openChildPage(\'GeneralMachiningInfo\', this);" style="border-left: 2px solid forestgreen; border-right: 2px solid forestgreen; border-top: 2px solid forestgreen; border-bottom: none;" id="generalMachiningTabButton">General</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'BlanksInfo\', this);" id="blanksTabButton" title="Blanks present will only be shown if the blank has been submitted, if the user is assigned to the task or the user is a Super User.">Blanks</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'ToolsInfo\', this);" id="toolsTabButton" title="This tab will not be enabled if task is not in machining." >Tools</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'SetupsInfo\', this);" id="setupsTabButton" title="This tab will not be enabled if task is not in machining. Setups present will only be shown if task is past Machining Queue phase, if the user is assigned to the task or the user is a Super User." >Setups</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'NotesInfo\', this);" id="notesTabButton">Notes</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'PostMachiningInfo\', this);" id="postMachiningTabButton">Post Machining</button>
                    ' . $pinkNoteTabButtonHTML . '
                    <div id="GeneralMachiningInfo" class="childtabcontent" style="display:block;">
                        <br><br>
                        <label style="font-size: 20px;"><strong>General:</strong></label>
                        <br><br>
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Machine:</label></strong>
                                </td>
                                <td width="20%" align="left">
                                '
                                .
                                getMachineAsSelectOptions($db, $userRow, $machineID, "enableOrderControl(this.value); checkAndChangeToolPositions(this.selectedIndex);", $statusFieldAccess, 'machineToolSlotMaxes') 
                                .
                                '
                                <input type="hidden" name="oldMachineID" id="oldMachineID" value="' . $machineID . '"></input>
                                </td>
                                <td width="10%">
                                </td>
                                <td width="30%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Order (99998 is lowest):</label></strong>
                                </td>
                                <td width="30%" align="left">
                                    <input name="machineTaskOrder" id="machineTaskOrder" title="This will only be set if there is a machine chosen." type="text" maxlength="11" style="height: 19px;  width:30%;" value="' . $theOrder . '" ' . $orderDisabledHTML . '>
                                    <input name="hiddenMachineTaskOrder" id="hiddenMachineTaskOrder" type="hidden" value="' . $theOrder . '">
                                    <input type="hidden" name="oldMachineTaskOrder" id="oldMachineTaskOrder" value="' . $theOrder . '"></input>
                                </td>
                            </tr>
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Fixture:</label></strong>
                                </td>
                                <td width="20%" align="left">
                                '
                                .
                                getFixturesAsSelectOptions ($db, $userRow, $fixtureID, "", $statusFieldAccess) 
                                .
                                '
                                </td>
                                <td width="10%">
                                    <input name="toFixture" id="toFixture" type="button" style="pointer-events: auto; cursor: hand; ' . $updateTaskVisibilityHTML . '" value="..." title="This will open a new tab to the fixture." onclick="javascript:if (document.getElementById(\'fixture\').value>0){window.open(\'updateTask.php?updateTaskID=\' + document.getElementById(\'fixture\').value + \'\', \'_blank\');} else{alert(\'There is no fixture to go and get.\');} return false;"/>
                                </td>
                                <td width="30%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Pending Options:</label></strong>
                                </td>
                                <td width="30%" align="left">
                                '
                                .
                                getSecondaryStatusCheckboxes($isWaitingToBeReviewed,$isPendingTools,$isPendingApproval)
                                .
                                '
                                </td>
                            </tr>
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Programmer:</label></strong>
                                </td>
                                <td width="20%" align="left">
                                    <div name="programmerDiv" id="programmerDiv"></div> 
                                </td>
                                <td width="10%">
                                </td>
                                <td width="30%" align="right">
                                    <strong><label style="height: 19px; width:40%;" >Program Checked By:</label></strong>
                                </td>
                                <td width="30%" align="left">
                                    <div name="programCheckedByDiv" id="programCheckedByDiv"></div> 
                                </td>
                            </tr>
                            '
                            .
                            $issuedToMachineDateHTML
                            .
                            '
                            <tr align="left" valign="top">
                                <td width="10%" align="right">
                                    <br>
                                    <strong><label style="height: 19px; width:40%;" >Hardware:</label></strong>
                                </td>
                                <td width="20%" align="left" colspan=4>
                                    <br>
                                    <textarea name="partHardware" id="partHardware" maxlength="500" class="intext" style="width: 100%; height: 70px; overflow: auto; resize:vertical">' .
                                    $partHardware .
                                    '</textarea>
                                </td>
                            </tr>
                        </table>
                        <br>
                    </div>
                    '
                    .
                    checkThenGetBlanksDiv($db, $userRow, $taskNumber, $blankValidationHTML)
                    .   
                    checkThenGetToolsDiv($db, $userRow, $taskNumber, $toolsValidationHTML)
                    .   
                    checkThenGetSetupsDiv($db, $userRow, $taskNumber, $setupsValidationHTML)
                    .
                    $notesHTML
                    .
                    '
                    <div id="PostMachiningInfo" class="childtabcontent" style="display:none;">
                        <br><br>
                        <label style="font-size: 20px;"><strong>Post Machining:</strong></label>
                        <br><br>
                        '
                        .
                        createPostMachiningInformation($isVacuumClean, $isWashForAnodize,
                                                       $hasAllowableCosmeticDamage, 
                                                       $isTappedPostMachining, $postMachiningTappingInstructions,
                                                       $isSandblasted, $sandBlastingInstructions,
                                                       $postMachiningNotes, $postMachiningFeedback)
                        .
                        '
                    </div>
                    ' . $pinkNoteTabContentHTML . '
                </div>
                <div id="Routing" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <br>
                    <button class="childtablink" type="button" onclick="openChildPage(\'StatusRoutingCurrent\', this);" id="statusRoutingCurrentTabButton" title="Blanks present will only be shown if the blank has been submitted, if the user is assigned to the task or the user is a Super User.">Current Routing</button>
                    ' . $canModifyRouteTabButton . '
                    <div id="StatusRoutingCurrent" class="childtabcontent" style="display:block; border-top: 2px solid forestgreen;">
                        ' . $canModifyCurrentRouteButton . '
                        <table>
                            <tr>
                                <td align="center">
                                    <b>Current Routing Trunk</b>
                                    <div style="clear: both; height: 430px; width: 350px; overflow-x: hidden; overflow-y: auto; border: 1px solid black;"> 
                                        ' . 
                                        $currentRoutingTrunkHTML 
                                        . '
                                    </div>
                                </td>
                                <td align="center">
                                    <b>Current Routing Branches</b>
                                    <div name="routingNodeBranches" id="routingNodeBranches" style="clear: both; height: 430px; width: 350px; overflow: auto; border: 1px solid black;"> 
                                     ' . $currentRoutingBranchesHTML . '
                                    </div>
                                </td>
                                <td align="center" style="v-align: middle;">
                                    ' . $replaceInitialWithCurrentHTML . '
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div id="StatusRoutingSetup" class="childtabcontent" style="display:block; border-top: 2px solid forestgreen;">
                        ' . $canModifyInitialRouteButton . $templateRadioHTML . '
                        <table>
                            <tr>
                                <td align="center" style="v-align: middle;">
                                    <b><a id="replaceCurrentWithInitial" name="replaceCurrentWithInitial" style="float: left; cursor: copy;" onclick="if (confirm(\'This will replace the current routing path with the initial route and set the current task to the initial routing node. This will also save the task and all of the attributes.  Are you sure you want to do this?\')){javascript:updateInitialRoutingElements(' . $taskNumber . '); if (replaceCurrentWithInitial(' . $taskNumber .')==true){$(\'#formSubmit\').click();}}" title="Clicking this will replace the current routing path with the initial route."><<<</a></b>
                                </td>
                                <td align="center">
                                    <b> Initial Task Status Routing </b>
                                    <div style="clear: both; height: 430px; width: 480px; overflow: auto; border: 1px solid black;"> 
                                        ' . 
                                        getStatusRoutingAsDraggableList($db, $userRow, $taskNumber, true) 
                                        . '
                                    </div>
                                </td>
                                <td align="middle">
                                    <b> Available Statuses </b>
                                    <div style="clear: both; height: 430px; width: 220px; overflow-x: hidden; overflow-y: auto; border: 1px solid black;"> 
                                        ' . 
                                        getStatusAsDraggableList($db, $userRow) 
                                        . '
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div id="History" style="background-color:' . $secondaryStatusColor . ';" class="tabcontent">
                    <br>
                    ' . retrieveTaskStatusesAsList($db, $userRow, $taskNumber) . '<br>
                </div>
            </form>
            <script language="JavaScript">
                var originalProgrammerID = ' . $programmerID . ';
                var originalProgramCheckedByID = ' . $programCheckedByID . ';
                var startServerTime = "' . $startServerTime . '";
                var copiedFromHasFeedback = "' . $assocTask["CopiedFromHasFeedback"] . '";
                var copiedFromTaskID = "' . $assocTask["CopiedFromTaskID"] . '";
                var wantsFirstPositionOnMachineWithMachiningTask = false;
                    
                // Code for validating the form
                // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                // for details
                var frmvalidator = new Validator("' . $modifyType . 'Task", "formSubmit");
                frmvalidator.addValidation("subPriority",
                                           "req",
                                           "Please enter the priority of this task.");
                frmvalidator.addValidation("subPriority",
                                           "posint",
                                           "Please enter the priority of this task as a number.");
                frmvalidator.addValidation("subPriority",
                                           "greaterthan=0",
                                           "The priority should be greater than 0.");
                frmvalidator.addValidation("subPriority",
                                           "lessthan=99999",
                                           "The priority should be less than 99999.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "req",
                                           "Please enter the order of this task.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "posint",
                                           "Please enter the order of this task as a number.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "greaterthan=0",
                                           "The order should be greater than 0.");
                frmvalidator.addValidation("machineTaskOrder",
                                           "lessthan=99999",
                                           "The order should be less than 99999.");
                frmvalidator.addValidation("deliverableQuantity",
                                           "posint",
                                           "Please enter the Deliverable Quantity of this task as a number.");
                frmvalidator.addValidation("deliverableQuantity",
                                           "greaterthan=0",
                                           "The Deliverable Quantity should be greater than 0.");
                frmvalidator.addValidation("totalQuantity",
                                           "posint",
                                           "Please enter the Total Quantity of this task as a number.");
                frmvalidator.addValidation("totalQuantity",
                                           "greaterthan=0",
                                           "The Total Quantity should be greater than 0.");
                frmvalidator.addValidation("title",
                                           "required",
                                           "There must be a value for the title.");
                '
                .
                $toolsValidationHTML
                .
                $blankValidationHTML
                . 
                $noteValidationHTML
                . 
                $setupsValidationHTML
                . 
                $stickyNoteValidationHTML
                .
                '
                frmvalidator.setAddnlValidationFunction(function() {return checkform("' . $taskNumber . '", 0);});
                    
                function parseCompany(stringToParse){
                    var theArray = stringToParse.split("|");

                    // determine if the array is the correct size
                    if (theArray.length > 1){
                        return theArray[1];
                    }
                }

                // Change the back button to ensure that is keeps get variables in order to know exactly where to go
                history.pushState(null, null, \'' . $_SERVER["REQUEST_URI"] . '\');
                window.addEventListener(\'popstate\', function(event) {
                    window.location.assign("updateTask.php?updateTaskID=' . $taskNumber . '&parentTaskId=0&cs=' . $companyID . '&ts=' . $selectedType . '");
                });
                
            </script>';
    }

    function validate_url($url) {
        // parse the string for a URL path
        $path = parse_url($url, PHP_URL_PATH);
        
        // Encode it
        $encoded_path = array_map('urlencode', explode('/', $path));
        
        // Do a string replace
        $url = str_replace($path, implode('/', $encoded_path), $url);

        // Determine if it is good and return it
        return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
    }
    
    function getTask($db, $userRow, $inTaskNumber, $parentTaskNumber, $fromWhatCompany, $fromWhatType, $fromWhatBaseURL){
        // Determine if they are attempting an update or not
        if ($inTaskNumber){
            // Create a query to determine if this user is allowed viewable access to this task
            $sql='SELECT t.TaskID, t.StatusID, t.UserID, usvl.ViewCategory ' .
                 'FROM tasks t ' .
                 'LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
                 'WHERE t.TaskID=' . $inTaskNumber . ';';

            // Query the database for the tasks 
            $canView = $db->queryDB($sql, $userRow, "task_presentation Form occurance 28");

            // Attempt to get the secondary status row
            $assocCanViewCheck = $canView->fetch_assoc();

            // Determine if they are allowed to see this
            if ($assocCanViewCheck["ViewCategory"] == "NOT VIEWABLE" &&
                $assocCanViewCheck["UserID"] != $userRow["UserID"]){
                // Let the user know what is going on
                echo ('<script>window.location = "invalid_access.php";</script>');

                // Leave this method
                return;
            }
        }

        // Determine if we are getting a parent or a child
        if ($parentTaskNumber == null || $parentTaskNumber==0){
            // Set the task number what was passed in at first
            $taskNumber=$inTaskNumber;

            // Determine if the parent is NOT null, meaning we are NOT creating a new task.
            if ($parentTaskNumber != null){
                // Create a query to ensure this is truly a parent
                $sql='SELECT ParentID FROM tasks WHERE TaskID=' . $inTaskNumber . ';';

                // Get what the current parent for this is
                $row = $db->queryDB($sql, $userRow, "task_presentation Form occurance 29");

                // Attempt to get the parent ID
                $assocParent = $row->fetch_assoc();

                // Get the parent ID
                $dbParentID = $assocParent["ParentID"];

                // Ensure that this one is truly a parent
                if ($dbParentID!=0){
                    // Set the task ID to it's parent
                    $taskNumber=$dbParentID;
                }
            }

            // Call the parent task creation sub-routine
            return getParentTask($db, $userRow, $taskNumber, $fromWhatCompany, $fromWhatType, $fromWhatBaseURL);
        }
        else {
            // Call the child task creation sub-routine
            return getChildTask($db, $userRow, $inTaskNumber, $parentTaskNumber, $fromWhatCompany, $fromWhatType, $fromWhatBaseURL);
        }
    }
    
    function retrieveSecondaryStatusesAsList($db, $userRow, $sortNumber){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableSecondaryStatusesRowCellHTML = '';

        // Determine if there is actually a sort passed in
        if ($sortNumber!=""){
            // Determine which sort the person wants
            switch ($sortNumber) {
                case 1:
                    // Sort as Name then Description
                    $sort = "Name, Description ";

                    break;
                case 5:
                    // Sort as Description then Name
                    $sort = "Description, Name ";

                    break;
                default:
                    // Sort as Name then Description
                    $sort = "Name, Description ";

                    break;
            }
        }

        // Determine if they are at a level to manage secondary statuses
        switch ($userRow["UserLevel"]){
            case 'MANAGEMENT':
            case 'EXECUTIVE':
            case 'SU':
                $updateableTitleRowCellHTML = '
                            <div class="cell updateCell">
                                <p><b>Edit</b></p>
                            </div>
                        ';

                break;
        }
        
        // Initialize the return
        $result = 
            '<input type="hidden" id="sortNumber" name="sortNumber" value="' . $sortNumber . '"/>
             <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell nameCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell descCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Description</b></p>
                    </div>' . 
                    $updateableTitleRowCellHTML . '
                </div>
             </li>';

        try {
            // Setup the query to get all secondary statuses
            $sql='SELECT *
                  FROM secondarystatuses 
                  ORDER BY ' . $sort . ';';

            // Query the database for the secondary statuses 
            $rows = $db->queryDB($sql, $userRow, "task_presentation occurance 30");

            // Determine if there are any rows before attempting to loop through them
            if ($rows != null && 
                mysqli_num_rows($rows)>0){

                // Loop through the returned results
                $amount=0;
                $lastOneUpdated = '';
                while ($row=mysqli_fetch_array($rows)){
                    // Set it up as though it is NOT deletable
                    $updateableSecondaryStatusesRowCellHTML = '
                        <div class="cell updateCell">
                            <span>
                                <table>
                                    <tr>
                                        <td>
                                        </td>
                                        <td>
                                            <input type="button" style="font-size:11px;" value="..." title="Edit this secondary status." ' . 
                                            'onclick="javascript:window.location=\'updateSecondaryStatus.php?updateSecondaryStatusID=' . $row["SecondaryStatusID"] . '\';"/>
                                        </td>
                                    </tr>
                                </table>
                            </span>
                        </div>
                        ';
                    
                    // Determine if this one is deletable
                    if ($row["SecondaryStatusID"] != -1){
                        // Assign the delete button attributes as though deletion is an option
                        $deleteButtonTitle = 'Remove this secondary status.';
                        $deleteButtonOnClick = 'onclick="javascript:if (confirm(\'Are you sure you want to delete this secondary status?\')) ' .
                                               '{window.location=\'redirectors/delete_secondary_status.php?deleteSecondaryStatusID=' . $row["SecondaryStatusID"] . '\';}"';

                        // Give the the delete option
                        $updateableSecondaryStatusesRowCellHTML = '
                            <div class="cell updateCell">
                                <span>
                                    <table>
                                        <tr>
                                            <td>
                                                <input type="button" style="font-size:11px; color:LIMEGREEN;" value="X" title="' . 
                                                $deleteButtonTitle . '" ' . $deleteButtonOnClick . '/>
                                            </td>
                                            <td>
                                                <input type="button" style="font-size:11px;" value="..." title="Edit this secondary status." ' . 
                                                'onclick="javascript:window.location=\'updateSecondaryStatus.php?updateSecondaryStatusID=' . $row["SecondaryStatusID"] . '\';"/>
                                            </td>
                                        </tr>
                                    </table>
                                </span>
                            </div>
                            ';
                    }

                    // Increment the row
                    $amount++;

                    // Add this option to the select
                    $result = $result .
                        '<li class="ui-state-default Table" >
                            <div class="Row" style="background-color: '. $row["RowColor"] . '; border-style: solid; border-color: BLACK;">
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div> 
                                <div class="cell descCell">
                                    <span>
                                        <p>' . $row["Description"] . '</p>
                                    </span>
                                </div>' . 
                                $updateableSecondaryStatusesRowCellHTML . '
                            </div>
                        </li>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getSecondaryStatus($db, $userRow, $secondaryStatusID){
        // Init all of the settings to the appropriate values
        $secondaryStatusName = '';
        $secondaryStatusDescription = '';
        $secondaryStatusColor = 'FFFFFF';
        $modifyType = 'add';
        
        // Determine if this is an update or not
        $secondaryStatusAssocTask = null;
        if ($secondaryStatusID>0){
            // Determine if the user editing is part of the main company
            if ($userRow["CompanyID"]!=1){
                // We should not even be in here if we are not a main company employee
                return;
            }
            
            // Create the query to get the the material specified
            $sql = 'SELECT * FROM secondarystatuses WHERE SecondaryStatusID = ' . $secondaryStatusID . ';';

            // Attempt to get the secondary status
            $secondaryStatusRow = $db->queryDB($sql, $userRow, "task_presentation Form occurance 31");

            // Attempt to get the secondary status row
            $secondaryStatusAssocTask = $secondaryStatusRow->fetch_assoc();

            // Set the things we can
            $secondaryStatusID = $secondaryStatusAssocTask["SecondaryStatusID"];
            $secondaryStatusName = $secondaryStatusAssocTask["Name"];
            $secondaryStatusDescription = $secondaryStatusAssocTask["Description"];
            $secondaryStatusColor = $secondaryStatusAssocTask["RowColor"];
            
            $modifyType = 'update';
        }

        return '
            <form action="' . $modifyType . 'SecondaryStatus.php?updateSecondaryStatusID=' . $secondaryStatusID . '" method="post" name="' . $modifyType . 'SecondaryStatus" enctype="multipart/form-data">  
                <table width=100%>
                    <tr width=100%>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <strong>Secondary Status Name:</strong>&nbsp;&nbsp; 
                        </td>
                        <td colspan=1 height="39" align="left" valign="middle" width="75%">
                            <input name="name" type="text" maxlength="25" class="intext" style="width: 100%;" value="' . $secondaryStatusName . '">
                        </td>
                    </tr>
                    <tr width=100%>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <strong>Secondary Status Color:</strong>&nbsp;&nbsp;
                        </td>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <script type="text/javascript">        
                              $(document).ready(
                                function()
                                {
                                  $("#rowColor").jPicker({window:{position:{x:"center",y:"center"},expandable: true,liveUpdate: true}});
                                });
                            </script>
                            <input id="rowColor" name="rowColor" type="text" maxlength="6" value="' . $secondaryStatusColor . '" style="width: 60px; height: 20px; overflow: auto; resize:none;"/>
                        </td>
                    </tr>
                    <tr width=100%>
                        <td colspan=2 width="100%"><strong>Secondary Status Description (1000 characters)</strong><br> 
                            <textarea name="description" id="description" maxlength="1000" class="intext" style="width: 100%; height: 100px; overflow: auto; resize:vertical;">' .
                            $secondaryStatusDescription .
                            '</textarea>
                        </td>
                    </tr>
                </table>
                <p align="right">
                    <input type="hidden" id="formSubmitted" name="formSubmitted" value="TRUE">
                    <input id="formSubmit" type="submit" onclick="this.disabled=true; this.form.submit();" style="cursor: hand; cursor: pointer;" value="' . $modifyType . ' Secondary Status" />
                </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("' . $modifyType . 'SecondaryStatus", "formSubmit");
                frmvalidator.addValidation("name",
                                           "required",
                                           "Please enter the secondary status name.");
            </script>';
    }
    
    function getSecondaryStatusAsSelectOptions($db, $userRow, $selected){
        // Initialize the return
        $result = '';
        try {
            // Determine if this is an SU user
            if ($userRow["CompanyID"]==1){
                // Showing a totally different thing for non editable users on status
                if ($userRow["UserLevel"]=='EXECUTIVE' || $userRow["UserLevel"]=='MANAGEMENT' || $userRow["UserLevel"]=='SU'){
                    // Create the query to run
                    $sql='SELECT * FROM secondarystatuses ORDER BY Name;';

                    // Query the database for the secondary status 
                    $rows = $db->queryDB($sql, $userRow, "task_presentation Form occurance 32");

                    // If there are rows, then they are good to go.
                    if ($rows == null){
                        return $result;
                    }
                    else{
                        // Loop through the returned results
                        $rowNumber = 0;

                        // Loop through the status rows
                        while ($row=mysqli_fetch_array($rows)){
                            // Determine if this is one that is to be selected
                            $selectedText='';
                            if ($selected != null and $selected==$row["SecondaryStatusID"]) {
                                // Create the selected html
                                $selectedText='selected';
                            }

                            // Add this option to the select
                            $result=$result . '<option title="' . $row["Description"] . '" label="' . $row["RowColor"] . '" value="' . $row["SecondaryStatusID"] . '" ' . $selectedText . '>' . $row["Name"] . ' </option>';
                        }

                        // Start the return with the beginning of the select
                        $result='<select name="secondaryStatus" id="secondaryStatus" onchange="document.getElementById(\'secondaryStatusDescription\').innerHTML=getSelectSelectedOptionAttribute(\'secondaryStatus\', \'title\'); document.getElementById(\'GeneralInfo\').style.backgroundColor=getSelectSelectedOptionAttribute(\'secondaryStatus\', \'label\'); document.getElementById(\'Machining\').style.backgroundColor=getSelectSelectedOptionAttribute(\'secondaryStatus\', \'label\'); ' . 
                                $onChangeHTML . '">' . $result . 
                                '</select>
                                 <input type="hidden" name="oldSecondaryStatus" id="oldSecondaryStatus" value="' . $selected . '"></input>
                                ';
                    }
                }
                else {
                    // Create the query to run
                    $sql='SELECT * FROM secondarystatuses WHERE SecondaryStatusID=' . $selected . ' ORDER BY Name;';

                    // Query the database for the secondary status 
                    $row = $db->queryDB($sql, $userRow, "task_presentation Form occurance 33");

                    // If there are rows, then they are good to go.
                    if ($row == null){
                        return $result;
                    }
                    else{
                        // Attempt to get the selected status row
                        $assocRow = $row->fetch_assoc();

                        // Only need a text box to show them their status, since they cannot change their own company
                        $result='<input type="hidden" name="secondaryStatus" id="secondaryStatus" value="' . $selected . '"></input>
                                 <input type="hidden" name="oldSecondaryStatus" id="oldSecondaryStatus" value="' . $selected . '"></input>
                                 <input class="intext" name="secondaryStatusName" id="secondaryStatusName" type="text" style="width: 100%;" value="' . $assocRow["Name"] . '" disabled>';
                    }
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function copyTask($db, $userRow, &$duplicateToolsString, $taskIDToCopy=null, $parentTaskID=0, &$newTaskID=-1, &$hasFeedback=0){
        // Create a variable to hold the success info and set it to successful at first
        $returnSuccess=true;
        
        // Create a variable to hold the newly created task ID
        $newTaskID=-1;
        
        try {
            // Start by creating a new task to work with, so we can get the newly created task ID
            $sql='INSERT INTO tasks (ParentID, CompanyID, SecondaryStatusID, ' . 
                                    'UserID, CreatedByID, Entry, TaskPrice, TypeID, Title, ' . 
                                    'DeliverableQuantity, TotalQuantity, CleanUp, FixtureToUseID, ' . 
                                    'PartHardware, LastUpdatedByID, IsVacuumClean, IsWashForAnodize, ' .  
                                    'IsSandblasted, SandBlastingInstructions, HasAllowableCosmeticDamage, ' .  
                                    'IsTappedPostMachining, PostMachiningTappingInstructions, ' .  
                                    'PostMachiningNotes, ProgrammerID, ProgramCheckedByID, StatusID, ' .  
                                    'Priority) ' .  
                 'SELECT DISTINCT ' . 
                        $parentTaskID . ', t1.CompanyID, t2.SecondaryStatusID,  ' . 
                        $userRow["UserID"] . ',' . $userRow["UserID"] . 
                        ',t2.Entry,t2.TaskPrice,t2.TypeID,t2.Title, ' . 
                        '0,0,t2.CleanUp,t2.FixtureToUseID, ' . 
                        't2.PartHardware,' . $userRow["UserID"] . ',t2.IsVacuumClean,t2.IsWashForAnodize, ' . 
                        't2.IsSandblasted,t2.SandBlastingInstructions,t2.HasAllowableCosmeticDamage, ' . 
                        't2.IsTappedPostMachining,t2.PostMachiningTappingInstructions, ' . 
                        't2.PostMachiningNotes,t2.ProgrammerID,t2.ProgramCheckedByID, ' . 
                        '(SELECT StatusID FROM status WHERE Name="Copy Review"), ' . 
                        '(SELECT (MAX(Priority)+1) ' . 
                        ' FROM tasks ' . 
                        ' WHERE CompanyID=t2.CompanyID ' . 
                        ' AND Priority<99998) ' . 
                 'FROM tasks t1  ' . 
                 'JOIN tasks t2 ON t2.TaskID=' . $taskIDToCopy . ' ' . 
                 'LIMIT 1;';
        
            // Determine if we have a parent passed in
            if ($parentTaskID!= null && $parentTaskID>0){
                // Create a query to get parent info as well as the rest
                $sql='INSERT INTO tasks (ParentID, CompanyID, SecondaryStatusID, ' . 
                                        'UserID, CreatedByID, Entry, TaskPrice, TypeID, Title, ' . 
                                        'DeliverableQuantity, TotalQuantity, CleanUp, FixtureToUseID, ' . 
                                        'PartHardware, LastUpdatedByID, IsVacuumClean, IsWashForAnodize, ' .  
                                        'IsSandblasted, SandBlastingInstructions, HasAllowableCosmeticDamage, ' .  
                                        'IsTappedPostMachining, PostMachiningTappingInstructions, ' .  
                                        'PostMachiningNotes, ProgrammerID, ProgramCheckedByID, StatusID, ' .  
                                        'DueDate, IdealDate, Priority, SubPriority) ' .  
                     'SELECT DISTINCT ' . 
                            $parentTaskID . ', t3.CompanyID, t2.SecondaryStatusID,  ' . 
                            $userRow["UserID"] . ',' . $userRow["UserID"] . 
                            ',t2.Entry,t2.TaskPrice,t3.TypeID,t2.Title, ' . 
                            '0,0,t2.CleanUp,t2.FixtureToUseID, ' . 
                            't2.PartHardware,' . $userRow["UserID"] . ',t2.IsVacuumClean,t2.IsWashForAnodize, ' . 
                            't2.IsSandblasted,t2.SandBlastingInstructions,t2.HasAllowableCosmeticDamage, ' . 
                            't2.IsTappedPostMachining,t2.PostMachiningTappingInstructions, ' . 
                            't2.PostMachiningNotes,t2.ProgrammerID,t2.ProgramCheckedByID, ' . 
                            '(SELECT StatusID FROM status WHERE Name="Copy Review"), ' . 
                            't3.DueDate, t3.IdealDate, t3.Priority, ' . 
                            '(SELECT IF(MAX(SubPriority) IS NULL, 1, MAX(SubPriority)+1) FROM tasks WHERE ParentID=' . $parentTaskID . ') ' .  
                     'FROM tasks t1  ' . 
                     'JOIN tasks t2 ON t2.TaskID=' . $taskIDToCopy . ' ' . 
                     'JOIN tasks t3 ON t3.TaskID=' . $parentTaskID . ' ' . 
                     'LIMIT 1;';
            }
            
            // Attempt to run the query and evaluate the response
            if (!$db->queryDB($sql, $userRow, "task_presentation Form occurance 34")){
            }
            else {
                // Get the most recent ID (task)
                $newTaskID = mysqli_insert_id($db->getDBConnection());
                
                // Ensure that we have a new task ID
                if ($newTaskID>0){
                    // Create all attachments from the old task to this task
                    copyAttachments($db, $userRow, $returnSuccess, $newTaskID, $taskIDToCopy);
                    
                    // Create all blanks from the old task to this task
                    copyBlanks($db, $userRow, $returnSuccess, $newTaskID, $taskIDToCopy);

                    // Create all notes from the old task to this task
                    copyNotes($db, $userRow, "TASK", false, $returnSuccess, $newTaskID, $taskIDToCopy);

                    // Create all tools from the old task to this task
                    copyTaskTools($db, $userRow, $returnSuccess, $newTaskID, $taskIDToCopy);

                    // Create all setups from the old task to this task
                    copySetups($db, $userRow, $returnSuccess, $duplicateToolsString, $newTaskID, $taskIDToCopy);
                    
                    // Create all routing information from the old task to this task
// TODO: Routing Figure out why this method does not seem to want to fire.
//                    copyRouting($db, $userRow, $returnSuccess, $newTaskID, $taskIDToCopy);

                    // Set the parent as if it has children
                    if ($parentTaskID!= null && $parentTaskID>0 && $returnSuccess){
                        // Create a query to update the parent with the fact it has children now.
                        $sql='UPDATE tasks SET HasChildren=1 WHERE TaskID=' . $parentTaskID . ';';
                        
                        // Run the update query on the parent
                        $db->queryDB($sql, $userRow, "task_presentation Form occurance 35");
                    }
                    
                    // Create a query to determine if the old task had pink notes
                    $sql='SELECT PostMachiningFeedback, ' . 
                                '(SELECT COUNT(*) FROM machiningsetups ms ' . 
                                 'LEFT JOIN notes n ON ms.MachiningSetupID = n.AssociatedCategoryID ' . 
                                 'WHERE n.Category="OPERATOR_FEEDBACK_NOTE" ' . 
                                 'AND ms.TaskID=' . $taskIDToCopy . ') AS AmountOfOperatorFeedback ' . 
                         'FROM tasks ' . 
                         'WHERE TaskID=' . $taskIDToCopy . ';';
                    $hasFeedbackRow = $db->queryDB($sql, $userRow, "task_presentation Form occurance 36");

                    // Determine if we even have a task to update
                    if (mysqli_num_rows($hasFeedbackRow)==1){
                        // Get the feedback row
                        $hasFeedbackAssocRow = $hasFeedbackRow->fetch_assoc();

                        // Determine if there are any pink notes
                        if (($hasFeedbackAssocRow["PostMachiningFeedback"]!=NULL && trim($hasFeedbackAssocRow["PostMachiningFeedback"]) != '') || 
                            $hasFeedbackAssocRow["AmountOfOperatorFeedback"]>0){
                            // Set it as having feedback
                            $hasFeedback=1;
                            
                            // Create a query to put the task into pink not feedback
                            $sql='UPDATE tasks ' . 
                                 'SET StatusID=(SELECT StatusID FROM status WHERE Name="Pink Note Copy Review") ' .
                                 'WHERE TaskID=' . $newTaskID . ';';
                            
                            // Run the update query on the new task ID to set it into pink note review status
                            $db->queryDB($sql, $userRow, "task_presentation Form occurance 35");
                        }
                    }
                    
                    // Create a query to add a row to the copied tasks linker table
                    $sql='INSERT INTO copiedtaskslinker' . 
                            '(CopiedFromTaskID, CopiedToTaskID, ' . 
                             'CopyingUserID, CopiedFromHasFeedback) ' . 
                         'VALUES ' . 
                            '(' . $taskIDToCopy . ',' . $newTaskID . ',' . 
                              $userRow["UserID"] . ',' . $hasFeedback . ');';
                    
                    // Attempt to run the query and evaluate the response
                    if ($db->queryDB($sql, $userRow, "task_presentation Form occurance 37")){
                    }
                    else {
                        // Assign the output to failed
                        return false;
                    }
                }
            }
        } 
        catch (Exception $ex) {
            // Assign the output to failed
            return false;
        } 
        
        // If we got here, then it must be a success
        return true;
    }
    
    function copyAttachments($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 attachments (FileType, TaskID, UserID, Title, ' . 
                            'Path, ByteSize, Description, IPAddress, SubmitDate, Datum) ' . 
                          'SELECT FileType, ' . $newTaskID . ', UserID, Title, ' . 
                            'Path, ByteSize, Description, IPAddress, SubmitDate, Datum ' . 
                            'FROM attachments WHERE TaskID=' . $taskIDToCopy . ';';

                // Attempt to update the task
                if (!$db->queryDB($sql, $userRow, "task_presentation Form occurance 38")){
                    // 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;
        }
    }
?>