/* 
 * Arrays to handle adding notes and their attachments on the page.
 * 
 * Dependencies:
 *      ./javascript/general.js
 */
var newNoteNumbersToAdd = new Array();
var newStickyNoteNumbersToAdd = new Array();

function getNewMaxNoteNumber(){
    // Set the result to zero for now
    var result = 0;
    
   // Loop through the result numbers to get the highest
   for (var loopNoteNumber in newNoteNumbersToAdd){
       // Determine if the number is higher than the current number
       if (newNoteNumbersToAdd[loopNoteNumber]>result){
           // make this the new high
           result = newNoteNumbersToAdd[loopNoteNumber];
       }
   }
   
    // Return the highest result
    return result;
}

function getNewMaxStickyNoteNumber(){
    // Set the result to zero for now
    var result = 0;
    
   // Loop through the result numbers to get the highest
   for (var loopNoteNumber in newStickyNoteNumbersToAdd){
       // Determine if the number is higher than the current number
       if (newStickyNoteNumbersToAdd[loopNoteNumber]>result){
           // make this the new high
           result = newStickyNoteNumbersToAdd[loopNoteNumber];
       }
   }
   
    // Return the highest result
    return result;
}

function createNewNoteNumberString(){
    // Set the result to zero for now
    var result = '';
    
   // Loop through the result numbers
   for (var loopNoteNumber in newNoteNumbersToAdd){
       // Add it to the string
       result = result+newNoteNumbersToAdd[loopNoteNumber].toString()+'|';
   }

    // Remove the last comma
    result=result.slice(0, (result.length-1));
    
    // Return the highest result
    return result;
}

function createNewStickyNoteNumberString(){
    // Set the result to zero for now
    var result = '';
    
   // Loop through the result numbers
   for (var loopNoteNumber in newStickyNoteNumbersToAdd){
       // Add it to the string
       result = result+newStickyNoteNumbersToAdd[loopNoteNumber].toString()+'|';
   }

    // Remove the last comma
    result=result.slice(0, (result.length-1));
    
    // Return the highest result
    return result;
}

function removeNewNoteNumber(noteNumberToRemove){
    // Set the removal item to zero for now
    var noteLocationToRemove = -1;
    
    // Loop through the result numbers to get the highest
    for (var loopNoteNumber in newNoteNumbersToAdd){
        // Determine if the number is higher than the current number
        if (newNoteNumbersToAdd[loopNoteNumber]===noteNumberToRemove){
            // set this as the one to remove
            noteLocationToRemove = loopNoteNumber;

            // Break out of the list
            break;
        }
    }

    // Remove it from the list
    newNoteNumbersToAdd.splice(noteLocationToRemove,1);
}

function removeNewStickyNoteNumber(noteNumberToRemove){
    // Set the removal item to zero for now
    var noteLocationToRemove = -1;
    
    // Loop through the result numbers to get the highest
    for (var loopNoteNumber in newStickyNoteNumbersToAdd){
        // Determine if the number is higher than the current number
        if (newStickyNoteNumbersToAdd[loopNoteNumber]===noteNumberToRemove){
            // set this as the one to remove
            noteLocationToRemove = loopNoteNumber;

            // Break out of the list
            break;
        }
    }

    // Remove it from the list
    newStickyNoteNumbersToAdd.splice(noteLocationToRemove,1);
}

function AlertNoteFilesize(attachmentElementName, number, newNote=false){
    // Init and get variables from the page
    var fileElement = document.getElementById(attachmentElementName + number);
    var oversized = document.getElementById('oversized' + number);
    var sizeinbytes = 0;
    var returnValue = 0; // Put as a false that there will be an alert

    // Determine if we are checking a new note or old
    if (newNote){
        // Get the old not oversized information
        oversized = document.getElementById('oversized' + number);
    }
    else {
        // Get the new not oversized information
        oversized = document.getElementById('oversizedCurrentNote' + number);
    }
    
    // Get the file size of what they want to upload
    sizeinbytes = fileElement.files[0].size;

    // get the max file size from the element
    var maxFileSize = document.getElementById('maxFileSize').value;
    
    // Determine if the size is ok
    if (sizeinbytes>maxFileSize){
        // Let the user know that the file is not going to be taken
        alert( 'The file chosen is approximately ' + getHumanReadableFileSize(sizeinbytes) + 
               '. That is larger than the alloted size of approximately ' + getHumanReadableFileSize(maxFileSize) +
               '. This file will not be uploaded and the value will be set to nothing.');
       
        // Set the background to something showing it is GTG
        document.getElementById('imageLineDiv' + number).style.backgroundColor = 'Transparent';
        
        // reset the value to nothing for speeds sake
        fileElement.value="";
        
        // Set the variable to be true for oversized
        oversized.value = 1;
        
        // Put as true that there is an alert
        returnValue = 1; 
        
    }
    else {
        // Set the background to something showing it is GTG
        document.getElementById('imageLineDiv' + number).style.backgroundColor = 'Green';
        
        // Set the variable to be false for oversized
        oversized.value = 0;
    }
    
    // Return the alert
    return returnValue;
}

