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

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

function createNewChildNumberString(type, parentID, savedParent=""){
    // Set the result to zero for now
    var result = '';
    
   // Loop through the result numbers
   for (var loopNoteNumber in parentArray[type+parentID+savedParent]){
       // Add it to the string
       result = result+parentArray[type+parentID+savedParent][loopNoteNumber].toString()+'|';
   }

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

function removeNewChildNumber(type, parentID, numberToRemove, savedParent=""){
    // Set the removal item to negative one for now
    var locationToRemove = -1;
    
    // Loop through the result numbers to get the highest
    for (var loopNoteNumber in parentArray[type+parentID+savedParent]){
        // Determine if the number is higher than the current number
        if (parentArray[type+parentID+savedParent][loopNoteNumber]===numberToRemove){
            // set this as the one to remove
            locationToRemove = loopNoteNumber;

            // Break out of the list
            break;
        }
    }

    // Remove it from the list
    parentArray[type+parentID+savedParent].splice(locationToRemove,1);
}

function checkChildFilesize(fileElementName, surroundDivName, number, maxSetupsFileSize=4294967296){
    // Init and get variables from the page
    var fileElement = document.getElementById(fileElementName + number);
    var sizeinbytes = 0;
    var returnValue = 0; // Put as a false that there will NOT be an alert

    // Get the file size of what they want to upload
    sizeinbytes = fileElement.files[0].size;

    // Determine if the size is ok
    if (sizeinbytes>maxSetupsFileSize){
        // 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(maxSetupsFileSize) +
               '. 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(surroundDivName + number).style.backgroundColor = 'Transparent';
        
        // Remove the file
        fileElement.files[0] = null;
        
        // reset the value to nothing for speeds sake
        fileElement.value="";
        
        // Put as true that there is an alert
        returnValue = 1; 
    }
    else {
        // Set the background to something showing it is GTG
        document.getElementById(surroundDivName + number).style.backgroundColor = 'Green';
    }
    
    // Return the alert
    return returnValue;
}

function currentChildAttachmentOnChange(type, parent, number){
    // Get the check element to modify
    var removeAttachmentCheckbox=document.getElementById(type + parent + 'RemoveAttachment' + number);
    var removeAttachmentLabel=document.getElementById(type + parent + 'RemoveAttachmentLabel' + number);
    
    // Get the Attachment element
    var theAttachmentElement = document.getElementById(type + parent + 'AttachmentElement' + 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 (checkChildFilesize(type + parent + 'AttachmentElement', type + parent + 'ImageLineDiv', 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(type + parent + 'ImageCell' + number);
    }
}

function addChildValidation(type, parent, blankToAddValidation, savedParent=""){
    console.log("in addChildValidation");

    // Ensure that the validator object is available
    if (typeof frmvalidator !== 'undefined'){
        // Add the validators
        frmvalidator.addValidation("new" + type + parent + savedParent + "NoteTitle" + blankToAddValidation,
                                   "req",
                                   "Please enter a title for all notes.");
        frmvalidator.addValidation("new" + type + parent + savedParent + "Note" + blankToAddValidation,
                                   "req",
                                   "Please enter note text for all.");
        frmvalidator.addValidation("new" + type + parent + savedParent + "NoteOrder" + blankToAddValidation,
                                   "req",
                                   "Please enter an order for all notes.");
        frmvalidator.addValidation("new" + type + parent + savedParent + "NoteOrder" + blankToAddValidation,
                                   "num",
                                   "Please enter the order for all notes as a number.");
        frmvalidator.addValidation("new" + type + parent + savedParent + "NoteOrder" + blankToAddValidation,
                                   "greaterthan=-.0000000001",
                                   "The order for all blanks should be greater than 0.");
    }
}

function removeNewChild(type, parent, noteToRemove, savedParent=""){
    console.log("in removeNewChild");

    // Get the element to remove
    var note = document.getElementById('new' + type + parent + savedParent + 'NoteDiv' + noteToRemove);

    // Remove it
    note.parentNode.removeChild(note);    
    
    // Remove this from the list
    removeNewChildNumber(type, parent, noteToRemove);
    
    // Reset the note number string
    var noteAmount = document.getElementById("new" + type + parent + "NoteNumbers");
    noteAmount.value=createNewChildNumberString(type, parent, savedParent);
}

function addNewChild(type, parent, parentNotSavedExtention="") {
    console.log("in addNewNote");

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

    // Create a div to hold the Order row
    var noteOrderLineDiv = document.createElement("div");
    noteOrderLineDiv.class = 'Row';
    noteOrderLineDiv.id = 'new' + type + parent + parentNotSavedExtention + 'NoteOrderLineDiv' + newNoteAmountID;
    noteOrderLineDiv.name = 'new' + type + parent + parentNotSavedExtention + 'NoteOrderLineDiv' + 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 = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'NoteOrder' + newNoteAmountID;    
    noteOrder.name = 'new' + type + parent + parentNotSavedExtention + 'NoteOrder' + 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 = 'new' + type + parent + parentNotSavedExtention + 'NoteDateLineDiv' + newNoteAmountID;
    noteDateLineDiv.name = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'NoteDate' + newNoteAmountID;    
    noteDate.name = 'new' + type + parent + parentNotSavedExtention + 'NoteDate' + 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 = 'new' + type + parent + parentNotSavedExtention + 'NoteTitleLineDiv' + newNoteAmountID;
    noteTitleLineDiv.name = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'NoteTitle' + newNoteAmountID;    
    noteTitle.name = 'new' + type + parent + parentNotSavedExtention + 'NoteTitle' + 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 = 'new' + type + parent + parentNotSavedExtention + 'NoteLineDiv' + newNoteAmountID;
    noteLineDiv.name = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'Note' + newNoteAmountID;    
    note.name = 'new' + type + parent + parentNotSavedExtention + 'Note' + 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 = 'new' + type + parent + parentNotSavedExtention + 'ImageLineDiv' + newNoteAmountID;
    imageLineDiv.name = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'ImageTableDiv' + newNoteAmountID;
    imageTableDiv.name = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'TypeLineDiv' + newNoteAmountID;
    attachmentLineDiv.name = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + '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 = 'new' + type + parent + parentNotSavedExtention + 'AttachmentElement' +  newNoteAmountID;    
    attachmentText.name = 'new' + type + parent + parentNotSavedExtention + 'AttachmentElement' + newNoteAmountID;    
    attachmentText.onselect = '';
    attachmentText.style = 'width: 80%; text-align: left; resize: none;';
    attachmentText.onchange = function(inType, inParent, inNewNoteAmountID, inSavedParent) {  
        return function() {
            // Get the file element
            var fileElement = document.getElementById('new' + inType + inParent + inSavedParent + 'AttachmentElement' + inNewNoteAmountID);
            
            // 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
           checkChildFilesize('new' + inType + inParent + inSavedParent + 'AttachmentElement', 'new' + type + parent + inSavedParent + 'ImageLineDiv', inNewNoteAmountID);
            }
        };
    }(type, parent, newNoteAmountID, parentNotSavedExtention);

    // 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 = 'new' + type + parent + parentNotSavedExtention + 'ButtonsDiv';
    buttonsDiv.name = '' + type + parent + parentNotSavedExtention + '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";
    removeBtn.type = "button";
    removeBtn.id = 'new' + type + parent + parentNotSavedExtention + 'SetupRemoveBtn' + newNoteAmountID;    
    removeBtn.style = 'margin-left: %90;';
    removeBtn.onclick = function(inType, inParent, inNewNoteAmountID,  inParentNotSavedExtention) {  
        return function() {
           removeNewChild(inType, inParent, inNewNoteAmountID,  inParentNotSavedExtention);
        };
    }(type, parent, newNoteAmountID, parentNotSavedExtention);

    // Add elements to the newly created DIV tags
    buttonsDiv.appendChild(removeBtn);
    
    // 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('new' + type + parent + parentNotSavedExtention + 'Notes');
    container.appendChild(noteDiv);
    
    // Determine if we have this array already
    if (typeof parentArray[type+parent+parentNotSavedExtention] === 'undefined'){
        // Create the new array list of child notes
        parentArray[type+parent+parentNotSavedExtention]=new Array();
    }
    
    // Add this ID to the list
    parentArray[type+parent+parentNotSavedExtention].push(newNoteAmountID);
    
    // Get the element and change the amount of notes
    var noteAmountDiv = document.getElementById('new' + type + parent + parentNotSavedExtention + 'NoteNumbers');
    noteAmountDiv.value=parentArray[type+parent+parentNotSavedExtention].join('|');
    
    // Determine if this parent is NOT a new parent
    if (parentNotSavedExtention===''){
        // Show the notes area and check the checkbox
        div_showCheckArea('hide' + type + parent + 'Notes', type + parent + 'Notes');
    }
    else{
        // Show the notes area and check the checkbox
        div_showCheckArea('newHide' + type + parent + parentNotSavedExtention + 'Notes', 'new' + type + parent + parentNotSavedExtention + 'Notes');
    }

    // Add any validation that we have
    addChildValidation(type, parent, newNoteAmountID, parentNotSavedExtention);
}
