<?php
    function getUsedMaterialTypeAsSelectOptions($db, $userRow, $selectName, $typeSelected, $onChange, $style, $addAllOption, $fieldsDisabled){
        try {
            // Initialize the return
            $result = '';

            // Determine if we have an onchange event
            $onChangeHTML = '';
            if ($onChange!=null){
                // Set the onChange of the select to be what was passed in
                $onChangeHTML = $onChange;
            }

            // Determine if the ALL option is added
            if ($addAllOption) {
                // Add ALL to the beginning array
                $result = '<option value="">ALL TYPES</option>';
            }
            
            // Create the array of category values by querying the database
            $sql = "SELECT * FROM materialstock GROUP BY Type ORDER BY Type DESC;";
            
            // Query the database
            $rows = $db->queryDB($sql, $userRow, "stocklist_presentation occurance 1");
            
            // Loop through the returned results
            while ($row=mysqli_fetch_array($rows)){
                // Reset it
                $selectedHTML = "";
                
                // Trim it down
                $loopMaterialType=str_replace(" ", "_", (trim($row["Type"], "'")));

                // Determine if this is the selected one
                if ($loopMaterialType==$typeSelected){
                    // Set this as the selected one
                    $selectedHTML = "selected";
                }
                
                // Add this option
                $result = $result . '<option value="' . $loopMaterialType . '" ' . $selectedHTML . '>' . $row["Type"] . '</option>';
            }

            // Start and finish the select statement
            $result='<select id="' . $selectName . '" name="' . $selectName . '" style="' . $style . '" onchange="' . $onChangeHTML . '" ' . $fieldsDisabled . '>' . $result . '</select>';
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function getUsedMaterialAsSelectOptions($db, $userRow, $inMaterialSelected, $onChange, $style, $addAllOption, $fieldsDisabled, $name, $disabledHTML){
        // Initialize the return
        $result = '';

        try {
            // Set the selected material
            $materialSelected=$inMaterialSelected;
            
            // Determine if the ALL option is added
            if ($addAllOption) {
                // Add ALL to the beginning array
                $result = '<option value="-1">ALL MATERIAL</option>';
            }
            
            // Create the query to run
            $sql='SELECT * FROM material ORDER BY LOWER(Category), LOWER(Name);';

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

            // Ensure we got rows back.
            if ($rows == null){
                return $result;
            }
            else{
                // hold onto a category to see if the category changes
                $loopCategory="";
                
                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if the category has changed
                    if ($loopCategory!=$row["Category"]){
                        // Set the loop category to the new category
                        $loopCategory=$row["Category"];
                        
                        // Add it to the select as a group
                        $result=$result . '<optgroup label="' . $loopCategory . '">';
                    }
                    
                    // Determine if this is one that is to be selected
                    $selectedText='';
                    if ($materialSelected != null and $materialSelected==$row["MaterialID"]) {
                        // Create the selected html
                        $selectedText='selected';
                    }

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

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

        // Return whatever we got
        return $result;
    }


    function retrieveInDepthStockedMaterialsLists($db, $userRow, $inCategory, $inSortNumber, $inMaterialID, $inSearchPhrase){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableMaterialRowCellHTML = '';
        $searchPhrase = '';
        $sort = "";
        $category = "";
        $materialID = -1;

        // Set the category HTML as though category is correct
        $whereHTML = 'WHERE 1=1 ';
            
        // Determine if the selected company is NOT the first one
        if ($inCategory != null && 
            $inCategory != -1){
            // Update the category
            $category = $inCategory;
            
            // Add a category in the where
            $whereHTML = $whereHTML . 'AND ms.Type="' . $category . '" ';
        }
            
        // Determine if the selected company is NOT the first one
        if ($inMaterialID != null && 
            $inMaterialID != -1){
            // Update the type
            $materialID = $inMaterialID;
            
            // Add a type in the where
            $whereHTML = $whereHTML . 'AND m.MaterialID=' . $materialID . ' ';
        }
        
        // Determine if we have a search phrase
        if ($inSearchPhrase != null && 
            $inSearchPhrase != ""){
            // Update the search
            $searchPhrase = strtoupper(htmlspecialchars($inSearchPhrase));
            
            // Add a search in the where
            $whereHTML = $whereHTML . "AND (UPPER(ms.Name) LIKE '%" . $searchPhrase . "%' " .
                                      "     OR UPPER(ms.Notes) LIKE '%" . $searchPhrase . "%') ";
        }
        
        // Determine if there is actually a sort passed in
        if ($inSortNumber!=""){
            // Determine which sort the person wants
            switch ($inSortNumber) {
                case 1:
                    // Sort as Category then name
                    $sort = "ms.Name, m.Category DESC, ms.Type DESC, ms.Amount, ms.LowReorderLevel ";

                    break;
                case 5:
                    // Sort as Name then Category
                    $sort = "m.Category DESC, ms.Name, ms.Type DESC, ms.Amount, ms.LowReorderLevel ";

                    break;
                case 10:
                    // Sort as Type then Category
                    $sort = "ms.Type DESC, ms.Name, m.Category DESC, ms.Amount, ms.LowReorderLevel ";

                    break;
                case 15:
                    // Sort as Amounte then Category
                    $sort = "ms.Amount, ms.Name, m.Category DESC, ms.Type DESC, ms.LowReorderLevel ";

                    break;
                case 20:
                    // Sort as Name then Category
                    $sort = "ms.LowReorderLevel, ms.Name, m.Category DESC, ms.Type DESC, ms.Amount ";

                    break;
                default:
                    // Sort as Category then name
                    $sort = "ms.Name, m.Category DESC, ms.Type DESC, ms.Amount, ms.LowReorderLevel ";

                    break;
            }
        }

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

                break;
        }
        
        // Get the category select drop down
        $materialCategorySelectHTML=getUsedMaterialTypeAsSelectOptions($db, $userRow, 'category', $category, 'javascript:CreateAndGotoSearchOptions();', '', true, false);

        // Get the type select drop down
        $materialSelectHTML=getUsedMaterialAsSelectOptions($db, $userRow, $materialID, 'javascript:CreateAndGotoSearchOptions();', '', true, false, 'materialID', '');

        // Initialize the return
        $result = 
            '
            <table style="width: 100%;" border="1"> 
                <tr style="width: 100%;"> 
                    <td colspan=3 width="50%">
                        <input type="hidden" id="sortNumber" name="sortNumber" value="' . $inSortNumber . '"/>
                        <b>Material Type:</b>&nbsp;&nbsp;&nbsp;&nbsp;' . $materialCategorySelectHTML . '  
                    </td> 
                    <td colspan=3 width="50%">
                        <b>Material:</b>&nbsp;&nbsp;&nbsp;&nbsp;' . $materialSelectHTML . ' 
                    </td> 
                </tr>
                <tr>
                    <td colspan=2 width="33%">
                        <b>Quantity:</b>&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" style="width:50px;" maxlength="11" name="quantity" id="quantity" value="1"/>
                    </td>
                    <td colspan=2 width="33%">
                        <b>Quantity Dimension:</b>&nbsp;&nbsp;&nbsp;&nbsp;' 
                        . 
                        $db->getTypeAsSelectOptions('jobblanks', 'QuantityDimension', 'quantityDimension', "None", null, 'width: 75px;', false, '') 
                        . '
                    </td>
                    <td colspan=2 width="33%">
                        <b>Wall Thickness:</b>&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" style="width:50px;" maxlength="10" name="wallThickness" id="wallThickness" value="0"/>
                    </td>
                </tr>
                <tr>
                    <td colspan=2>
                        <b>Dimension 1:</b>&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" style="width:50px;" maxlength="15" name="dimension1" id="dimension1" value="0" />
                        <br>
                        '
                        .
                        createCutTypeRadioButton('dimension1Radio', 'dimension1', 0, 0, '', '')
                        .
                        '
                    </td>
                    <td colspan=2>
                        <b>Dimension 2:</b>&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" style="width:50px;" maxlength="15" name="dimension2" id="dimension2" value="0"/>
                        <br>
                        '
                        .
                        createCutTypeRadioButton('dimension2Radio', 'dimension2', 0, 0, '', '')
                        .
                        '
                    </td>
                    <td colspan=2>
                        <b>Dimension 3:</b>&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" style="width:50px;" maxlength="15" name="dimension3" id="dimension3" value="0"/>
                        <br>
                        '
                        .
                        createCutTypeRadioButton('dimension3Radio', 'dimension3', 0, 0, '', '')
                        .
                        '
                    </td>
                </tr>
                <tr>
                    <td colspan=6>
                        <div style="text-align:left; margin-top: 8px;font-size: 90%; font-weight: normal; padding: 0px 7px 10px 0px;">
                            <label style="font-weight:bold; font-size: 1.2em;" for="searchPhrase">Search Phrase:&nbsp;&nbsp;&nbsp;&nbsp;</label>
                            <input name="searchPhrase" id="searchPhrase" type="text" style="width: 70%;" value="' . htmlentities($searchPhrase, ENT_QUOTES) . '"/>
                            <input name="submitButton" id="submitButton" type="button" value="Search" title="Search the stock for a phrase." onclick="CreateAndGotoSearchOptions()" style="text-align:right;"/> 
                            <br>
                        </div>
                    </td> 
                </tr>
            </table>

            <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell nameCell" onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell catCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Category</b></p>
                    </div>
                    <div class="cell typeCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Type</b></p>
                    </div>
                    <div class="cell amountCell" onclick="document.getElementById(\'sortNumber\').value=15; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Amount</b></p>
                    </div>
                    <div class="cell llCell" onclick="document.getElementById(\'sortNumber\').value=20; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Low Level</b></p>
                    </div>' . 
                    $updateableTitleRowCellHTML . '
                </div>
            </li>';

        try {
            // Setup the query to be where they only get users in their company
            // and tasks that are NOT in stocked status
            $sql = 'SELECT ms.*, m.Category, m.MaterialRowColor, m.Name AS MaterialName ' .  
                   'FROM materialstock ms, ' . 
                        'material m ' . 
                   'LEFT OUTER JOIN ' . 
                        '(SELECT COUNT(*) AS AmountOnMaterialStock, MaterialID ' . 
                        ' FROM materialstock GROUP BY MaterialID) msm ON m.MaterialID = msm.MaterialID ' . 
                   $whereHTML . 
                   'AND m.MaterialID = ms.MaterialID ' . 
                   'ORDER BY ' . $sort . ';';
//echo '<script>alert("' . addslashes($sql) . '");</script>';
//var_dump($sql);
            
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "stocklist_presentation occurance 3");

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

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

                // Loop through the returned results
                $amount=0;
                $lastOneUpdated = '';
                while ($row=mysqli_fetch_array($rows)){
                    // Assign the delete button attributes as though deletion is an option
                    $deleteButtonTextColor = 'LIMEGREEN';
                    $deleteButtonTitle = 'Remove this stocked material.';
                    $deleteButtonOnClick = 'onclick="javascript:if (confirm(\'Are you sure you want to delete this stocked material?\')) ' .
                                           '{window.location=\'redirectors/delete_stocked_material.php?deleteStockedMaterialID=' . $row["MaterialStockID"] . '\';}"';

                    // Determine if this company is assigned to any tasks
                    if ($row["AmountUsedOnActiveTask"]!=null){
                        // Assign the delete buttons attributes such that deletion will not happen
                        $deleteButtonTextColor = 'RED';
                        $deleteButtonTitle = 'Check what active task this stock is used on.';
                        $deleteButtonOnClick = 'onclick="javascript:alert(\'This material stock is used on '. $row["AmountUsedOnActiveTask"] . 
                                               ' active tasks.\n\nWait until this material is no longer being used actively or change tasks ' . 
                                               'to reflect different stock.\');"';
                    }

                    // Determine if they are at a level to manage material stock
                    switch ($userRow["UserLevel"]){
                        case 'MID-MANAGEMENT':
                        case 'MANAGEMENT':
                        case 'EXECUTIVE':
                        case 'SU':
                            // Give the the delete option
                            $updateableMaterialRowCellHTML = '
                                <div class="cell updateCell">
                                    <span>
                                        <table>
                                            <tr>
                                                <td>
                                                    <input type="button" style="font-size:11px;" value="X" title="Remove this stocked material." ' . 
                                                    'onclick="window.location=\'redirectors/delete_stocked_material.php?deleteStockedMaterialID=' . 
                                                    $row["MaterialStockID"] . '\';"/>
                                                </td>
                                                <td>
                                                    <input type="button" style="font-size:11px;" value="..." title="Edit this material." ' . 
                                                    'onclick="javascript:window.open(\'updateStockedMaterial.php?updateStockedMaterialID=' . $row["MaterialStockID"] . '\', \'_blank\');"/>
                                                </td>
                                            </tr>
                                        </table>
                                    </span>
                                </div>
                                ';
                    }

                    // Increment the row
                    $amount++;

                    // Determine what color this row should be
                    $typeColor="#FFFFFF";
                    switch($row["Type"]){
                        case 'Tube':
                            $typeColor='#f47d42';
                            break;
                        case 'Round':
                            $typeColor='#ae82d8';
                            break;
                        case 'Plate':
                            $typeColor='#e585df';
                            break;
                        case 'Other':
                            $typeColor='#f7e7d7';
                            break;
                        case 'Extrusion':
                            $typeColor='#789a9e';
                            break;
                        case 'Cast':
                            $typeColor='#e8d08f';
                            break;
                        default:
                            $typeColor='#FFFFFF';
                            break;
                    }
                        
                    // Determine if the loop type is different than the last one
                    if ($loopToolCategory!=$row["Category"]){
                        // Determine if this is NOT the first type
                        if ($loopToolCategory!=''){
                            // Finish the last type div
                            $result = $result . '</DIV>';
                        }

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

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

                        // Set the name of the new type as the ID
                        $result = $result . '<DIV id="' . $id . '">';
                    }
                    
                    // Determine if the amount is lower than the low level
                    $alertBackground = '';
                    $alertBackgroundColor = '';
                    if ($row["Amount"]<=$row["LowReorderLevel"]){
                        // Add a border to the amount in question
                        $alertBackground = ' alertBackground';
                        $alertBackgroundColor='style="background-color: #FFFFFF"';
                    }

                    // Add this option to the select
                    $result = $result .
                        '<li class="ui-state-default Table" >
                            <div class="Row" style="background-color: '. $row["MaterialRowColor"] . '; border-style: solid; border-color: BLACK;">
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div>
                                <div class="cell catCell">
                                    <span>
                                        <p>' . $row["Category"] . '</p>
                                    </span>
                                </div>
                                <div class="cell typeCell" style="background-color: '. $typeColor . ';">
                                    <span>
                                        <p>' . $row["Type"] . '</p>
                                    </span>
                                </div>
                                <div class="cell amountCell ' . $alertBackground . '" ' . $alertBackgroundColor . '>
                                    <span>
                                        <p>' . $row["Amount"] . ' ' . $row["Units"] . '</p>
                                    </span>
                                </div>
                                <div class="cell llCell">
                                    <span>
                                        <p>' . $row["LowReorderLevel"] . '</p>
                                    </span>
                                </div>' . 
                                $updateableMaterialRowCellHTML . '
                            </div>
                        </li>';

                    // Determine if the loop type is different than the last one
                    if ($loopToolCategory!=$row["Category"]){
                        // End the DIV Set the name of the type as the ID
                        $result = $result . '<DIV id="' . $loopToolCategory . '"';
                    }
                }
                
                // Determine if the loop did the loopty loop
                if ($loopToolCategory!=''){
                    // Finish the last type div
                    $result = $result . '</DIV>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    function retrieveStockedMaterialsAsList($db, $userRow, $inCategory, $inSortNumber, $inMaterialID, $inSearchPhrase){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableMaterialRowCellHTML = '';
        $searchPhrase = '';
        $sort = "";
        $category = "";
        $materialID = -1;

        // Set the category HTML as though category is correct
        $whereHTML = 'WHERE 1=1 ';
            
        // Determine if the selected company is NOT the first one
        if ($inCategory != null && 
            $inCategory != -1){
            // Update the category
            $category = $inCategory;
            
            // Add a category in the where
            $whereHTML = $whereHTML . 'AND ms.Type="' . $category . '" ';
        }
            
        // Determine if the selected company is NOT the first one
        if ($inMaterialID != null && 
            $inMaterialID != -1){
            // Update the type
            $materialID = $inMaterialID;
            
            // Add a type in the where
            $whereHTML = $whereHTML . 'AND m.MaterialID=' . $materialID . ' ';
        }
        
        // Determine if we have a search phrase
        if ($inSearchPhrase != null && 
            $inSearchPhrase != ""){
            // Update the search
            $searchPhrase = strtoupper(htmlspecialchars($inSearchPhrase));
            
            // Add a search in the where
            $whereHTML = $whereHTML . "AND (UPPER(ms.Name) LIKE '%" . $searchPhrase . "%' " .
                                      "     OR UPPER(ms.Notes) LIKE '%" . $searchPhrase . "%' " .
                                      "     OR UPPER(ms.Location) LIKE '%" . $searchPhrase . "%') ";
        }
        
        // Determine if there is actually a sort passed in
        if ($inSortNumber!=""){
            // Determine which sort the person wants
            switch ($inSortNumber) {
                case 1:
                    // Sort as Category then name
                    $sort = "ms.Name, m.Category DESC, ms.Type DESC, ms.Amount, ms.LowReorderLevel, ms.Location ";

                    break;
                case 3:
                    // Sort as Location then name
                    $sort = "ms.Location, ms.Name, m.Category DESC, ms.Type DESC, ms.Amount, ms.LowReorderLevel ";

                    break;
                case 5:
                    // Sort as Name then Category
                    $sort = "m.Category DESC, ms.Name, ms.Type DESC, ms.Amount, ms.LowReorderLevel, ms.Location ";

                    break;
                case 10:
                    // Sort as Type then Category
                    $sort = "ms.Type DESC, ms.Name, m.Category DESC, ms.Amount, ms.LowReorderLevel, ms.Location ";

                    break;
                case 15:
                    // Sort as Amounte then Category
                    $sort = "ms.Amount, ms.Name, m.Category DESC, ms.Type DESC, ms.LowReorderLevel, ms.Location ";

                    break;
                case 20:
                    // Sort as Name then Category
                    $sort = "ms.LowReorderLevel, ms.Name, m.Category DESC, ms.Type DESC, ms.Amount, ms.Location ";

                    break;
                default:
                    // Sort as Category then name
                    $sort = "ms.Name, m.Category DESC, ms.Type DESC, ms.Amount, ms.LowReorderLevel, ms.Location ";

                    break;
            }
        }

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

                break;
        }
        
        // Get the category select drop down
        $materialCategorySelectHTML=getUsedMaterialTypeAsSelectOptions($db, $userRow, 'category', $category, 'javascript:CreateAndGotoSearchOptions();', '', true, false);

        // Get the type select drop down
        $materialSelectHTML=getUsedMaterialAsSelectOptions($db, $userRow, $materialID, 'javascript:CreateAndGotoSearchOptions();', '', true, false, 'materialID', '');

        // Initialize the return
        $result = 
            '
            <input type="hidden" id="sortNumber" name="sortNumber" value="' . $inSortNumber . '"/>
            <table style="width: 100%;"> 
                <tr style="width: 100%;"> 
                    <td style="width: 50%;">
                        Material Type: ' . $materialCategorySelectHTML . '  
                    </td> 
                    <td style="width: 50%;">
                        Material: ' . $materialSelectHTML . ' 
                    </td> 
                </tr>
                <tr>
                    <td style="width: 50%;" colspan=2>
                        <div style="text-align:left; margin-top: 8px;font-size: 90%; font-weight: normal; padding: 0px 7px 10px 0px;">
                            <label for="searchPhrase">Search Phrase: </label>
                            <input name="searchPhrase" id="searchPhrase" type="text" style="width: 70%;" value="' . htmlentities($searchPhrase, ENT_QUOTES) . '"/>
                            <input name="submitButton" id="submitButton" type="button" value="Search" title="Search the stock for a phrase." onclick="CreateAndGotoSearchOptions()" style="text-align:right;"/> 
                            <br>
                        </div>
                    </td> 
                </tr>
            </table>

            <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell nameCell" onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell locationCell" onclick="document.getElementById(\'sortNumber\').value=3; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Location</b></p>
                    </div>
                    <div class="cell catCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Category</b></p>
                    </div>
                    <div class="cell typeCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Type</b></p>
                    </div>
                    <div class="cell amountCell" onclick="document.getElementById(\'sortNumber\').value=15; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Amount</b></p>
                    </div>
                    <div class="cell llCell" onclick="document.getElementById(\'sortNumber\').value=20; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Low Level</b></p>
                    </div>' . 
                    $updateableTitleRowCellHTML . '
                </div>
            </li>';

        try {
            // Setup the query to be where they only get users in their company
            // and tasks that are NOT in stocked status
            $sql = 'SELECT ms.*, m.Category, m.MaterialRowColor, m.Name AS MaterialName  
                    FROM materialstock ms, 
                         material m 
                    LEFT OUTER JOIN 
                         (SELECT COUNT(*) AS AmountOnMaterialStock, MaterialID 
                          FROM materialstock GROUP BY MaterialID) msm ON m.MaterialID = msm.MaterialID ' .
                    $whereHTML . '
                    AND m.MaterialID = ms.MaterialID
                    ORDER BY ' . $sort . ';';
//var_dump($sql);
            
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "stocklist_presentation occurance 3");

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

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

                // Loop through the returned results
                $amount=0;
                $lastOneUpdated = '';
                while ($row=mysqli_fetch_array($rows)){
                    // Assign the delete button attributes as though deletion is an option
                    $deleteButtonTextColor = 'LIMEGREEN';
                    $deleteButtonTitle = 'Remove this stocked material.';
                    $deleteButtonOnClick = 'onclick="javascript:if (confirm(\'Are you sure you want to delete this stocked material?\')) ' .
                                           '{window.location=\'redirectors/delete_stocked_material.php?deleteStockedMaterialID=' . $row["MaterialStockID"] . '\';}"';

                    // Determine if this company is assigned to any tasks
                    if ($row["AmountUsedOnActiveTask"]!=null){
                        // Assign the delete buttons attributes such that deletion will not happen
                        $deleteButtonTextColor = 'RED';
                        $deleteButtonTitle = 'Check what active task this stock is used on.';
                        $deleteButtonOnClick = 'onclick="javascript:alert(\'This material stock is used on '. $row["AmountUsedOnActiveTask"] . 
                                               ' active tasks.\n\nWait until this material is no longer being used actively or change tasks ' . 
                                               'to reflect different stock.\');"';
                    }

                    // Determine if they are at a level to manage material stock
                    switch ($userRow["UserLevel"]){
                        case 'MID-MANAGEMENT':
                        case 'MANAGEMENT':
                        case 'EXECUTIVE':
                        case 'SU':
                            // Give the the delete option
                            $updateableMaterialRowCellHTML = '
                                <div class="cell updateCell">
                                    <span>
                                        <table>
                                            <tr>
                                                <td>
                                                    <input type="button" style="font-size:11px;" value="X" title="Remove this stocked material." ' . 
                                                    'onclick="window.location=\'redirectors/delete_stocked_material.php?deleteStockedMaterialID=' . 
                                                    $row["MaterialStockID"] . '\';"/>
                                                </td>
                                                <td>
                                                    <input type="button" style="font-size:11px;" value="..." title="Edit this material." ' . 
                                                    'onclick="javascript:window.open(\'updateStockedMaterial.php?updateStockedMaterialID=' . $row["MaterialStockID"] . '\', \'_blank\');"/>
                                                </td>
                                            </tr>
                                        </table>
                                    </span>
                                </div>
                                ';
                    }

                    // Increment the row
                    $amount++;

                    // Determine what color this row should be
                    $typeColor="#FFFFFF";
                    switch($row["Type"]){
                        case 'Tube':
                            $typeColor='#f47d42';
                            break;
                        case 'Round':
                            $typeColor='#ae82d8';
                            break;
                        case 'Plate':
                            $typeColor='#e585df';
                            break;
                        case 'Other':
                            $typeColor='#f7e7d7';
                            break;
                        case 'Extrusion':
                            $typeColor='#789a9e';
                            break;
                        case 'Cast':
                            $typeColor='#e8d08f';
                            break;
                        default:
                            $typeColor='#FFFFFF';
                            break;
                    }
                        
                    // Determine if the loop type is different than the last one
                    if ($loopToolCategory!=$row["Category"]){
                        // Determine if this is NOT the first type
                        if ($loopToolCategory!=''){
                            // Finish the last type div
                            $result = $result . '</DIV>';
                        }

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

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

                        // Set the name of the new type as the ID
                        $result = $result . '<DIV id="' . $id . '">';
                    }
                    
                    // Determine if the amount is lower than the low level
                    $alertBackground = '';
                    $alertBackgroundColor = '';
                    if ($row["Amount"]<=$row["LowReorderLevel"]){
                        // Add a border to the amount in question
                        $alertBackground = ' alertBackground';
                        $alertBackgroundColor='style="background-color: #FFFFFF"';
                    }
                    
                    // Determine if we have a location
                    $location='Not Entered';
                    if ($row["Location"]!=null && trim($row["Location"])!=''){
                        $location=$row["Location"];
                    }

                    // Add this option to the select
                    $result = $result .
                        '<li class="ui-state-default Table" >
                            <div class="Row" style="background-color: '. $row["MaterialRowColor"] . '; border-style: solid; border-color: BLACK;">
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div>
                                <div class="cell locationCell">
                                    <span>
                                        <p>' . $location . '</p>
                                    </span>
                                </div>
                                <div class="cell catCell">
                                    <span>
                                        <p>' . $row["Category"] . '</p>
                                    </span>
                                </div>
                                <div class="cell typeCell" style="background-color: '. $typeColor . ';">
                                    <span>
                                        <p>' . $row["Type"] . '</p>
                                    </span>
                                </div>
                                <div class="cell amountCell ' . $alertBackground . '" ' . $alertBackgroundColor . '>
                                    <span>
                                        <p>' . $row["Amount"] . ' ' . $row["Units"] . '</p>
                                    </span>
                                </div>
                                <div class="cell llCell">
                                    <span>
                                        <p>' . $row["LowReorderLevel"] . '</p>
                                    </span>
                                </div>' . 
                                $updateableMaterialRowCellHTML . '
                            </div>
                        </li>';

                    // Determine if the loop type is different than the last one
                    if ($loopToolCategory!=$row["Category"]){
                        // End the DIV Set the name of the type as the ID
                        $result = $result . '<DIV id="' . $loopToolCategory . '"';
                    }
                }
                
                // Determine if the loop did the loopty loop
                if ($loopToolCategory!=''){
                    // Finish the last type div
                    $result = $result . '</DIV>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

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