function AlertStickyNoteFilesize(attachmentElementName, number, newNote=false){
    // Init and get variables from the page
    var fileElement = document.getElementById(attachmentElementName + number);
    var oversized = document.getElementById('oversizedSticky' + number);
    var sizeinbytes = 0;
    var returnValue = 0; // Put as a false that there will be an alert

    // Determine if we are checking a new note or old
    if (newNote){
        // Get the old not oversized information
        oversized = document.getElementById('oversizedSticky' + number);
    }
    else {
        // Get the new not oversized information
        oversized = document.getElementById('oversizedCurrentStickyNote' + number);
    }
    
    // Get the file size of what they want to upload
    sizeinbytes = fileElement.files[0].size;

    // get the max file size from the element
    var maxFileSize = document.getElementById('maxFileSize').value;
    
    // Determine if the size is ok
    if (sizeinbytes>maxFileSize){
        // Let the user know that the file is not going to be taken
        alert( 'The file chosen is approximately ' + getHumanReadableFileSize(sizeinbytes) + 
               '. That is larger than the alloted size of approximately ' + getHumanReadableFileSize(maxFileSize) +
               '. This file will not be uploaded and the value will be set to nothing.');
       
        // Set the background to something showing it is GTG
        document.getElementById('stickyImageLineDiv' + number).style.backgroundColor = 'Transparent';
        
        // reset the value to nothing for speeds sake
        fileElement.value="";
        
        // Set the variable to be true for oversized
        oversized.value = 1;
        
        // Put as true that there is an alert
        returnValue = 1; 
        
    }
    else {
        // Set the background to something showing it is GTG
        document.getElementById('stickyImageLineDiv' + number).style.backgroundColor = 'Green';
        
        // Set the variable to be false for oversized
        oversized.value = 0;
    }
    
    // Return the alert
    return returnValue;
}

function currentNoteAttachmentOnChange(number){
    // Get the check element to modify
    var removeAttachmentCheckbox=document.getElementById('removeAttachment' + number);
    var removeAttachmentLabel=document.getElementById('removeAttachmentLabel' + number);
    
    // Get the Attachment element
    var theAttachmentElement = document.getElementById('attachmentElementCurrentNote'+number);

    // Check to see that the name is good or not
    if (doesFileNameHaveBadChars(theAttachmentElement.value)){
        // Give an alert that the file name has bad characters
        alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");

        // Remove the file
        theAttachmentElement.files[0]=null;
        theAttachmentElement.value='';
        
        // determine if the checkbox was there before
        if (removeAttachmentCheckbox!==null){
            // Show the checkbox to remove the old file again
            removeAttachmentCheckbox.style="";
            removeAttachmentLabel.style="";
        }
        
        return;
    }

    // Let them check the file and check if it is a good file
    if (AlertNoteFilesize('attachmentElementCurrentNote', number)===1){
        // determine if the checkbox was there before
        if (removeAttachmentCheckbox!==null){
            // Show the checkbox to remove the old file again
            removeAttachmentCheckbox.style="";
            removeAttachmentLabel.style="";
        }
    }
    else {
        // determine if the checkbox was there before
        if (removeAttachmentCheckbox!==null){
            // Show the checkbox to remove the old file again
            removeAttachmentCheckbox.style="display:none;";
            removeAttachmentLabel.style="display:none;";
        }

        // Hide the image cell
        div_hide('imageCell' + number);
    }
}

