<?php
    function getCompanyUnderTask($db, $userRow, $showWhatFinishedState, $typeID, $selectedCompany, $taskSearchPhrase, $selectedStatus, $parentsOnly=1){
        // Initialize the return
        $result = '';

        try {
            // Determine if we are dealing with an appropriate level SU employee
            if ($userRow["CompanyID"]==1 && 
                ($userRow["UserLevel"]=='SU' ||
                 $userRow["UserLevel"]=='EXECUTIVE' ||
                 $userRow["UserLevel"]=='MANAGEMENT' ||
                 $userRow["UserLevel"]=='MID-MANAGEMENT')
               ){
                // Init vars
                $selectedText = '';
                $foundOneInList = false;

                // Create the query to run
                $sql='';

                // Determine if there is a status that is selected
                $statusSQL='';
                if (is_numeric($selectedStatus) && $selectedStatus>0){
                    // Add a SQL delimiter for status
                    $statusSQL=' AND s.StatusID=' . $selectedStatus . ' ';
                }

                // Check to see what is default for seeing closed tasks
                $realShowWhatFinishedState=$showWhatFinishedState;
                $showOptionsSQL = '';
                if ($showWhatFinishedState==0){
                    // What are the user defaults
                    $realShowWhatFinishedState = $userRow["ShowWhatFinishedState"];
                }

                // Check to see what is set in the combo box for seeing completed tasks
                switch ($realShowWhatFinishedState){
                    case 6:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 AND t.Closed=1 ';

                        break;
                    case 5:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND (t.Completed=1 OR t.Closed=1) ';

                        break;
                    case 4:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Closed=1 ';

                        break;
                    case 3:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 ';

                        break;
                    case 2:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed<>1 AND t.Closed<>1 ';

                        break;
                    case 1:
                        // Set it to include completed tasks
                        $showOptionsSQL = '';

                        break;
                    default:
                }

                // Determine if we have a seacrch phrase
                $searchPhraseSQL = '';
                $searchFromSubtasks = '';
                if ($taskSearchPhrase!=null && trim($taskSearchPhrase)!=""){
                    // Convert in case special html chars
                    $convertedSearchPhrase = htmlspecialchars($taskSearchPhrase);

                    // Determine if we have a number
                    if (is_numeric($taskSearchPhrase)){
                        // Create a search phrase
                        $searchPhraseSQL=" and (t.Title LIKE '%" . $convertedSearchPhrase . "%' " .
                                               "OR t.TaskID = '" . $convertedSearchPhrase . "' " .
                                               "OR t.Entry LIKE '%" . $convertedSearchPhrase . "%')";
                    }
                    else {
                        // Make it lower case
                        $lowerCaseSearchPhrase = strtolower ($convertedSearchPhrase);

                        // Create a search phrase
                        $searchPhraseSQL=" and (LOWER(t.Title) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                               "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                               "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
                    }

                    $searchFromSubtasks = "OR t.TaskID IN (SELECT DISTINCT ParentID " .
                                                           "FROM status s, companies c, tasks t " . 
                                                           "WHERE s.StatusID = t.StatusID " .
                                                           "AND t.CompanyID=c.CompanyID " . 
                                                           "AND (s.name <> 'Stocked' OR c.Store=1) " . 
                                                           "AND t.CompanyID=c.CompanyID " . 
                                                           "AND t.TypeID=" . $typeID . " " .
                                                           $showOptionsSQL .
                                                           $searchPhraseSQL . ") ";    
                }
                
                
                // Determine if this is for parents only
                $parentSQL = '';
                if ($parentsOnly==1){
                    $parentSQL = ' AND t.ParentID = 0 ';
                }
                
                // Create the query to run
                $sql=
                    'SELECT DISTINCT c.CompanyID, c.CompanyName ' .
                    'FROM tasks t ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'WHERE s.StatusID = t.StatusID ' .
                       $parentSQL .
                       ' AND t.CompanyID=c.CompanyID ' .
                       'AND t.TypeID=' . $typeID . ' ' .
                       $showOptionsSQL .
                       $searchPhraseSQL . 
                       $searchFromSubtasks .
                       $statusSQL .
                       ' ORDER BY CompanyName;';

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

                // Determine if some rows were returned
                if ($rows == null){
                    return $result;
                }
                else{
                    // Loop through the returned results
                    while ($row=mysqli_fetch_array($rows)){
                        // Re-Init var
                        $selectedText = '';

                        // Determine if this is one selected
                        if ($selectedCompany == $row["CompanyID"]){
                            // Set the selected text to be all companies
                            $selectedText = 'selected';

                            // Set the variable
                            $foundOneInList = true;
                        }

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

                    // Create defaults
                    $allCompaniesDefaultSelect='<option value="-3">ALL Companies</option>';
                    $suCompaniesDefaultSelect='<option value="-2">SU Companies</option>';
                    $customerCompaniesDefaultSelect='<option value="-1">Customer Companies</option>';
                                    
                    // Determine if this is one selected
                    if (!$foundOneInList){
                        // Determine if it is the ALL companies or ALL Customers or SU companies
                        switch ($selectedCompany) {
                            case -3:
                                // set this as the default
                                $allCompaniesDefaultSelect='<option value="-3" selected>ALL Companies</option>';

                                break;
                            case -2:
                                // set this as the default
                                $suCompaniesDefaultSelect='<option value="-2" selected>SU Companies</option>';

                                break;
                            case -1:
                                // set this as the default
                                $customerCompaniesDefaultSelect='<option value="-1" selected>Customer Companies</option>';

                                break;
                            default:
                                break;
                        }
                    }

                    
                    
                    // Start the return with the beginning of the select
                    $result='<label for="companySelected">Company: </label>' . 
                            '<select name="companySelected" id="companySelected"  ' . 
                            'onchange="CreateAndGotoSearchOptions()" style="align:left;" ' .
                            'style="text-align:left;">' . $allCompaniesDefaultSelect . 
                            $suCompaniesDefaultSelect . $customerCompaniesDefaultSelect . 
                            $result . '</select>';
                }
            }
            else {
                // Create a hidden control with their company ID
                $result='<input type="hidden" name="companySelected" id="companySelected" value="' . ($userRow["CompanyID"]) . '"/>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getTaskStatusCombo($db, $userRow, $showWhatFinishedState, $typeID, $selectedCompany, $taskSearchPhrase, $selectedStatus, $parentsOnly=1){
        // Initialize the return
        $result = '';

        try {
            // Determine if we are dealing with an appropriate level SU employee
            if ($userRow["CompanyID"]==1 && 
                ($userRow["UserLevel"]=='SU' ||
                 $userRow["UserLevel"]=='EXECUTIVE' ||
                 $userRow["UserLevel"]=='MANAGEMENT' ||
                 $userRow["UserLevel"]=='MID-MANAGEMENT')
               ){
                // Init vars
                $selectedText = '';

                // Create the query to run
                $sql='';

                // Determine if the selected company is a singular company
                $selectedCompanySQL='';
                if (is_numeric($selectedCompany) && 
                    $selectedCompany > 0){
                    // Add the selected company SQL
                    $selectedCompanySQL = ' AND t.CompanyID=' . $selectedCompany . ' ';
                }
                else if (is_numeric($selectedCompany) && 
                         $selectedCompany < 0){
                    // Determine if it is the ALL companies or ALL Customers or SU companies
                    switch ($selectedCompany) {
                        case -2:
                            // Set it to bring up the SU and the SU's main companies
                            $selectedCompanySQL = ' AND (t.CompanyID=1 OR c.MainSubCompany=1) ';

                            break;
                        case -1:
                            // Set it to bring up everything BUT the SU and the SU's main companies
                            $selectedCompanySQL = ' AND t.CompanyID<>1 AND c.MainSubCompany<>1 ';

                            break;
                        default:
                            break;
                    }
                }

                // Check to see what is default for seeing closed tasks
                $realShowWhatFinishedState=$showWhatFinishedState;
                $showOptionsSQL = '';
                if ($showWhatFinishedState==0){
                    // What are the user defaults
                    $realShowWhatFinishedState = $userRow["ShowWhatFinishedState"];
                }

                // Check to see what is set in the combo box for seeing completed tasks
                switch ($realShowWhatFinishedState){
                    case 6:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 AND t.Closed=1 ';

                        break;
                    case 5:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND (t.Completed=1 OR t.Closed=1) ';

                        break;
                    case 4:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Closed=1 ';

                        break;
                    case 3:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 ';

                        break;
                    case 2:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed<>1 AND t.Closed<>1 ';

                        break;
                    case 1:
                        // Set it to include completed tasks
                        $showOptionsSQL = '';

                        break;
                    default:
                }

                // Determine if we have a search phrase
                $searchPhraseSQL = '';
                $searchFromSubtasks = '';
                if ($taskSearchPhrase!=null && trim($taskSearchPhrase)!=""){
                    // Convert in case special html chars
                    $convertedSearchPhrase = htmlspecialchars($taskSearchPhrase);

                    // Determine if we have a number
                    if (is_numeric($taskSearchPhrase)){
                        // Create a search phrase
                        $searchPhraseSQL=" and (t.Title LIKE '%" . $convertedSearchPhrase . "%' " .
                                               "OR t.TaskID = '" . $convertedSearchPhrase . "' " .
                                               "OR t.Entry LIKE '%" . $convertedSearchPhrase . "%')";
                    }
                    else {
                        // Make it lower case
                        $lowerCaseSearchPhrase = strtolower ($convertedSearchPhrase);

                        // Create a search phrase
                        $searchPhraseSQL=" and (LOWER(t.Title) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                               "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                               "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
                    }

                    $searchFromSubtasks = "OR t.TaskID IN (SELECT DISTINCT ParentID " .
                                                           "FROM status s, companies c, tasks t " . 
                                                           "WHERE s.StatusID = t.StatusID " .
                                                           "AND t.CompanyID=c.CompanyID " . 
                                                           "AND (s.name <> 'Stocked' OR c.Store=1) " . 
                                                           "AND t.CompanyID=c.CompanyID " . 
                                                           "AND t.TypeID=" . $typeID . " " .
                                                           $showOptionsSQL .
                                                           $searchPhraseSQL . ") ";    
                }
                
                // Determine if this is for parents only
                $parentSQL = '';
                if ($parentsOnly==1){
                    $parentSQL = ' AND t.ParentID = 0 ';
                }
                
                // Create the query to run
                $sql=
                    'SELECT DISTINCT s.StatusID, s.Name ' .
                    'FROM tasks t ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'WHERE s.StatusID = t.StatusID ' .
                       $parentSQL .
                       ' AND t.CompanyID=c.CompanyID ' .
                       'AND t.TypeID=' . $typeID . ' ' .
                       $selectedCompanySQL .
                       $showOptionsSQL .
                       $searchPhraseSQL . 
                       $searchFromSubtasks .
                       ' ORDER BY Name;';

//echo '<script>alert("' . addslashes($sql) . '");</script>';

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

                // Determine if some rows were returned
                if ($rows == null){
                    return $result;
                }
                else{
                    // Loop through the returned results
                    while ($row=mysqli_fetch_array($rows)){
                        // Re-Init var
                        $selectedText = '';

                        // Determine if this is one selected
                        if ($selectedStatus == $row["StatusID"]){
                            // Set the selected text to be all companies
                            $selectedText = 'selected';
                        }

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

                    // Create default
                    $allStatusesSelect='<option value="-1">ALL</option>';
                                    
                    // Start the return with the beginning of the select
                    $result='<label for="statusSelected">Status: </label>' . 
                            '<select name="statusSelected" id="statusSelected"  ' . 
                            'onchange="CreateAndGotoSearchOptions()" style="align:left;" ' .
                            'style="text-align:left;">' . $allStatusesSelect . 
                            $result . '</select>';
                }
            }
            else {
                // Create a hidden control with their company ID
                $result='<input type="hidden" name="statusSelected" id="statusSelected" value="' . ($userRow["CompanyID"]) . '"/>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getDelineations($db, $userRow, $showWhatFinishedState, $tasksPerPage, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus) {
        // Initialize the return
        $result = '';

//echo '<script>alert("' . addslashes($taskSearchPhrase) . '");</script>';
        try {
            // Determine if this is a SU company user or customer
            if ($userRow["CompanyID"]==1){
                // Start the return with the beginning of the select
                $result=
                    '
                    <div id="tabDiv" style="padding: 14px 0px 0px 14px; border: none;">
                        <button id="typeTabID1" class="btn" ' . ($typeTab==1?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=1; CreateAndGotoSearchOptions();">Machining</button>
                        <button id="typeTabID2" class="btn" ' . ($typeTab==2?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=2; CreateAndGotoSearchOptions();">Design</button>
                        <button id="typeTabID3" class="btn" ' . ($typeTab==3?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=3; CreateAndGotoSearchOptions();">Programming</button>
                        <button id="typeTabID4" class="btn" ' . ($typeTab==4?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=4; CreateAndGotoSearchOptions();">In-House</button>
                    </div>
                    <div style="text-align:center; margin: 8px;font-size: 90%; font-weight: normal; border: 1px solid darkgray; padding: 0px 7px 10px 7px;">
                        <br>
                        <table>
                            <tr>
                                <td colspan=3>
                                    <label for="searchPhrase">Search Phrase: </label>
                                    <input name="searchPhrase" id="searchPhrase" type="text" style="width: 70%;" value="' . htmlentities($taskSearchPhrase, ENT_QUOTES) . '">
                                    <input name="submitButton" id="submitButton" type="button" value="Search" title="Search the task for a phrase." onclick="CreateAndGotoSearchOptions()" style="text-align:right;"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan=1>
                                '
                                .
                                    getCompanyUnderTask($db, $userRow, $showWhatFinishedState, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus,1)
                                .
                                '
                                </td>
                                <td colspan=1 width="8%">
                                </td>
                                <td colspan=1>
                                '
                                .
                                    getShowNoShowCombo($showWhatFinishedState,true,'','align:right;')
                                .
                                '
                                </td>
                            </tr>
                            <tr>
                                <td colspan=1>
                                '
                                .
                                    getTaskStatusCombo($db, $userRow, $showWhatFinishedState, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus,1)
                                .
                                '
                                </td>
                                <td colspan=1 width="8%">
                                </td>
                                <td colspan=1>
                                '
                                .
                                    getTasksPerPageCombo($tasksPerPage)
                                .
                                '
                                </td>
                            </tr>
                        </table>
                        <input type="hidden" name="typeSelected" id="typeSelected" value="' . ($typeTab) . '"/>
                    </div>';
            }
            else {
                // Start the return with the beginning of the select
                $result=
                        '
                        <div id="tabDiv" style="padding: 14px 0px 0px 14px; border: none;">
                            <button id="typeTabID1" class="btn" ' . ($typeTab==1?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=1; CreateAndGotoSearchOptions();">Machining</button>
                            <button id="typeTabID2" class="btn" ' . ($typeTab==2?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=2; CreateAndGotoSearchOptions();">Design</button>
                            <button id="typeTabID3" class="btn" ' . ($typeTab==3?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=3; CreateAndGotoSearchOptions();">Programming</button>
                            <button id="typeTabID4" class="btn" ' . ($typeTab==4?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=4; CreateAndGotoSearchOptions();">In-House</button>
                        </div>
                        <div style="text-align:center; margin: 8px;font-size: 90%; font-weight: normal; border: 1px solid darkgray; padding: 0px 7px 10px 7px;">
                            <br>
                            <table>
                                <tr>
                                    <td colspan=2>
                                        <label for="searchPhrase">Search Phrase: </label>
                                        <input name="searchPhrase" id="searchPhrase" type="text" style="width: 70%;" value="' . htmlentities($taskSearchPhrase, ENT_QUOTES) . '">
                                    </td>
                                    <td colspan=1>
                                        <input name="submitButton" id="submitButton" type="button" value="Search" title="Search the task for a phrase." onclick="CreateAndGotoSearchOptions()" style="text-align:right;"/>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan=1>
                                    '
                                    .
                                        getShowNoShowCombo($showWhatFinishedState,true,'','align:right;')
                                    .
                                    '
                                    </td>
                                    <td colspan=1 width="8%">
                                    </td>
                                    <td colspan=1>
                                    '
                                    .
                                        getTasksPerPageCombo($tasksPerPage)
                                    .
                                    '
                                    </td>
                                    </td>
                                </tr>
                            </table>
                            <input type="hidden" name="typeSelected" id="typeSelected" value="' . ($typeTab) . '"/>
                            <input type="hidden" name="companySelected" id="companySelected" value="' . $userRow["CompanyID"] . '"/>
                            '
                            .
                                getTaskStatusCombo($db, $userRow, $showWhatFinishedState, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus,1)
                            .
                            '
                        </div>';
            }
                
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function retrieveParentTasksAsList($db, $userRow, $selectedType, $showWhatFinishedState, $tasksPerPage, $currentPage, $selectedCompany, $taskSearchPhrase, $sortNumber, $selectedStatus){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableTaskRowCellHTML = '';
        $companyTitleRowCellHTML = '';
        $searchPhraseSQL = '';
        $searchFromSubtasks = '';
        
        $sortSQL = 'CASE WHEN IdealDate IS NULL THEN 1 ELSE 0 END, IdealDate, ' .
                   'CASE WHEN DueDate IS NULL THEN 1 ELSE 0 END, DueDate, TaskID';

        if ($sortNumber!=""){
            // Determine which sort the person wants
            switch ($sortNumber) {
                case 1:
                    // Sort as priority the most high
                    $sortSQL = "Priority, " . $sortSQL;

                    break;
                case 5:
                    // Sort as title the most high
                    $sortSQL = "Title, " . $sortSQL;

                    break;
                case 10:
                    // Sort as status by flow the most high
                    $sortSQL = "ProcessOrder, " . $sortSQL;

                    break;
                case 15:
                    // Sort as task ID the most high
                    $sortSQL = "TaskID DESC, " . $sortSQL;

                    break;
                case 20:
                    // Sort as Due date the most high
                    $sortSQL = 'CASE WHEN DueDate IS NULL THEN 1 ELSE 0 END, DueDate, ' .
                               'CASE WHEN IdealDate IS NULL THEN 1 ELSE 0 END, IdealDate, TaskID';

                    break;
                case 25:
                    // Sort as Company name the most high
                    $sortSQL = "CompanyName, " . $sortSQL;

                    break;
                default:
                    break;
            }
        }

        // Determine if there is a status that is selected
        $selectedStatusSQL='';
        if (is_numeric($selectedStatus) && $selectedStatus>0){
            // Add a SQL delimiter for status
            $selectedStatusSQL=' AND s.StatusID=' . $selectedStatus . ' ';
        }

        // Determine if this is a user of the SU company so I can set the selected company
        $selectedCompanySQL = '';
        if ($userRow["CompanyID"]==1){
            // Determine if the selected company is a singular company
            if ($selectedCompany != null && 
                $selectedCompany > 0){
                // Add the selected company SQL
                $selectedCompanySQL = 'AND t.CompanyID=' . $selectedCompany . ' ';
            }
            else if ($selectedCompany != null && 
                     $selectedCompany < 0){
                // Determine if it is the ALL companies or ALL Customers or SU companies
                switch ($selectedCompany) {
                    case -2:
                        // Set it to bring up the SU and the SU's main companies
                        $selectedCompanySQL = 'AND (t.CompanyID=1 OR c.MainSubCompany=1) ';

                        break;
                    case -1:
                        // Set it to bring up everything BUT the SU and the SU's main companies
                        $selectedCompanySQL = 'AND t.CompanyID<>1 AND c.MainSubCompany<>1 ';

                        break;
                    default:
                        break;
                }
            }
        }
        else {
            // Set the selected company as the user's company
            $selectedCompanySQL = 'AND t.CompanyID=' . $userRow["CompanyID"] . ' ';
        }

        // Check to see what is default for seeing closed tasks
        $realShowWhatFinishedState=$showWhatFinishedState;
        $showOptionsSQL = '';
        if ($showWhatFinishedState==0){
            // What are the user defaults
            $realShowWhatFinishedState = $userRow["ShowWhatFinishedState"];
        }

        // Check to see what is set in the combo box for seeing completed tasks
        switch ($realShowWhatFinishedState){
            case 6:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 AND t.Closed=1 ';

                break;
            case 5:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND (t.Completed=1 OR t.Closed=1) ';

                break;
            case 4:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Closed=1 ';

                break;
            case 3:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 ';

                break;
            case 2:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Completed<>1 AND t.Closed<>1 ';

                break;
            case 1:
                // Set it to include completed tasks
                $showOptionsSQL = '';

                break;
            default:
        }

        // Determine if there is a search term
        if (trim($taskSearchPhrase)!=""){
            // Convert in case special html chars
            $convertedSearchPhrase = htmlspecialchars($taskSearchPhrase);
            
            // Determine if we have a number
            if (is_numeric($taskSearchPhrase)){
                // Create a search phrase
                $searchPhraseSQL=" and (t.Title LIKE '%" . $convertedSearchPhrase . "%' " .
                                       "OR t.TaskID = '" . $convertedSearchPhrase . "' " .
                                       "OR t.Entry LIKE '%" . $convertedSearchPhrase . "%')";
            }
            else {
                // Make it lower case
                $lowerCaseSearchPhrase = strtolower ($convertedSearchPhrase);

                // Create a search phrase
                $searchPhraseSQL=" and (LOWER(t.Title) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                       "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                       "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
            }
            
            $searchFromSubtasks = 'OR t.TaskID IN (SELECT DISTINCT ParentID ' .
                                                  'FROM status s, companies c, tasks t ' .
                                                  'WHERE s.StatusID = t.StatusID ' .
                                                  'AND t.CompanyID=c.CompanyID ' .
                                                  'AND (s.name <> "Stocked" OR c.Store=1) ' . 
                                                  'AND t.CompanyID=c.CompanyID ' .  
                                                  $selectedCompanySQL .
                                                  $selectedStatusSQL .
                                                  'AND t.TypeID=' . $selectedType . ' ' .
                                                  $showOptionsSQL .
                                                  $searchPhraseSQL . ') ';   
        }

        // determine if this is a user in the super company. The company 
        // with it's ID as '1' in the TMS is the Super Company.
        if ($userRow["CompanyID"]==1){
            $companyTitleRowCellHTML = '
                        <div class="cell companyCell" onclick="document.getElementById(\'sortNumber\').value=25; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                            <p><b>Company</b></p>
                        </div>
                ';
        }

        // 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 = 
            '
             <input type="hidden" id="sortNumber" name="sortNumber" value="' . $sortNumber . '"/>
             <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell priCell" onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>#</b></p>
                    </div>
                    <div class="cell titleCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Title</b></p>
                    </div>
                    <div class="cell statusCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Status</b></p>
                    </div>
                    <div class="cell taskIDCell" onclick="document.getElementById(\'sortNumber\').value=15; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Task ID</b></p>
                    </div>
                    <div class="cell dateCell" onclick="document.getElementById(\'sortNumber\').value=20; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Due Date</b></p>
                    </div>' . 
                    $companyTitleRowCellHTML . 
                    $updateableTitleRowCellHTML . '
                </div>
            </li>';

        try {
            // Determine if they are set to user preferences
            $realTasksPerPage=$tasksPerPage;
            if ($tasksPerPage==0){
                // Set it to the real user's preferences
                $realTasksPerPage=$userRow["TasksPerPage"];
            }
            
            // Create the offset we are looking at currently
            $offset=(($currentPage-1)*$realTasksPerPage);
            
            // Setup the query to be where they only get users in their company
            // and tasks that are NOT in stocked status
            $sql=   'SELECT (SELECT MAX(LastUpdated) FROM tasks WHERE CompanyID=' . $userRow["CompanyID"] . ') as LastOneUpdated, ' . 
                        's.ProcessOrder as ProcessOrder, s.Name AS StatusName, s.StatusRowColor, ' . 
                        'c.CompanyName AS CompanyName, c.CompanyRowColor, c.MainSubCompany, ' . 
                        'c.Store, t.Priority, t.Title, t.Entry, t.IdealDate, t.DueDate, t.Completed, t.Expedite, ' . 
                        't.Closed, t.TaskID, t.UserDeletable, t.ParentID, t.HasChildren, usvl.ViewCategory ' .
                    'FROM tasks t ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
                    'WHERE s.StatusID = t.StatusID' .
                       ' AND (usvl.ViewCategory IS NULL OR t.UserID=' . $userRow["UserID"] . ')' .
                       ' AND t.ParentID = 0 ' .
                       ' AND t.CompanyID=c.CompanyID ' .
                       ' AND (s.name <> "Stocked" OR c.Store=1) ' .
                       ' AND t.CompanyID=' . $userRow["CompanyID"] . 
                       ' AND t.TypeID=' . $selectedType . ' ' .
                       $showOptionsSQL .
                       $searchPhraseSQL . 
                       $searchFromSubtasks .
                    'ORDER BY ' . $sortSQL . ' ' .
                    'LIMIT ' . $offset . ', ' . $realTasksPerPage . ';';
            
            $countsql=
                    'SELECT COUNT(*) AS TheCount ' .
                    'FROM tasks t ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
                    'WHERE s.StatusID = t.StatusID' .
                       ' AND (usvl.ViewCategory IS NULL OR t.UserID=' . $userRow["UserID"] . ')' .
                       ' AND t.ParentID = 0 ' .
                       ' AND t.CompanyID=c.CompanyID ' .
                       ' AND (s.name <> "Stocked" OR c.Store=1) ' .
                       ' AND t.CompanyID=' . $userRow["CompanyID"] . 
                       ' AND t.TypeID=' . $selectedType . ' ' .
                       $showOptionsSQL .
                       $searchPhraseSQL . 
                       $searchFromSubtasks . ';';
            
            // determine if this is a user in the super company. The company 
            // with it's ID as '1' in the TMS is the Super Company.
            if ($userRow["CompanyID"]==1){
                // Create the query to run
                $sql=
                    'SELECT (SELECT MAX(LastUpdated) FROM tasks) as LastOneUpdated, ' . 
                           's.ProcessOrder as ProcessOrder, s.Name AS StatusName, s.StatusRowColor, c.CompanyName AS CompanyName, ' . 
                           'c.CompanyRowColor, c.MainSubCompany, c.Store, t.Priority, t.Title, t.Entry, t.IdealDate, ' . 
                           't.DueDate, t.Completed, t.Closed, t.TaskID, t.UserDeletable, t.ParentID, t.HasChildren, t.Expedite, ' .
                           'ss.RowColor AS SSRowColor, ss.Description AS SSDescription, ss.Name AS SSName, 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 (usvl.ViewCategory IS NULL OR t.UserID=' . $userRow["UserID"] . ')' .
                       ' AND t.ParentID = 0 ' .
                       ' AND t.CompanyID=c.CompanyID ' .
                       $selectedCompanySQL .
                       $selectedStatusSQL .
                       'AND t.TypeID=' . $selectedType . ' ' .
                       $showOptionsSQL .
                       $searchPhraseSQL . 
                       $searchFromSubtasks .
                    'ORDER BY ' . $sortSQL . ', ' .
                              'CASE WHEN IdealDate IS NULL THEN 1 ELSE 0 END, IdealDate, ' .
                              'CASE WHEN DueDate IS NULL THEN 1 ELSE 0 END, DueDate, TaskID, ParentID ' .
                    'LIMIT ' . $offset . ', ' . $realTasksPerPage . ';';
                
//echo '<script>alert("' . addslashes($sql) . '");</script>';
                $countsql=
                    'SELECT COUNT(*) AS TheCount ' .
                    'FROM tasks t ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'LEFT JOIN (SELECT * FROM usertostatusviewinglinker WHERE UserID=' . $userRow["UserID"] . ') usvl ON t.StatusID = usvl.StatusID ' .
                    'WHERE s.StatusID = t.StatusID ' .
                       ' AND (usvl.ViewCategory IS NULL OR t.UserID=' . $userRow["UserID"] . ')' .
                       ' AND t.ParentID = 0 ' .
                       ' AND t.CompanyID=c.CompanyID ' .
                       $selectedCompanySQL .
                       $selectedStatusSQL .
                       'AND t.TypeID=' . $selectedType . ' ' .
                       $showOptionsSQL .
                       $searchPhraseSQL . 
                       $searchFromSubtasks . ';';
            }

//echo '<script>alert("' . addslashes($sql) . '");</script>';
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "tasks_presentation Form occurance 3");

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

                 // Query the database for the count of the actual tasks 
                 $maxRowsQuery = $db->queryDB($countsql, $userRow, "tasks_presentation Form occurance 4");
            
                 // Determine if we have one row to look at
                 $numberOfRows=0;
                 if ($maxRowsQuery){
                     // Get the Row returned
                     $maxRowsAssoc = $maxRowsQuery->fetch_assoc();
            
                     // Get the number of rows that would have happened without the limit
                     $numberOfRows = $maxRowsAssoc["TheCount"]; 
                }
               
                // Loop through the returned results
                $amount=0;
                $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, "tasks_presentation Form occurance 4");

                    // Init some count variables
                    $notesToOthersFromMe=0;
                    $notesToMeFromOthers=0;
                    $stickyNoteHTML='';
                    $notesNumeric='';
                    $notesTextual='';
                    
                    // 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++;
                        }
                    }
                    
                    // 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 tasks t
                            LEFT JOIN notes n ON t.TaskID = n.AssociatedCategoryID
                            WHERE t.ParentID=' . $row["TaskID"] . '
                            AND n.Category=\'TASK\' 
                            AND n.IsSticky=1;';
                    
                    // Query the database for the the note count 
                    $stickyNoteChildRows = $db->queryDB($sql, $userRow, "tasks_presentation Form occurance 5");

                    // Init some count variables
                    $childNotesToOthersFromMe=0;
                    $childNotesToMeFromOthers=0;
                    $childNotesNumeric='';
                    $childNotesTextual='';
                    
                    // Loop through the returned results
                    while ($stickyNoteChildRow=mysqli_fetch_array($stickyNoteChildRows)){
                        // Determine if this sticky note should be counted because this
                        // person made the note and needs to keep track of who read it
                        if ($stickyNoteChildRow["EnteredByID"]==$userRow["UserID"] &&
                            $stickyNoteChildRow["AmountNotReadByEveryone"]>0){
                            // Increment the count of child notes I made that have not been read by everyone
                            $childNotesToOthersFromMe++;
                        }
                        
                        // Make this separate to count the ones I made that I want myself to reread
                        if ($stickyNoteChildRow["AmountNotReadByMe"]>0){
                            // Increment the count of child notes I made that have not been read by everyone
                            $childNotesToMeFromOthers++;
                        }
                    }
                    
                    // Determine if there are notes to show them
                    if ($notesToOthersFromMe>0 || $notesToMeFromOthers>0 || $childNotesToOthersFromMe || $childNotesToMeFromOthers){
                        // Determine if we have any parent sticky notes
                        $onClickSticky='alert(\'There are no main task sticky notes that needs attention. In order to see the sub-task sticky notes you should first click into the parent and see them from there on in the sub-task sticky notes tab.\');';
                        if ($notesToOthersFromMe>0 || $notesToMeFromOthers>0){
                            // Add the ability to see the sticky notes of the parent
                            $onClickSticky='popUp=popupWindow(\'view_sticky_notes.php?acid=' . $row["TaskID"] . '&c=TASK\', \'_blank\', window.parent, 700, 500);';

                            // Create the informational bit
                            $notesNumeric='<div style="position: absolute; top: 18%; left: 25%; transform:rotate(15deg);"><b><font style="color:red;">' . $notesToMeFromOthers . '</font><font style="color:black;">(</font><font style="color:green;">' . $notesToOthersFromMe . '</font><font style="color:black;">)</font></b></div>';
                            $notesTextual='There are ' . $notesToMeFromOthers . ' notes to you that you have not read, ' . $notesToOthersFromMe . ' notes that you wrote that have not been read by all recipients.';
                        }

                        // Determine if there are any children
                        if ($childNotesToOthersFromMe>0 || $childNotesToMeFromOthers>0){
                            // Create the informational bit
                            $childNotesNumeric='<div style="position: absolute; top: 46%; left: 16%; transform:rotate(15deg);"><b><font style="color:DodgerBlue;">' . $childNotesToMeFromOthers . '</font><font style="color:black;">(</font><font style="color:Orange;">' . $childNotesToOthersFromMe . '</font><font style="color:black;">)</font></b></div>';
                            $childNotesTextual='There are ' . $childNotesToMeFromOthers . ' notes on sub-tasks that you have not read and ' . $childNotesToOthersFromMe . ' notes on sub-tasks that you wrote that have not been read by all recipients.';
                        }

                        $stickyNoteHTML=
                                '<div style="position: absolute; top: 10%; left:-85%;" onclick="' . $onClickSticky . '" 
                                                                                       onmouseover="document.body.style.cursor = \'pointer\';" 
                                                                                       onmouseout="document.body.style.cursor = \'default\';"
                                                                                       title="' . $notesTextual . ' ' . $childNotesTextual . '">
                                    <img src="images/post_it.png" alt="Sticky Notes" style="height:35px; transform:rotate(15deg);">
                                    ' . $notesNumeric . '
                                    ' . $childNotesNumeric . '
                                 </div>';
                    }
                    
                    // Create the visualized task orientation as though this IS the parent
                    $firstFour = str_pad($row["TaskID"],4,"0",STR_PAD_LEFT);
                    $lastFour = '0000';

                    // Determine if this is a parent or a child so we can make all of the status changes to the children as well.
                    if ($row["ParentID"] != 0){
                        // Create the visualized task orientation as though this IS the parent
                        $firstFour = str_pad($row["ParentID"],4,"0",STR_PAD_LEFT);
                        $lastFour = str_pad($row["TaskID"],4,"0",STR_PAD_LEFT);
                    }

                    // 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=' . $selectedCompany . '&ts=' . $selectedType . '\';"/>';

                    // 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 task?\')) {DeleteTaskAndReturn(' . $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='';
                    }

                    // Set the last one updated to that value.  Should be the same for every row
                    $lastOneUpdated = $row["LastOneUpdated"];
                    $companyTaskRowCellHTML = '';
                    $updateableTaskRowCellHTML = '';

                    // determine if this is a user in the super company and color the company cell.
                    if ($userRow["CompanyID"]==1){
                        // Set the color of the company cell to the appropriate company's color
                        $companyTaskRowCellHTML = '
                            <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';"/>';
                    }
                    
                    // Determine if this task has children
                    $childCheckboxHTML = '';
                    $children = '';
                    $parentBorderColor = '';
                    if ($row["HasChildren"] == 1){
                        // Get the children
                        $children = retrieveChildTasksAsList($db, $userRow, $row["TaskID"], false, $selectedCompany, $selectedType);
                        
                        // Make the children
                        $childCheckboxHTML = '<table>
                                                <tr>
                                                  <td style="text-align: center; vertical-align: middle;" colspan=2>
                                                      <label style="font-size:10px; font-weight: bold; color:LimeGreen;">Children</label>
                                                      <input class="notinput" name="hideChildren' . $row["TaskID"] . '" id="hideChildren' . $row["TaskID"] . '" type="checkbox" class="hideChildren" onclick="javascript:div_toggleVisibilityOnCheckbox(\'hideChildren' . $row["TaskID"] . '\',\'childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '\', \'NORMAL\');"/>
                                                  </td>
                                                </tr>
                                              </table>';
                        
                        // TODO: Remove for real
                        $childCheckboxHTML = '<tr>
                                                  <td style="text-align: center; vertical-align: middle;" colspan=2>
                                                      <label style="font-size:10px; font-weight: bold; color:Black;">Has SubTasks</label>
                                                  </td>
                                              </tr>';
                        
                        $parentBorderColor = 'style="border-color: limegreen;"';
                    }

                    // 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">
                                    <table>
                                        <tr>
                                            <td>
                                            ' .
                                            $taskEditButtonHTML
                                            . '
                                            </td>
                                        </tr>
                                    </table>' .
                                    $childCheckboxHTML . '
                                </div>
                                ';
                            
                            // determine if this is a user in the super company. 
                            // If so, then they can see the company column.
                            if ($userRow["CompanyID"]==1){
                                // Show company column
                                $companyTaskRowCellHTML = '
                                    <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                            <p>' . $row["CompanyName"] . '</p>
                                    </div>
                                    ';
                                
                                // Determine if this task is a SU company and the user is also of the same company
                                if ($row["MainSubCompany"]==1){
                                    // Give the the delete option
                                    $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell">
                                            <table>
                                                <tr>
                                                    <td>
                                                        ' .
                                                        $taskDeleteButtonHTML
                                                        . '
                                                    </td>
                                                    <td>
                                                        ' .
                                                        $taskEditButtonHTML
                                                        . '
                                                    </td>
                                                </tr>
                                            </table>' .
                                            $childCheckboxHTML . '
                                        </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">
                                        <table>
                                            <tr>
                                                <td>
                                                    ' .
                                                    $taskDeleteButtonHTML
                                                    . '
                                                </td>
                                                <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                </td>
                                            </tr>
                                        </table>' .
                                        $childCheckboxHTML . '
                                    </div>
                                    ';
                            }
                            else {
                                // Remove the delete option
                                $updateableTaskRowCellHTML = '
                                    <div class="cell updateCell">
                                        <table>
                                            <tr>
                                                <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                </td>
                                            </tr>
                                        </table>' .
                                        $childCheckboxHTML . '
                                    </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){
                                // These user of the super company can see the company name
                                $companyTaskRowCellHTML = '
                                    <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                        <p>' . $row["CompanyName"] . '</p>
                                    </div>
                                    ';

                                // 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">
                                            <table>
                                                <tr>
                                                    <td>
                                                            ' .
                                                            $taskDeleteButtonHTML
                                                            . '
                                                        </td>
                                                    <td>
                                                        ' .
                                                        $taskEditButtonHTML
                                                        . '
                                                    </td>
                                                </tr>
                                            </table>' .
                                            $childCheckboxHTML . '
                                        </div>
                                        ';
                                }
                                else{
                                    // special update cell for super users at this level
                                    $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell">
                                            <table>
                                                <tr>
                                                    <td>
                                                        ' .
                                                        $taskEditButtonHTML
                                                        . '
                                                    </td>
                                                </tr>
                                            </table>' .
                                            $childCheckboxHTML . '
                                        </div>
                                        ';
                                }
                            }

                            // Break out of this one
                            break;
                        case 'SU':
                            $companyTaskRowCellHTML = '
                                <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                    <p>' . $row["CompanyName"] . '</p>
                                </div>
                                ';
                            $updateableTaskRowCellHTML = '
                                <div class="cell updateCell">
                                    <table>
                                        <tr>
                                            <td>
                                                ' .
                                                $taskDeleteButtonHTML
                                                . '
                                            </td>
                                            <td>
                                                ' .
                                                $taskEditButtonHTML
                                                . '
                                            </td>
                                        </tr>
                                    </table>' .
                                    $childCheckboxHTML . '
                                </div>
                                ';

                            // Break out of this one
                            break;
                    }

                    // Increment the row
                    $amount++;

                    // Assume that the row is disabled
                    $rowStatus = 'ui-state-disabled';
                    
                    // Determine if the very specific case is true to allow for drag and drop priority change
                    if ($taskSearchPhrase=="" &&
                        $sortNumber == 1 && 
                        $selectedCompany > 0 &&
                        $selectedStatus==-1 &&
                        $numberOfRows<=$realTasksPerPage){
                        // Set row to not be moveable
                        $rowStatus = '';
                    }

                    // First check if we are completed or closed
                    if ($row["Completed"] || $row["Closed"]){
                        // Set row to not be moveable
                        $rowStatus = 'ui-state-disabled ';

                        // 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
                            $textSecondaryColor='color:#000000;';
                        }

                        // set them to be something
                        $secondaryStatusBackgroundColor = "background-color:" . $row["SSRowColor"] . ";" . $textSecondaryColor;
                        $secondaryStatusTitle = 'Secondary Status: ' . $row["SSName"] . ' - ' . $row["SSDescription"];
                    }

                    // Add this option to the select
                    $result = $result .
                        '<li id="' . $row["Priority"] . '" name="' . $row["Priority"] . '" class="ui-state-default ' . $rowStatus . ' Table ' . $rowExpedite . '" title="' . $expediteTitle . '" ' . $parentBorderColor . '>
                            <div name="test" title="' . $secondaryStatusTitle . '" class="Row" style="background-color: '. $color . '; border-style: solid; Height: 40px;" ondblclick="addStickyNoteDialog(' . $row["TaskID"] . ');">
                                <div class="cell priCell" style="position:relative; ' . $secondaryStatusBackgroundColor .'">
                                    ' . $stickyNoteHTML . '
                                    <p>' . (($row["Priority"]==99999) ? '-':$row["Priority"]) . '</p>
                                </div>
                                <div class="cell" style="' . $textColorHTML . '">
                                    <p>' . $row["Title"] . '</p>
                                </div>
                                <div class="cell statusCell" style="' . $textColorHTML . '">
                                    <p>' . $row["StatusName"] . '</p>
                                </div>
                                <div class="cell taskIDCell" style="' . $textColorHTML . '">
                                    <p>' . $firstFour . '-' . $lastFour . '</p>
                                </div>
                                <div class="cell dateCell" title="Ideal Date: ' . $idealDate . '" style="' . $textColorHTML . '">
                                    <p>' . $row["DueDate"] . '</p>
                                </div>' . 
                                $companyTaskRowCellHTML . 
                                $updateableTaskRowCellHTML . '
                            </div>
                        <div class="childrenDiv Row" name="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" id="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" style="display: none; ">
                            <div class="cell">
                                <span>' . $children . '</span>
                        </div>
                        </div>
                        </li>';
//                        <div name="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" id="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" class="childrenDiv" style="display: none; ">
//                            ' . $children . '
//                        </div>';
                }

               // Determine if there are more than the tasks that they have asked for per page
               $pageSelector='';
               
               if ($numberOfRows>$realTasksPerPage){
                   // Initialize the loop counter
                   $loopPageNumber = 0;
                   
                   // Create a back link and forward link
                   $backLink = '';
                   $forwardLink = '';
                   $firstPageLink = '';
                   $lastPageLink = '';
                   
                   do {
                        // Increment the loop counter
                        $loopPageNumber++;

                        // Only putting the extra links if we have more than 7 pages
                        if ($numberOfRows/$realTasksPerPage > 7){
                            // Determine if we are NOT on the first page
                            if ($currentPage>1){
                                // setup the back link to go back to the previous page 
                                $backLink = '<a href="tasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                            '&sn=' . $sortNumber . '&cp=' . ($currentPage-1) . '"> < </a>&nbsp;&nbsp;';
                            }

                            // Determine if we are NOT on the last page
                            if ($currentPage != $loopPageNumber){
                                // setup the back link to go forward to the next page 
                                $forwardLink = '<a href="tasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                               '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                               '&sn=' . $sortNumber . '&cp=' . ($currentPage+1) . '"> > </a>&nbsp;&nbsp;';
                            }
                            else{
                                // Reset the forward link
                                $forwardLink='';
                            }
                        }
                        
                        
                        // Determine if the selected this is the selected page
                        $selectedStyling='';
                        if ($loopPageNumber==$currentPage){
                            // Bold it
                            $selectedStyling='color: white; background-color:#0073e6;';
                        }
                       

                        // Determine if this is within +/- 3 of the current row
                        if ($loopPageNumber>($currentPage-3) && $loopPageNumber<=($currentPage+3) ){
                            // Add the link
                            $pageSelector = $pageSelector . '<a href="tasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                            '&sn=' . $sortNumber . '&cp=' . $loopPageNumber . '" style="' . $selectedStyling . 
                                            '"> ' . $loopPageNumber . ' </a>&nbsp;&nbsp;';
                        }
                        else {
                            if ($loopPageNumber<($currentPage-2)){
                                // setup the first page link
                                $firstPageLink = '<a href="tasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                            '&sn=' . $sortNumber . '&cp=1"> 1 </a>&nbsp;&nbsp;...&nbsp;&nbsp;';
                            }
                            
                            if ($loopPageNumber>($currentPage+3)){
                                // setup the last page link
                                $lastPageLink = '...&nbsp;&nbsp;<a href="tasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                                '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                                '&sn=' . $sortNumber . '&cp=' . $loopPageNumber . '"> ' . $loopPageNumber . 
                                                ' </a>&nbsp;&nbsp;';
                            }
                            
                        }
                   }while(1 < $numberOfRows/($loopPageNumber*$realTasksPerPage));
                   
                   $pageSelector = '<div style="text-align:center; font-size: 90%; border: 1px solid darkgray; padding: 2px 2px 2px 2px;">
                                   ' . $backLink . $firstPageLink . $pageSelector . $lastPageLink . $forwardLink . '
                                   </div>';

               }
                
                // Add the closest date to the result
                $result = $pageSelector . $result . 
                          '<input type="hidden" id="LastOneUpdated" name="LastOneUpdated" value="' . $lastOneUpdated . '"/> ' .
                          $pageSelector;
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getEmployeesUnderCompany($db, $userRow, $showWhatFinishedState, $typeID, $selectedCompany=-1, $selectedStatus=-1, $assignedTo=-1){
        // Initialize the return
        $result = '';

        try {
            // Determine if we are dealing with an appropriate level SU employee
            if ($userRow["CompanyID"]==1 && 
                ($userRow["UserLevel"]=='SU' ||
                 $userRow["UserLevel"]=='EXECUTIVE' ||
                 $userRow["UserLevel"]=='MANAGEMENT' ||
                 $userRow["UserLevel"]=='MID-MANAGEMENT')
               ){
                // Init vars
                $selectedText = '';
                $foundOneInList = false;

                // Create the query to run
                $sql='';

                // Determine if there is a status that is selected
                $statusSQL='';
                if (is_numeric($selectedStatus) && $selectedStatus>0){
                    // Add a SQL delimiter for status
                    $statusSQL=' AND s.StatusID=' . $selectedStatus . ' ';
                }

                // Check to see what is default for seeing closed tasks
                $realShowWhatFinishedState=$showWhatFinishedState;
                $showOptionsSQL = '';
                if ($showWhatFinishedState==0){
                    // What are the user defaults
                    $realShowWhatFinishedState = $userRow["ShowWhatFinishedState"];
                }

                // Check to see what is set in the combo box for seeing completed tasks
                switch ($realShowWhatFinishedState){
                    case 6:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 AND t.Closed=1 ';

                        break;
                    case 5:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND (t.Completed=1 OR t.Closed=1) ';

                        break;
                    case 4:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Closed=1 ';

                        break;
                    case 3:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 ';

                        break;
                    case 2:
                        // Set it to include completed tasks
                        $showOptionsSQL = $showOptionsSQL . ' AND t.Completed<>1 AND t.Closed<>1 ';

                        break;
                    case 1:
                        // Set it to include completed tasks
                        $showOptionsSQL = '';

                        break;
                    default:
                }

                // Set the standard for selected company to be SU company with any task
                $suUserSQL = '';

                // Determine if the choice is not a specific user
                $allSUUsersSelectedText='selected';
                $allUsersSelectedText='';
                if ($assignedTo>=-1){
                    // Only look for users of the SU company
                    $suUserSQL = ' AND u.CompanyID=1 ';
                }
                else if ($assignedTo==-2){
                    // Change them around
                    $allSUUsersSelectedText='';
                    $allUsersSelectedText='selected';
                }
                
                // Determine if a specific company has been chosen
                $specificCompanySQL='';
                if ($selectedCompany>0){
                    // Add the delimiter for the specific company
                    $specificCompanySQL=' AND t.CompanyID= ' . $selectedCompany . ' ';
                    
                }

                // Create the query to run
                $sql=
                    'SELECT DISTINCT u.* ' .
                    'FROM tasks t ' .
                    'LEFT JOIN users u ON t.UserID = u.UserID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'WHERE t.UserID>0 ' .
                    'AND u.UserTemplateOnly=0 ' .
                    'AND t.TypeID=' . $typeID . ' ' .
                    $suUserSQL . $showOptionsSQL . $specificCompanySQL . $statusSQL .
                    'ORDER BY CompanyID, LastName;';
                
                // Query the database for the users 
                $rows = $db->queryDB($sql, $userRow, "tasks_presentation Form occurance 5");

                // Determine if some rows were returned
                if ($rows == null){
                    return $result;
                }
                else{
                    // Loop through the returned results
                    while ($row=mysqli_fetch_array($rows)){
                        // Re-Init var
                        $selectedText = '';

                        // Determine if this is one selected
                        if ($assignedTo == $row["UserID"]){
                            // Set the selected text to be all companies
                            $selectedText = 'selected';

                            // Set the variable
                            $foundOneInList = true;
                        }

                        // Add this option to the select
                        $result=$result . '<option value="' . $row["UserID"] . '" ' . $selectedText . '>' . $row["UserName"] . '(' .$row["FirstName"] . ' ' . $row["LastName"] . ')</option>';
                    }

                    // Determine if this is one selected
                    if (!$foundOneInList){
                        // Set the selected text to be all companies
                        $selectedText = 'selected';
                    }

                    // Start the return with the beginning of the select
                    $result='<label for="assignedTo">Assigned To: </label>' . 
                            '<select name="assignedTo" id="assignedTo"  ' . 
                            'onchange="CreateAndGotoSearchOptions()" style="align:left;" ' .
                            'style="text-align:left;">' .
                            '<option value="-2" ' . $allUsersSelectedText . '>Show All</option>' . 
                            '<option value="-1" ' . $allSUUsersSelectedText . '>Show SU Company Users</option>' . $result .
                            '</select>';
                }
            }
            else {
                // Create a hidden control with their company ID
                $result='<input type="hidden" name="assignedTo" id="assignedTo" value="' . ($userRow["UserID"]) . '"/>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getAssignedDelineations($db, $userRow, $showWhatFinishedState, $tasksPerPage, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus, $assignedTo=-1) {
        // Initialize the return
        $result = '';

        try {
            // Start the return with the beginning of the select
            $result=
                    '
                    <div id="tabDiv" style="padding: 14px 0px 0px 14px; border: none;">
                        <button id="typeTabID1" class="btn" ' . ($typeTab==1?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=1; CreateAndGotoSearchOptions();">Machining</button>
                        <button id="typeTabID2" class="btn" ' . ($typeTab==2?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=2; CreateAndGotoSearchOptions();">Design</button>
                        <button id="typeTabID3" class="btn" ' . ($typeTab==3?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=3; CreateAndGotoSearchOptions();">Programming</button>
                        <button id="typeTabID4" class="btn" ' . ($typeTab==4?'style=color:black; ':'') . 'onclick="document.getElementById(\'typeSelected\').value=4; CreateAndGotoSearchOptions();">In-House</button>
                    </div>
                    <div style="text-align:center; margin: 8px;font-size: 90%; font-weight: normal; border: 1px solid darkgray; padding: 0px 7px 10px 7px;">
                        <br>
                        <table>
                            <tr>
                                <td colspan=3>
                                    <label for="searchPhrase">Search Phrase: </label>
                                    <input name="searchPhrase" id="searchPhrase" type="text" style="width: 70%;" value="' . htmlentities($taskSearchPhrase, ENT_QUOTES) . '">
                                    <input name="submitButton" id="submitButton" type="button" value="Search" title="Search the task for a phrase." onclick="CreateAndGotoSearchOptions()" style="text-align:right;"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan=1>
                                '
                                .
                                    getCompanyUnderTask($db, $userRow, $showWhatFinishedState, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus,0)
                                .
                                '
                                </td>
                                <td colspan=1 width="8%">
                                </td>
                                <td colspan=1>
                                '
                                .
                                    getShowNoShowCombo($showWhatFinishedState,true,'','align:right;')
                                .
                                '
                                </td>
                            </tr>
                            <tr>
                                <td colspan=1>
                                '
                                .
                                    getEmployeesUnderCompany($db, $userRow, $showWhatFinishedState, $typeTab, $selectedCompany, $selectedStatus, $assignedTo)
                                .
                                '
                                </td>
                                <td colspan=1 width="8%">
                                </td>
                                <td colspan=1>
                                '
                                .
                                    getTasksPerPageCombo($tasksPerPage)
                                .
                                '
                                </td>
                            </tr>
                            <tr>
                                <td colspan=3>
                                '
                                .
                                    getTaskStatusCombo($db, $userRow, $showWhatFinishedState, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus, 0)
                                .
                                '
                                </td>
                            </tr>
                        </table>
                        <input type="hidden" name="typeSelected" id="typeSelected" value="' . ($typeTab) . '"/>
                    </div>';
                
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function retrieveAssignedTasksAsList($db, $userRow, $selectedType, $showWhatFinishedState, $tasksPerPage, $currentPage, $selectedCompany, $taskSearchPhrase, $sortNumber, $selectedStatus, $assignedTo=-1){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableTaskRowCellHTML = '';
        $companyTitleRowCellHTML = '';
        $searchPhraseSQL = '';
        
        $sortSQL = 'CASE WHEN IdealDate IS NULL THEN 1 ELSE 0 END, IdealDate, ' .
                   'CASE WHEN DueDate IS NULL THEN 1 ELSE 0 END, DueDate, TaskID, ParentID';

        if ($sortNumber!=""){
            // Determine which sort the person wants
            switch ($sortNumber) {
                case 1:
                    // Sort as priority the most high
                    $sortSQL = "Priority, " . $sortSQL;

                    break;
                case 5:
                    // Sort as title the most high
                    $sortSQL = "Title, " . $sortSQL;

                    break;
                case 10:
                    // Sort as status by flow the most high
                    $sortSQL = "ProcessOrder, " . $sortSQL;

                    break;
                case 15:
                    // Sort as task ID the most high
                    $sortSQL = "TaskID DESC, " . $sortSQL;

                    break;
                case 20:
                    // Sort as Due date the most high
                    $sortSQL = 'CASE WHEN DueDate IS NULL THEN 1 ELSE 0 END, DueDate, ' .
                               'CASE WHEN IdealDate IS NULL THEN 1 ELSE 0 END, IdealDate, TaskID, ParentID';

                    break;
                case 25:
                    // Sort as Company name the most high
                    $sortSQL = "CompanyName, " . $sortSQL;

                    break;
                case 30:
                    // Sort as Company name the most high
                    $sortSQL = "t.UserID, " . $sortSQL;

                    break;
                default:
                    break;
            }
        }

        // Check to see what is default for seeing closed tasks
        $realShowWhatFinishedState=$showWhatFinishedState;
        $showOptionsSQL = '';
        if ($showWhatFinishedState==0){
            // What are the user defaults
            $realShowWhatFinishedState = $userRow["ShowWhatFinishedState"];
        }

        // Check to see what is set in the combo box for seeing completed tasks
        switch ($realShowWhatFinishedState){
            case 6:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 AND t.Closed=1 ';

                break;
            case 5:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND (t.Completed=1 OR t.Closed=1) ';

                break;
            case 4:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Closed=1 ';

                break;
            case 3:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Completed=1 ';

                break;
            case 2:
                // Set it to include completed tasks
                $showOptionsSQL = $showOptionsSQL . ' AND t.Completed<>1 AND t.Closed<>1 ';

                break;
            case 1:
                // Set it to include completed tasks
                $showOptionsSQL = '';

                break;
            default:
        }

        // Determine if there is a search term
        if (trim($taskSearchPhrase)!=""){
            // Convert in case special html chars
            $convertedSearchPhrase = htmlspecialchars($taskSearchPhrase);
            
            // Determine if we have a number
            if (is_numeric($taskSearchPhrase)){
                // Create a search phrase
                $searchPhraseSQL=" and (t.Title LIKE '%" . $convertedSearchPhrase . "%' " .
                                       "OR t.TaskID = '" . $convertedSearchPhrase . "' " .
                                       "OR t.Entry LIKE '%" . $convertedSearchPhrase . "%')";
            }
            else {
                // Make it lower case
                $lowerCaseSearchPhrase = strtolower ($convertedSearchPhrase);

                // Create a search phrase
                $searchPhraseSQL=" and (LOWER(t.Title) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                       "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                       "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
            }
        }

        // Determine if there is a status that is selected
        $selectedStatusSQL='';
        if (is_numeric($selectedStatus) && $selectedStatus>0){
            // Add a SQL delimiter for status
            $selectedStatusSQL=' AND s.StatusID=' . $selectedStatus . ' ';
        }

        // Determine if this is a user of the SU company so I can set the selected company
        $selectedCompanySQL = '';
        // Determine if the selected company is a singular company
        if ($selectedCompany != null && 
            $selectedCompany > 0){
            // Add the selected company SQL
            $selectedCompanySQL = 'AND t.CompanyID=' . $selectedCompany . ' ';
        }
        else if ($selectedCompany != null && 
                 $selectedCompany < 0){
            // Determine if it is the ALL companies or ALL Customers or SU companies
            switch ($selectedCompany) {
                case -2:
                    // Set it to bring up the SU and the SU's main companies
                    $selectedCompanySQL = 'AND (t.CompanyID=1 OR c.MainSubCompany=1) ';

                    break;
                case -1:
                    // Set it to bring up everything BUT the SU and the SU's main companies
                    $selectedCompanySQL = 'AND t.CompanyID<>1 AND c.MainSubCompany<>1 ';

                    break;
                default:
                    break;
            }
        }
        
        // Determine if the choice is not a specific user
        $userIsInCompanySQL = '';
        if ($assignedTo==-1){
            // Only look for users of the SU company
            $userIsInCompanySQL = ' AND u.CompanyID=1 ';
        }
        
        // Determine if the choice is not a specific user
        $assignedtoSQL = ' AND t.UserID > 0 ';
        if ($assignedTo>0){
            // Only look for users of the SU company
            $assignedtoSQL = '  AND t.UserID = ' . $assignedTo . ' ';
        }
        
        // determine if this is a user in the super company. The company 
        // with it's ID as '1' in the TMS is the Super Company.
        if ($userRow["CompanyID"]==1){
            $companyTitleRowCellHTML = '
                        <div class="cell companyCell" onclick="document.getElementById(\'sortNumber\').value=25; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                            <p><b>Company</b></p>
                        </div>
                ';
        }

        // 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 = 
            '
             <input type="hidden" id="sortNumber" name="sortNumber" value="' . $sortNumber . '"/>
             <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell priCell" onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>#</b></p>
                    </div>
                    <div class="cell titleCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Title</b></p>
                    </div>
                    <div class="cell employeeCell" onclick="document.getElementById(\'sortNumber\').value=30; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Assigned To</b></p>
                    </div>
                    <div class="cell statusCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Status</b></p>
                    </div>
                    <div class="cell taskIDCell" onclick="document.getElementById(\'sortNumber\').value=15; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Task ID</b></p>
                    </div>
                    <div class="cell dateCell" onclick="document.getElementById(\'sortNumber\').value=20; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Due Date</b></p>
                    </div>' . 
                    $companyTitleRowCellHTML . 
                    $updateableTitleRowCellHTML . '
                </div>
            </li>';

        try {
            // Determine if they are set to user preferences
            $realTasksPerPage=$tasksPerPage;
            if ($tasksPerPage==0){
                // Set it to the real user's preferences
                $realTasksPerPage=$userRow["TasksPerPage"];
            }
            
            // Create the offset we are looking at currently
            $offset=(($currentPage-1)*$realTasksPerPage);
            
            // Create the query to run
            $sql=
                'SELECT s.ProcessOrder as ProcessOrder, s.Name AS StatusName, s.StatusRowColor, ' . 
                       'c.CompanyName AS CompanyName, c.CompanyRowColor, c.MainSubCompany, c.Store, ' . 
                       'u.FirstName, u.LastName, u.UserName, ' . 
                       't.Priority, t.Title, t.Entry, t.IdealDate, t.DueDate, t.Completed, t.Closed, ' . 
                       't.TaskID, t.UserDeletable, t.ParentID, t.HasChildren, t.DueDate, t.Completed, ' . 
                       't.Closed, t.TaskID, t.UserDeletable, t.ParentID, t.HasChildren, t.Expedite, ' .
                       'ss.RowColor AS SSRowColor, ss.Description AS SSDescription, ss.Name AS SSName, usvl.ViewCategory, ' .
                       '(SELECT COUNT(*) FROM copiedtaskslinker WHERE CopiedFromTaskID=t.TaskID GROUP BY CopiedFromTaskID) AS AmountCopiedFromThisTask ' .
                'FROM tasks t ' .
                'LEFT JOIN users u ON t.UserID = u.UserID ' .
                '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 (usvl.ViewCategory IS NULL OR t.UserID=' . $userRow["UserID"] . ')' .
                   ' AND t.CompanyID=c.CompanyID ' .
                   ' AND t.TypeID=' . $selectedType . ' ' .
                   $assignedtoSQL .
                   $selectedStatusSQL .
                   $selectedCompanySQL .
                   $userIsInCompanySQL .
                   $showOptionsSQL .
                   $searchPhraseSQL . 
                'ORDER BY t.Expedite DESC, ' . $sortSQL . ' ' .
                'LIMIT ' . $offset . ', ' . $realTasksPerPage . ';';
            
            $countsql=
                'SELECT COUNT(*)AS TheCount ' .
                'FROM tasks t ' .
                'LEFT JOIN users u ON t.UserID = u.UserID ' .
                'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                'WHERE s.StatusID = t.StatusID ' .
                   ' AND t.CompanyID=c.CompanyID ' .
                   ' AND t.TypeID=' . $selectedType . ' ' .
                   $assignedtoSQL .
                   $selectedStatusSQL .
                   $selectedCompanySQL .
                   $userIsInCompanySQL .
                   $showOptionsSQL .
                   $searchPhraseSQL . ';';

            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "tasks_presentation Form occurance 6");

            // 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;
                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, "tasks_presentation Form occurance 4");

                    // Init some count variables
                    $notesToOthersFromMe=0;
                    $notesToMeFromOthers=0;
                    $stickyNoteHTML='';
                    $notesNumeric='';
                    $notesTextual='';
                    
                    // 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++;
                        }
                    }
                    
                    // Create a query to get appropriate sticky notes for this task
                    $sql = 'SELECT n.EnteredByID, 
                                   (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 tasks t
                            LEFT JOIN notes n ON t.TaskID = n.AssociatedCategoryID
                            WHERE t.ParentID=' . $row["TaskID"] . '
                            AND n.Category=\'TASK\' 
                            AND n.IsSticky=1;';
                    
                    // Query the database for the the note count 
                    $stickyNoteChildRows = $db->queryDB($sql, $userRow, "tasks_presentation Form occurance 5");

                    // Init some count variables
                    $childNotesToOthersFromMe=0;
                    $childNotesToMeFromOthers=0;
                    $childNotesNumeric='';
                    $childNotesTextual='';
                    
                    // Loop through the returned results
                    while ($stickyNoteChildRow=mysqli_fetch_array($stickyNoteChildRows)){
                        // Determine if this sticky note should be counted because this
                        // person made the note and needs to keep track of who read it
                        if ($stickyNoteChildRow["EnteredByID"]==$userRow["UserID"] &&
                            $stickyNoteChildRow["AmountNotReadByEveryone"]>0){
                            // Increment the count of child notes I made that have not been read by everyone
                            $childNotesToOthersFromMe++;
                        }
                        
                        // Make this separate to count the ones I made that I want myself to reread
                        if ($stickyNoteChildRow["AmountNotReadByMe"]>0){
                            // Increment the count of child notes I made that have not been read by everyone
                            $childNotesToMeFromOthers++;
                        }
                    }
                    
                    // Determine if there are notes to show them
                    if ($notesToOthersFromMe>0 || $notesToMeFromOthers>0 || $childNotesToOthersFromMe || $childNotesToMeFromOthers){
                        // Determine if we have any parent sticky notes
                        $onClickSticky='alert(\'There are no main task sticky notes that needs attention. In order to see the sub-task sticky notes you should first click into the parent and see them from there on in the sub-task sticky notes tab.\');';
                        if ($notesToOthersFromMe>0 || $notesToMeFromOthers>0){
                            // Add the ability to see the sticky notes of the parent
                            $onClickSticky='popUp=popupWindow(\'view_sticky_notes.php?acid=' . $row["TaskID"] . '&c=TASK\', \'_blank\', window.parent, 700, 500);';

                            // Create the informational bit
                            $notesNumeric='<div style="position: absolute; top: 18%; left: 25%; transform:rotate(15deg);"><b><font style="color:red;">' . $notesToMeFromOthers . '</font><font style="color:black;">(</font><font style="color:green;">' . $notesToOthersFromMe . '</font><font style="color:black;">)</font></b></div>';
                            $notesTextual='There are ' . $notesToMeFromOthers . ' notes to you that you have not read, ' . $notesToOthersFromMe . ' notes that you wrote that have not been read by all recipients.';
                        }

                        // Determine if there are any children
                        if ($childNotesToOthersFromMe>0 || $childNotesToMeFromOthers>0){
                            // Create the informational bit
                            $childNotesNumeric='<div style="position: absolute; top: 46%; left: 18%; transform:rotate(15deg);"><b><font style="color:DodgerBlue;">' . $childNotesToMeFromOthers . '</font><font style="color:black;">(</font><font style="color:Orange;">' . $childNotesToOthersFromMe . '</font><font style="color:black;">)</font></b></div>';
                            $childNotesTextual='There are ' . $childNotesToMeFromOthers . ' notes on sub-tasks that you have not read and ' . $childNotesToOthersFromMe . ' notes on sub-tasks that you wrote that have not been read by all recipients.';
                        }

                        $stickyNoteHTML=
                                '<div style="position: absolute; top: 10%; left:-85%;" onclick="' . $onClickSticky . '" 
                                                                                       onmouseover="document.body.style.cursor = \'pointer\';" 
                                                                                       onmouseout="document.body.style.cursor = \'default\';"
                                                                                       title="' . $notesTextual . ' ' . $childNotesTextual . '">
                                    <img src="images/post_it.png" alt="Sticky Notes" style="height:35px; transform:rotate(15deg);">
                                    ' . $notesNumeric . '
                                    ' . $childNotesNumeric . '
                                 </div>';
                    }
                    
                    // Create the visualized task orientation as though this IS the parent
                    $firstFour = str_pad($row["TaskID"],4,"0",STR_PAD_LEFT);
                    $lastFour = '0000';

                    // 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=' . $selectedCompany . '&ts=' . $selectedType . '&at=' . $assignedTo . '\';"/>';

                    // 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 task?\')) {DeleteTaskAndReturn(' . $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='';
                    }

                    // Set the last one updated to that value.  Should be the same for every row
                    $companyTaskRowCellHTML = '';
                    $employeeTaskRowCellHTML = '';
                    $updateableTaskRowCellHTML = '';

                    // determine if this is a user in the super company and color the company cell.
                    if ($userRow["CompanyID"]==1){
                        // Set the color of the company cell to the appropriate company's color
                        $companyTaskRowCellHTML = '
                            <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';"/>';
                    }
                    
                    // determine if this is a user in the super company and color the company cell.
                    if ($userRow["CompanyID"]==1){
                        // Set the color of the company cell to the appropriate company's color
                        $companyTaskRowCellHTML = '
                            <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';"/>';
                    }
                    
                    // Determine if this task has children
                    $childCheckboxHTML = '';
                    $children = '';
                    $parentBorderColor = '';
                    if ($row["HasChildren"] == 1){
                        // Get the children
                        $children = retrieveChildTasksAsList($db, $userRow, $row["TaskID"], false, $selectedCompany, $selectedType);
                        
                        // Make the children
                        $childCheckboxHTML = '<table>
                                                <tr>
                                                  <td style="text-align: center; vertical-align: middle;" colspan=2>
                                                      <label style="font-size:10px; font-weight: bold; color:LimeGreen;">Children</label>
                                                      <input class="notinput" name="hideChildren' . $row["TaskID"] . '" id="hideChildren' . $row["TaskID"] . '" type="checkbox" class="hideChildren" onclick="javascript:div_toggleVisibilityOnCheckbox(\'hideChildren' . $row["TaskID"] . '\',\'childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '\', \'NORMAL\');"/>
                                                  </td>
                                                </tr>
                                              </table>';
                        
                        // TODO: Remove for real
                        $childCheckboxHTML = '<tr>
                                                  <td style="text-align: center; vertical-align: middle;" colspan=2>
                                                      <label style="font-size:10px; font-weight: bold; color:Black;">Has SubTasks</label>
                                                  </td>
                                              </tr>';
                        
                        $parentBorderColor = 'style="border-color: limegreen;"';
                    }
                    else if ($row["ParentID"] != 0){
                        $childCheckboxHTML = '<tr>
                                                  <td style="text-align: center; vertical-align: middle;" colspan=2>
                                                      <label style="font-size:10px; font-weight: bold; color:Peru;">Parent ID: ' . $row["ParentID"] . '</label>
                                                  </td>
                                              </tr>';
                        
                        $parentBorderColor = 'style="border-color:Peru ;"';
                    }

                    // 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">
                                    <table>
                                        <tr>
                                            <td>
                                            ' .
                                            $taskEditButtonHTML
                                            . '
                                            </td>
                                        </tr>
                                    </table>' .
                                    $childCheckboxHTML . '
                                </div>
                                ';
                            
                            // determine if this is a user in the super company. 
                            // If so, then they can see the company column.
                            if ($userRow["CompanyID"]==1){
                                // Show company column
                                $companyTaskRowCellHTML = '
                                    <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                            <p>' . $row["CompanyName"] . '</p>
                                    </div>
                                    ';
                                
                                // Determine if this task is a SU company and the user is also of the same company
                                if ($row["MainSubCompany"]==1){
                                    // Give the the delete option
                                    $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell">
                                            <table>
                                                <tr>
                                                    <td>
                                                        ' .
                                                        $taskDeleteButtonHTML
                                                        . '
                                                    </td>
                                                    <td>
                                                        ' .
                                                        $taskEditButtonHTML
                                                        . '
                                                    </td>
                                                </tr>
                                            </table>' .
                                            $childCheckboxHTML . '
                                        </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">
                                        <table>
                                            <tr>
                                                <td>
                                                    ' .
                                                    $taskDeleteButtonHTML
                                                    . '
                                                </td>
                                                <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                </td>
                                            </tr>
                                        </table>' .
                                        $childCheckboxHTML . '
                                    </div>
                                    ';
                            }
                            else {
                                // Remove the delete option
                                $updateableTaskRowCellHTML = '
                                    <div class="cell updateCell">
                                        <table>
                                            <tr>
                                                <td>
                                                    ' .
                                                    $taskEditButtonHTML
                                                    . '
                                                </td>
                                            </tr>
                                        </table>' .
                                        $childCheckboxHTML . '
                                    </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){
                                // These user of the super company can see the company name
                                $companyTaskRowCellHTML = '
                                    <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                        <p>' . $row["CompanyName"] . '</p>
                                    </div>
                                    ';

                                // 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">
                                            <table>
                                                <tr>
                                                    <td>
                                                            ' .
                                                            $taskDeleteButtonHTML
                                                            . '
                                                        </td>
                                                    <td>
                                                        ' .
                                                        $taskEditButtonHTML
                                                        . '
                                                    </td>
                                                </tr>
                                            </table>' .
                                            $childCheckboxHTML . '
                                        </div>
                                        ';
                                }
                                else{
                                    // special update cell for super users at this level
                                    $updateableTaskRowCellHTML = '
                                        <div class="cell updateCell">
                                            <table>
                                                <tr>
                                                    <td>
                                                        ' .
                                                        $taskEditButtonHTML
                                                        . '
                                                    </td>
                                                </tr>
                                            </table>' .
                                            $childCheckboxHTML . '
                                        </div>
                                        ';
                                }
                            }

                            // Break out of this one
                            break;
                        case 'SU':
                            $companyTaskRowCellHTML = '
                                <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                    <p>' . $row["CompanyName"] . '</p>
                                </div>
                                ';
                            $updateableTaskRowCellHTML = '
                                <div class="cell updateCell">
                                    <table>
                                        <tr>
                                            <td>
                                                ' .
                                                $taskDeleteButtonHTML
                                                . '
                                            </td>
                                            <td>
                                                ' .
                                                $taskEditButtonHTML
                                                . '
                                            </td>
                                        </tr>
                                    </table>' .
                                    $childCheckboxHTML . '
                                </div>
                                ';

                            // Break out of this one
                            break;
                    }

                    // Increment the row
                    $amount++;

                    // 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
                            $textSecondaryColor='color:#000000;';
                        }

                        // set them to be something
                        $secondaryStatusBackgroundColor = "background-color:" . $row["SSRowColor"] . ";" . $textSecondaryColor;
                        $secondaryStatusTitle = 'Secondary Status: ' . $row["SSName"] . ' - ' . $row["SSDescription"];
                    }

                    // Add this option to the select
                    $result = $result .
                        '<li id="' . $row["Priority"] . '" name="' . $row["Priority"] . '" class="ui-state-default ui-state-disabled Table ' . $rowExpedite . '" ' . $parentBorderColor . ' title="' . $expediteTitle . '">
                            <div name="test" title="' . $secondaryStatusTitle . '" class="Row" style="background-color: '. $color . '; border-style: solid; Height: 40px;" ondblclick="addStickyNoteDialog(' . $row["TaskID"] . ');">
                                <div class="cell priCell" style="position:relative; ' . $secondaryStatusBackgroundColor .'">
                                    ' . $stickyNoteHTML . '
                                    <p>' . (($row["Priority"]==99999) ? '-':$row["Priority"]) . '</p>
                                </div>
                                <div class="cell" style="' . $textColorHTML . '">
                                    <p>' . $row["Title"] . '</p>
                                </div>
                                <div class="cell employeeCell" style="' . $textColorHTML . '">
                                    <p>' . $row["FirstName"] . '  ' . $row["LastName"] . '</p>
                                </div>
                                <div class="cell statusCell" 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>' . 
                                $companyTaskRowCellHTML . 
                                $updateableTaskRowCellHTML . '
                            </div>
                        <div class="childrenDiv Row" name="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" id="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" style="display: none; ">
                            <div class="cell">
                                <span>' . $children . '</span>
                        </div>
                        </div>
                        </li>';
//                        <div name="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" id="childrenRows' . $row["TaskID"] . '_' . $row["Priority"] . '" class="childrenDiv" style="display: none; ">
//                            ' . $children . '
//                        </div>';
                }
                
                // Query the database for the count of the actual tasks 
                $maxRowsQuery = $db->queryDB($countsql, $userRow, "tasks_presentation Form occurance 7");

                // Determine if we have one row to look at
                $numberOfRows=0;
                if ($maxRowsQuery){
                    // Get the Row returned
                    $maxRowsAssoc = $maxRowsQuery->fetch_assoc();
                    
                    // Get the number of rows that would have happened without the limit
                    $numberOfRows = $maxRowsAssoc["TheCount"]; 
               }
               
               // Determine if there are more than the tasks that they have asked for per page
               $pageSelector='';
               if ($numberOfRows>$realTasksPerPage){
                   // Initialize the loop counter
                   $loopPageNumber = 0;
                   
                   // Create a back link and forward link
                   $backLink = '';
                   $forwardLink = '';
                   $firstPageLink = '';
                   $lastPageLink = '';
                   
                   do {
                        // Increment the loop counter
                        $loopPageNumber++;

                        // Only putting the extra links if we have more than 7 pages
                        if ($numberOfRows/$realTasksPerPage > 7){
                            // Determine if we are NOT on the first page
                            if ($currentPage>1){
                                // setup the back link to go back to the previous page 
                                $backLink = '<a href="etasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                            '&sn=' . $sortNumber . '&cp=' . ($currentPage-1) . '&at=' . $assignedTo . 
                                            '"> < </a>&nbsp;&nbsp;';
                            }

                            // Determine if we are NOT on the last page
                            if ($currentPage != $loopPageNumber){
                                // setup the back link to go forward to the next page 
                                $forwardLink = '<a href="etasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                               '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                               '&sn=' . $sortNumber . '&cp=' . ($currentPage+1) . '&at=' . $assignedTo . 
                                               '"> > </a>&nbsp;&nbsp;';
                            }
                            else{
                                // Reset the forward link
                                $forwardLink='';
                            }
                        }
                        
                        
                        // Determine if the selected this is the selected page
                        $selectedStyling='';
                        if ($loopPageNumber==$currentPage){
                            // Bold it
                            $selectedStyling='color: white; background-color:#0073e6;';
                        }
                       

                        // Determine if this is within +/- 3 of the current row
                        if ($loopPageNumber>($currentPage-3) && $loopPageNumber<=($currentPage+3) ){
                            // Add the link
                            $pageSelector = $pageSelector . '<a href="etasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                            '&sn=' . $sortNumber . '&cp=' . $loopPageNumber . '&at=' . $assignedTo. 
                                            '" style="' . $selectedStyling . '"> ' . $loopPageNumber . ' </a>&nbsp;&nbsp;';
                        }
                        else {
                            if ($loopPageNumber<($currentPage-2)){
                                // setup the first page link
                                $firstPageLink = '<a href="etasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                            '&sn=' . $sortNumber . '&cp=1&at=' . $assignedTo. '"> 1 </a>&nbsp;&nbsp;...&nbsp;&nbsp;';
                            }
                            
                            if ($loopPageNumber>($currentPage+3)){
                                // setup the last page link
                                $lastPageLink = '...&nbsp;&nbsp;<a href="etasks.php?sfs=' . $showWhatFinishedState . '&tpp=' . $realTasksPerPage . 
                                                '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&ts=' . $selectedType . 
                                                '&sn=' . $sortNumber . '&cp=' . $loopPageNumber . '&at=' . $assignedTo. '"> ' . 
                                                $loopPageNumber . ' </a>&nbsp;&nbsp;';
                            }
                            
                        }
                   }while(1 < $numberOfRows/($loopPageNumber*$realTasksPerPage));
                   
                   $pageSelector = '<div style="text-align:center; font-size: 90%; border: 1px solid darkgray; padding: 2px 2px 2px 2px;">
                                   ' . $backLink . $firstPageLink . $pageSelector . $lastPageLink . $forwardLink . '
                                   </div>';

               }
                
                // Add the closest date to the result
                $result = $pageSelector . $result . $pageSelector;
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }        
    
    function retrieveMachinesToHoldTasks($db, $userRow){
        // determine if this is a user in the super company. The company 
        // with it's ID as '1' in the TMS is the Super Company. Non-SU
        // users cannot see tasks on machines.
        if ($userRow["CompanyID"]!=1){
            return;
        }
        // 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 header
        $headerResult = 
            '
             <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell titleCell">
                        <p><b>Title</b></p>
                    </div>
                    <div class="cell statusCell">
                        <p><b>Status</b></p>
                    </div>
                    <div class="cell taskIDCell">
                        <p><b>Task ID</b></p>
                    </div> 
                    <div class="cell companyCell">
                        <p><b>Company</b></p>
                    </div>' . 
                    $updateableTitleRowCellHTML . '
                </div>
            </li>';

        try {
            // Create the query to run
            $sql=
                'SELECT Name, IsDown, MachineID, Type ' .
                'FROM machines ' .
                'WHERE ShowOnWhiteboard=1 ' . 
                'ORDER BY Type DESC, Name;';
            $sql = 'SELECT m.Name, m.IsDown, m.MachineID, m.Type  ' . 
                   'FROM machines m ' . 
                   'LEFT JOIN (SELECT * FROM usertomachineviewinglinker WHERE UserID=' . $userRow["UserID"] . ') umvl ON m.MachineID = umvl.MachineID ' .
                   'WHERE m.ShowOnWhiteboard=1 ' . 
                   'AND   umvl.ViewCategory IS NULL;';

//echo '<script>alert("' . addslashes($sql) . '");</script>';

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

            // 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
                $currentMachineID = null;
                while ($row=mysqli_fetch_array($rows)){
                    // Set it to an empty string for now 
                    $color = '';

                    // Determine the type to determine the color
                    switch($row["Type"]){
                        case 'BANDSAW' :
                            $color='#FFA07A';
                            break;
                        case 'CMM' :
                            $color='#AF7AC5';
                            break;
                        case 'DRILL' :
                            $color='#F9E79F';
                            break;
                        case 'EDM' :
                            $color='#48C9B0';
                            break;
                        case 'LASER TABLE' :
                            $color='#F1948A';
                            break;
                        case 'LATHE' :
                            $color='#F5B041';
                            break;
                        case 'MISCELLANEOUS' :
                            $color='#33383b';
                            break;
                        case 'MILL' :
                            $color='#28B463';
                            break;
                        case 'SURFACE GRINDER' :
                            $color='#ABB2B9';
                            break;
                        case 'WATERJET' :
                            $color='#3498DB';
                            break;
                        default:
                            $color='#797D7F';
                            break;
                    }
                    
                    // Determine if the machine has changed
                    if ($row["MachineID"]!=$currentMachineID){
                        // Determine if there was a last machine or not
                        if ($currentMachineID!=null){
                            // End the last portlet, portlet content and tasks sortable
                            $result = $result . '
                                            </ul>
                                        </div>
                                    </div>';
                        }

                        // Begin the next portlet, portlet content, tasks sortable and column headers
                        $result = $result . '
                            <div id="' . $row["MachineID"] . '" name="' . $row["MachineID"] . '" class="portlet">
                                <div class="portlet-header" style="color:' . $color . '";>' . $row["Name"] . '</div>
                                <div class="portlet-content">
                                    <ul id="portletTasks' . $row["MachineID"] . '" name="portletTasks' . $row["MachineID"] . '" class="tasksSortable connectedSortable">
                            '  . $headerResult ;
                        
                        // Set this as the current machine that we are looking at
                        $currentMachineID=$row["MachineID"];
                    }
                }
                
                // Determine if we have any result for them right now
                if ($result!=""){
                    // End the last portlet, portlet content and tasks sortable
                    $result = $result . '
                                    </ul>
                                </div>
                            </div>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function createUsersToAssignContent($db, $userRow, $controlName, $assignWhatToUser){
        // determine if this is a user in the super company. The company 
        // with it's ID as '1' in the TMS is the Super Company. Non-SU
        // users cannot see tasks on machines.
        if ($userRow["CompanyID"]!=1){
            return "";
        }

        try {
            // Create the query to run
            $sql=
                'SELECT * ' .
                'FROM users ' .
                'WHERE SUEmployee=1 ' .
                'AND   UserTemplateOnly=0 ' .
                'AND   AccountStatus="ACTIVE" ' .
                'ORDER BY UserName;';

            // Add the none to the select
            $result=$result . '<option value="-1">Nobody</option>';
                    
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "tasks_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)){
                    // Add this option to the select
                    $result=$result . '<option value="' . $row["UserID"] . '">' . $row["UserName"] . ' (' . $row["FirstName"] . '  ' . $row["LastName"] . ')</option>';
                }
            }
            
            $result = '
                <table width="100%" border="0">
                    <tr>
                        <td height="39" align="left">
                            <strong>Assign ' . $assignWhatToUser . ' to: </strong>
                            <select name="' . $controlName . '" id="' . $controlName . '">
                            ' . 
                            $result . ' 
                            </select>
                        </td>
                    </tr>
                </table>
                ';
        } catch (Exception $ex) {
            // Return nothing
            return "";
        }

        // Return whatever we got
        return $result;
    }
?>       
