<?php

function showNoteDatum($row){
    // Show the file
    header("Content-Disposition: attachment; filename=" .$row["FileName"]);
    header("Content-Length: " . $row["ByteSize"]);
    header("Content-Type: " . $row["FileType"]);
    header('Content-Transfer-Encoding: binary');

    // Clean it up before we send out the file
    while (ob_get_level()) {
        ob_end_clean();
    }

    // Spit out the data
    die($row["Datum"]);
}

function getQuarterNumber($month) {
    // assume 1st quarter
    $returnQuarter = 1;

    // Check wthat quarter was determined as passed in
    switch ($month) {
        case 4:
        case 5:
        case 6:
            // Create return as April 1st
            $returnQuarter = 2;

            // No need to check the others
            break;
        case 7:
        case 8:
        case 9:
            // Create return as July 1st
            $returnQuarter = 3;

            // No need to check the others
            break;
        case 10:
        case 11:
        case 12:
            // Create return as October 1st
            $returnQuarter = 4;

            // No need to check the others
            break;
    }

    // Return whatever we have
    return $returnQuarter;
}

function calculateQuarterStart($forDate) {
    // Setup the return value as start of 1st quarter (January 1st)
    $dateToCheck = new DateTime();
    $returnQuarterStart = new DateTime();

    // Determine if we have something passed in
    if ($forDate != null) {
        // Determine if it is a date object
        if ($forDate instanceof DateTime) {
            // set the date to be the same directly
            $dateToCheck = $forDate;
        } else {
            try {
                // assume it is a string and I will handle it
                $dateToCheck = new DateTime($forDate);
            } catch (Exception $ex) {
                unset($ex);
            }
        }
    }

    // Get the current month
    $currentMonth = $dateToCheck->format("n");

    // Get the current year
    $currentYear = $dateToCheck->format("Y");

    // Set the default to be January 1st
    $returnQuarterStart = $dateToCheck->createFromFormat('d/m/Y H:i:s', '01/01/' . $currentYear . ' 00:00:00');

    // Check wthat quarter was determined as passed in
    switch ($currentMonth) {
        case 4:
        case 5:
        case 6:
            // Create return as April 1st
            $returnQuarterStart = $dateToCheck->createFromFormat('d/m/Y H:i:s', '01/04/' . $currentYear . ' 00:00:00');

            // No need to check the others
            break;
        case 7:
        case 8:
        case 9:
            // Create return as July 1st
            $returnQuarterStart = $dateToCheck->createFromFormat('d/m/Y H:i:s', '01/07/' . $currentYear . ' 00:00:00');

            // No need to check the others
            break;
        case 10:
        case 11:
        case 12:
            // Create return as October 1st
            $returnQuarterStart = $dateToCheck->createFromFormat('d/m/Y H:i:s', '01/10/' . $currentYear . ' 00:00:00');

            // No need to check the others
            break;
    }

    // Return whatever we have
    return $returnQuarterStart;
}