function currentStickyNoteAttachmentOnChange(number){
    // Get the check element to modify
    var removeAttachmentCheckbox=document.getElementById('removeStickyNoteAttachment' + number);
    var removeAttachmentLabel=document.getElementById('removeStickyAttachmentLabel' + number);
    
    // Get the Attachment element
    var theAttachmentElement = document.getElementById('attachmentElementCurrentStickyNote'+number);

    // Check to see that the name is good or not
    if (doesFileNameHaveBadChars(theAttachmentElement.value)){
        // Give an alert that the file name has bad characters
        alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");

        // Remove the file
        theAttachmentElement.files[0]=null;
        theAttachmentElement.value='';
        
        // determine if the checkbox was there before
        if (removeAttachmentCheckbox!==null){
            // Show the checkbox to remove the old file again
            removeAttachmentCheckbox.style="";
            removeAttachmentLabel.style="";
        }
        
        return;
    }
        
    // Let them check the file and check if it is a good file
    if (AlertNoteFilesize('attachmentElementCurrentStickyNote', number)===1){
        // determine if the checkbox was there before
        if (removeAttachmentCheckbox!==null){
            // Show the checkbox to remove the old file again
            removeAttachmentCheckbox.style="";
            removeAttachmentLabel.style="";
        }
    }
    else {
        // determine if the checkbox was there before
        if (removeAttachmentCheckbox!==null){
            // Show the checkbox to remove the old file again
            removeAttachmentCheckbox.style="display:none;";
            removeAttachmentLabel.style="display:none;";
        }

        // Hide the image cell
        div_hide('imageCell' + number);
    }
}

