/**
 * 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, current, remove_i18n, updateFunction) {

    // Where to write the list
    this.list_target = list_target;
    // How many elements?
    if (current) {
        this.count = current;
    }
    else {
        this.count = 0;
    }
    // How many elements?
    this.id = 0;
    // Is there a maximum?
    if (max) {
        this.max = max;
    }
    else {
        this.max = -1;
    }

    this.removeStr = remove_i18n;
    this.updateFunction = updateFunction;

    /**
     * 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') {
            // Element name
            element.name = 'attachFile';
            // Element ID
            element.id = 'attachFile_' + this.count;

            // Add reference to this object
            element.multi_selector = this;

            // What to do when a file is selected
            element.onchange = function() {
                // unhide the list
                list_target.style.display = "block";

                // New file input
                var new_element = document.createElement('input');
                new_element.type = 'file';

                // 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);

                // Hide this: we can't use display:none because Safari doesn't like it
                this.style.position = 'absolute';
                this.style.left = '-1000px';

            };
            // If we've reached maximum number, disable input element
            if (this.max != -1 && this.count >= this.max) {
                element.style.display = "none";
                element.disabled = true;
            }

            // File element counter
            this.count++;
            // Most recent element
            this.current_element = element;
        }
        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) {
        // Row div
        var new_row = document.createElement('div');
        new_row.className = "jive-attach-item";

        // attachment icon
        var new_row_image = document.createElement('img');
        new_row_image.src = "images/attach-7x11.gif";
        new_row_image.alt = "";
        new_row_image.width = "7";
        new_row_image.height = "11";
        new_row_image.border = "0";
        new_row_image.style.value = "margin: 3px 1px 0px 0px;"

        // Delete link
        var new_row_link = document.createElement('a');
        new_row_link.href = '#';
        new_row_link.innerHTML = this.removeStr;

        // References
        new_row.element = element;

        new_row.appendChild(new_row_image);
        new_row.appendChild(document.createTextNode(" "));

        // Remove function
        new_row_link.onclick = function() {

            // Remove element from form
            this.parentNode.element.parentNode.removeChild(this.parentNode.element);

            // Remove this row from the list
            this.parentNode.parentNode.removeChild(this.parentNode);

            // Decrement counter
            this.parentNode.element.multi_selector.count--;

            this.parentNode.element.multi_selector.updateFunction(this.parentNode.element.multi_selector.count - 1);

            // hide list if no elements left
            if (this.parentNode.element.multi_selector.count < 2) {
                list_target.style.display = "none";
            }

            // Re-enable input element (if it's disabled)
            this.parentNode.element.multi_selector.current_element.style.display = "block";
            this.parentNode.element.multi_selector.current_element.disabled = false;

            // Appease Safari
            // without it Safari wants to reload the browser window
            // which nixes your already queued uploads
            return false;
        };

        var ua = navigator.userAgent;
        var isWindows = ua.indexOf('Windows') != -1;
        var isMac = !isWindows && ua.indexOf('Mac') != -1;

        // Set row value
        var elValue = element.value;
        // grab only the filename minus the path
        var fName = elValue;
        if (fName.indexOf('\\') != -1 && isWindows) {
            fName = fName.substring(fName.lastIndexOf('\\') + 1);
        }
        else if (fName.indexOf('/') != -1) {
            fName = fName.substring(fName.lastIndexOf('/') + 1);
        }
        else if (fName.indexOf(':') != -1 && isMac) {
            fName = fName.substring(fName.lastIndexOf(':') + 1);
        }
        new_row.appendChild(document.createTextNode(fName));

        // Add remove link
        new_row.appendChild(document.createTextNode(" ("));
        new_row.appendChild(new_row_link);
        new_row.appendChild(document.createTextNode(")"));

        // Add it to the list
        this.list_target.appendChild(new_row);

        this.updateFunction(this.count - 1);
    };

    this.removeAttachment = function(elementID, id) {

        // Add a hidden field removeAttachID -> id
        var new_element = document.createElement('input');
        new_element.type = 'hidden';
        new_element.name = "removeAttachID";
        new_element.value = id;

        // Replace div with hidden field
        var e = document.getElementById(elementID);
        e.parentNode.replaceChild(new_element, e);

        // decrement the counter
        this.count--;

        // hide list if no elements left
        if (this.count < 2) {
            list_target.style.display = "none";
        }

        // Re-enable input element (if it's disabled)
        this.current_element.style.display = "block";
        this.current_element.disabled = false;

    };
};