<?php
    function getCompaniesWithTaskBlanks($db, $userRow, $showWhatFinishedState, $selectedCompany, $taskSearchPhrase, $selectedStatus){
        // 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 = '';
                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 jb.Reason 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 jb.Reason LIKE '%" . $convertedSearchPhrase . "%' " .
                                               "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                               "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
                    }
                }
                
                // 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 ' .
                    'LEFT JOIN jobblanks jb ON t.TaskID = jb.TaskID ' .
                    'WHERE jb.JobBlanksID IS NOT NULL ' .
                      'AND s.StatusID = t.StatusID ' .
                      'AND t.CompanyID=c.CompanyID ' .
                      $showOptionsSQL .
                      $searchPhraseSQL . 
                      $statusSQL .
                      ' ORDER BY CompanyName;';

                // Query the database for the user 
                $rows = $db->queryDB($sql, $userRow, "blanks_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, $selectedCompany, $taskSearchPhrase, $selectedStatus){
        // 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 = '';
                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 jb.Reason 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 jb.Reason LIKE '%" . $convertedSearchPhrase . "%' " .
                                               "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                               "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
                    }
                }
                
                // 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 ' .
                    'LEFT JOIN jobblanks jb ON t.TaskID = jb.TaskID ' .
                    'WHERE jb.JobBlanksID IS NOT NULL ' .
                      'AND s.StatusID = t.StatusID ' .
                      'AND t.CompanyID=c.CompanyID ' .
                      $selectedCompanySQL .
                      $showOptionsSQL .
                      $searchPhraseSQL . 
                      ' ORDER BY Name;';

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

                // Query the database for the user 
                $rows = $db->queryDB($sql, $userRow, "blanks_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, $blanksPerPage, $selectedCompany, $taskSearchPhrase, $selectedStatus, $showReadiedBlanks) {
        // 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){
                // Determine if they want to see readied blanks
                $showReadiedBlanksHTML='';
                if ($showReadiedBlanks==1){
                    // Set it to checked
                    $showReadiedBlanksHTML='checked';
                }

                // Start the return with the beginning of the select
                $result=
                    '
                    <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>
                                '
                                .
                                    getCompaniesWithTaskBlanks($db, $userRow, $showWhatFinishedState, $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, $selectedCompany, $taskSearchPhrase, $selectedStatus,1)
                                .
                                '
                                </td>
                                <td colspan=1 width="8%">
                                </td>
                                <td colspan=1>
                                '
                                .
                                    getBlanksPerPageCombo($blanksPerPage)
                                .
                                '
                                </td>
                            </tr>
                            <tr>
                                <td colspan=1>
                                    <label>Show Readied Blanks: </label>
                                    <input class="notinput" name="showReadiedBlanks" id="showReadiedBlanks" type="checkbox" onclick="javascript:CreateAndGotoSearchOptions();" ' . $showReadiedBlanksHTML . '/>
                                </td>
                                <td colspan=1 width="8%">
                                </td>
                                <td colspan=1>
                                </td>
                            </tr>
                        </table>
                    </div>';
            }
            else {
                // Start the return with the beginning of the select
                $result=
                        '
                        <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($blanksPerPage)
                                    .
                                    '
                                    </td>
                                    </td>
                                </tr>
                            </table>
                            <input type="hidden" name="companySelected" id="companySelected" value="' . $userRow["CompanyID"] . '"/>
                            '
                            .
                                getTaskStatusCombo($db, $userRow, $showWhatFinishedState, $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 createDimensionsCell($row){
        // Set the return to nothing for now
        $returnHTML='<div class="cell dimensionsCell" style="background-color: lightgrey;">
                        <p>Not Given</p>
                     </div>';
        
        try{
            // Setup a title of nothing for now
            $title='Quantity: ' . $row["Quantity"] . '&#10;';
            
            // Set dimension one text box html border to be rough color
            $dimension1CSS = ' color: LimeGreen;';

            // Determine if it is other than rough
            if ($row["Dimension1Precise"]==1){
                // Set dimension one text box html border to be precise color
                $dimension1CSS = ' color: red;';
                
                // Add the title to indicated that it is precise
                $title=$title . 'Dimension 1: ' . $row["Dimension1"] . ' Precise &#10;';
            }
            else if ($row["Dimension1Clean"]==1){
                // Set dimension one text box html border to be clean color
                $dimension1CSS = ' color: #c79f00;';
                
                // Add the title to indicated that it is clean
                $title=$title . 'Dimension 1: ' . $row["Dimension1"] . ' Clean &#10;';
            }
            else {
                // Add the title to indicated that it is rough
                $title=$title . 'Dimension 1: ' . $row["Dimension1"] . ' Rough &#10;';
            }

            // Set dimension one text box html border to be rough color
            $dimension2CSS = ' color: LimeGreen;';

            // Determine if it is other than rough
            if ($row["Dimension2Precise"]==1){
                // Set dimension two text box html border to be precise color
                $dimension2CSS = ' color: red;';
                
                // Add the title to indicated that it is precise
                $title=$title . 'Dimension 2: ' . $row["Dimension2"] . ' Precise &#10;';
            }
            else if ($row["Dimension2Clean"]==1){
                // Set dimension two text box html border to be clean color
                $dimension2CSS = ' color: #c79f00;';
                
                // Add the title to indicated that it is clean
                $title=$title . 'Dimension 2: ' . $row["Dimension2"] . ' Clean &#10;';
            }
            else {
                // Add the title to indicated that it is rough
                $title=$title . 'Dimension 2: ' . $row["Dimension2"] . ' Rough &#10;';
            }

            // Set dimension one text box html border to be rough color
            $dimension3CSS = ' color: LimeGreen;';

            // Determine if it is other than rough
            if ($row["Dimension3Precise"]==1){
                // Set dimension three text box html border to be precise color
                $dimension3CSS = ' color: red;';
                
                // Add the title to indicated that it is precise
                $title=$title . 'Dimension 3: ' . $row["Dimension3"] . ' Precise &#10;';
            }
            else if ($row["Dimension3Clean"]==1){
                // Set dimension three text box html border to be clean color
                $dimension3CSS = ' color: #c79f00;';
                
                // Add the title to indicated that it is clean
                $title=$title . 'Dimension 3: ' . $row["Dimension3"] . ' Clean &#10;';
            }
            else {
                // Add the title to indicated that it is rough
                $title=$title . 'Dimension 3: ' . $row["Dimension3"] . ' Rough &#10;';
            }
            
            // Set the return to nothing for now
            $returnHTML='<div class="cell dimensionsCell" style="background-color: lightgrey; text-align:center;" title="' . $title . '">
                            <p>
                                <label> Quantity: ' . $row["Quantity"] . ' </label><br>' . 
                               '<label style="' . $dimension1CSS . '"> ' . $row["Dimension1"] . ' </label>X' . 
                               '<label style="' . $dimension2CSS . '"> ' . $row["Dimension2"] . ' </label>X' . 
                               '<label style="' . $dimension3CSS . '"> ' . $row["Dimension3"] . ' </label>
                            </p>
                         </div>';
        } 
        catch (Exception $ex) {

        }
        
        return $returnHTML;
    }
    
    function retrieveBlanksAsList($db, $userRow, $showWhatFinishedState, $blanksPerPage, $currentPage, $selectedCompany, $taskSearchPhrase, $sortNumber, $selectedStatus, $showReadiedBlanks){
        // Init variables
        $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';

        if ($sortNumber!=""){
            // Determine which sort the person wants
            switch ($sortNumber) {
                case 1:
                    // Sort as priority the most high
                    $sortSQL = "Priority, SubPriority, " . $sortSQL . 
                               ", ParentID ASC, TaskID ASC, MaterialCategory, MaterialName, Type, CompanyName";

                    break;
                case 5:
                    // Sort as task IDs the most high
                    $sortSQL = "ParentID ASC, TaskID ASC, Priority, SubPriority, " . $sortSQL . 
                               ", MaterialCategory, MaterialName, Type, CompanyName";

                    break;
                case 10:
                    break;
                case 15:
                    // Sort as material info the most high
                    $sortSQL = "MaterialCategory, MaterialName, Type, Priority, SubPriority, " . $sortSQL . 
                               ", ParentID ASC, TaskID ASC, CompanyName";

                    break;
                case 20:
                    // Sort as Due date the most high
                    $sortSQL = $sortSQL . ", Priority, SubPriority, ParentID ASC, TaskID ASC, " . 
                               "MaterialCategory, MaterialName, Type, CompanyName";

                    break;
                case 25:
                    // Sort as Company name the most high
                    $sortSQL = "CompanyName, Priority, SubPriority, " . $sortSQL . 
                               ", ParentID ASC, TaskID ASC, MaterialCategory, MaterialName, Type";

                    break;
                case 30:
                    // Sort as pending on the bottom
                    $sortSQL = "CASE WHEN jb.IsPendingStock=1 THEN 99998 ELSE Priority END, SubPriority, " . $sortSQL . 
                               ", ParentID ASC, TaskID ASC, MaterialCategory, MaterialName, Type, CompanyName";

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

        // 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 jb.Reason 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(jb.Reason) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                       "OR LOWER(t.Entry) LIKE '%" . $lowerCaseSearchPhrase . "%' " .
                                       "OR LOWER(s.Name) = '" . $lowerCaseSearchPhrase . "') ";
            }
        }
        
        // Determine if they want to see submitted blanks
        $showReadiedBlanksSQL='AND jb.BlankReady=0 ';
        if ($showReadiedBlanks==1){
            // Set it up to show readied blanks
            $showReadiedBlanksSQL='';
        }

        // 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" title="Sort by task priority." onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>#</b></p>
                    </div>
                    <div class="cell taskInfoCell" title="Sort by task ID then blank ID." onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>For Task Info</b></p>
                    </div>
                    <div class="cell dimensionsCell">
                        <p><b>Quantity/Dimensions</b></p>
                    </div>
                    <div class="cell materialCell" title="Sort by material type then name." onclick="document.getElementById(\'sortNumber\').value=15; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Material</b></p>
                    </div>
                    <div class="cell dateCell" title="Sort by task due date." onclick="document.getElementById(\'sortNumber\').value=20; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Due Date</b></p>
                    </div>
                    <div class="cell companyCell" title="Sort by company." onclick="document.getElementById(\'sortNumber\').value=25; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Company</b></p>
                    </div>
                    <div class="cell updateCell" title="Move waiting for stock tasks to the bottom." onclick="document.getElementById(\'sortNumber\').value=30; CreateAndGotoSearchOptions();" style="cursor: pointer;" >
                        <p><b>Edit</b></p>
                    </div>
                </div>
            </li>';

        try {
            // Determine if they are set to user preferences
            $realBlanksPerPage=$blanksPerPage;
            if ($blanksPerPage==0){
                // Set it to the real user's preferences
                $realBlanksPerPage=$userRow["TasksPerPage"];
            }
            
            // Create the offset we are looking at currently
            $offset=(($currentPage-1)*$realBlanksPerPage);
            
            // Create the query to run
            $sql='SELECT jb.*, ' .
                         's.ProcessOrder as ProcessOrder, s.Name AS StatusName, s.StatusRowColor, ' .
                         'c.CompanyName AS CompanyName, c.CompanyRowColor, c.MainSubCompany, c.Store, ' . 
                         't.Priority, t.SubPriority, t.Title, t.Entry, t.IdealDate, t.DueDate, t.Completed, t.Closed, t.UserDeletable, t.ParentID, t.Expedite, ' .
                         'ss.RowColor AS SSRowColor, ss.Description AS SSDescription, ss.Name AS SSName, ' .
                         'm.Name AS MachineName, mat.MaterialRowColor, mat.Name AS MaterialName, mat.Category AS MaterialCategory ' .
                  'FROM jobblanks jb ' .
                  'LEFT JOIN tasks t ON jb.TaskID = t.TaskID ' .
                  'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                  'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                  'LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID ' .
                  'LEFT JOIN tasktomachinelinker tml ON t.TaskID = tml.TaskID ' .
                  'LEFT JOIN machines m ON tml.MachineID = m.MachineID ' .
                  'LEFT JOIN material mat ON jb.MaterialID = mat.MaterialID ' .
                  'WHERE jb.Submitted=1 ' . 
                    $showReadiedBlanksSQL .
                    $selectedCompanySQL . ' ' .
                    $selectedStatusSQL . ' ' .
                    $showOptionsSQL . ' ' .
                    $searchPhraseSQL . ' ' .
                  'ORDER BY ' . $sortSQL . ' ' . 
                  'LIMIT ' . $offset . ', ' . $realBlanksPerPage . ';';

            $countsql=
                'SELECT COUNT(*) AS TheCount ' .
                    'FROM jobblanks jb ' .
                    'LEFT JOIN tasks t ON jb.TaskID = t.TaskID ' .
                    'LEFT JOIN companies c ON t.CompanyID = c.CompanyID ' .
                    'LEFT JOIN status s ON t.StatusID = s.StatusID ' .
                    'LEFT JOIN secondarystatuses ss ON t.SecondaryStatusID = ss.SecondaryStatusID ' .
                    'LEFT JOIN tasktomachinelinker tml ON t.TaskID = tml.TaskID ' .
                    'LEFT JOIN machines m ON tml.MachineID = m.MachineID ' .
                    'LEFT JOIN material mat ON jb.MaterialID = mat.MaterialID ' .
                    'WHERE jb.Submitted=1 ' . 
                      $showReadiedBlanksSQL . 
                      $selectedCompanySQL . ' ' .
                      $selectedStatusSQL . ' ' .
                      $showOptionsSQL . ' ' .
                      $searchPhraseSQL . ';';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "blanks_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, "blanks_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;
                while ($row=mysqli_fetch_array($rows)){
                    // manipulate some values returned from the query
                    $machineName = ($row["MachineName"])==null?'Not Assigned':$row["MachineName"];
                    
                    // 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.';
                    }
                    
                    // Determine if this blank in pending stock
                    $pendingStockColor="White";
                    $pendingStockTitle="";
                    if ($row["IsPendingStock"]==1){
                        // Set the color to purple 
                        $pendingStockColor="#e0cef2";
                        
                        // Add a title
                        $pendingStockTitle="&#10;This blank is pending stock.";
                    }
                    
                    // 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["JobBlanksID"] . ' ' .
                            'AND n.Category=\'BLANK\' ' . 
                            'AND n.IsSticky=1;';
                    
                    // Query the database for the the note count 
                    $stickyNoteRows = $db->queryDB($sql, $userRow, "blanks_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 blank
                    $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 blanks b
                            LEFT JOIN notes n ON b.JobBlanksID = n.AssociatedCategoryID
                            WHERE b.JobBlanksID=' . $row["JobBlanksID"] . '
                            AND n.Category=\'BLANK\' 
                            AND n.IsSticky=1;';
                    
                    // Query the database for the the note count 
                    $stickyNoteChildRows = $db->queryDB($sql, $userRow, "blanks_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 blank sticky notes that needs attention. In order to see the blank sticky notes you should go to the blanks paget and see them from there or in the blanks 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["JobBlanksID"] . '&c=BLANK\', \'_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 blanks that you have not read and ' . $childNotesToOthersFromMe . ' notes on blanks 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 blank
                    $blankEditButtonHTML = '<input type="button" style="font-size:9px;" value="..." title="Edit this blank." onclick="javascript:window.location=\'updateBlank.php?updateBlankID=' . $row["JobBlanksID"] . '\';"/>';

                    // Determine if this blank is already readied
                    $blankReadyButtonHTML = '';
                    if ($row["BlankReady"]==0){
                        // Create a default html for the button to set this blank as ready since it hasn't been readied already
                        $blankReadyButtonHTML = '<input type="button" style="font-size:9px;" value="✔" title="Ready this blank." onclick="javascript:if (confirm(\'This will set the blank as ready, remove any material holds and drop from this list. Continue?\')) {ReadyBlankAndReturn(' . $row["JobBlanksID"] . ');}"/>';
                    }

                    // Determine if we are waiting on this blank
                    $updateCellColor='background-color: LightGreen;';
                    $waitingStockTitle='';
                    if ($row["IsPendingStock"]==1){
                        // Change the background color to orange
                        $updateCellColor='background: white repeating-linear-gradient(135deg,rgba(239, 255, 61, 1),rgba(239, 255, 61, 1) 3px,rgba(255, 5, 5, 1) 3px,rgba(255, 5, 5, 1) 6px);';
                        
                        // Setup the title of the update cell appropriately
                        $waitingStockTitle='title="This blank is pending stock to be released."';
                    }

                    // 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 there is an Due Date
                    $dueDate = "N/A";
                    if ($row["DueDate"] != null && $row["DueDate"] != ""){
                        // Assign Due Date to it
                        $dueDate=$row["DueDate"];
                    }

                    // Determine if this is a manual machining status
                    $textColorHTML='';
                    if ($row["StatusName"]=="Manual Machining"){
                        // Set the text to white
                        $textColorHTML=' color:#FFFFFF;';
                    }
                    
                    // 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"];

                    // Determine if this is expedite or not
                    $rushCellColor = "background-color:#48D1CC; "; // Medium Turquoise
                    $rushTitle='';
                    if ($row["Rush"]==1){
                        // Set it to a hot color
                        $rushCellColor = "background-color:#FF007F; "; // Hot Pink
                        
                        // Create a rush title
                        $rushTitle='&#10;This blank is rushed!';
                    }

                    // Add this option to the select
                    $result = $result .
                        '<li id="' . $row["Priority"] . '" name="' . $row["Priority"] . '" class="ui-state-default ui-state-disabled Table ' . $rowExpedite . '" title="' . $expediteTitle . '">
                            <div name="test" class="Row" style="background-color: '. $color . '; border-style: solid; Height: 40px;" ondblclick="addStickyNoteDialog(' . $row["JobBlanksID"] . ');">
                                <div class="cell priCell" title="' . $secondaryStatusTitle . '" style="position:relative; ' . $secondaryStatusBackgroundColor .'">
                                    ' . $stickyNoteHTML . '
                                    <p>' . (($row["Priority"]==99999) ? '-':$row["Priority"]) . '</p>
                                </div>
                                <div class="cell" style="' . $textColorHTML . 
                                    '" title="For TID: ' . $firstFour . '-' . $lastFour . '&#10;Title: ' . $row["Title"] . 
                                    '&#10;Status: ' . $row["StatusName"] . '&#10;Machine: ' . $machineName .
                                    '&#10;Priority: ' . $row["Priority"] . '&#10;SubPriority: ' . $row["SubPriority"] . 
                                    '&#10;Due Date: ' . $dueDate . '&#10;Ideal Date: ' . $idealDate . '">
                                    <p>For TID: ' . $firstFour . '-' . $lastFour . '<br>Title: ' . $row["Title"] . '</p>
                                </div>
                                ' . createDimensionsCell($row) . '
                                <div class="cell materialCell" style="background-color: ' . $pendingStockColor . ';text-align: left;" title="Category: ' . $row["MaterialCategory"] . '&#10;Name: ' . $row["MaterialName"] . '&#10;Type: ' . $row["Type"] . $pendingStockTitle . '">
                                    <p>
                                        <label style="color:' . $row["MaterialRowColor"] . '">Type: ' . $row["Type"] . '</label>
                                        <br>
                                        <label style="color:' . $row["MaterialRowColor"] . '">Name: ' . $row["MaterialName"] . '</label>
                                    </p>
                                </div>
                                <div class="cell dateCell" title="Ideal Date: ' . $idealDate . $rushTitle .'" style="' . $rushCellColor . '" text-align:center;">
                                    <p>' . $row["DueDate"] . '</p>
                                </div>
                                <div class="cell companyCell" style="background-color: '. $row["CompanyRowColor"] . ';">
                                    <p>' . $row["CompanyName"] . '</p>
                                </div>
                                <div class="cell updateCell" style="' . $updateCellColor . '" ' . $waitingStockTitle . '>
                                    <table>
                                        <tr>
                                            <td style="text-align:center;">
                                                <button style="font-size:9px;" title="Print the blank request." onclick="javascript: window.open(\'pdf_templates/blank_request.php?jbid=' . $row["JobBlanksID"] . '&sessionID=' . session_id() . '\', \'_blank\'); return true;"><img src="images/print.png" width="8" height="11"></button>
                                            </td>
                                            <td>
                                                ' .
                                                $blankEditButtonHTML
                                                . '
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                ' .
                                                $blankReadyButtonHTML
                                                . '
                                            </td>
                                            <td>
                                                <input type="button" style="font-size:9px;" value="+" title="This will copy the blank to a specified quantity for prepping." onclick="javascript:copyBlankRequestDialog(' . $row["JobBlanksID"] . ');"/>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </li>';
                }

               // Determine if there are more than the tasks that they have asked for per page
               $pageSelector='';
               
               if ($numberOfRows>$realBlanksPerPage){
                   // 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/$realBlanksPerPage > 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="blanks.php?sfs=' . $realShowWhatFinishedState . '&bpp=' . $realBlanksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase .  '&srb=' . $showReadiedBlanks .
                                            '&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="blanks.php?sfs=' . $realShowWhatFinishedState . '&bpp=' . $realBlanksPerPage . 
                                               '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&srb=' . $showReadiedBlanks .
                                               '&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="blanks.php?sfs=' . $realShowWhatFinishedState . '&bpp=' . $realBlanksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&srb=' . $showReadiedBlanks .
                                            '&sn=' . $sortNumber . '&cp=' . $loopPageNumber . '" style="' . $selectedStyling . 
                                            '"> ' . $loopPageNumber . ' </a>&nbsp;&nbsp;';
                        }
                        else {
                            if ($loopPageNumber<($currentPage-2)){
                                // setup the first page link
                                $firstPageLink = '<a href="blanks.php?sfs=' . $realShowWhatFinishedState . '&bpp=' . $realBlanksPerPage . 
                                            '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&srb=' . $showReadiedBlanks .
                                            '&sn=' . $sortNumber . '&cp=1"> 1 </a>&nbsp;&nbsp;...&nbsp;&nbsp;';
                            }
                            
                            if ($loopPageNumber>($currentPage+3)){
                                // setup the last page link
                                $lastPageLink = '...&nbsp;&nbsp;<a href="blanks.php?sfs=' . $realShowWhatFinishedState . '&bpp=' . $realBlanksPerPage . 
                                                '&cs=' . $selectedCompany . '&sp=' . $taskSearchPhrase . '&srb=' . $showReadiedBlanks .
                                                '&sn=' . $sortNumber . '&cp=' . $loopPageNumber . '"> ' . $loopPageNumber . 
                                                ' </a>&nbsp;&nbsp;';
                            }
                            
                        }
                   }while(1 < $numberOfRows/($loopPageNumber*$realBlanksPerPage));
                   
                   $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 getEmployeesUnderCompany($db, $userRow, $showWhatFinishedState, $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 ' .
                    $suUserSQL . $showOptionsSQL . $specificCompanySQL . $statusSQL .
                    'ORDER BY CompanyID, LastName;';
                
                // Query the database for the users 
                $rows = $db->queryDB($sql, $userRow, "blanks_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;
    }
?>       