function addNewNote() {
    console.log("in addNewNote");

    // Increment the amount that is currently in the array
    var newNoteAmountID=getNewMaxNoteNumber()+1;
    
    // Create the answer div
    var noteDiv = document.createElement("div");
    noteDiv.class = 'Table';
    noteDiv.style = 'margin: 5px; width: 100%; border-bottom-style:dashed; border-width: 1px; display: inline-block; text-align: right;';
    noteDiv.id = 'newNoteDiv' + newNoteAmountID;
    noteDiv.name = 'newNoteDiv' + newNoteAmountID;

    // Create a div to hold the Order row
    var noteOrderLineDiv = document.createElement("div");
    noteOrderLineDiv.class = 'Row';
    noteOrderLineDiv.id = 'noteOrderDiv' + newNoteAmountID;
    noteOrderLineDiv.name = 'noteOrderDiv' + newNoteAmountID;
    noteOrderLineDiv.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the note row to the note div
    noteDiv.appendChild(noteOrderLineDiv);
    
    // Create the note order label
    var noteOrderLabel = document.createElement("label");
    noteOrderLabel.textContent="Order: ";
    noteOrderLabel.id = 'noteOrderLabel' + newNoteAmountID;    
    noteOrderLabel.style = 'width: 20%; text-align: center;';

    // Add the note order label to the note order row
    noteOrderLineDiv.appendChild(noteOrderLabel);
    
    // Create the note order text
    var noteOrder = document.createElement("textarea");
    noteOrder.rows = '1';
    noteOrder.id = 'newNoteOrder' + newNoteAmountID;    
    noteOrder.name = 'newNoteOrder' + newNoteAmountID;    
    noteOrder.style = 'width: 80%; text-align: left; resize: none;';
    noteOrder.value = 99999;
    noteOrder.maxLength = 3;

    // Add the note order text to the note order row div
    noteOrderLineDiv.appendChild(noteOrder);
    
    // Create a div to hold the note row
    var noteDateLineDiv = document.createElement("div");
    noteDateLineDiv.class = 'Row';
    noteDateLineDiv.id = 'noteDateLineDiv' + newNoteAmountID;
    noteDateLineDiv.name = 'noteDateLineDiv' + newNoteAmountID;
    noteDateLineDiv.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the note row to the note div
    noteDiv.appendChild(noteDateLineDiv);
    
    // Create the note date label
    var noteDateLabel = document.createElement("label");
    noteDateLabel.textContent="Note Date: ";
    noteDateLabel.id = 'noteDateLabel' + newNoteAmountID;    
    noteDateLabel.style = 'width: 20%;';

    // Add the note label to the note label div
    noteDateLineDiv.appendChild(noteDateLabel);
    
    // Create the note date text
    var currentDate = date2str(new Date(), 'yyyy-MM-ddThh:mm');
    var noteDate = document.createElement("INPUT");
    noteDate.type = "datetime-local";
    noteDate.id = 'newNoteDate' + newNoteAmountID;    
    noteDate.name = 'newNoteDate' + newNoteAmountID;  
    noteDate.value = currentDate;
    noteDate.style = 'width: 80%;';

    // Add the note label to the note label div
    noteDateLineDiv.appendChild(noteDate);
    
    // Create a div to hold the Title row
    var noteTitleLineDiv = document.createElement("div");
    noteTitleLineDiv.class = 'Row';
    noteTitleLineDiv.id = 'noteTitleLineDiv' + newNoteAmountID;
    noteTitleLineDiv.name = 'noteTitleLineDiv' + newNoteAmountID;
    noteTitleLineDiv.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the note row to the note div
    noteDiv.appendChild(noteTitleLineDiv);
    
    // Create the note title label
    var noteTitleLabel = document.createElement("label");
    noteTitleLabel.textContent="Note Title (Required): ";
    noteTitleLabel.id = 'noteTitleLabel' + newNoteAmountID;    
    noteTitleLabel.style = 'width: 20%; text-align: center;';

    // Add the note label to the note label div
    noteTitleLineDiv.appendChild(noteTitleLabel);
    
    // Create the note date text
    var noteTitle = document.createElement("textarea");
    noteTitle.rows = '1';
    noteTitle.id = 'newNoteTitle' + newNoteAmountID;    
    noteTitle.name = 'newNoteTitle' + newNoteAmountID;  
    noteTitle.style = 'width: 80%; text-align: left; resize: none;';
    noteTitle.maxLength = 30;

    // Add the note label to the note label div
    noteTitleLineDiv.appendChild(noteTitle);
    
    // Create a div to hold the Title row
    var noteLineDiv = document.createElement("div");
    noteLineDiv.class = 'Row';
    noteLineDiv.id = 'noteLineDiv' + newNoteAmountID;
    noteLineDiv.name = 'noteLineDiv' + newNoteAmountID;
    noteLineDiv.style = 'width: 100%; margin: 5px; vertical-align: top;';

    // Add the note row to the note div
    noteDiv.appendChild(noteLineDiv);
    
    // Create the note title label
    var noteLabel = document.createElement("label");
    noteLabel.textContent="Note (Required): ";
    noteLabel.id = 'noteLabel' + newNoteAmountID;    
    noteLabel.style = 'width: 20%; text-align: center;';

    // Add the note label to the note label div
    noteLineDiv.appendChild(noteLabel);
    
    // Create the note date text
    var note = document.createElement("textarea");
    note.rows = '5';
    note.id = 'newNote' + newNoteAmountID;    
    note.name = 'newNote' + newNoteAmountID;  
    note.style = 'width: 80%; text-align: left; resize: none;';
    note.maxLength = 2000;

    // Add the note label to the note label div
    noteLineDiv.appendChild(note);
    
    // Create a div to hold the image row
    var imageLineDiv = document.createElement("div");
    imageLineDiv.class = 'Row';
    imageLineDiv.id = 'imageLineDiv' + newNoteAmountID;
    imageLineDiv.name = 'imageLineDiv' + newNoteAmountID;
    imageLineDiv.style = 'width: 100%; margin: 5px; vertical-align: top;';

    // Add the image row to the note div
    noteDiv.appendChild(imageLineDiv);
    
    // Create the attachment table
    var imageTableDiv = document.createElement("div");
    imageTableDiv.class = 'Table';
    imageTableDiv.id = 'imageTableDiv' + newNoteAmountID;
    imageTableDiv.name = 'imageTableDiv' + newNoteAmountID;

    // Add the attachment row to the attachment table
    imageLineDiv.appendChild(imageTableDiv);
    
    // Create a row for the attachment
    var attachmentLineDiv = document.createElement("div");
    attachmentLineDiv.class = 'Row';
    attachmentLineDiv.id = 'typeLineDiv' + newNoteAmountID;
    attachmentLineDiv.name = 'typeLineDiv' + newNoteAmountID;

    // Add the attachment row to the attachment table
    imageTableDiv.appendChild(attachmentLineDiv);
    
    // Create the attachment label
    var attachmentLabel = document.createElement("label");
    attachmentLabel.class = 'cell mainLabelCell';
    attachmentLabel.textContent="File: ";
    attachmentLabel.id = 'attachmentLabel' + newNoteAmountID;    
    attachmentLabel.style = 'width: 20%; text-align: center;';

    // Add the attachment label to the attachment label div
    attachmentLineDiv.appendChild(attachmentLabel);
    
    var attachmentText = document.createElement("input");
    attachmentText.class = 'cell fileInputCell';
    attachmentText.type="file";
    attachmentText.disabled = false;
    attachmentText.id = 'newNoteAttachmentElement' + newNoteAmountID;    
    attachmentText.name = 'newNoteAttachmentElement' + newNoteAmountID;    
    attachmentText.onselect = '';
    attachmentText.style = 'width: 80%; text-align: left; resize: none;';
    attachmentText.onchange = function(a) {  
        return function() {
            // Get the file element
            var fileElement = document.getElementById('newNoteAttachmentElement' + a);
            
            // Check to see that the name is good or not
            if (doesFileNameHaveBadChars(fileElement.value)){
                // Give an alert that the file name has bad characters
                alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");
                
                // Remove the file
                fileElement.files[0]=null;
                fileElement.value='';
            }
            else {
                // Check for the file size
                AlertNoteFilesize('newNoteAttachmentElement', a, true);
            }
        };
    }(newNoteAmountID);

    // Add the attachment to the attachment line div
    attachmentLineDiv.appendChild(attachmentText);
    
    // Create a div to hold the button
    var buttonsDiv = document.createElement("div");
    buttonsDiv.class = 'Row';
    buttonsDiv.id = 'buttonsDiv';
    buttonsDiv.name = 'buttonsDiv';
    buttonsDiv.style = 'font-size: 12px; width: 100%; margin: 5px; vertical-align: middle;';

    // Create the remove setup button
    var removeBtn = document.createElement("button");
    removeBtn.textContent="Remove Note";
    removeBtn.style = 'margin-left: %90;';
    removeBtn.onclick = function(i) {  
        return function() {
           removeNewNote(i);
        };
    }(newNoteAmountID);

    // Add elements to the newly created DIV tags
    buttonsDiv.appendChild(removeBtn);
    
    // Create the oversized text
    var oversized = document.createElement("textarea");
    oversized.id = 'oversized' + newNoteAmountID;    
    oversized.name = 'oversized' + newNoteAmountID;  
    oversized.style = 'display: none;';
    oversized.value = 0;

    // Add the note label to the note label div
    buttonsDiv.appendChild(oversized);
    
    // Append the button section to the note section
    noteDiv.appendChild(buttonsDiv);

    // Add the new div tag to the main div tag
    var container = document.getElementById("newNotes");
    container.appendChild(noteDiv);
    
    // Add this ID to the list
    newNoteNumbersToAdd.push(newNoteAmountID);
    
    // Get the element and change the amount of notees
    var noteAmountDiv = document.getElementById("newNoteNumbers");
    noteAmountDiv.value=newNoteNumbersToAdd.join('|');
    
    // Add any validation that we have
    addNoteValidation(newNoteAmountID);
}

