/**
 * Convert a single file-input element into a 'multiple' input list
 *
 * Usage:
 *
 *   1. Create a file input element (no name)
 *      eg. <input type="file" id="first_file_element">
 *
 *   2. Create a DIV for the output to be written to
 *      eg. <div id="files_list"></div>
 *
 *   3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
 *      eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
 *
 *   4. Add the first element
 *      eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
 *
 *   5. That's it.
 *
 *   You might (will) want to play around with the addListRow() method to make the output prettier.
 *
 *   You might also want to change the line
 *       element.name = 'file_' + this.count;
 *   ...to a naming convention that makes more sense to you.
 *
 * Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *
 * Credit:
 *   If you're nice, you'll leave this bit:
 *
 *   Class by Stickman -- http://www.the-stickman.com
 *      with thanks to:
 *      [for Safari fixes]
 *         Luis Torrefranca -- http://www.law.pitt.edu
 *         and
 *         Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com
 *      [for duplicate name bug]
 *         'neal'
 */
function MultiSelector(list_target, max) {

    // Where to write the list
    this.list_target = list_target;
    // How many elements?
    this.count = 0;
    this.sequence = 0;

    // Is there a maximum?
    if (max) {
        this.max = max;
    } else {
        this.max = -1;
    }
    ;

    /**
     * Add a new file input element
     */
    this.addElement = function(element) {

        // Make sure it's a file input element
        if (element.tagName == 'INPUT' && element.type == 'file') {

            // Add reference to this object
            element.multi_selector = this;

            // What to do when a file is selected
            element.onchange = function() {
                var isUnique = true;

                $("input[id^='file_']").each(function(index) {
                    if ($(this).val() == element.value) {
                        isUnique = false;
                        return false;
                    }
                });
                if (!isUnique) {
                    this.value = '';
                    alert('Filename must be unique');
                    return;
                }

                //IE8 Fix
                if (this.handled) {
                    return;
                } else {
                    this.handled = true;
                }

                // New file input
                var new_element = document.createElement('input');
                new_element.type = 'file';
                if (this.id) {
                    new_element.id = this.id;
                }
                if (this.name) {
                    new_element.name = this.name;
                }
                xAddClass(new_element, 'file');

                this.id = 'file_' + this.multi_selector.sequence;
                this.name = 'files[' + this.multi_selector.sequence + ']';
                this.className = 'fileinput';

                // File element counter
                this.multi_selector.count++;
                this.multi_selector.sequence++;

                // Add new element
                this.parentNode.insertBefore(new_element, this);

                // Apply 'update' to element
                this.multi_selector.addElement(new_element);

                // Update list
                this.multi_selector.addListRow(this, new_element.parentNode.parentNode);

                // Hide this: we can't use display:none because Safari doesn't like it
                xAddClass(this, 'off_screen');


            };
            // If we've reached maximum number, disable input element
            if (this.max != -1 && this.count >= this.max) {
                element.disabled = true;
                this.showWarning();
            }
            ;

            // Most recent element
            this.current_element = element;

            this.checkEmpty();

        } else {
            // This can only be applied to file input elements!
            alert('Error: not a file input element');
        }
        ;

    };

    /**
     * Add a new row to the list of files
     */
    this.addListRow = function(element, element_to_insert_before) {

        // Row div
        var new_row = document.createElement('tr');

        // Delete button
        var delete_button = document.createElement('img');
        delete_button.src = '../../gfx/delete.gif';
        delete_button.title = removeTranslated();
        delete_button.alt = removeTranslated();

        // References
        new_row.element = element;

        // Delete function
        delete_button.onclick = function() {

            // Remove element from form
            var element = this.parentNode.parentNode.element;

            element.parentNode.removeChild(element);

            // Remove this row from the list
            this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);

            // Decrement counter
            element.multi_selector.count--;

            // Re-enable input element (if it's disabled)
            element.multi_selector.current_element.disabled = false;
            element.multi_selector.hideWarning();


            // Check list length
            element.multi_selector.checkEmpty();

            // Appease Safari
            //    without it Safari wants to reload the browser window
            //    which nixes your already queued uploads
            return false;
        };

        //Create cell
        var filename_cell = document.createElement('td');
        filename_cell.innerHTML = element.multi_selector.cutOutFilename(element.value) + '&nbsp;';

        var delete_cell = document.createElement('td');
        xAddClass(delete_cell, 'remove');
        delete_cell.appendChild(delete_button);

        new_row.appendChild(filename_cell);
        new_row.appendChild(delete_cell);

        // Add it to the list
        element_to_insert_before.parentNode.insertBefore(new_row, element_to_insert_before);

    };

    this.cutOutFilename = function(value) {
        var backSlashSplit = value.split("\\");
        var forwardSlashSplitOnLastElement = backSlashSplit[backSlashSplit.length - 1].split("/");
        return forwardSlashSplitOnLastElement[forwardSlashSplitOnLastElement.length - 1];
    };

    this.showWarning = function() {
        warning = xGetElementById('multifile_warning');
        xRemoveClass(warning, 'invisible');
    };

    this.hideWarning = function() {
        warning = xGetElementById('multifile_warning');
        xAddClass(warning, 'invisible');
    };

    this.checkEmpty = function() {
        hideable = xGetElementById('multifile_hidden_when_empty');

        if (hideable != null) {
            if (this.count > 0 && xHasClass(hideable, 'invisible')) {
                xRemoveClass(hideable, 'invisible');
            }

            if (this.count == 0 && !xHasClass(hideable, 'invisible')) {
                xAddClass(hideable, 'invisible');
            }
        }
    };
}
;