function getToolTypeHTML($db, $userRow, $controlName, $selected, $category, $onChangeHTML, $includeAll=0, $style=""){
    // Initialize the return
    $result = '';

    try {
        // Init the tool type name
        $toolTypeSelected=1;

        // Set the tool type start to be regular machine tools.  Add categories to here.
        $toolTypeSelectedQuery='"TOOL"';

        // Determine if it is NOT of the tool category
        if ($category==2){
            // Set the tool type start to be regular machine tools
            $toolTypeSelectedQuery='"MISCELLANEOUS"';
        }

        // If the $selected variable is -1, then this is in an add page.  
        if ($selected!=-1){
            // Set the selected tool type
            $toolTypeSelected=$selected;
        }

        // Create the query to run
        $sql='SELECT * FROM tooltype WHERE CategoryName=' . $toolTypeSelectedQuery . ' ORDER BY LOWER(Name);';

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

        // Ensure we got rows back.
        if ($rows == null){
            return $result;
        }
        else{
            // Loop through the returned results
            $selectedText='';
            while ($row=mysqli_fetch_array($rows)){
                $selectedText='';
                // Determine if this is one that is to be selected
                if ($toolTypeSelected != null and $toolTypeSelected==$row["ToolTypeID"]) {
                    // Create the selected html
                    $selectedText='selected';
                }

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

            // Determine if they want the all option
            if ($includeAll==1){
//                // determine if any got selected
//                if ($selectedText==''){
//                    // Create the selected html
//                    $selectedText='selected';
//                }
                
                // Add the all types option
                $result= '<option value="-1" ' . $selectedText . '>ALL TYPES</option>' . $result;
            }
            
            // End the select
            $result=$result . '</select>';

            // Start the return with the beginning of the select
            $result= '<select name="' . $controlName . '" id="' . $controlName . '"  onchange="' . $onChangeHTML . '" style="' . $style . '">' . $result;
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return whatever we got
    return $result;
}

function taskRowsHaveMajorDifferences($taskRow1, $taskRow2) {
    // Setup the return result to be false at first
    $result = false;

    // Create a try just to stop errors.  If there is an error, just assume it is NOT equal
    try {
        // Start to compare rows.  It is assumed that the rows are already assoc 
        // and they have the fields that I am looking at here.
        if($taskRow1["ParentID"]!=$taskRow2["ParentID"] ||
           $taskRow1["CompanyID"]!=$taskRow2["CompanyID"] ||
           $taskRow1["StatusID"]!=$taskRow2["StatusID"] ||
           $taskRow1["UserID"]!=$taskRow2["UserID"] ||
           $taskRow1["TypeID"]!=$taskRow2["TypeID"] ||
           $taskRow1["Priority"]!=$taskRow2["Priority"] ||
           $taskRow1["Invoiced"]!=$taskRow2["Invoiced"] ||
           $taskRow1["Completed"]!=$taskRow2["Completed"] ||
           $taskRow1["Closed"]!=$taskRow2["Closed"] ||
           $taskRow1["Title"]!=$taskRow2["Title"] ||
           $taskRow1["Entry"]!=$taskRow2["Entry"] ||
           $taskRow1["DueDate"]!=$taskRow2["DueDate"] ||
           $taskRow1["IdealDate"]!=$taskRow2["IdealDate"] ||
           $taskRow1["DeliverableQuantity"]!=$taskRow2["DeliverableQuantity"] ||
           $taskRow1["HasChildren"]!=$taskRow2["HasChildren"] ||
           $taskRow1["SubPriority"]!=$taskRow2["SubPriority"] ||
           $taskRow1["TotalQuantity"]!=$taskRow2["TotalQuantity"] ||
           $taskRow1["Expedite"]!=$taskRow2["Expedite"]) {
            // Set the result to true that important things have changed
            $result = true;
        }
    } catch (Exception $ex) {
        // Error would probably be a result of two rows that do not have the same fields.
        // This means they are NOT equal.
        $result = false;
    }
    
    Return $result;
}

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

    try {
        // Determine if a note ID was provided
        if (isset($noteID)) {
            // Setup the query to be where it gets attachments for this note
            $sql = 'SELECT AttachmentID, Title, FileType, ByteSize FROM attachments ' .
                    'WHERE NoteID=' . $noteID . ' ORDER BY SubmitDate;';

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

            // 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') {
                    $result = $result .
                            '<div class="cell checkCell">
                                        <input class="notinput" type="checkbox" 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 retrieveCurrentAddresses($db, $userRow, $id, $whichID) {
    // Set the return result to nothing in case nothing is passed in for task number
    $result = '';

    try {
        // Determine if a user number was provided
        if (isset($id)) {

            // Setup the query to be where they only get users in their company
            $sql = 'SELECT * FROM addresses a, addresslinker al ' .
                    'WHERE a.AddressID = al.AddressID ' .
                    'AND al.' . $whichID . '=' . $id . ' ' .
                    'ORDER BY a.Address1;';

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

            // Determine if there are any addresses
            if ($rows!=null && mysqli_num_rows($rows)>0){
                // Initialize variables
                $result = '<div class="Table" id="currentAddress" name="currentAddress">
                               <div class="Row">
                                    <div class="cell cell1"></div>
                                    <div class="cell">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 = '';

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

                    // Determine if this is the first row
                    if ($rowNumber == 1) {

                    }

                    // Add the attachment to the table
                    $result = $result .
                            '   <div class="Row" style="height: 60px;">
                                    <div class="cell cell1" style="vertical-align: middle;">' . $rowNumber . '</div>
                                    <div class="cell addressCell" style="vertical-align: middle;">
                                        <br>
                                        1-<input name="currentAddress1' . $row["AddressID"] . '" type="text" maxlength="150" class="intext" style="background-color: transparent; width: 90%; border: 1px dotted; padding: 2px 2px 2px 2px;" value="' . $row["Address1"] . '"></input>
                                        <br><br>
                                        2-<input name="currentAddress2' . $row["AddressID"] . '" type="text" maxlength="150" class="intext" style="background-color: transparent; width: 90%; border: 1px dotted; padding: 2px 2px 2px 2px;" value="' . $row["Address2"] . '"></input>
                                        <br><br>
                                    </div>
                                    <div class="cell cityCell" style="vertical-align: middle;">
                                        <input name="currentCity' . $row["AddressID"] . '" type="text" maxlength="75" class="intext" style="background-color: transparent; width: 100%; border: 1px dotted; padding: 2px 2px 2px 2px;" value="' . $row["City"] . '"></input>
                                    </div>
                                    <div class="cell stateCell" style="vertical-align: middle;">
                                    ' 
                                    .
                                        getStatesAsSelectOptions($row["State"], 'currentState' . $row["AddressID"], '', true)
                                    . 
                                    '
                                    </div>
                                    <div class="cell zipCell" style="vertical-align: middle;">
                                        <input name="currentZip' . $row["AddressID"] . '" type="text" maxlength="5" class="intext" style="background-color: transparent; border: 1px dotted; padding: 2px 2px 2px 2px; width: 50px;" value="' . $row["Zip"] . '"></input>
                                    </div>
                                    <div class="cell phoneCell" style="vertical-align: middle;">
                                        <br>
                                        1-<input name="currentPhone1' . $row["AddressID"] . '" type="text" maxlength="12" class="intext" style="background-color: transparent; border: 1px dotted; padding: 2px 2px 2px 2px; width: 90%;" value="' . $row["PhoneNumber1"] . '"></input>
                                        <br><br>
                                        2-<input name="currentPhone2' . $row["AddressID"] . '" type="text" maxlength="12" class="intext" style="background-color: transparent; border: 1px dotted; padding: 2px 2px 2px 2px; width: 90%;" value="' . $row["PhoneNumber2"] . '"></input>
                                        <br><br>
                                    </div>
                                    <div class="cell checkCell" style="vertical-align: middle;">
                                        <input type="checkbox" onclick="handleAddressClick(this);" value="' . $row["AddressID"] . '"></input>
                                    </div>
                                </div>';

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

                // Add the hidden field to the form
                $result = '<strong>Current Addresses: </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 getCompanyHTML($db, $userRow, $selected, $onChangeHTML, $allEditable, $needsSUDelimiting, $mainSubCompany, $style='width: 100%;') {
    // Initialize the return
    $result = '';

    try {
        // Init the company name
        $companyName = '';
        $companySelected = 1;

        // If the $selected variable is -1, then this is in an add page.  Set selected to main company.
        if ($selected != -1) {
            // Set the selected company
            $companySelected = $selected;
        }

        // Create the query to run
        $sql = 'SELECT * FROM companies where CompanyID=' . $userRow["CompanyID"] . ' ORDER BY CompanyName;';

        // Determine if we are dealing with a SU company user
        if ($userRow["CompanyID"] == 1) {
            // Create the query to run
            $sql = 'SELECT * FROM companies WHERE CompanyID=' . $userRow["CompanyID"] .
                    ' OR CompanyID=' . $companySelected . ' OR active = 1 ORDER BY CompanyName;';

            // Determine if this is a lower level user
            if (($userRow["UserLevel"] == "MANAGEMENT" || $userRow["UserLevel"] == "MID-MANAGEMENT" || 
                 $userRow["UserLevel"] == "MINIMAL" || $userRow["UserLevel"] == "TYPICAL") &&
                 $userRow["CanAddAllParent"]!=1){
                // Determine if it needs delimination and this is a main company
                if (($needsSUDelimiting && $mainSubCompany) ||
                        $selected = -1) {
                    // Create the query to run
                    $sql = 'SELECT * FROM companies WHERE CompanyID=' . $userRow["CompanyID"] .
                            ' OR CompanyID=' . $companySelected . ' OR MainSubCompany=1 AND active=1 ORDER BY CompanyName;';
                }
            }
        }

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

        // 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
            while ($row = mysqli_fetch_array($rows)) {
                // Determine if this is one that is to be selected
                $selectedText = '';
                if ($companySelected != null and $companySelected == $row["CompanyID"]) {
                    // Create the selected html
                    $selectedText = 'selected';

                    // Save the company name for later
                    $companyName = $row["CompanyName"];
                }

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

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

            // Showing a totally different thing for non editable users on company
            if ($allEditable === 'disabled') {
                // Only need a text box to show them their company, since they cannot change their own company
                $result = '<input type="hidden" name="company" id="company" value="' . $companySelected . '"></input>
                             <input id="companyName" name="companyName" type="text" maxlength="150" class="intext" style="' . $style . '" value="' . $companyName . '" ' . $allEditable . '>';
            } else {
                // Start the return with the beginning of the select
                $result = '<select name="company" id="company" ' . $allEditable . ' onchange="' . $onChangeHTML . '" ' . $allEditable . ' style="' . $style . '" >' . $result;
            }
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return whatever we got
    return $result;
}

function getSidebar($userRow, $activePage) {
    // Here is the sub tasks for the accounts page
    $accountSubTasks = '';
    $companySubTasks = '';
    $financialsSubTasks = '';
    $tasksSubTasks = '';
    $equipmentSubTasks = '';
    $timecardSubTasks = '';

    // Initialize used variables and assume that we are NOT on that page
    $tasksScript = 'non';
    $financialsScript = 'non';
    $companiesScript = 'non';
    $accountsScript = 'non';
    $equipmentScript = 'non';
    $timecardScript = 'non';

    // Determine if we have an active page
    if ($activePage!=null){
        // Determine what the user preference is for tasks.  Set to machining as default
        $ts=1;
        switch ($userRow["PrimaryTaskType"]) {
            case 'DESIGNING':
                // Set to desiging tasks
                $ts=2;
                
                // Leve this case statement
                break;
            case 'PROGRAMMING':
                // Set to programming tasks
                $ts=3;
                
                // Leve this case statement
                break;
            case 'IN-HOUSE':
                // Set to in-house tasks
                $ts=4;
                
                // Leve this case statement
                break;
            default:
                break;
        }
        
        // First determine what page we are currently on
        switch ($activePage) {
            case 'tasks':
                // We are on that page, so remove the non and add subtasks
                $tasksScript = '';

                // Determine if this is a user from the super company to add specifics for SU company
                $viewByEmployeeHTML='';
                $viewByMachineHTML='';
                $viewSecondaryStatusesHTML='';
                if ($userRow["CompanyID"] == 1) {
                    $viewByEmployeeHTML = '<li><a href="etasks.php?ts=' . $ts . '&at=' . $userRow["UserID"] . '">View By Assigned</a></li>';
                    $viewByMachineHTML = '<li><a href="machiningTasks.php">View By Machine</a></li>';
                    $viewSecondaryStatusesHTML = '<li><a style="border-top: 2px solid dodgerblue;" href="secondaryStatuses.php">Secondary Statuses</a></li>
                                                  <li><a href="addSecondaryStatus.php">Add Secondary Status</a></li>';
                }
                
                // Determine if this user can add main tasks
                $addTaskHTML='';
                if ($userRow["UserLevel"]=='SU' || $userRow["UserLevel"]=='EXECUTIVE' || $userRow["CanAddAllParent"]==1){
                    // Set it to allow for all tasks to be able to add
                    $addTaskHTML='<li><a href="addTask.php">Add Parent Task</a></li>';
                }
                else {
                    // Determine if this is a SU company user
                    if ($userRow["CompanyID"] == 1){
                        // Set it to allow for tasks for the SU company
                        $addTaskHTML='<li><a href="addTask.php">Add SU Company Task</a></li>';
                    }
                    
                }

                // In order to determine the level of this person's account, I need to know their type
                switch ($userRow["UserLevel"]) {
                    case 'MINIMAL' :
                    case 'TYPICAL' :
                        // Set the sub tasks to be appropriate for this level
                        $tasksSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="tasks.php?ts=' . $ts . '">View All</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                    case 'MID-MANAGEMENT' :
                        // Set the sub tasks to be appropriate for this level
                        $tasksSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                            <li><a href="tasks.php?ts=' . $ts . '">View All</a></li>
                                            '
                                            .
                                            $viewByEmployeeHTML
                                            .
                                            $viewByMachineHTML
                                            .
                                            $addTaskHTML
                                            .
                                            '
                                         </ul>';

                        // Break out of this case statement
                        break;
                    case 'MANAGEMENT':
                        // Set the sub tasks to be appropriate for this level
                        $tasksSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                            <li><a href="tasks.php?ts=' . $ts . '">View All</a></li>
                                            '
                                            .
                                            $viewByEmployeeHTML
                                            .
                                            $viewByMachineHTML
                                            .
                                            $addTaskHTML
                                            .
                                            $viewSecondaryStatusesHTML
                                            . 
                                            '
                                         </ul>';

                        // Break out of this case statement
                        break;
                    case 'EXECUTIVE':
                    case 'SU':
                        // Set the sub tasks to be appropriate for this level
                        $tasksSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                            <li><a href="tasks.php?ts=' . $ts . '">View All</a></li>
                                            '
                                            .
                                            $viewByEmployeeHTML
                                            .
                                            $viewByMachineHTML
                                            .
                                            $addTaskHTML
                                            .
                                            $viewSecondaryStatusesHTML
                                            . 
                                            '
                                         </ul>';

                        // Break out of this case statement
                        break;
                }

                // Break out of this case statement
                break;
            case 'financials':
                // We are on that page, so remove the non
                $financialsScript = '';
                
                // Determine if the user is an SU company user
                if ($userRow["CompanyID"]==1){

                    // In order to determine the level of this person's account, I need to know their type
                    switch ($userRow["UserLevel"]) {
                        case 'TYPICAL' :
                        case 'MID-MANAGEMENT' :
                        case 'MANAGEMENT':
                            // Set the sub tasks to be appropriate for this level
                            $financialsSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                        <li><a href="benefits.php">Benefits Summary</a></li>
                                     </ul>';

                            // Break out of this case statement
                            break;
                        case 'EXECUTIVE':
                        case 'SU':
                            // Set the sub tasks to be appropriate for this level
                            $financialsSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                        <li><a href="benefits.php">Benefits Summary</a></li>
                                        <li><a href="viewEmployeeBenefits.php">View Employee\'s Benefits</a></li>
                                     </ul>';

                            // Break out of this case statement
                            break;
                    }
                }

                // Break out of this case statement
                break;
            case 'companies':
                // We are on that page, so remove the non
                $companiesScript = '';

                // In order to determine the level of this person's account, I need to know their type
                switch ($userRow["UserLevel"]) {
                    case 'MANAGEMENT':
                    case 'EXECUTIVE':
                        // Set the sub tasks to be appropriate for this level
                        $companySubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="vendors.php">View Vendors</a></li>
                                    <li><a href="addVendor.php">Add Vendor</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                    case 'SU':
                        // Set the sub tasks to be appropriate for this level
                        $companySubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="companies.php">View Customers</a></li>
                                    <li><a href="addCompany.php">Add Customer</a></li>
                                    <li><a href="vendors.php">View Vendors</a></li>
                                    <li><a href="addVendor.php">Add Vendor</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                }

                // Break out of this case statement
                break;
            case 'accounts':
                // We are on that page, so remove the non
                $accountsScript = '';

                $viewUserTemplatesHTML='';
                if ($userRow["CompanyID"] == 1) {
                    $viewUserTemplatesHTML='<li><a style="border-top: 2px solid dodgerblue;" href="userTemplates.php">List User Templates</a></li>
                                            <li><a href="addUserTemplate.php">Add User Template</a></li>';
                }
                
                // In order to determine the level of this person's account, I need to know their type
                switch ($userRow["UserLevel"]) {
                    case 'TYPICAL' :
                    case 'MID-MANAGEMENT' :
                    case 'MANAGEMENT':
                        // Set the sub tasks to be appropriate for this level
                        $accountSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="updateUser.php?updateUserID=' . $userRow["UserID"] . '">Personal Profile</a></li>
                                    <li><a href="users.php?cs=' . $userRow["CompanyID"] . '">List System Users</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                    case 'EXECUTIVE':
                    case 'SU':
                        // Set the sub tasks to be appropriate for this level
                        $accountSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="updateUser.php?updateUserID=' . $userRow["UserID"] . '">Personal Profile</a></li>
                                    <li><a href="users.php?cs=' . $userRow["CompanyID"] . '">List System Users</a></li>
                                    <li><a href="addUser.php">Add User</a></li>
                                    '
                                    .
                                    $viewUserTemplatesHTML
                                    .
                                    '
                                 </ul>';
                        
                        // Break out of this case statement
                        break;
                }

                // Break out of this case statement
                break;
            case 'equipment':
                // We are on that page, so remove the non
                $equipmentScript = '';

                // In order to determine the level of this person's account, I need to know their type
                switch ($userRow["UserLevel"]) {
                    case 'TYPICAL' :
                    case 'MID-MANAGEMENT' :
                        // Set the sub tasks to be appropriate for this level
                        $equipmentSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a style="border-bottom: 2px solid dodgerblue;" href="machines.php">Machines</a></li>
                                    <li><a href="tools.php?c=1&tt=-1">Tools</a></li>
                                    <li><a href="addTool.php?c=1">Add Tool</a></li>
                                    <li><a href="tools.php?c=2&tt=-1">Miscellaneous</a></li>
                                    <li><a href="addTool.php?c=2">Add Miscellaneous</a></li>
                                    <li><a href="tooltypes.php">Tool Types</a></li>
                                    <li><a style="border-bottom: 2px solid dodgerblue;" href="addToolType.php">Add Tool Type</a></li>
                                    <li><a href="stockedMaterials.php">Stocked Material</a></li>
                                    <li><a href="searchStockedMaterialInDepth.php">In-Depth Search Stocked Material</a></li>
                                    <li><a href="addStockedMaterial.php">Add Stocked Material</a></li>
                                    <li><a href="materialTypes.php">Material Types</a></li>
                                    <li><a href="addMaterialType.php">Add Material Type</a></li>
                                    <li><a style="border-top: 2px solid dodgerblue;" href="blanks.php">Blanks To Prepare</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                    case 'MANAGEMENT':
                    case 'EXECUTIVE':
                    case 'SU':
                        // Set the sub tasks to be appropriate for this level
                        $equipmentSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="machines.php">Machines</a></li>
                                    <li><a style="border-bottom: 2px solid dodgerblue;" href="addMachine.php">Add Machine</a></li>
                                    <li><a href="tools.php?c=1&tt=-1">Tools</a></li>
                                    <li><a href="addTool.php?c=1">Add Tool</a></li>
                                    <li><a href="tools.php?c=2&tt=-1">Miscellaneous</a></li>
                                    <li><a href="addTool.php?c=2">Add Miscellaneous</a></li>
                                    <li><a href="tooltypes.php">Tool Types</a></li>
                                    <li><a style="border-bottom: 2px solid dodgerblue;" href="addToolType.php">Add Tool Type</a></li>
                                    <li><a href="stockedMaterials.php">Stocked Material</a></li>
                                    <li><a href="searchStockedMaterialInDepth.php">In-Depth Search Stocked Material</a></li>
                                    <li><a href="addStockedMaterial.php">Add Stocked Material</a></li>
                                    <li><a href="materialTypes.php">Material Types</a></li>
                                    <li><a href="addMaterialType.php">Add Material Type</a></li>
                                    <li><a style="border-top: 2px solid dodgerblue;" href="blanks.php">Blanks To Prepare</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                }

                // Break out of this case statement
                break;
            case 'timecard':
                // We are on that page, so remove the non
                $timecardScript = '';

                // Setup the labor categories
                $viewLaborCategoriesHTML='';
                if ($userRow["CompanyID"] == 1) {
                    // Setup the labor categories sidebar
                    $viewLaborCategoriesHTML = '<li><a style="border-top: 2px solid dodgerblue;" href="laborCategories.php">Labor Categories</a></li>
                                                <li><a href="addLaborCategory.php">Add Labor Category</a></li>';
                }

                // In order to determine the level of this person's account, I need to know their type
                switch ($userRow["UserLevel"]) {
                    case 'TYPICAL' :
                    case 'MID-MANAGEMENT' :
                    case 'TIMECARD ONLY' :
                        // Set the sub tasks to be appropriate for this level
                        $timecardSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="updateTimecard.php">Current Timecard</a></li>
                                    <li><a href="timecardHistory.php?timecardUserID=' . $userRow["UserID"] . '">Timecard History</a></li>
                                    <li><a href="clockedStatus.php">Clock Status</a></li>
                                 </ul>';

                        // Break out of this case statement
                        break;
                    case 'MANAGEMENT':
                        // Set the sub tasks to be appropriate for this level
                        $timecardSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="updateTimecard.php">Current Timecard</a></li>
                                    <li><a href="timecardHistory.php?timecardUserID=' . $userRow["UserID"] . '">Timecard History</a></li>
                                    <li><a href="clockedStatus.php">Clock Status</a></li>
                                    '
                                    .
                                    $viewLaborCategoriesHTML
                                    . 
                                    '
                                 </ul>';

                        // Break out of this case statement
                        break;
                    case 'EXECUTIVE':
                    case 'SU':
                        // Set the sub tasks to be appropriate for this level
                        $timecardSubTasks = '<ul id="SideNav" class="MenuBarVertical">
                                    <li><a href="updateTimecard.php">Current Timecard</a></li>
                                    <li><a href="timecardHistory.php?timecardUserID=' . $userRow["UserID"] . '">Timecard History</a></li>
                                    <li><a href="viewEmployeeTimecards.php">View Employee Timecards</a></li>
                                    <li><a href="clockedStatus.php">Clock Status</a></li>
                                    '
                                    .
                                    $viewLaborCategoriesHTML
                                    . 
                                    '
                                 </ul>';

                        // Break out of this case statement
                        break;
                }

                // Break out of this case statement
                break;
        }
    }

    // Determine if this is a user from the super company
    $companyInfoSidebar='';
    if ($userRow["CompanyID"] == 1) {
        switch ($userRow["UserLevel"]) {
            case 'MANAGEMENT':
            case 'EXECUTIVE':
                // Add the subtasks
                $companyInfoSidebar = '<a href="vendors.php"><img src="images/companies_title_' . $companiesScript . 
                                      'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' . $companySubTasks;

            // Break out of this case statement
            break;
        }
    }
    
    // Setup variables for things that should only be used by SU users
    $assetsHTML="";
    $timecardsHTML="";
    $financialHTML="";
            
    // Determine if this is a user from the super company
    if ($userRow["CompanyID"] == 1) {
        // Set the variavles for the SU company users HTML
        $assetsHTML = '<a href="machines.php"><img src="images/assets_title_' . $equipmentScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
                      $equipmentSubTasks;
        $timecardsHTML = '<a href="clockedStatus.php"><img src="images/timecards_title_' . $timecardScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
                         $timecardSubTasks;
        
        // Determine if this user is a SU or EXECUTIVE 
        if ($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="SU"){
            // set group benefits as the main page
            $financialHTML = '<a href="viewEmployeeBenefits.php"><img src="images/financials_title_' . $financialsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
                             $financialsSubTasks;
        }
        else{
            // set individual benefits as the main page
        $financialHTML = '<a href="benefits.php"><img src="images/financials_title_' . $financialsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
                         $financialsSubTasks;
        }
    }
    
    // Determine what type of user we have here
    switch ($userRow["UserLevel"]) {
        case 'SU':
            // Echo out the html for this user
            echo
            '<a href="tasks.php?ts=' . $ts . '"><img src="images/tasks_title_' . $tasksScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $tasksSubTasks . $assetsHTML .
            '<a href="users.php?cs=' . $userRow["CompanyID"] . '"><img src="images/accounts_title_' . $accountsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $accountSubTasks .
            '<a href="companies.php"><img src="images/companies_title_' . $companiesScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $companySubTasks . $timecardsHTML . $financialHTML;

            // Break out of this case statement
            break;
        case 'EXECUTIVE':
        case 'MANAGEMENT':
            // Echo out the html for this user
            echo
            '<a href="tasks.php?ts=' . $ts . '"><img src="images/tasks_title_' . $tasksScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $tasksSubTasks . $assetsHTML . 
            '<a href="users.php?cs=' . $userRow["CompanyID"] . '"><img src="images/accounts_title_' . $accountsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $accountSubTasks .
            $companyInfoSidebar . $timecardsHTML . $financialHTML;

            // Break out of this case statement
            break;
        case 'TYPICAL' :
        case 'MID-MANAGEMENT' :
            // Echo out the html for this user
            echo
            '<a href="tasks.php?ts=' . $ts . '"><img src="images/tasks_title_' . $tasksScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $tasksSubTasks . $assetsHTML .
            '<a href="updateUser.php?updateUserID=' . $userRow["UserID"] . '"><img src="images/accounts_title_' . $accountsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $accountSubTasks .
            $companyInfoSidebar . $timecardsHTML . $financialHTML;

            // Break out of this case statement
            break;
        case 'MINIMAL' :
            // Echo out the html for this user
            echo
            '<a href="tasks.php?ts=' . $ts . '"><img src="images/tasks_title_' . $tasksScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $tasksSubTasks . 
            '<a href="updateUser.php?updateUserID=' . $userRow["UserID"] . '"><img src="images/accounts_title_' . $accountsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $accountSubTasks .
            $companyInfoSidebar . $timecardsHTML;

            // Break out of this case statement
            break;
        case 'TIMECARD ONLY' :
            // Echo out the html for this user
            echo
            '<a href="updateUser.php?updateUserID=' . $userRow["UserID"] . '"><img src="images/accounts_TCO_title_' . $accountsScript . 'select.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>' .
            $accountSubTasks .
            $companyInfoSidebar . $timecardsHTML;

            // Break out of this case statement
            break;

    }

    echo '<a href="redirectors/logout.php"><img src="images/logout_title.png" border="0" style="border-top: 1px dotted #C5C6C8;"/></a>';
}

function retrieveChildTasksAsList($db, $userRow, $parentID, $inParentSubtask, $fromWhatCompany, $fromWhatType) {
    // Init variables
    $updateableTitleRowCellHTML = '';
    $updateableTaskRowCellHTML = '';

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

            break;
    }

    // Initialize the return
    $result = '<ul>
                <li class="Table">
                    <div class="Heading">
                        <div class="cell priCell">
                            <p><b>#</b></p>
                        </div>
                        <div class="cell titleCell">
                            <p><b>Title</b></p>
                        </div>
                        <div class="cell quantityCell">
                            <p><b>Quantity</b></p>
                        </div>
                        <div class="cell childStatusCell">
                            <p><b>Status</b></p>
                        </div>
                        <div class="cell taskIDCell">
                            <p><b>Task ID</b></p>
                        </div>
                        <div class="cell dateCell">
                            <p><b>Due Date</b></p>
                        </div>' .
                        $updateableTitleRowCellHTML . '
                    </div>
                </li>';
    try {
        // Setup the query to be where they only get users in the parent company,
        // tasks that are NOT in stocked status, completed preference and of the 
        // type passed in.
        $sql = ' SELECT s.ProcessOrder as ProcessOrder, s.Name AS StatusName, s.StatusRowColor,' . 
               ' c.CompanyName AS CompanyName, c.CompanyRowColor, c.MainSubCompany,' .
               ' c.Store, t.SubPriority, t.Title, t.Entry, t.IdealDate, t.DueDate, t.Completed, t.Expedite, ' .
               ' t.Closed, t.TaskID, t.UserDeletable, t.ParentID, t.UserID, t.DeliverableQuantity, ' .
               ' ss.RowColor AS SSRowColor, ss.Description AS SSDescription, ss.Name AS SSName, ss.SecondaryStatusID, ' . 
               ' usvl.ViewCategory, ' .
               ' (SELECT COUNT(*) FROM copiedtaskslinker WHERE CopiedFromTaskID=t.TaskID GROUP BY CopiedFromTaskID) AS AmountCopiedFromThisTask' .
               ' FROM tasks t' .
               ' LEFT JOIN status s ON t.StatusID = s.StatusID' .
               ' LEFT JOIN companies c ON t.CompanyID = c.CompanyID' .
               ' LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID' .
               ' LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
               ' WHERE s.StatusID = t.StatusID' .
               ' AND t.CompanyID=c.CompanyID' .
               ' AND t.ParentID=' . $parentID .
               ' ORDER BY SubPriority;';
//echo '<script>alert("' . addslashes($sql) . '");</script>';

        // Query the original database query
        $rows = $db->queryDB($sql, $userRow, "presentation Form occurance 5");

        // 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
            $lastOneUpdated = '';
            while ($row = mysqli_fetch_array($rows)) {
                // Determine if it is an expedite part
                $rowExpedite='';
                $expediteTitle='';
                if ($row["Expedite"]==1){
                    // This one is common
                    $rowExpedite=' expediteTaskBackground';
                        
                    // Setup the title
                    $expediteTitle='This part is expedited. It takes highest priority.';
                }

                // Create a query to get appropriate sticky notes for this task
                $sql = 'SELECT n.*, 
                               (SELECT COUNT(*) FROM stickynoteusers WHERE MarkedAsRead=0 AND NoteID=n.NoteID) AS AmountNotReadByEveryone,
                               (SELECT COUNT(*) FROM stickynoteusers WHERE MarkedAsRead=0 AND NoteID=n.NoteID AND SendToID=' . $userRow["UserID"] . ') AS AmountNotReadByMe
                        FROM notes n
                        WHERE n.AssociatedCategoryID=' . $row["TaskID"] . '
                        AND n.Category=\'TASK\' 
                        AND n.IsSticky=1;';

                // Query the database for the the note count 
                $stickyNoteRows = $db->queryDB($sql, $userRow, "presentation Form occurance 6");

                // Init some count variables
                $notesToOthersFromMe=0;
                $notesToMeFromOthers=0;
                $stickyNoteHTML='';

                // Loop through the returned results
                while ($stickyNoteRow=mysqli_fetch_array($stickyNoteRows)){
                    // Determine if this sticky note should be counted because this
                    // person made the note and needs to keep track of who read it
                    if ($stickyNoteRow["EnteredByID"]==$userRow["UserID"] &&
                        $stickyNoteRow["AmountNotReadByEveryone"]>0){
                        // Increment the count of ones I made that have not been read by everyone
                        $notesToOthersFromMe++;
                    }

                    // Make this separate to count the ones I made that I want myself to reread
                    if ($stickyNoteRow["AmountNotReadByMe"]>0){
                        // Increment the count of ones I made that have not been read by everyone
                        $notesToMeFromOthers++;
                    }
                }

                // Determine if there are notes to show them
                if ($notesToOthersFromMe>0 || $notesToMeFromOthers>0){
                    $stickyNoteHTML=
                            '<div style="position: absolute; top: 10%; left:-55%;" onclick="popUp=popupWindow(\'view_sticky_notes.php?acid=' . $row["TaskID"] . '&c=TASK\', \'_blank\', window.parent, 700, 500);" 
                                                                                   onmouseover="document.body.style.cursor = \'pointer\';" 
                                                                                   onmouseout="document.body.style.cursor = \'default\';"
                                                                                   title="There are ' . $notesToMeFromOthers . ' notes to you that you have not read and ' . $notesToOthersFromMe . ' notes that you wrote that have not been read by all recipients.">
                                <img src="images/post_it.png" alt="Sticky Notes" style="height:20px; transform:rotate(15deg);">
                                <div style="position: absolute; top: 20%; left: 14%; transform:rotate(15deg);"><b><font style="color:red; font-size:9px">' . $notesToMeFromOthers . '</font><font style="color:black; font-size:9px">(</font><font style="color:green; font-size:9px">' . $notesToOthersFromMe . '</font><font style="color:black; font-size:9px">)</font></b></div>
                             </div>';
                }

                $updateableTaskRowCellHTML = '';
                
                // Create a default html for the button to edit the task
                $taskEditButtonHTML = '<input type="button" style="font-size:9px;" value="..." title="Edit this task." onclick="javascript:window.location=\'updateTask.php?updateTaskID=' . $row["TaskID"] . '&parentTaskId=' . $row["ParentID"] . '&cs=' . $fromWhatCompany . '&ts=' . $fromWhatType . '\'; this.form.submit();"/>';

                // Create a default html for the button to delete the task
                $taskDeleteButtonHTML = '<input type="button" style="font-size:9px;" value="X" title="Remove this subtask." onclick="javascript:if (confirm(\'Are you sure you want to delete this subtask?\')) {window.location=\'redirectors/delete_task.php?deleteTaskID=' . $row["TaskID"] . '\';}"/>';

                // Determine if their allowed to see this task
                if ($row["ViewCategory"] == "NOT VIEWABLE" &&
                    $row["UserID"] != $userRow["UserID"]){
                    // Create a default html for the button to edit the task
                    $taskEditButtonHTML = '';

                    // Create a default html for the button to delete the task
                    $taskDeleteButtonHTML = '';
                }
                else {
                    // Check if they would like to submit the parent first
                    if ($inParentSubtask) {
                        // Set up the html to include submitting the parent first
                       $taskEditButtonHTML = '<input type="button" style="font-size:9px;" value="..." title="Edit this task." onclick="javascript:document.getElementById(\'redirectTo\').value=\'updateTask.php?updateTaskID=' . $row["TaskID"] . '&parentTaskId=' . $row["ParentID"] . '&cs=' . $fromWhatCompany . '&ts=' . $fromWhatType . '\'; this.form.submit();"/>';

                        // Create a default html for the button to delete the task
                        //$taskDeleteButtonHTML = '<input type="button" style="font-size:9px;" value="X" title="Remove this subtask." onclick="javascript:if (confirm(\'Are you sure you want to delete this subtask?\')) {document.getElementById(\'redirectTo\').value=\'redirectors/delete_task.php?deleteTaskID=' . $row["TaskID"] . '\'; this.form.submit();}"/>';
                        $taskDeleteButtonHTML = '<input type="button" style="font-size:9px;" value="X" title="Remove this subtask." onclick="javascript:getDeleteChildDialog(' . $row["TaskID"] . ');"/>';
                    }
                }

                // Determine if this task has other tasks that were copied from it.
                //  If so, we cannot allow a delete.
                if ($row["AmountCopiedFromThisTask"]>0 || $row["HasChildren"] == 1){
                    // set as NO html for this button
                    $taskDeleteButtonHTML='';
                }

                // Determine what the user level is to setup the task row cell
                switch ($userRow["UserLevel"]) {
                    case 'MID-MANAGEMENT':
                        // Give the the delete option
                        $updateableTaskRowCellHTML = '
                                <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                    <table>
                                        <tr>
                                            <td>
                                            ' .
                                            $taskEditButtonHTML
                                            . '
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                ';

                        // determine if this is a user in the super company and Determine if this task is for a SU company
                        if ($userRow["CompanyID"] == 1 &&
                                $row["MainSubCompany"] == 1) {
                            // Give the the delete option
                            $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                            <table>
                                                <tr>
                                                    <td>
                                                    ' .
                                                    $taskDeleteButtonHTML
                                                    . '
                                                    </td>
                                                    <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                        ';
                        }

                        // Break out of this one
                        break;
                    case 'MANAGEMENT':
                    case 'EXECUTIVE':
                        // Determine if this task is user deletable
                        if ($row["UserDeletable"] && $userRow["CompanyID"] != 1) {
                            // Give the the delete option
                            $updateableTaskRowCellHTML = '
                                    <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                        <table>
                                            <tr>
                                                <td>
                                                ' .
                                                $taskDeleteButtonHTML
                                                . '
                                                </td>
                                                <td>
                                                ' .
                                                $taskEditButtonHTML
                                                . '
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                    ';
                        } else {
                            // Remove the delete option
                            $updateableTaskRowCellHTML = '
                                    <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                        <table>
                                            <tr>
                                                <td>
                                                ' .
                                                $taskEditButtonHTML
                                                . '
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                    ';
                        }

                        // determine if this is a user in the super company. 
                        // If so, then they can delete no matter what at this level.
                        if ($userRow["CompanyID"] == 1) {
                            // Determine if this is an exec
                            if ($userRow["UserLevel"] == "EXECUTIVE" ||
                                    ($userRow["UserLevel"] == "MANAGEMENT" && $row["MainSubCompany"] == 1)) {
                                // special update cell for super users at this level
                                $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                            <table>
                                                <tr>
                                                    <td>
                                                        ' .
                                                        $taskDeleteButtonHTML
                                                        . '
                                                    </td>
                                                    <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                        ';
                            } else {
                                // special update cell for super users at this level
                                $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                            <table>
                                                <tr>
                                                    <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                        ';
                            }
                        }

                        // Break out of this one
                        break;
                    case 'SU':
                        $updateableTaskRowCellHTML = '
                                <div class="cell updateCell ' . $rowExpedite . '" title="' . $expediteTitle . '">
                                    <table>
                                        <tr>
                                            <td>
                                                ' .
                                                $taskDeleteButtonHTML
                                                . '
                                            </td>
                                            <td>
                                            ' .
                                            $taskEditButtonHTML
                                            . '
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                ';

                        // Break out of this one
                        break;
                }

                // First check if we are completed or closed
                if ($row["Completed"] || $row["Closed"]) {
                    // Set a dull color
                    $color = '#BDBDBD';

                    // Determine if it is closed too in order to change a different color
                    if ($row["Closed"]) {
                        // Set a dull blue color
                        $color = '#8c8c8c';
                    }
                } else {
                    // Set it to the color of the row state 
                    $color = '#' . $row["StatusRowColor"];
                }

                // Determine if there is an Ideal Date
                $idealDate = "N/A";
                if ($row["IdealDate"] != null && $row["IdealDate"] != "") {
                    // Assign Ideal Date to it
                    $idealDate = $row["IdealDate"];
                }

                // Determine if this is a manual machining status
                $textColorHTML='';
                if ($row["StatusName"]=="Manual Machining"){
                    // Set the text to white
                    $textColorHTML='color:#FFFFFF;';
                }
                
                // Set the secondary status as a base 
                $secondaryStatusBackgroundColor = '';
                $secondaryStatusTitle = '';
                
                // Determine if this user is of the SU Company
                if ($userRow["CompanyID"] == 1){
                    // Determine if this is manual machining and of normal secondary status
                    $textSecondaryColor='';
                    if ($row["StatusName"]=="Manual Machining" && 
                        $row["SecondaryStatusID"]==-1){
                        // Set the text to black
                        $textSecondaryColorHTML='color:#000000;';
                    }
                    
                    // set them to be something
                    $secondaryStatusBackgroundColor = "background-color:" . $row["SSRowColor"] . ";" . $textSecondaryColorHTML;
                    $secondaryStatusTitle = 'Secondary Status: ' . $row["SSName"] . ' - ' . $row["SSDescription"];
                }

                // Add this option to the select
                $result = $result .
                        '<li id="subtask' . $row["SubPriority"] . '" class="ui-state-default Table" >
                            <div class="Row" style="background-color: '. $color . '; border-style: solid;  border-color: ' . $row["CompanyRowColor"] . ';" ondblclick="if (window.confirm(\'Adding a note on subtasks will refresh the parent task afterwards.  All unsaved data will go back to the previous state.\n\nAre you sure that you would like to do this?\')) {addStickyNoteDialog(' . $row["TaskID"] . ');}">
                                <div class="cell priCell" style="position:relative; ' . $textColorHTML . $secondaryStatusBackgroundColor .'" title="' . $secondaryStatusTitle . '" >
                                    ' . $stickyNoteHTML . '
                                    <p>' . $row["SubPriority"] . '</p>
                                </div>
                                <div class="cell" style="' . $textColorHTML . '">
                                    <p>' . $row["Title"] . '</p>
                                </div>
                                <div class="cell quantityCell" style="' . $textColorHTML . '">
                                    <p>' . $row["DeliverableQuantity"] . '</p>
                                </div>
                                <div class="cell childStatusCell" style="' . $textColorHTML . '">
                                    <p>' . $row["StatusName"] . '</p>
                                </div>
                                <div class="cell taskIDCell" style="' . $textColorHTML . '">
                                    <p>' . $row["TaskID"] . '</p>
                                </div>
                                <div class="cell dateCell" title="Ideal Date: ' . $idealDate . '" style="' . $textColorHTML . '">
                                    <p>' . $row["DueDate"] . '</p>
                                </div>' .
                                $updateableTaskRowCellHTML . '
                            </div>
                        </li>';

//                    $result = $result 
//                            . '    <tr>'
//                            . '        <td>' . $row["SubPriority"] . '</td>'
//                            . '        <td>' . $row["Title"] . '</td>'
//                            . '        <td>' . $row["StatusName"] . '</td>'
//                            . '        <td>' . $row["TaskID"] . '</td>'
//                            . '        <td>' . $row["DueDate"] . '</td>'
//                            . '        <td>' . $updateableTaskRowCellHTML . '</td>'
//                            . '    </tr>';
            }

            $result = $result . '</ul>';
//                $result = '<table width=%90>'
//                        . $result
//                        . '</table>';
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return whatever we got
    return $result;
}

function getVendorAsSelectOptions($db, $userRow, $selected, $onChangeHTML, $allFieldsAccess, $onFocusHTML="", $style=""){
   // Initialize the returnn
   $result = '';
   try {
       // Set disabled to be whatever was passed in
       $disableHTML=$allFieldsAccess;

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

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

       // If there is only one result for a username/password combo, then they are good to go.
       if ($rows == null){
           return $result;
       }
       else{
           // Setup the selected name to be nothing for now
           $selectedVendorName="None Chosen";

           while ($row=mysqli_fetch_array($rows)){
               // Determine if this is one that is to be selected
               $selectedText='';
               if ($selected != null && $selected==$row["VendorID"]) {
                   // Create the selected html
                   $selectedText='selected';

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

               // Add this option to the select
               $result=$result . '<option value="' . $row["VendorID"] . '" ' . $selectedText . '>' . $row["VendorName"] . '</option>';
           }
       }
       
        // 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="vendor" id="vendor" value="' . $selected . '"></input>
                     <input class="intext" name="vendorName" id="vendorName" type="text" style="' . $style . '" value="' . $selectedVendorName . '" ' . $allFieldsAccess . '><br><br>';
        }
        else {
            // Start the return with the beginning of the select
            $result='<select name="vendor" id="vendor" onchange="' . 
                    $onChangeHTML . '" onfocus="' . $onFocusHTML . '" ' . $disableHTML . ' style="' . $style . '"><option value="-1">' . 
                    'None Chosen</option>' . $result . '</select>';
        }
   } catch (Exception $ex) {
       // Assign the output string as to what happened
       return $result;
   }

   // Return whatever we got
   return $result;
}

function getLaborCategoryAsSelectOptions($db, $userRow, $inSelected, $which='ALL', $style='', $onchange=''){
    // Initialize the return
    $result = '';
    $selected=$inSelected;
    try {
        // Determine if this is an SU user
        if ($userRow["CompanyID"]==1){
            // Determine if they do not want all of them
            $whereClause='';
            if ($which=='Clocked In'){
                // Setup a where clause to include only clocked in
                $whereClause='WHERE IsOnTheClock=1 ';
            }
            else if ($which=='Clocked Out'){
                // Setup a where clause to include only clocked out
                $whereClause='WHERE IsOnTheClock=0 ';
            }
            
            // Create the query to run
            $sql='SELECT lc.* 
                  FROM laborcategories lc
                  ' .
                  $whereClause
                  . '
                  ORDER BY Name;';

            // Query the database for the labor categories
            $rows = $db->queryDB($sql, $userRow, "presentation Form occurance 8");

            // If there are rows, then they are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                // Determine if they want to have me get the standard work area
                if ($selected==null){
                    // Set the selected to whatever their standard is
                    $selected=$userRow["StandardLaborCategoryID"];
                }
                
                // Loop through the status rows
                $mainTitleDescription='';
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if this is one that is to be selected
                    $selectedText='';
                    if ($selected != null and $selected==$row["LaborCategoryID"]) {
                        // Create the selected html
                        $selectedText='selected';
                        
                        // Set the main title description
                        $mainTitleDescription=$row["Description"];
                    }

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

                // Start the return with the beginning of the select
                $result='<select title="' . $mainTitleDescription . '" name="laborCategory" id="laborCategory" style="' . $style . '" onchange="' . $onchange . '">' 
                            . $result . 
                        '</select>
                        ';
            }
        }
    } catch (Exception $ex) {
        // Assign the output string as to what happened
        return $result;
    }

    // Return whatever we got
    return $result;
}

function retrieveTaskStatusesAsList($db, $userRow, $taskID) {
    // Initialize the return
    $result = '<ul>
                <li class="Table">
                    <div class="Heading">
                        <div class="cell historyCurrentCell">
                            <p><b>Current</b></p>
                        </div>
                        <div class="cell historyStatusCell">
                            <p><b>Status</b></p>
                        </div>
                        <div class="cell historyUserCell">
                            <p><b>Starting User</b></p>
                        </div>
                        <div class="cell historyUserCell">
                            <p><b>Assigned To User</b></p>
                        </div>
                        <div class="cell historyDateCell">
                            <p><b>Start Time</b></p>
                        </div>
                        <div class="cell historyUserCell">
                            <p><b>End User</b></p>
                        </div>
                        <div class="cell historyDateCell">
                            <p><b>End Time</b></p>
                        </div>
                    </div>
                </li>';
    try {
        // Create a query to get the necessary information to display the task 
        // statuses that this task has gone through. Adjust times for server time.
        $sql='SELECT ts.*, ts.StartDate - INTERVAL 1 HOUR AS StartDateHere, ts.EndDate - INTERVAL 1 HOUR AS EndDateHere, ' . 
             'su.UserName AS StartingUser, eu.UserName AS EndingUser, IF(au.UserName IS NULL, "Unknown", au.UserName) AS AssignedToUser, s.StatusRowColor, s.Name AS StatusName ' . 
             'FROM taskstatus ts ' . 
             'LEFT JOIN users au ON ts.AssignedToUserID = au.UserID ' . 
             'LEFT JOIN users su ON ts.StartingUserID = su.UserID ' . 
             'LEFT JOIN users eu ON ts.CompletingUserID = eu.UserID ' . 
             'LEFT JOIN status s ON ts.StatusID = s.StatusID ' .
             'WHERE ts.TaskID=' . $taskID . ' ' .
             'ORDER BY ts.TaskStatusID ASC';
//echo '<script>alert("' . addslashes($sql) . '");</script>';

        // Query the original database query
        $rows = $db->queryDB($sql, $userRow, "presentation Form occurance 9");

        // 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
            while ($row = mysqli_fetch_array($rows)) {
                // Set it to the color of the row state 
                $color = '#' . $row["StatusRowColor"];

                // Determine if this is a manual machining status
                $textColorHTML='';
                if ($row["StatusName"]=="Manual Machining"){
                    // Set the text to white
                    $textColorHTML='color:#FFFFFF;';
                }
                
                // Set the current cell to no current for now
                $currentCellColor='background-color:#FF0000;';
                
                // Determine the color of the current cell
                if ($row["Current"]==1){
                    // Set the current color to green
                    $currentCellColor='background-color:#00FF00;';
                }
                
                // Add this option to the select
                $result = $result .
                        '<li class="ui-state-default Table" >
                            <div class="Row" style="background-color: '. $color . '; border-style: solid;" title="Comment: ' . $row["Comment"] . '">
                                <div class="cell historyCurrentCell" style="' . $currentCellColor . $textColorHTML . '">
                                    <p></p>
                                </div>
                                <div class="cell historyStatusCell" style="' . $textColorHTML . '">
                                    <p>' . $row["StatusName"] . '</p>
                                </div>
                                <div class="cell historyUserCell" style="' . $textColorHTML . '">
                                    <p>' . $row["StartingUser"] . '</p>
                                </div>
                                <div class="cell historyUserCell" style="' . $textColorHTML . '">
                                    <p>' . $row["AssignedToUser"] . '</p>
                                </div>
                                <div class="cell historyDateCell" style="' . $textColorHTML . '">
                                    <p>' . $row["StartDateHere"] . '</p>
                                </div>
                                <div class="cell historyUserCell" style="' . $textColorHTML . '">
                                    <p>' . $row["EndingUser"] . '</p>
                                </div>
                                <div class="cell historyDateCell" style="' . $textColorHTML . '">
                                    <p>' . $row["EndDateHere"] . '</p>
                                </div>
                            </div>
                        </li>';

            }

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

    // Return whatever we got
    return $result;
}

?>       