function addNewStickyNote() {
    console.log("in addNewStickyNote");

    // Increment the amount that is currently in the array
    var newNoteAmountID=getNewMaxStickyNoteNumber()+1;
    
    // Create the answer div
    var noteDiv = document.createElement("div");
    noteDiv.id = 'newStickyNoteDiv' + newNoteAmountID;
    noteDiv.name = 'newStickyNoteDiv' + newNoteAmountID;

    // Create the first note table
    var noteTableDiv1= document.createElement("div");
    noteTableDiv1.class = 'Table';
    noteTableDiv1.style = 'width: 98%; border-top-style:dashed; border-width: 1px; display: inline-block; text-align: right;';

    // Add the first note table to the note div
    noteDiv.appendChild(noteTableDiv1);
    
    // Create a div to hold the Title row
    var noteTitleLineDiv = document.createElement("div");
    noteTitleLineDiv.class = 'Row';
    noteTitleLineDiv.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the note row to the note div
    noteTableDiv1.appendChild(noteTitleLineDiv);
    
    // Create the note title label
    var noteTitleLabel = document.createElement("label");
    noteTitleLabel.textContent="Note Title (Required): ";

    // Add the note label to the note label row
    noteTitleLineDiv.appendChild(noteTitleLabel);
    
    // Create the note title text
    var noteTitle = document.createElement("textarea");
    noteTitle.rows = '1';
    noteTitle.id = 'newStickyNoteTitle' + newNoteAmountID;    
    noteTitle.name = 'newStickyNoteTitle' + newNoteAmountID;  
    noteTitle.style = 'width: 80%; text-align: left; resize: none;';
    noteTitle.maxLength = 30;

    // Add the title label to the note title row
    noteTitleLineDiv.appendChild(noteTitle);
    
    
    
    
    // Create the second note table
    var noteTableDiv2= document.createElement("table");
    noteTableDiv2.style = 'margin: 5px; width: 98%; border-width: 1px;';

    // Add the second note table to the note div
    noteDiv.appendChild(noteTableDiv2);
    
    // Create a div to hold the Header row
    var noteHeaderLineDiv = document.createElement("tr");
    noteHeaderLineDiv.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the header row to the second table
    noteTableDiv2.appendChild(noteHeaderLineDiv);
    
    // Create a div to hold the recipients cell
    var noteRecipientsCellDiv = document.createElement("td");
    noteRecipientsCellDiv.style = 'width: 50%; margin: 5px; vertical-align: middle;';

    // Add the recipients cell to the note row
    noteHeaderLineDiv.appendChild(noteRecipientsCellDiv);
    
    // Create the recipients label
    var recipientsLabel = document.createElement("label");
    recipientsLabel.textContent="Choose the Recipients: ";
    recipientsLabel.style = 'width: 98%; text-align: center;';

    // Add the recipients label
    noteRecipientsCellDiv.appendChild(recipientsLabel);
    
    // Create the recipients select box
    var recipients = document.createElement("select");
    recipients.id = 'newStickyNoteTo' + newNoteAmountID + '[]';   
    recipients.name = 'newStickyNoteTo' + newNoteAmountID + '[]';  
    recipients.style = 'width: 98%; height: ' + (17.25*amountOfLines) + '; text-align: left;';
    recipients.multiple="multiple";
    recipients.innerHTML=stickyNoteCompaniesSelectInner;
    recipients.onchange = function() {  
        // Determine if the value selected is the everybody 
        if (this.selectedIndex===0){
            // Loop through the options
            for (var loopNumber=0; loopNumber<this.length; loopNumber++){
                // Determine if we are on the first one 
                if (loopNumber===0){
                    // Unselect this one
                    this[loopNumber].selected=false;
                }
                else {
                    // Select this one
                    this[loopNumber].selected=true;
                }
            }
        }
    };

    // Add the recipients
    noteRecipientsCellDiv.appendChild(recipients);

    // Create a div to hold the content cell
    var noteContentCellDiv = document.createElement("td");
    noteContentCellDiv.style = 'width: 50%; margin: 5px; vertical-align: middle;';

    // Add the content cell to the note row
    noteHeaderLineDiv.appendChild(noteContentCellDiv);
    
    // Create the note content label
    var noteContentLabel = document.createElement("label");
    noteContentLabel.textContent="Note Content: ";
    noteContentLabel.style = 'width: 98%; text-align: center;';

    // Add the note content label
    noteContentCellDiv.appendChild(noteContentLabel);

    // Create the note content
    var noteContent = document.createElement("textarea");
    noteContent.rows = '5';
    noteContent.id = 'newStickyNote' + newNoteAmountID;    
    noteContent.name = 'newStickyNote' + newNoteAmountID;  
    noteContent.style = 'width: 98%; text-align: left; height: ' + (17.25*amountOfLines) + '; resize: none;';
    noteContent.maxLength = 2000;
    
    // Add the note content
    noteContentCellDiv.appendChild(noteContent);



    // Create a div to hold the image row
    var noteImageLineDiv = document.createElement("tr");
    noteImageLineDiv.id = 'stickyImageLineDiv' + newNoteAmountID;
    noteImageLineDiv.name = 'stickyImageLineDiv' + newNoteAmountID;
    noteImageLineDiv.style = 'width: 100%; margin: 5px; vertical-align: middle;';

    // Add the image row to the second table
    noteTableDiv2.appendChild(noteImageLineDiv);
    
    // Create a div to hold the image cell
    var noteImageCellDiv = document.createElement("td");
    noteImageCellDiv.style = 'width: 50%; margin: 5px; vertical-align: middle;';
    noteImageCellDiv.colspan = 1;

    // Add the image cell to the image row
    noteImageLineDiv.appendChild(noteImageCellDiv);
    
    // Create the attachment table
    var imageTableDiv = document.createElement("div");
    imageTableDiv.class = 'Table';

    // Add the attachment row to the attachment table cell
    noteImageCellDiv.appendChild(imageTableDiv);
    
    // Create a row for the attachment
    var attachmentLineDiv = document.createElement("div");
    attachmentLineDiv.class = 'Row';

    // Add the attachment row to the attachment table
    imageTableDiv.appendChild(attachmentLineDiv);
    
    // Create the attachment label
    var attachmentLabel = document.createElement("label");
    attachmentLabel.class = 'cell mainLabelCell';
    attachmentLabel.textContent="File: ";

    // Add the attachment label to the attachment label div
    attachmentLineDiv.appendChild(attachmentLabel);
    
    var attachmentText = document.createElement("input");
    attachmentText.class = 'cell fileInputCell';
    attachmentText.type="file";
    attachmentText.disabled = false;
    attachmentText.id = 'newStickyNoteAttachmentElement' + newNoteAmountID;    
    attachmentText.name = 'newStickyNoteAttachmentElement' + newNoteAmountID;    
    attachmentText.onselect = '';
    attachmentText.style = 'width: 80%; text-align: left; resize: none;';
    attachmentText.onchange = function(a) {  
        return function() {
            // Get the file element
            var fileElement = document.getElementById('newStickyNoteAttachmentElement' + a);
            
            // Check to see that the name is good or not
            if (doesFileNameHaveBadChars(fileElement.value)){
                // Give an alert that the file name has bad characters
                alert("Bad characters (currently only commas) were detected in the file name. Rename file and try again.");
                
                // Remove the file
                fileElement.files[0]=null;
                fileElement.value='';
            }
            else {
                // Check for the file size
                AlertStickyNoteFilesize('newStickyNoteAttachmentElement', a, true);
            }
        };
    }(newNoteAmountID);

    // Add the attachment to the attachment line div
    attachmentLineDiv.appendChild(attachmentText);

    
    
    
    // Add the buttons cell to the image row
    noteImageLineDiv.appendChild(noteImageCellDiv);
    
    // Create a div to hold the buttons cell
    var buttonsCellDiv = document.createElement("td");
    buttonsCellDiv.style = 'width: 50%; margin: 5px; vertical-align: middle; text-align: right;';
    buttonsCellDiv.colspan = 1;

    // Add the recipients cell to the image row
    noteImageLineDiv.appendChild(buttonsCellDiv);
    
    // Create the remove setup button
    var removeBtn = document.createElement("button");
    removeBtn.textContent="Remove Note";
    removeBtn.onclick = function(i) {  
        return function() {
           removeNewStickyNote(i);
        };
    }(newNoteAmountID);

    // Add elements to the newly created DIV tags
    buttonsCellDiv.appendChild(removeBtn);
    
    // Create the oversized text
    var oversized = document.createElement("textarea");
    oversized.id = 'oversizedSticky' + newNoteAmountID;    
    oversized.name = 'oversizedSticky' + newNoteAmountID;  
    oversized.style = 'display: none;';
    oversized.value = 0;

    // Add the note label to the note label div
    buttonsCellDiv.appendChild(oversized);
    


 
    // Add the new div tag to the main div tag
    var container = document.getElementById("newStickyNotes");
    container.appendChild(noteDiv);
    
    // Add this ID to the list
    newStickyNoteNumbersToAdd.push(newNoteAmountID);
    
    // Get the element and change the amount of notees
    var noteAmountDiv = document.getElementById("newStickyNoteNumbers");
    noteAmountDiv.value=newStickyNoteNumbersToAdd.join('|');
    
    // Add any validation that we have
    addStickyNoteValidation(newNoteAmountID);
}

