<?php    
    function retrieveCurrentNotes($db, $userRow, $inAssociatedCategoryID, $inCategoryType, &$validationHTML="", $allowSUCompanyDeletion=false){
        // Set the return result to nothing in case nothing is passed in for task number
        $result='';

        try {
            // Init necessary variables
            $associatedCategoryID=$inAssociatedCategoryID;
            $categoryType=$inCategoryType;

            // Determine if I am supposed to check for current notes or not
            if ($associatedCategoryID!=null && is_numeric($associatedCategoryID) &&
                $categoryType!=null){
                $levelsAllowedToSee='';

                // Determine if they want to see employee notes
                if ($categoryType=='EMPLOYEE'){
                    // Create condition that only the higher levels see lower levels notes
                    $levelsAllowedToSee = 'AND (u.UserLevel IN ('; 
                    switch ($userRow["UserLevel"]){
                        case 'SU':
                            // Allow SU's to See SU's and Exec's
                            $levelsAllowedToSee = $levelsAllowedToSee . '"SU", "EXECUTIVE", ';
                        case 'EXECUTIVE':
                            // Allow EXECUTIVE's to See MANAGEMENT's
                            $levelsAllowedToSee = $levelsAllowedToSee . '"MANAGEMENT", ';
                        case 'MANAGEMENT':
                            // Allow MANAGEMENT's to See MID-MANAGEMENT's
                            $levelsAllowedToSee = $levelsAllowedToSee . '"MID-MANAGEMENT", ';
                        case 'MID-MANAGEMENT' :
                            // Allow MID-MANAGEMENT's to See TYPICAL's
                            $levelsAllowedToSee = $levelsAllowedToSee . '"TYPICAL", ';
                        case 'TYPICAL' :
                            // Allow TYPICAL's to See MINIMAL's
                            $levelsAllowedToSee = $levelsAllowedToSee . '"MINIMAL") ' . 
                                          'OR n.EnteredByID = ' . $userRow["UserID"] . ') ';

                            // Exit from adding to the string, since minimal canot see anything
                            break;
                        case 'MINIMAL' :
                            // Allow these to see none
                            $levelsAllowedToSee = ' '; 
                    }
                }

                // Create the query to get the the notes and the user that created the notes
                $sql = 'SELECT n.*, u.FirstName, u.LastName, u.UserLevel ' .
                       'FROM notes n ' . 
                       'INNER JOIN users u ON n.EnteredByID = u.UserID ' .
                       'WHERE n.AssociatedCategoryID=' . $associatedCategoryID . ' ' .
                       $levelsAllowedToSee . ' AND n.Category="' . $categoryType . '" '. 
                       'AND n.IsSticky=0 ' .
                       'ORDER BY n.NoteOrder, n.Date DESC;';

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

                // Attempt to get all of the notes for this category type and ID
                $rows = $db->queryDB($sql, $userRow, "note_presentation Form occurance 1");

                // Determine if there were rows for the task(s)
                if ($rows != null && 
                    mysqli_num_rows($rows)>0){
                    // Init some variables
                    $notesIDArray=null;

                    // Reset the validation HTML
                    $validationHTML='';

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

                        // Set the things we can
                        $noteID = $row["NoteID"];
                        $noteOrder=$row["NoteOrder"];
                        $noteDate=$row["Date"];
                        $noteTitle = $row["Title"];
                        $note=$row["Note"];
                        $noteEnteredByID=$row["EnteredByID"];
                        $noteEnteredByFirstName = $row["FirstName"];
                        $noteEnteredByLastName = $row["LastName"];

                        // Start adding the notes that are in the database
                        $result = $result . 
                                    '   <div class="Table" id="currentNote' . $noteID . '" name="currentNote' . $noteID . '" style="margin-top:10px; border-top-style:dashed; border-width: 1px; text-align: left;">
                                            <div class="Row" id="noteEnteredByLineDiv' . $noteID . '" name="noteEnteredByLineDiv' . $noteID . '"> 
                                                <input type="hidden" name="enteredBy' . $noteID . '" id="enteredBy' . $noteID . '" value="' . $noteEnteredByID . '">
                                                <input type="hidden" name="noteID' . $noteID . '" id="noteID' . $noteID . '" value="' . $noteID . '">
                                                <input type="hidden" name="associatedCategoryID' . $noteID . '" id="associatedCategoryID' . $noteID . '" value="' . $associatedCategoryID . '">
                                                <input type="hidden" name="categoryType' . $noteID . '" id="categoryType' . $noteID . '" value="' . $categoryType . '">
                                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;">Created By:</label></div>
                                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;"><label style="width:100%;">' . $noteEnteredByFirstName . '  ' . $noteEnteredByLastName . '</label></div>
                                            </div>
                                            <div class="Row" id="NoteOrderLineDiv' . $noteID . '" name="NoteOrderLineDiv' . $noteID . '"> 
                                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;">Order:</label></div>
                                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;"><input style="width:100%;" type="text" maxlength="5" name="noteOrder' . $noteID . '" id="noteOrder' . $noteID . '" value="' . $noteOrder . '"/></div>
                                            </div>
                                            <div class="Row" id="noteDateLineDiv' . $noteID . '" name="noteDateLineDiv' . $noteID . '"> 
                                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;">Date:</label></div>
                                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;"><input style="width:100%;" type="datetime-local" name="noteDate' . $noteID . '" id="noteDate' . $noteID . '" value="' . str_replace(" ","T",$noteDate) . '"/></div>
                                            </div>
                                            <div class="Row" id="noteTitleLineDiv' . $noteID . '" name="noteTitleLineDiv' . $noteID . '"> 
                                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;">Title (required):</label></div>
                                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;"><input style="width:100%;" type="text" maxlength="25" name="noteTitle' . $noteID . '" id="noteTitle' . $noteID . '" value="' . $noteTitle . '"/></div>
                                            </div>
                                            <div class="Row" id="noteLineDiv' . $noteID . '" name="noteLineDiv' . $noteID . '"> 
                                                <div class="noteTableCell fullNoteLabelCell" style="width: 15%;"><label style="width:100%;">Note (required):</label></div>
                                                <div class="noteTableCell fullNoteTextCell" style="width: 85%;">
                                                    <textarea name="note' . $noteID . '" id="note' . $noteID . '" maxlength="4000" class="intext" style="width: 100%; height: 111px; overflow: auto; resize:none">' .
                                                    $note .
                                                    '</textarea>
                                                </div>
                                            </div>
                                    ';

                        // Get the size of the file
                        $fileSize = $row["ByteSize"]; 
                        $fname    = $row["FileName"]; 
                        $fileType = $row["FileType"]; 

                        //Init variables
                        $viewtag = '';
                        $removeNoteTag='';
                        $removeAttachmentTag=' 
                                        Replace Attachment
                                        <br>
                                        <input type="hidden" name="oversizedCurrentNote' . $noteID . '" id="oversizedCurrentNote' . $noteID . '" value=0></input>
                                        <input type="file" name="attachmentElementCurrentNote' . $noteID . '" id="attachmentElementCurrentNote' . $noteID . '" onChange="currentNoteAttachmentOnChange(' . $noteID . ');"></input>
                                     ';

                        // Determine if the user is an executive or not
                        if ($userRow["UserLevel"]=='SU' || ($allowSUCompanyDeletion && $userRow["CompanyID"]==1)){
                            $removeNoteTag = $removeNoteTag . '  
                                            <br>
                                            <label id="removeNoteLabel' . $noteID . '">Remove Note</label>
                                            <input class="notinput" type="checkbox" id="removeNote' . $noteID . '" name="removeNote' . $noteID . '" title="This being checked on update will remove the note." value="' . $noteID . '"></input>
                                         ';
                        }

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

                            // Determine if the user is an executive or not
                            if ($userRow["UserLevel"]=='SU' || ($allowSUCompanyDeletion && $userRow["CompanyID"]==1)){
                                $removeAttachmentTag = $removeAttachmentTag . '  
                                                <br>
                                                <label id="removeAttachmentLabel' . $noteID . '">Remove Attachment</label>
                                                <input class="notinput" type="checkbox" id="removeAttachment' . $noteID . '" name="removeAttachment' . $noteID . '" title="This being checked on update will remove the attachment." value="' . 
                                                $noteID . '"  onclick="javascript:div_toggleVisibilityOnCheckbox(\'removeAttachment' . $noteID . '\',\'imageCell' . $noteID . '\', \'OPPOSITE\');"></input>
                                             ';
                            }

                            // Add the attachment to the table
                            $result = $result .
                                '   <div class="Row" name="imageLineDiv' . $noteID . '" id="imageLineDiv' . $noteID . '">
                                        <div class="noteTableCell" style="width: 20%; text-align: left;"> ' . 
                                        $removeAttachmentTag .
                                        $removeNoteTag .
                                        '
                                        </div>
                                        <div class="noteTableCell" name="imageCell' . $noteID . '" id="imageCell' . $noteID . '" style="width: 80%; text-align: center;">
                                            ' . $fname . '
                                            <br>
                                            <a href="php_only_scripts/show_blob.php?id=' . $noteID . '&tbl=notes&idf=NoteID&bf=Datum&tyf=FileType&nmf=FileName&szf=ByteSize">Download</a>' .
                                            $viewtag . '
                                            <br>
                                            Type=' . $fileType . '  
                                            <br> 
                                            Size=' . $fileSize . ' KB
                                        </div>
                                    </div>';
                        }
                        else {
                            // Don't show anything about any attachment except adding one
                            $result = $result .
                                '   <div class="Row" name="imageLineDiv' . $noteID . '" id="imageLineDiv' . $noteID . '">
                                        <div class="noteTableCell" style="width: 20%; text-align: left;"> ' . 
                                        $removeAttachmentTag .
                                        $removeNoteTag .
                                        '
                                        </div>
                                        <div class="noteTableCell" name="imageCell' . $noteID . '" id="imageCell' . $noteID . '" style="width: 80%; text-align: center;">
                                        </div>
                                    </div>';
                        }

                        // Finish the tag
                        $result = $result . '</div>';

                        // Add something to the array list
                        $notesIDArray = $notesIDArray . $row["NoteID"] . '|';

                        // Add the validators for these
                        $validationHTML = $validationHTML . '
                                            frmvalidator.addValidation("noteTitle' . $noteID . '",
                                                                       "req",
                                                                       "Please enter a title for all notes.");
                                            frmvalidator.addValidation("note' . $noteID . '",
                                                                       "req",
                                                                       "Please enter note text for all.");
                                            frmvalidator.addValidation("noteOrder' . $noteID . '",
                                                                       "req",
                                                                       "Please enter an order for all notes.");
                                            frmvalidator.addValidation("noteOrder' . $noteID . '",
                                                                       "num",
                                                                       "Please enter the order for all notes as a number.");
                                            frmvalidator.addValidation("noteOrder' . $noteID . '",
                                                                       "greaterthan=-.0000000001",
                                                                       "The order for all blanks should be greater than 0.");
                                        ';

                    }

                    // Add the hidden field to the form
                    $result = 
                            '<label  style="font-size: 20px;"><strong>Current Notes: </strong></label>
                             <div id="currentNotesDiv" style="">
                                 <input type="hidden" name="currentNotesArray" id="currentNotesArray" value="' . $notesIDArray . '"></input>
                                 <input type="hidden" name="deleteCurrentNotes" id="deleteCurrentNotes" value=""></input>
                                 ' .
                                 $result .
                            '</div>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return the created HTML
        return $result;
    }

    function updateOldNotes($db, $userRow){
        // Determine if there are current notes to look at
        if (isset($_POST['currentNotesArray']) and $_POST['currentNotesArray']!=0){
            // Remove the last delimiter
            $numbersToRemoveAsString = substr($_POST['currentNotesArray'], 0, -1);

            // Get the amount of current notes as a variable
            $notesNums=explode('|', $numbersToRemoveAsString);

            // Loop through and get all new note elements
            foreach ($notesNums as $loopNumber){
                // Get the value of the not removal flag
                $removeNote = (isset($_POST['removeNote'.$loopNumber])?1:0);

                // Determine if we are removing this note
                if ($removeNote){
                    // Let's create a query to delete the note
                    $sql='DELETE FROM notes WHERE NoteID=' . $loopNumber . ';';
                }
                else {
                    $noteOrder=htmlspecialchars($_POST['noteOrder'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $noteDate=htmlspecialchars($_POST['noteDate'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $noteTitle=htmlspecialchars($_POST['noteTitle'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $note=htmlspecialchars($_POST['note'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $fname    = null; 
                    $fileSize = null; 
                    $fileType = null; 
                    $content  = null;
                    $oversized = htmlspecialchars($_POST['oversizedCurrentNote'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $removeAttachment = (isset($_POST['removeAttachment'.$loopNumber])?1:0);
                    $fileSQL = '';

                    // determine if they are asking to remove the image
                    if($removeAttachment) {
                        // Set the values for removal of the file for now
                        $fileSQL = ',FileName=null ,ByteSize=null ,FileType=null,Datum=null';
                    }
                    elseif (!$oversized && is_uploaded_file($_FILES['attachmentElementCurrentNote'.$loopNumber]['tmp_name'])) {
                        // Get the properties of the file to upload
                        $fname    = $db->getDBConnection()->real_escape_string($_FILES['attachmentElementCurrentNote'.$loopNumber]['name']); 
                        $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['attachmentElementCurrentNote'.$loopNumber]['tmp_name']);
                        $fileSize = intval($_FILES['attachmentElementCurrentNote'.$loopNumber]['size']);
                        $fileType = $db->getDBConnection()->real_escape_string($_FILES['attachmentElementCurrentNote'.$loopNumber]['type']);

                        // Determine if the file size is such that the database han handle storing it. The database can handle 4GB (4,294,967,296 Bytes)
                        if ($fileSize < 4294967296){
                            //process the file
                            $content = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));

                            // Determine if we got any data
                            if ($content!=null) {
                                // Determine if the magic quotes option is on
                                if(!get_magic_quotes_gpc()){
                                    // Add slashes to the name
                                    $fname = addslashes($fname);
                                }

                                // Create the file sqlpart of this
                                if ($fname!=null) {$fileSQL = $fileSQL . ',FileName="' . $fname . '"';}
                                if ($fileSize!=null) {$fileSQL = $fileSQL . ',ByteSize="' . $fileSize . '"';}
                                if ($fileType!=null) {$fileSQL = $fileSQL . ',FileType="' . $fileType . '"';}
                                if ($content!=null) {$fileSQL = $fileSQL . ',Datum="' . $content . '"';}
                            }
                        }
                        else {
                            // Let the user know the file was NOT uploaded
                            echo("The file ('" . $fname . "') will not be uploaded, because it is too large. File must be under 4GB. Old file (if any) will remain.");
                        }
                    }   

                    // Let's create the update query off of what we have
                    $sql='UPDATE notes SET ';
                    if ($noteOrder!=null) {$sql = $sql . 'NoteOrder=' . $noteOrder;}
                    if ($noteDate!=null) {$sql = $sql . ', Date="' . $noteDate . '"';}
                    if ($noteTitle!=null) {$sql = $sql . ', Title="' . $noteTitle . '"';}
                    if ($note!=null) {$sql = $sql . ',Note="' . $note . '"';}
                    if ($fileSQL!="") {$sql = $sql . $fileSQL;}
                    if ($associatedCategoryID!=null) {$sql = $sql . ',AssociatedCategoryID=' . $associatedCategoryID;}
                    $sql=$sql .' WHERE NoteID=' . $loopNumber . ';';
                }

                // Attempt to run the query and get the response
                if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 2.")){
                }
            }
        }
    }

    function addNewNotesToDB($db, $userRow, $associatedCategoryID, $enteredBy, $category){
        // Determine if there are new notes
        if (isset($_POST['newNoteNumbers']) && $_POST['newNoteNumbers']!=0){
            // Get the amount of new notes as a variable
            $noteNumStrings=$_POST['newNoteNumbers'];
            $noteNums=explode('|', $noteNumStrings);

            // Loop through and get all new note elements
            foreach ($noteNums as $loopNumber){
                // Get the posted items that I am worried about
                $noteOrder=htmlspecialchars($_POST['newNoteOrder'.$loopNumber], ENT_QUOTES, 'UTF-8');
                $noteDate=htmlspecialchars($_POST['newNoteDate'.$loopNumber], ENT_QUOTES, 'UTF-8');
                $noteTitle=htmlspecialchars($_POST['newNoteTitle'.$loopNumber], ENT_QUOTES, 'UTF-8');
                $note=htmlspecialchars($_POST['newNote'.$loopNumber], ENT_QUOTES, 'UTF-8');
                $fname    = null; 
                $fileSize = null; 
                $fileType = null; 
                $content  = null;
                $oversized = htmlspecialchars($_POST['oversized'.$loopNumber], ENT_QUOTES, 'UTF-8');

                // determine if the image has been uploaded
                if(!$oversized && is_uploaded_file($_FILES['newNoteAttachmentElement'.$loopNumber]['tmp_name'])) {
                    // Get the properties of the file to upload
                    $fname    = $db->getDBConnection()->real_escape_string($_FILES['newNoteAttachmentElement'.$loopNumber]['name']); 
                    $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['newNoteAttachmentElement'.$loopNumber]['tmp_name']);
                    $fileSize = intval($_FILES['newNoteAttachmentElement'.$loopNumber]['size']);
                    $fileType = $db->getDBConnection()->real_escape_string($_FILES['newNoteAttachmentElement'.$loopNumber]['type']);

                    // Determine if the file size is such that the database han handle storing it. The database can handle 4GB (4,294,967,296 Bytes)
                    if ($fileSize < 4294967296){
                        //process the file
                        $content = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));

                        // Determine if we got any data
                        if ($content!=null) {
                            // Determine if the magic quotes option is on
                            if(!get_magic_quotes_gpc()){
                                // Add slashes to the name
                                $fname = addslashes($fname);
                            }
                        }
                    }
                    else {
                        // reset all values to nothing
                        $fname    = null; 
                        $fileSize = null; 
                        $fileType = null; 
                        $content  = null;

                        // Let the user know the file was NOT uploaded
                        echo("The file ('" . $fname . "') will not be uploaded, because it is too large. File must be under 4GB.");
                    }
                }   

                // Let's create the insert query off of what we have
                $sql='INSERT INTO notes (';
                if ($noteOrder!=null) {$sql = $sql . 'NoteOrder';}
                if ($noteDate!=null) {$sql = $sql . ', Date';}
                if ($noteTitle!=null) {$sql = $sql . ', Title';}
                if ($note!=null) {$sql = $sql . ',Note';}
                if ($fname!=null) {$sql = $sql . ',FileName';}
                if ($fileSize!=null) {$sql = $sql . ',ByteSize';}
                if ($fileType!=null) {$sql = $sql . ',FileType';}
                if ($content!=null) {$sql = $sql . ',Datum';}
                if ($associatedCategoryID!=null) {$sql = $sql . ',AssociatedCategoryID';}
                if ($enteredBy!=null) {$sql = $sql . ', EnteredByID';}
                if ($category!=null) {$sql = $sql . ', Category';}
                $sql=$sql .') VALUES (';
                if ($noteOrder!=null) {$sql = $sql . $noteOrder;}
                if ($noteDate!=null) {$sql = $sql . ', "' . $noteDate . '"';}
                if ($noteTitle!=null) {$sql = $sql . ', "' . $noteTitle . '"';}
                if ($note!=null) {$sql = $sql . ', "' . $note . '"';}
                if ($fname!=null) {$sql = $sql . ', "' . $fname . '"';}
                if ($fileSize!=null) {$sql = $sql . ', "' . $fileSize . '"';}
                if ($fileType!=null) {$sql = $sql . ', "' . $fileType . '"';}
                if ($content!=null) {$sql = $sql . ', "' . $content . '"';}
                if ($associatedCategoryID!=null) {$sql = $sql . ', ' . $associatedCategoryID . ' ';}
                if ($enteredBy!=null) {$sql = $sql . ', ' . $enteredBy . ' ';}
                if ($category!=null) {$sql = $sql . ', "' . $category . '" ';}
                $sql=$sql .');';

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

                // Attempt to run the query and get the response
                if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 3.")){
                }
            }
        }
    }

    function retrieveNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $includeCheckbox=true, &$validationHTML="", $allowSUCompanyDeletion=false){
        // Get any current notes
        $results=retrieveCurrentNotes($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $validationHTML="", $allowSUCompanyDeletion);

        // Determine if we added some notes
        $noteColorHtml = '';
        if ($results != '') {
            // Change the color of the Notes Title font
            $noteColorHtml = 'style="color:LimeGreen;"';
        }

        if ($includeCheckbox){
            // Init all of the settings to the appropriate values as though there is a checkbox
            $noteDiv = '
                            <input name="hideNotes" id="hideNotes" class="notinput" type="checkbox" onclick="javascript:div_toggleVisibilityOnCheckbox(\'hideNotes\',\'notes\', \'NORMAL\');"></input>
                            <strong><label for="hideNotes" ' . $noteColorHtml . '>Notes </label></strong>
                            <div id="notes" style="display: none; font-weight: bold; font-size: 12px; width: 100%;">
                                <table width="100%">
                                    <tr width="100%">
                                        <td align="left" width="50%">
                                            <label style="font-size: 20px;"><strong>New Notes: </strong></label>
                                        </td>
                                        <td align="right" width="50%">
                                            <input type="hidden" id="newNoteNumbers" name="newNoteNumbers" value="0"></input>
                                            <button type="button" onClick="addNewNote(\'USER\'); if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};" align="right">Add New Note</button>
                                        </td>
                                    </tr>
                                </table>
                                <div id="newNotes" style="border-top-style:dashed; border-width: 1px; ">
                                </div>
                                ' .
                                $results .
                            '</div>
                        ';
        }
        else {
            // Init all of the settings to the appropriate values as though it is a tab
            $noteDiv = '
                            <div id="NotesInfo" class="childtabcontent" style="display: none;">
                                <br><br>
                                <label style="font-size: 20px;"><strong>New Notes: </strong></label>
                                <div id="newNotes" style="">
                                </div>
                                <p align="right" style="border-top-style:dashed; border-width: 1px; font-weight: bold;font-size: 12px;">
                                    <input type="hidden" id="newNoteNumbers" name="newNoteNumbers" value="0"></input>
                                    <button type="button" onClick="addNewNote(\'USER\'); if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};" align="right">Add New Note</button>
                                </p>' .
                                $results .
                                '
                            </div>
                        ';
        }

        // Return the result
        return $noteDiv;
    }

    function retrieveStickyNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $includeCheckbox=true, &$validationHTML="", $visibility='ReadCheckboxOnly'){
        // Get any current notes
        $results=viewAllStickyNoteContent($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $visibility, $validationHTML);

        // Determine if we added some notes
        $noteColorHtml = '';
        if ($results != '') {
            // Change the color of the Notes Title font
            $noteColorHtml = 'style="color:LimeGreen;"';
        }

        if ($includeCheckbox){
            // Init all of the settings to the appropriate values as though there is a checkbox
            $noteDiv = createStickyNoteEmployeesInnerHTML($db, $userRow, false) .
                       '
                            <input name="hideStickyNotes" id="hideStickyNotes" class="notinput" type="checkbox" onclick="javascript:div_toggleVisibilityOnCheckbox(\'hideStickyNotes\',\'stickyNotes\', \'NORMAL\');"></input>
                            <strong><label for="hideStickyNotes" ' . $noteColorHtml . '>Sticky Notes </label></strong>
                            <div id="stickyNotes" style="display: none; font-weight: bold; font-size: 12px; width: 100%;">
                                <table width="100%">
                                    <tr width="100%">
                                        <td align="left" width="50%">
                                            <label style="font-size: 20px;"><strong>New Sticky Notes: </strong></label>
                                        </td>
                                        <td align="right" width="50%">
                                            <input type="hidden" id="newStickyNoteNumbers" name="newStickyNoteNumbers" value="0"></input>
                                            <button type="button" onClick="console.log(addNewStickyNote(\'TASK\')); if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};" align="right">Add New Sticky Note</button>
                                        </td>
                                    </tr>
                                </table>
                                <div id="newStickyNotes" style="border-top-style:dashed; border-width: 1px; ">
                                </div>
                                ' .
                                $results .
                            '</div>
                        ';
        }
        else {
            // Init all of the settings to the appropriate values as though it is a tab
            $noteDiv = createStickyNoteEmployeesInnerHTML($db, $userRow, false) .
                       '
                            <div id="StickyNotesInfo">
                                <label style="font-size: 20px;"><strong>New Sticky Notes: </strong></label>
                                <div id="newStickyNotes" style="">
                                </div>
                                <p align="right" style="border-top-style:dashed; border-width: 1px; font-weight: bold;font-size: 12px;">
                                    <input type="hidden" id="newStickyNoteNumbers" name="newStickyNoteNumbers" value="0"></input>
                                    <button type="button" onClick="console.log(addNewStickyNote(\'TASK\')); if (typeof _isDirty !== \'undefined\' && _isDirty !== null) {_isDirty=true;};" align="right">Add New Sticky Note</button>
                                </p>' .
                                $results .
                                '
                            </div>
                        ';
        }

        // Return the result
        return $noteDiv;
    }

    function checkThenGetStickyNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, &$validationHTML=""){
        // Init all of the settings to the appropriate values
        $noteDiv = '';

        // Determine if the user editing this is part of the SU company
        if ($userRow["CompanyID"]==1)
        {
            // get the div
            $noteDiv = retrieveStickyNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, false, $validationHTML, 'All');
        }

        // Return the result
        return $noteDiv;
    }

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

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

            // Add the Everyone to the select
            $result=$result . '<option value="-1">Everybody</option>';
                    
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "tasks_presentation Form occurance 10");

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

                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Add this option to the select
                    $result=$result . '<option value="' . $row["UserID"] . '">' . $row["UserName"] . ' (' . $row["FirstName"] . '  ' . $row["LastName"] . ')</option>';
                }
            }
            
            $result = '
                <table width="100%" border="0">
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label for="stickyNoteTitle">Title:</label></strong>
                            <input type="text" maxlength="25" name="stickyNoteTitle" id="stickyNoteTitle" style="width:90%;" value=""/>
                        </td>
                        <td>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <strong>Choose the Recipients: </strong>
                            <br>
                            <select name="stickyNoteTo" id="stickyNoteTo" multiple style="height: 310px;" title="ctrl-click to select mutiple recipients.">
                            ' . 
                            $result . ' 
                            </select>
                        </td>
                        <td height="39" align="left" style="width:400px;">
                            <strong>Note Content: </strong>
                            <br>
                            <textarea name="stickyNoteContent" id="stickyNoteContent" maxlength="2000" style="width: 100%; height: 310px; overflow: auto; resize:none" value=""/></textarea>
                        </td>
                    </tr>
                    <!-- TODO: For now, I cannot figure out how to submit an image through ajax. Come back to this.
                    <tr>
                        <td>
                        </td>
                        <td height="39" align="left" colspan=2>
                            <strong>Image: </strong>
                            <br>
                            <input type="file" name="stickyNoteImage" id="stickyNoteImage"></input>
                        </td>
                    </tr>
                    -->
                </table>
                ';
        } catch (Exception $ex) {
            // Return nothing
            return "";
        }

        // Return whatever we got
        return $result;
    }
                                      
    function viewAllStickyNoteContent($db, $userRow, $inAssociatedCategoryID, $inCategoryType, $area="ViewOnly", &$validationHTML=""){
        // Set the return result to nothing in case nothing is passed in for task number
        $result='';
        $tabs='';

        try {
            // Init necessary variables
            $associatedCategoryID=$inAssociatedCategoryID;
            $categoryType=$inCategoryType;
            $notesIDArray=null;

            // Determine if we have enough to check for sticky notes
            if ($associatedCategoryID!=null && is_numeric($associatedCategoryID) &&
                $categoryType!=null){

                // Create the query to get the the notes and the user that created the notes
                $sql = 'SELECT n.*, u.FirstName, u.LastName, u.UserLevel, IF(unr.UsersNotRead IS NULL, "NONE", unr.UsersNotRead) AS UsersNotRead, umf.UsersMeantFor, ' .
                       '       (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 ' . 
                       'INNER JOIN users u ON n.EnteredByID = u.UserID ' .
                       'LEFT JOIN (SELECT snu.NoteID, ' .
                       '           GROUP_CONCAT(DISTINCT u2.UserName ORDER BY u2.UserName SEPARATOR", ") AS UsersNotRead ' .
                       '           FROM stickynoteusers snu ' .
                       '           LEFT JOIN users u2 ON snu.SendToID = u2.UserID ' .
                       '           WHERE snu.MarkedAsRead=0 ' .
                       '           GROUP BY snu.NoteID) unr ON n.NoteID = unr.NoteID ' .
                       'LEFT JOIN (SELECT snu2.NoteID, ' .
                       '           GROUP_CONCAT(DISTINCT u3.UserName ORDER BY u3.UserName SEPARATOR", ") AS UsersMeantFor ' .
                       '           FROM stickynoteusers snu2 ' .
                       '           LEFT JOIN users u3 ON snu2.SendToID = u3.UserID ' .
                       '           GROUP BY snu2.NoteID) umf ON n.NoteID = umf.NoteID ' .
                       'WHERE n.AssociatedCategoryID=' . $associatedCategoryID . ' ' .
                       'AND n.Category="' . $categoryType . '" '. 
                       'AND n.IsSticky=1 ' .
                       'AND (n.EnteredByID=' . $userRow["UserID"] . ' OR UsersMeantFor LIKE "%' . $userRow["UserName"] . '%") ' .
                       'ORDER BY n.Date DESC;';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
                
                // Attempt to get all of the notes for this category type and ID
                $rows = $db->queryDB($sql, $userRow, "note_presentation Form occurance 11");

                // Determine if there were rows for the task(s)
                if ($rows != null && 
                    mysqli_num_rows($rows)>0){
                    // Reset the validation HTML
                    $validationHTML='';
                    
// TODO: Attempt to add percentage tabs.
//                    // Count the number of rows
//                    $numberOfStickyNotes=mysqli_num_rows($rows);
//
//                    // Create a tab size
//                    $tabPercentage=floor(600/($numberOfStickyNotes+1));

                    // Loop through the returned results
                    $amount=0;
                    while ($row=mysqli_fetch_array($rows)){
                        // Set the things we can
                        $noteID = $row["NoteID"];
                        $noteDate=$row["Date"];
                        $noteTitle = $row["Title"];
                        $note=$row["Note"];
                        $noteEnteredByID=$row["EnteredByID"];
                        $noteEnteredByFirstName = $row["FirstName"];
                        $noteEnteredByLastName = $row["LastName"];

                        // Increment the amount
                        $amount++;

                        // Init some variables
                        $mostEnabledHTML='disabled';
                        $noteReadEnabledHTML='disabled';

                        // Lets determine what it is being used for
                        switch ($area) {
                            case "ViewOnly":
                                $mostEnabledHTML='disabled';
                                $noteReadEnabledHTML='disabled';

                                break;

                            case "ReadCheckboxOnly":
                                $mostEnabledHTML='disabled';
                                $noteReadEnabledHTML='';

                                break;

                            case "All":
                                $mostEnabledHTML='';
                                $noteReadEnabledHTML='';

                                break;

                            default:
                                break;
                        }

                        // Determine if this note was made by me
                        $markAllAsReadHTML='';
                        $tabWordColorClass='childtablinkblack';
                        $tabTitle='This sticky note has been read by everyone.';
                        if ($noteEnteredByID==$userRow["UserID"]) {
                            
                            // Now see if there are any notes not read by recipients
                            if ($row["AmountNotReadByEveryone"]>0){
                                // Enable the note areas, so he can modify his note
                                $mostEnabledHTML='';

                                // Set the word color to green
                                $tabWordColorClass='childtablinkgreen';
                                
                                // Set the title to reflect information on it
                                $tabTitle='This sticky note was sent by you and has has not been read by all recipients.';
                        
                                // Add a checkbox to mark all people as read for the note
                                $markAllAsReadHTML = '  
                                               <div class="Row" id="stickyNoteNotReadByOthersCheckboxDiv' . $noteID . '" name="stickyNoteNotReadByOthersCheckboxDiv' . $noteID . '"> 
                                                   <div class="noteTableCell fullNoteLabelCell" style="width: 25%;">
                                                       <label id="markAllAsReadLabel' . $noteID . '">Mark ALL As Read: </label>
                                                   </div>
                                                   <div class="noteTableCell fullNoteTextCell" style="width: 75%;">
                                                       <input class="notinput" type="checkbox" id="markAllStickyNotesAsRead' . $noteID . '" name="markAllStickyNotesAsRead' . $noteID . '" title="Checking this will marked everyone the note was for as read this note.  Including yourself."></input>
                                                   </div>
                                               </div>
                                             ';
                            }
                        }
                        
                        // Determine if this note needs to be read by me
                        $markReadByMeHTML='';
                        if ($row["AmountNotReadByMe"]>0){
                            // Set the word color to red
                            $tabWordColorClass='childtablinkred';

                            // Set the title to reflect information on it
                            $tabTitle='This sticky note is meant for you and you have not marked it as read.';

                            // Add a checkbox to mark all people as read for the note
                            $markReadByMeHTML = '  
                                           <div class="Row" id="stickyNoteReadByMeCheckboxDiv' . $noteID . '" name="stickyNoteReadByMeCheckboxDiv' . $noteID . '"> 
                                               <div class="noteTableCell fullNoteLabelCell" style="width: 25%;">
                                                   <label id="markStickyNoteAsReadByMeLabel' . $noteID . '">Mark As Read By Me: </label>
                                               </div>
                                               <div class="noteTableCell fullNoteTextCell" style="width: 75%;">
                                                   <input class="notinput" type="checkbox" id="markStickyNoteAsReadByMe' . $noteID . '" name="markStickyNoteAsReadByMe' . $noteID . '" title="Checking this will set this note as being read by you."></input>
                                               </div>
                                           </div>
                                         ';
                        }
                        
                        // Start the tabs
                        $tabs = $tabs . '
                                <button class="childtablink ' . $tabWordColorClass . '" title="' . $tabTitle . '" type="button" onclick="openChildPage(\'stickyNote' .$amount . '\', this);"id="stickyNoteTabButton' . $amount . '">' . $amount . ' (' . $noteDate . ')</button>';          
                        
                        // Start adding the notes that are in the database
                        $result = $result . 
                                    '<div id="stickyNote' . $amount . '" class="childtabcontent" style="display:block; border-top: 2px solid forestgreen;">
                                        <div class="Table" id="currentStickyNote' . $noteID . '" name="currentStickyNote' . $noteID . '" style="text-align: left; width:700;">
                                           <div class="Row" id="stickyNoteEnteredByLineDiv' . $noteID . '" name="stickyNoteEnteredByLineDiv' . $noteID . '"> 
                                               <input type="hidden" name="stickyNoteEnteredBy' . $noteID . '" id="stickyNoteEnteredBy' . $noteID . '" value="' . $noteEnteredByID . '">
                                               <input type="hidden" name="stickyNoteID' . $noteID . '" id="stickyNoteID' . $noteID . '" value="' . $noteID . '">
                                               <input type="hidden" name="stickyNoteAssociatedCategoryID' . $noteID . '" id="stickyNoteAssociatedCategoryID' . $noteID . '" value="' . $associatedCategoryID . '">
                                               <input type="hidden" name="stickyNoteCategoryType' . $noteID . '" id="stickyNoteCategoryType' . $noteID . '" value="' . $categoryType . '">
                                               <div class="noteTableCell fullNoteLabelCell" style="width: 25%;"><label style="width:20%;">Created By:</label></div>
                                               <div class="noteTableCell fullNoteTextCell" style="width: 75%;"><label style="width:90%;">' . $noteEnteredByFirstName . '  ' . $noteEnteredByLastName . '</label></div>
                                           </div>
                                           <div class="Row" id="stickyNoteDateLineDiv' . $noteID . '" name="stickyNoteDateLineDiv' . $noteID . '"> 
                                               <div class="noteTableCell fullNoteLabelCell" style="width: 25%;"><label style="width:20%;">Date Added:</label></div>
                                               <div class="noteTableCell fullNoteTextCell" style="width: 75%;"><input style="width:90%;" type="datetime-local" name="stickyNoteDate' . $noteID . '" id="stickyNoteDate' . $noteID . '" disabled value="' . str_replace(" ","T",$noteDate) . '"/></div>
                                           </div>
                                           <div class="Row" id="stickyNoteTitleLineDiv' . $noteID . '" name="stickyNoteTitleLineDiv' . $noteID . '"> 
                                               <div class="noteTableCell fullNoteLabelCell" style="width: 25%;"><label style="width:20%;">Title (required):</label></div>
                                               <div class="noteTableCell fullNoteTextCell" style="width: 75%;"><input style="width:90%;" type="text" maxlength="25" name="stickyNoteTitle' . $noteID . '" id="stickyNoteTitle' . $noteID . '" ' . $mostEnabledHTML . ' value="' . $noteTitle . '"/></div>
                                           </div>
                                           <div class="Row" id="stickyNoteLineDiv' . $noteID . '" name="stickyNoteLineDiv' . $noteID . '"> 
                                               <div class="noteTableCell fullNoteLabelCell" style="width: 25%;"><label style="width:20%;">Note (required):</label></div>
                                               <div class="noteTableCell fullNoteTextCell" style="width: 75%;">
                                                   <textarea name="stickyNote' . $noteID . '" id="stickyNote' . $noteID . '" maxlength="2000" class="intext" style="width: 90%; height: 111px; overflow: auto; resize:none" ' . $mostEnabledHTML . '>' .
                                                   $note .
                                                   '</textarea>
                                               </div>
                                           </div>
                                           ' . $markReadByMeHTML . '
                                           ' . $markAllAsReadHTML . '
                                           <div class="Row"> 
                                               <div class="noteTableCell fullNoteLabelCell" style="width: 25%;">
                                                   <label id="usersNotReadLabel1' . $noteID . '">Users Unread: </label>
                                               </div>
                                               <div class="noteTableCell fullNoteTextCell" style="width: 75%;">
                                                   <label id="usersNotReadLabel2' . $noteID . '">&nbsp;' . $row["UsersNotRead"] . '</label>
                                               </div>
                                           </div>
                                    ';

                        //Init variables
                        $viewtag = '';
                        $removeNoteTag='';
                        $removeAttachmentTag='';
                        
                        // Get the file information
                        $fileSize = $row["ByteSize"]; 
                        $fname    = $row["FileName"]; 
                        $fileType = $row["FileType"]; 

                        //Init variables
                        $removeAttachmentTag=' 
                                        <input type="hidden" name="oversizedCurrentStickyNote' . $noteID . '" id="oversizedCurrentStickyNote' . $noteID . '" value=0></input>
                                     ';
                        if ($area==='All'){
                            //Init variables
                            $removeAttachmentTag=' 
                                            Replace Attachment
                                            <br>
                                            <input type="hidden" name="oversizedCurrentStickyNote' . $noteID . '" id="oversizedCurrentStickyNote' . $noteID . '" value=0></input>
                                            <input type="file" name="attachmentElementCurrentStickyNote' . $noteID . '" id="attachmentElementCurrentStickyNote' . $noteID . '" onChange="currentStickyNoteAttachmentOnChange(' . $noteID . ');"></input>
                                         ';
                            
                            // Determine if the user is an su or not
                            if ($userRow["UserLevel"]=='SU'){
                                $removeNoteTag = $removeNoteTag . '  
                                                <br>
                                                <label id="removeStickyNoteLabel' . $noteID . '">Remove Sticky Note</label>
                                                <input class="notinput" type="checkbox" id="removeStickyNote' . $noteID . '" name="removeStickyNote' . $noteID . '" title="This being checked on update will remove the note." value="' . $noteID . '"></input>
                                             ';
                            }
                        }
                        

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

                            // Determine if the user is an su or not
                            if ($userRow["UserLevel"]=='SU' && $area==='All'){
                                $removeAttachmentTag = $removeAttachmentTag . '  
                                                <br>
                                                <label id="removeStickyAttachmentLabel' . $noteID . '">Remove Attachment</label>
                                                <input class="notinput" type="checkbox" id="removeStickyNoteAttachment' . $noteID . '" name="removeStickyNoteAttachment' . $noteID . '" title="This being checked on update will remove the attachment." value="' . 
                                                $noteID . '"  onclick="javascript:div_toggleVisibilityOnCheckbox(\'removeStickyNoteAttachment' . $noteID . '\',\'imageCell' . $noteID . '\', \'OPPOSITE\');"></input>
                                             ';
                            }

                            // Add the attachment to the table
                            $result = $result .
                                '   <div class="Row" name="imageLineDiv' . $noteID . '" id="imageLineDiv' . $noteID . '">
                                        <div class="noteTableCell" style="width: 20%; text-align: left;"> ' . 
                                        $removeAttachmentTag .
                                        $removeNoteTag .
                                        '
                                        </div>
                                        <div class="noteTableCell" name="imageCell' . $noteID . '" id="imageCell' . $noteID . '" style="width: 80%; text-align: center;">
                                            ' . $fname . '
                                            <br>
                                            <a href="php_only_scripts/show_blob.php?id=' . $noteID . '&tbl=notes&idf=NoteID&bf=Datum&tyf=FileType&nmf=FileName&szf=ByteSize">Download</a>' .
                                            $viewtag . '
                                            <br>
                                            Type=' . $fileType . '  
                                            <br> 
                                            Size=' . $fileSize . ' KB
                                        </div>
                                    </div>';
                        }
                        else {
                            // Don't show anything about any attachment except adding one
                            $result = $result .
                                '   <div class="Row" name="imageLineDiv' . $noteID . '" id="imageLineDiv' . $noteID . '">
                                        <div class="noteTableCell" style="width: 20%; text-align: left;"> ' . 
                                        $removeAttachmentTag .
                                        $removeNoteTag .
                                        '
                                        </div>
                                        <div class="noteTableCell" name="imageCell' . $noteID . '" id="imageCell' . $noteID . '" style="width: 80%; text-align: center;">
                                        </div>
                                    </div>';
                        }

                        // Finish the tags
                        $result = $result . '</div></div>';

                        // Add something to the array list
                        $notesIDArray = $notesIDArray . $row["NoteID"] . '|';

                        // Add the validators for these
                        $validationHTML = $validationHTML . '
                                            frmvalidator.addValidation("stickyNoteTitle' . $noteID . '",
                                                                       "req",
                                                                       "Please enter a title for all sticky notes.");
                                            frmvalidator.addValidation("stickyNote' . $noteID . '",
                                                                       "req",
                                                                       "Please enter sticky note text for all.");
                                        ';

                    }

                    // Add the hidden field to the form
                    $result = 
                            '<label  style="font-size: 20px;"><strong>Current Sticky Notes: </strong></label>
                             <div id="currentNotesDiv" style="">
                                 <input type="hidden" name="currentStickyNotesArray" id="currentStickyNotesArray" value="' . $notesIDArray . '"></input>
                                 <input type="hidden" name="deleteStickyCurrentNotes" id="deleteStickyCurrentNotes" value=""></input>
                                 ' .
                                 $tabs .
                                 $result .
                            '</div>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return the created HTML
        return $result;
    }
    
    function updateOldStickyNotes($db, $userRow){
        // Determine if there are current notes to look at
        if (isset($_POST['currentStickyNotesArray']) and $_POST['currentStickyNotesArray']!=0){
            // Remove the last delimiter
            $numbersToRemoveAsString = substr($_POST['currentStickyNotesArray'], 0, -1);

            // Get the amount of current notes as a variable
            $notesNums=explode('|', $numbersToRemoveAsString);

            // Loop through and get all old sticky note elements
            foreach ($notesNums as $loopNumber){
                // Get the value of the note removal flag
                $removeNote = (isset($_POST['removeStickyNote'.$loopNumber])?1:0);

                // Determine if we are removing this note
                if ($removeNote){
                    // Let's create a query to delete the note
                    $sql='DELETE FROM notes WHERE NoteID=' . $loopNumber . ';';
                    
                    // Attempt to run the query and get the response
                    if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 12.")){
                        // since we are successful, we need to remove all users attached to this sticky note
                        $sql='DELETE FROM stickynoteusers WHERE NoteID=' . $loopNumber . ';';
                    
                        // Attempt to run the query and get the response
                        if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 13.")){
                        }
                    }
                }
                else {
                    $noteDate=htmlspecialchars($_POST['stickyNoteDate'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $noteTitle=htmlspecialchars($_POST['stickyNoteTitle'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $note=htmlspecialchars($_POST['stickyNote'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $fname    = null; 
                    $fileSize = null; 
                    $fileType = null; 
                    $content  = null;
                    $oversized = htmlspecialchars($_POST['oversizedCurrentStickyNote'.$loopNumber], ENT_QUOTES, 'UTF-8');
                    $removeAttachment = (isset($_POST['removeStickyNoteAttachment'.$loopNumber])?1:0);
                    $fileSQL = '';

                    // determine if they are asking to remove the image
                    if($removeAttachment) {
                        // Set the values for removal of the file for now
                        $fileSQL = ',FileName=null ,ByteSize=null ,FileType=null,Datum=null';
                    }
                    elseif (!$oversized && is_uploaded_file($_FILES['attachmentElementCurrentStickyNote'.$loopNumber]['tmp_name'])) {
                        // Get the properties of the file to upload
                        $fname    = $db->getDBConnection()->real_escape_string($_FILES['attachmentElementCurrentStickyNote'.$loopNumber]['name']); 
                        $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['attachmentElementCurrentStickyNote'.$loopNumber]['tmp_name']);
                        $fileSize = intval($_FILES['attachmentElementCurrentStickyNote'.$loopNumber]['size']);
                        $fileType = $db->getDBConnection()->real_escape_string($_FILES['attachmentElementCurrentStickyNote'.$loopNumber]['type']);

                        // Determine if the file size is such that the database han handle storing it. The database can handle 4GB (4,294,967,296 Bytes)
                        if ($fileSize < 4294967296){
                            //process the file
                            $content = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));

                            // Determine if we got any data
                            if ($content!=null) {
                                // Determine if the magic quotes option is on
                                if(!get_magic_quotes_gpc()){
                                    // Add slashes to the name
                                    $fname = addslashes($fname);
                                }

                                // Create the file sqlpart of this
                                if ($fname!=null) {$fileSQL = $fileSQL . ',FileName="' . $fname . '"';}
                                if ($fileSize!=null) {$fileSQL = $fileSQL . ',ByteSize="' . $fileSize . '"';}
                                if ($fileType!=null) {$fileSQL = $fileSQL . ',FileType="' . $fileType . '"';}
                                if ($content!=null) {$fileSQL = $fileSQL . ',Datum="' . $content . '"';}
                            }
                        }
                        else {
                            // Let the user know the file was NOT uploaded
                            echo("The file ('" . $fname . "') will not be uploaded, because it is too large. File must be under 4GB. Old file (if any) will remain.");
                        }
                    }   

                    // Let's create the update query off of what we have
                    $sql='UPDATE notes SET IsSticky=1 ';
                    if ($noteTitle!=null) {$sql = $sql . ', Title="' . $noteTitle . '"';}
                    if ($note!=null) {$sql = $sql . ', Note="' . $note . '"';}
                    if ($noteDate!=null) {$sql = $sql . ', Date="' . $noteDate . '"';}
                    if ($fileSQL!="") {$sql = $sql . $fileSQL;}
                    if ($associatedCategoryID!=null) {$sql = $sql . ',AssociatedCategoryID=' . $associatedCategoryID;}
                    $sql=$sql .' WHERE NoteID=' . $loopNumber . ';';
                    
                    // Attempt to run the query and get the response
                    if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 14.")){
                        // Attempt to get some variables with regards to updating the sticky notes users
                        $markStickyNoteAsReadByMe = (isset($_POST['markStickyNoteAsReadByMe'.$loopNumber])?1:0);
                        $markAllStickyNotesAsRead = (isset($_POST['markAllStickyNotesAsRead'.$loopNumber])?1:0);
                        
                        // Determine if this user wants to update everyone to say this note was read
                        if ($markAllStickyNotesAsRead==1){
                            // Setup the query appropriately
                            $sql="UPDATE stickynoteusers SET MarkedAsRead=1 " .
                                 "WHERE NoteID=" . $loopNumber . ";";
                        }
                        else if ($markStickyNoteAsReadByMe==1){
                            // Setup the query appropriately
                            $sql="UPDATE stickynoteusers SET MarkedAsRead=1 " .
                                 "WHERE NoteID=" . $loopNumber . " " .
                                    
                                 "AND SendToID=" . $userRow["UserID"] . ";";
                        }
                        
                        // Attempt to run the query and get the response
                        if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 15.")){
                        }
                    }
                }
            }
        }
    }
    
    function addStickyNoteRecipients($db, $userRow, $inNoteID, $inRecipients){
        $result = $inNoteID;
        
        // Set up what the user posted at first, to be changed with logic.
        $noteID = $inNoteID;
        $recipients=$inRecipients;
        
        try {
            // Ensure that we have something to work on, a not ID and the CSV string of user IDs
            if ($noteID>0 && 
                $recipients!=null && $recipients!=''){
                // create a query to determine if we have a note to add recipients to
                $sql = 'SELECT * FROM notes ' .
                       'WHERE NoteID = ' . $noteID . ';';
                
                // Attempt to run the query
                $noteRow = $db->queryDB($sql, $userRow, "note_presentation Form occurance 16");
                
                // Count the rows to ensure we have one
                if (mysqli_num_rows($noteRow)==1){
                    // Determine if everybody is selected
                    if (strpos($recipients,'-1')!==false){
                        // Create a query to insert everyone in the SU company for this note
                        $sql='INSERT INTO stickynoteusers (NoteID, SendToID) ' .
                             'SELECT ' . $noteID . ', UserID FROM users WHERE SUEmployee=1 AND UserTemplateOnly=0 AND AccountStatus="ACTIVE";';

                        // Attempt to run the query and get the response
                        if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 17.")){
                        }
                        else {
                            // Send a message back of the failure
                            $result = 'There was an error trying to add to the DB some recipients of the sticky note.';
                        }
                    }
                    else {
                        // Create an array of recipient user IDs
                        $users = explode (",", $recipients); 

                        // Attempt to loop through the users
                        foreach ($users as &$user) {
                            // Let's create the insert query off of what we have
                            $sql='INSERT INTO stickynoteusers (NoteID, SendToID) ' .
                                 'VALUES (' . $noteID . ', ' . $user . ');';

                            // Attempt to run the query and get the response
                            if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 18.")){
                            }
                            else {
                                // Send a message back of the failure
                                $result = 'There was an error trying to add to the DB some recipients of the sticky note.';
                            }
                        }
                    }
                }
                else {
                    // Send and error message back
                    return 'There is no sticky note to add recipients to. Recipients Aborted.';
                }
            }
            else {
                // Send and error message back
                return 'There is no sticky note to add recipients to. Recipients Aborted.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'There was an error trying to add the recipients to the sticky  note. ' .  
                   '.\n\n The error is: \n' . $ex->getMessage();
        }

        // Return whatever we got
        return $result;
    }
    
    function addNewStickyNotesToDB($db, $userRow, $associatedCategoryID, $enteredBy, $category){
        // Determine if there are new notes
        if (isset($_POST['newStickyNoteNumbers']) && $_POST['newStickyNoteNumbers']!=0){
            // Get the amount of new notes as a variable
            $noteNumStrings=$_POST['newStickyNoteNumbers'];
            $noteNums=explode('|', $noteNumStrings);

            // Loop through and get all new note elements
            foreach ($noteNums as $loopNumber){
                // Get the posted items that I am worried about
                $noteTitle=htmlspecialchars($_POST['newStickyNoteTitle'.$loopNumber], ENT_QUOTES, 'UTF-8');
                $note=htmlspecialchars($_POST['newStickyNote'.$loopNumber], ENT_QUOTES, 'UTF-8');
                $fname    = null; 
                $fileSize = null; 
                $fileType = null; 
                $content  = null;
                $oversized = htmlspecialchars($_POST['oversizedSticky'.$loopNumber], ENT_QUOTES, 'UTF-8');

                // determine if the image has been uploaded
                if(!$oversized && is_uploaded_file($_FILES['newStickyNoteAttachmentElement'.$loopNumber]['tmp_name'])) {
                    // Get the properties of the file to upload
                    $fname    = $db->getDBConnection()->real_escape_string($_FILES['newStickyNoteAttachmentElement'.$loopNumber]['name']); 
                    $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['newStickyNoteAttachmentElement'.$loopNumber]['tmp_name']);
                    $fileSize = intval($_FILES['newStickyNoteAttachmentElement'.$loopNumber]['size']);
                    $fileType = $db->getDBConnection()->real_escape_string($_FILES['newStickyNoteAttachmentElement'.$loopNumber]['type']);

                    // Determine if the file size is such that the database han handle storing it. The database can handle 4GB (4,294,967,296 Bytes)
                    if ($fileSize < 4294967296){
                        //process the file
                        $content = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));

                        // Determine if we got any data
                        if ($content!=null) {
                            // Determine if the magic quotes option is on
                            if(!get_magic_quotes_gpc()){
                                // Add slashes to the name
                                $fname = addslashes($fname);
                            }
                        }
                    }
                    else {
                        // reset all values to nothing
                        $fname    = null; 
                        $fileSize = null; 
                        $fileType = null; 
                        $content  = null;

                        // Let the user know the file was NOT uploaded
                        echo("The file ('" . $fname . "') will not be uploaded, because it is too large. File must be under 4GB.");
                    }
                }   

                // Let's create the insert query off of what we have
                $sql='INSERT INTO notes (IsSticky ';
                if ($noteTitle!=null) {$sql = $sql . ', Title';}
                if ($note!=null) {$sql = $sql . ',Note';}
                if ($fname!=null) {$sql = $sql . ',FileName';}
                if ($fileSize!=null) {$sql = $sql . ',ByteSize';}
                if ($fileType!=null) {$sql = $sql . ',FileType';}
                if ($content!=null) {$sql = $sql . ',Datum';}
                if ($associatedCategoryID!=null) {$sql = $sql . ',AssociatedCategoryID';}
                if ($enteredBy!=null) {$sql = $sql . ', EnteredByID';}
                if ($category!=null) {$sql = $sql . ', Category';}
                $sql=$sql .') VALUES (1 ';
                if ($noteTitle!=null) {$sql = $sql . ', "' . $noteTitle . '"';}
                if ($note!=null) {$sql = $sql . ', "' . $note . '"';}
                if ($fname!=null) {$sql = $sql . ', "' . $fname . '"';}
                if ($fileSize!=null) {$sql = $sql . ', "' . $fileSize . '"';}
                if ($fileType!=null) {$sql = $sql . ', "' . $fileType . '"';}
                if ($content!=null) {$sql = $sql . ', "' . $content . '"';}
                if ($associatedCategoryID!=null) {$sql = $sql . ', ' . $associatedCategoryID . ' ';}
                if ($enteredBy!=null) {$sql = $sql . ', ' . $enteredBy . ' ';}
                if ($category!=null) {$sql = $sql . ', "' . $category . '" ';}
                $sql=$sql .');';

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

                // Attempt to run the query and get the response
                if ($db->queryDB($sql, $userRow, "note_presentation Form occurance 19.")){
                    // Get the most recent ID (note)
                    $newNoteID = mysqli_insert_id($db->getDBConnection());
                    
                    // Determine if there was a sticky note made
                    if ((int)trim($newNoteID)>0){
                        // Check for the user to assign this sticky note to
                        $stickyNoteTo=-1;
                        if (isset($_POST['newStickyNoteTo'.$loopNumber]) ){
                            // Hold on to the user to assign this sticky note to
                            $stickyNoteTo = $_POST['newStickyNoteTo'.$loopNumber];

                            // Retrieving each selected option
                            $stickyNoteToCSV='';
                            foreach ($_POST['newStickyNoteTo'.$loopNumber] as $subject){
                                // Create a comma separated string of UserIDs
                                $stickyNoteToCSV = $stickyNoteToCSV . $subject . ',';
                            }
                            
                            // Remove last comma
                            $stickyNoteToCSV=substr($stickyNoteToCSV, 0, -1);
    
                            // Attempt to add the recipients
                            addStickyNoteRecipients($db, $userRow, $newNoteID, $stickyNoteToCSV);            
                        }
                    }
                }
            }
        }
    }
    
    function createStickyNoteEmployeesAsJSON($db, $userRow, $suCompanyOnly=true){
        // Initialize the return
        $result = '';
        $encoded_companies=null;
        try {
            // Setup the query to be where they only get users in the SU company
            $sql=
                'SELECT * ' .
                'FROM users ' .
                'WHERE SUEmployee=1 ' .
                'AND   UserTemplateOnly=0 ' .
                'AND   AccountStatus="ACTIVE" ' .
                'ORDER BY CompanyID, UserName;';
            
            // Determine if the SU Company is NOT set
            if ($suCompanyOnly==false){
                // Setup the query to be where they only get users in the SU company AND their company
                $sql='SELECT * FROM users ' .
                     'WHERE (CompanyID=' . $userRow["CompanyID"] . ' OR SUEmployee=1) ' .
                     'AND UserTemplateOnly=0 ' .
                     'AND AccountStatus="ACTIVE" ' . 
                     'ORDER BY CompanyID, UserName;';
            }
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "note_presentation Form occurance 20");

            // Determine if there are any rows
            if ($rows == null){
                return $result;
            }
            else{
                // Initialize the variable to be used
                $localCompanyID='';
                $companies=array();

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

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

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

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

                    // Increment the counters
                    ++$employeeCount;
                }

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

            }
        } 
        catch (Exception $ex) {
        }
        finally {
            // Create the javascript code to create the array to be used to repopulate the employees
            $result=$result . '
                <script type="text/javascript">
                    // using JSON.parse with json_encode
                    var stickyNoteCompanies = ' . $encoded_companies . ';
                </script>';
        }

        // Return whatever we got
        return $result;
    }
    
    function createStickyNoteEmployeesInnerHTML($db, $userRow, $suCompanyOnly=true){
        // Initialize the return
        $result = '';
        $amountOfLines=1;
        $innerHtml='<option value="-1">Everybody</option>';
        try {
            // Setup the query to be where they only get users in the SU company
            $sql=
                'SELECT u.*, c.CompanyName ' .
                'FROM users u ' .
                'LEFT JOIN companies c ON u.CompanyID=c.CompanyID ' .
                'WHERE u.SUEmployee=1 ' .
                'AND   u.UserTemplateOnly=0 ' .
                'AND   u.AccountStatus="ACTIVE" ' .
                'ORDER BY c.CompanyID, u.UserName;';
            
            // Determine if the SU Company is NOT set
            if ($suCompanyOnly==false && $userRow["CompanyID"]!=1){
                // Setup the query to be where they only get users in the SU company AND their company
                $sql='SELECT u.*, c.CompanyName FROM users u ' .
                     'LEFT JOIN companies c ON u.CompanyID=c.CompanyID ' .
                     'WHERE (c.CompanyID=' . $userRow["CompanyID"] . ' OR u.SUEmployee=1) ' .
                     'AND u.UserTemplateOnly=0 ' .
                     'AND u.AccountStatus="ACTIVE" ' . 
                     'ORDER BY c.CompanyID, u.UserName;';
            }
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "note_presentation Form occurance 21");

            // Determine if there are any rows
            if ($rows == null){
                return $result;
            }
            else{
                // Initialize the variable to be used
                $localCompanyID='';

                // Loop through the returned results
                $counter = -1;
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if the company ID has changed
                    if ($localCompanyID!=$row["CompanyID"]){
                        // Increment the first array counter
                        ++$counter;

                        // Increment the amount of lines
                        $amountOfLines++;
                        
                        // Set the option group got a new company
                        $innerHtml = $innerHtml . '<optgroup label="' . $row["CompanyName"] . '">';
                        
                        // Set the current company to what is in the loop now
                        $localCompanyID=$row["CompanyID"];
                    }

                    // Increment the amount of lines
                    $amountOfLines++;
                    
                    // Determine if this is the SU company
                    if ($row["CompanyID"]==1) {
                        // add this option
                        $innerHtml = $innerHtml . '<option class="EmployeeOption" value="' . $row["UserID"] . '">' . $row["UserName"] . ' (' . $row["FirstName"] . ' ' . $row["LastName"] . ')</option>';
                    }
                    else {
                        // add this option
                        $innerHtml = $innerHtml . '<option value="' . $row["UserID"] . '">' . $row["UserName"] . ' (' . $row["FirstName"] . ' ' . $row["LastName"] . ')</option>';
                    }
                }

            }
        } 
        catch (Exception $ex) {
        }
        finally {
            // Create the javascript code to create the array to be used to repopulate the employees
            $result=$result . '
                <script type="text/javascript">
                    // create a variable to hold the inner HTML of the selects
                    var amountOfLines = ' . $amountOfLines . ';
                    var stickyNoteCompaniesSelectInner = \'' . $innerHtml . '\';
                </script>';
        }

        // Return whatever we got
        return $result;
    }
    
    function copyNotes($db, $userRow, $category, $copyStickyNotes, &$currentSuccess, 
                       $newAssociatedCategoryID, $associatedCategoryIDToCopy=null){
        try {
            // Determine if they are currently successful as well as the proper variables are passed in
            if ($currentSuccess && 
                $category!=null && $category!="" &&
                $associatedCategoryIDToCopy!= null && $associatedCategoryIDToCopy>0 && 
                $newAssociatedCategoryID!= null && $newAssociatedCategoryID>0){

                // Determine if the user  wants to copy sticky notes
                $stickySQL='AND IsSticky=0 ';
                if ($copyStickyNotes){
                    $stickySQL = '';
                }
                
                // Create the query as if there is a parent
                $sql='INSERT INTO notes(AssociatedCategoryID, Category, ' . 
                        'Title, Note, EnteredByID, ByteSize, Datum, FileName, ' . 
                        'FileType, NoteOrder, IsSticky, Date) ' . 
                      'SELECT ' . $newAssociatedCategoryID . ', Category, ' . 
                        'Title, Note, EnteredByID, ByteSize, Datum, FileName, ' . 
                        'FileType, NoteOrder, IsSticky, Date ' . 
                        'FROM notes ' . 
                        'WHERE AssociatedCategoryID=' . $associatedCategoryIDToCopy . ' ' .
                        $stickySQL .
                        'AND Category="' . $category . '";';

                // Attempt to update the task
                if (!$db->queryDB($sql, $userRow, "note_presentation Form occurance 22")){
                    // Set all as a fail
                    $currentSuccess=false;
                }
            }
        } 
        catch (Exception $ex) {
            // Assign the output string as to what happened
            return $currentSuccess;
        } 
        finally {
            // Return the result
            return $currentSuccess;
        }
    }
?>   