function addNoteValidation(blankToAddValidation){
    console.log("in addNoteValidation");

    // Ensure that the validator object is available
    if (typeof frmvalidator !== 'undefined'){
        // Add the validators
        frmvalidator.addValidation("newNoteTitle" + blankToAddValidation,
                                   "req",
                                   "Please enter a title for all notes.");
        frmvalidator.addValidation("newNote" + blankToAddValidation,
                                   "req",
                                   "Please enter note text for all.");
    }
}

function addStickyNoteValidation(blankToAddValidation){
    console.log("in addStickyNoteValidation");

    // Ensure that the validator object is available
    if (typeof frmvalidator !== 'undefined'){
        // Add the validators
        frmvalidator.addValidation("newStickyNoteTitle" + blankToAddValidation,
                                   "req",
                                   "Please enter a title for all notes.");
        frmvalidator.addValidation("newStickyNote" + blankToAddValidation,
                                   "req",
                                   "Please enter note text for all.");
    }
}

function removeNewNote(noteToRemove){
    console.log("in removeNewNote");

    // Get the element to remove
    var note = document.getElementById('newNoteDiv'+noteToRemove);

    // Remove it
    note.parentNode.removeChild(note);    
    
    // Remove this from the list
    removeNewNoteNumber(noteToRemove);
    
    // Reset the note number string
    var noteAmount = document.getElementById("newNoteNumbers");
    noteAmount.value=createNewNoteNumberString();
}

function removeNewStickyNote(noteToRemove){
    console.log("in removeNewStickyNote");

    // Get the element to remove
    var note = document.getElementById('newStickyNoteDiv'+noteToRemove);

    // Remove it
    note.parentNode.removeChild(note);    
    
    // Remove this from the list
    removeNewStickyNoteNumber(noteToRemove);
    
    // Reset the note number string
    var noteAmount = document.getElementById("newStickyNoteNumbers");
    noteAmount.value=createNewStickyNoteNumberString();
}

function displayCorrectCompanyEmployeesForNewStickyNotes() {
    // Start the inner HTML with everybody
    var innerHtml='<option value="-1" selected>Everybody</option>';
    
    var whichOne=0;
    while (typeof stickyNoteCompanies[whichOne]!== 'undefined'){
        
    
    // Loop through the companies defined
//    for(var i = 0; i < stickyNoteCompanies.length; i++) {
        // Determine if this is the SU company
        if (stickyNoteCompanies[i]["CompanyID"]===1) {
            // Add the SU company group
            innerHtml = innerHtml + '<optgroup label="' + stickyNoteCompanies[i]["CompanyName"] + '">';

            // Loop through the values in super company's array
            var suCompanyEmployees = stickyNoteCompanies[i].employees;
            for(i = 0; i < suCompanyEmployees.length; i++) {
                // add this option
                innerHtml = innerHtml + '<option class="EmployeeOption" value="' + suCompanyEmployees[i].UserID + '">' + suCompanyEmployees[i].UserName + ' (' + suCompanyEmployees[i].FirstName + ' ' + suCompanyEmployees[i].LastName + ')</option>';
            }
        }
        else {
            // Add the SU company group
            innerHtml = innerHtml + '<optgroup label="' + stickyNoteCompanies[i]["CompanyName"]  + '">';

            // Loop through the values in selected company's array
            var selectedCompanyEmployees = stickyNoteCompanies[i].employees;
            for(i = 0; i < selectedCompanyEmployees.length; i++) {
                innerHtml = innerHtml + '<option value="' + selectedCompanyEmployees[i].UserID + '">' + selectedCompanyEmployees[i].UserName + ' (' + selectedCompanyEmployees[i].FirstName + ' ' + selectedCompanyEmployees[i].LastName + ')</option>';
            }
        }
        
        whichOne++;
    }    
    
//    // get the employees task assigned to combo now by ID
//    var cmbTaskEmployees = document.getElementById('assignedTo');
//
//    // Determine if the task assigned to combo box exists
//    if (typeof(cmbTaskEmployees) !== 'undefined' && cmbTaskEmployees !== null){
//        cmbTaskEmployees.innerHTML=innerHtml;
//    }

    stickyNoteCompaniesSelectInner=innerHtml;
} 

function addStickyNote(sessionID, taskIDStickyNote, category, stickyNoteTo, stickyNoteTitle, stickyNoteContent){
    // Set the return value to success for now
    $success=true;

    // Setup the parameters to pass to PHP
    var params = {
        "categoryID" : taskIDStickyNote,
        "stickyNoteCategory" : category,
        "stickyNoteTo" : stickyNoteTo,
        "stickyNoteTitle" : stickyNoteTitle,
        "stickyNoteContent" : stickyNoteContent,
        "sessionID" : sessionID
    };

    // Create the string containing the PHP file to use
    var url = "php_only_scripts/jquery_only/add_sticky_note.php";

    // Setup AJAX for communication
    $.ajax({
        context : this,
        type    : "GET", 
        url     : url, 
        data    : params, 
        dataType: "text", 
        encode  : true,
        async   : false, 
        cache   : false
    })
    .done(function(returnData){
        // Check to see if there is a reason NOT to allow the move
        if (returnData.includes("ABORT STICKY NOTE")){
            // Set the return value failed
            $success=false;

            // Split the string on the double colon
            var errorStrings=returnData.trim().split("::");

            // Give an alert popup of the problem
            alert(errorStrings[1]);

            // Log any errors to the console
            console.log(returnData.trim());
        }
// TODO: For now, I cannot figure out how to submit an image through ajax. Come back to this.
//                else if (isNaN(data.trim())===false){
//                    // Create a null object
//                    var fd = null;
//
//                    // Get the files from the file input object
//                    var files = document.getElementById("stickyNoteImage").files;
//
//                    // Check file selected or not
//                    if(files.length > 0 ){
//                        // Create a new form data object
//                        var fd = new FormData();
//
//                        // Append the Task ID as the first thing
//                        fd.append('taskID',data.trim());
//                        
//                        // Append the files object to the form data object
//                        fd.append('file',files[0]);
//                        
//                        // Add the image
//                        $success&=addStickyImage(fd);
//                    }
//
//                    // Refresh the tasks now to show current data
//                    refreshMachineTasks();
//                }
    })
    .fail(function(data){   
        // Log any errors to the console
        console.log(data);

        // Set the return value failed
        $success=false;
    });

    // Return what we got for success
    return $success;
}


