<commit_before>/*!
 * Copyright 2012 Sakai Foundation (SF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

define(['jquery', 'underscore', 'oae/api/oae.core', 'jquery-plugins/jquery.fileupload', 'jquery-plugins/jquery.iframe-transport'], function($, _, oae) {

    return function(uid, showSettings) {

        ////////////////////
        // Initialization //
        ////////////////////

        // Initialize the modal dialog
        var modalContainer = oae.api.util.modal($('#addcontent_container'));

        /**
         * Initialize the add content overlay. We show the modal container,
         * and fill out the user's group memberships in the target libraries
         */
        var initAddContent = function() {
            // Show the modal dialog every time the trigger is clicked
            $(document).on('click', '.oae-trigger-addcontent', function() {
                modalContainer.open();
            });
        };

        ////////////////////
        // Left hand menu //
        ////////////////////

        /**
         * Make the left hand items clickable, so the user can switch between the form for
         * uploading a file, creating a document and adding a link
         */
        var setUpLeftMenu = function() {
            $(document).on('click', '.addcontent-container-lhchoice-item', function() {
                // Give the clicked element the selected style
                $('.addcontent-container-lhchoice-item').removeClass('addcontent-container-lhchoice-selected-item');
                $(this).addClass('addcontent-container-lhchoice-selected-item');
                // Show the correct container
                $('.addcontent-newitem-container').hide();
                $('#' + $(this).attr('id') + '_container').show();
            });
        };

        ////////////////////////
        // Content collection //
        ////////////////////////

        // Variable that keeps track of the content items that are queued for adding
        var contentToAdd = [];

        /**
         * Set up the validation for the add content form. This will be a single form containing upload file,
         * create document and add link, but only one of them will be visible at a time, which is the part
         * of the form that will be validated.
         */
        var setUpValidation = function() {
            var validateOpts = {
                'insertAfterLabel': true,
                'messages': {
                    'addcontent_upload_content_title': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_FILENAME__', 'addcontent'),
                    'addcontent_add_document_title': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_DOCUMENT_TITLE__', 'addcontent'),
                    'addcontent_add_link_url': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_VALID_URL__', 'addcontent')
                },
                'submitHandler': addContentToList
            };
            oae.api.util.validation().validate($('#addcontent_upload_content_form'), validateOpts);
        };

        /**
         * When the add form validation has succeeded, this function will add the added items into the right hand
         * `Collected items` panel
         */
        var addContentToList = function() {
            var contentObj = null;
            // Adding a document
            if ($('#addcontent_add_document_container').is(':visible')) {
                contentObj = {
                    'name': $('#addcontent_add_document_title').val(),
                    'description': $('#addcontent_add_document_description').val(),
                    'visibility': $('#addcontent_add_document_permissions').val(),
                    'type': 'document'
                };
            // Adding a link
            } else if ($('#addcontent_add_link_container').is(':visible')) {
                contentObj = {
                    'link': $('#addcontent_add_link_url').val(),
                    'name': $('#addcontent_add_link_title').val() || $('#addcontent_add_link_url').val(),
                    'description': $('#addcontent_add_link_description').val(),
                    'visibility': $('#addcontent_add_link_permissions').val(),
                    'type': 'link'
                };
            }
            // Add the item to the queue
            contentToAdd.push(contentObj);
            oae.api.util.renderTemplate($('#addcontent_container_selecteditems_template'), {'items': contentToAdd}, $('#addcontent_container_selecteditems_list'));
            // Clear the form
            $('#addcontent_upload_content_form')[0].reset();
            // Enable the Done, add collected button
            $('#addcontent_done_add_collected').removeAttr('disabled');
        };

        /////////////////
        // MEMBERSHIPS //
        /////////////////

        /**
         * Fill the 'Save all to' dropdown with all of the current user's
         * group memberships
         */
        var initMemberships = function() {
            oae.api.group.memberOf(null, null, null, function(err, memberships) {
                oae.api.util.renderTemplate($('#addcontent_saveto_template'), memberships, $('#addcontent_saveto'));
            });
        };

        initAddContent();
        setUpLeftMenu();
        setUpValidation();
        initMemberships();

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        return;




























        /////////////////////////////
        // CONFIGURATION VARIABLES //
        /////////////////////////////

        // Containers
        var $addcontentContainer = $('#addcontent_container');
        var $addcontentContainerNewItem = $('#addcontent_container_newitem');
        var $addcontentContainerSelectedItemsContainer = $('#addcontent_container_selecteditems_container');
        var $addcontentSelecteditemsEditDataContainer = $('#addcontent_selecteditems_edit_data_container');
        var addcontentSelecteditemsEditDataContainer = '#addcontent_selecteditems_edit_data_container';
        var $addcontentSelectedItemsEditPermissionsContainer = $('#addcontent_selecteditems_edit_permissions_container');
        var addcontentSelectedItemsEditPermissionsContainer = '#addcontent_selecteditems_edit_permissions_container';
        var $addcontentNewItemContainer = $('.addcontent_newitem_container');

        // Templates
        var addcontentUploadContentTemplate = '#addcontent_upload_content_template';
        var addcontentAddDocumentTemplate = '#addcontent_add_document_template';
        var addcontentAddLinkTemplate = '#addcontent_add_link_template';
        var addcontentSelectedItemsTemplate = 'addcontent_selecteditems_template';
        var addcontentSelectedItemsEditPermissionsTemplates = 'addcontent_selecteditems_edit_permissions_template';
        var addcontentSelectedItemsEditDataTemplate = 'addcontent_selecteditems_edit_data_template';
        
        // Elements
        var $addcontentContainerLHChoiceItem = $('.addcontent_container_lhchoice_item');
        var addcontentContainerLHChoiceSelectedSubitem = '.addcontent_container_lhchoice_selected_subitem';
        var $addcontentContainerLHChoiceSubItem = $('.addcontent_container_lhchoice_subitem');
        var $addcontentContainerNewItemAddToList = $('.addcontent_container_newitem_add_to_list');
        var addcontentContainerStartUploadButton = '.addcontent_container_start_upload';
        var addcontentSelectedItemsRemove = '.addcontent_selecteditems_remove';
        var addcontentSelectedItemsActionsEdit = '.addcontent_selecteditems_actions_edit';
        var addcontentSelectedItemsActionsPermissions = '.addcontent_selecteditems_actions_permissions';
        var addcontentSelectedItemsEditDataClose = '.addcontent_selecteditems_edit_data_close';
        var addcontentContainerNewItemSaveChanges = '.addcontent_container_newitem_save_changes';
        var addcontentSelectedItemsEditIndex = '.addcontent_selecteditems_edit_index';
        var $addcontentContainerNewItemRaquoRight = $('#addcontent_container_newitem_raquo_right');
        var addcontentAddLinkURL = '#addcontent_add_link_url';
        var addcontentAddLinkTitle = '#addcontent_add_link_title';
        var addcontentAddLinkDescription = '#addcontent_add_link_description';
        var addcontentUploadContentOriginalTitle = '.addcontent_upload_content_originaltitle';
        var addcontentUploadContentTitle = '#addcontent_upload_content_title';
        var addcontentUploadContentDescription = '#addcontent_upload_content_description';
        var addcontentUploadContentPermissions = '#addcontent_upload_content_permissions';
        var addcontentAddDocumentTitle = '#addcontent_add_document_title';
        var addcontentAddDocumentPermissions = '#addcontent_add_document_permissions';
        var addcontentAddDocumentDescription = '#addcontent_add_document_description';
        var addcontentSelectedItemsEditDataTitle = '#addcontent_selecteditems_edit_data_title';
        var addcontentSelectedItemsEditDataDescription = ' #addcontent_selecteditems_edit_data_description';
        var addcontentSelectedItemsEditPermissionsPermissions = '#addcontent_selecteditems_edit_permissions_permissions';
        var addcontentUploadContentFields = '#addcontent_upload_content_fields';
        var addcontentSaveTo = '#addcontent_saveto';
        var addcontentSelectedItemsEditDataForm = '#addcontent_selecteditems_edit_data_form';

        // Classes
        var addcontentContainerLHChoiceSelectedItem = 'addcontent_container_lhchoice_selected_item';
        var addcontentContainerLHChoiceItemClass = 'addcontent_container_lhchoice_item';
        var addcontentContainerNewItemExtraRoundedBorderClass = 'addcontent_container_newitem_extraroundedborder';
        var addcontentContainerLHChoiceSelectedSubitemClass = 'addcontent_container_lhchoice_selected_subitem';
        var addcontentContainerNewItemRaquoRightDocumentsposition = 'addcontent_container_newitem_raquo_right_documentsposition';
        var addcontentContainerNewItemAddToListDocumentsposition = 'addcontent_container_newitem_add_to_list_documentsposition';
        var addcontentContainerNewItemAddToListUploadNewContent = 'addcontent_container_newitem_add_to_list_upload_new_content';
        var addcontentContainerNewItemAddToListAddLink = 'addcontent_container_newitem_add_to_list_add_link';
        
        // List Variables
        var itemsToUpload = [];
        var itemsUploaded = 0;
        var brandNewContent = {};
        var allNewContent = [];
        var lastUpload = [];
        var libraryToUploadTo = '';
        // Keep track of number of files in the upload list selected by browsing the OS
        // This number will later be used to check against the multifile list of uploads to avoid bug (https://jira.sakaiproject.org/browse/SAKIII-3269)
        var numberOfBrowsedFiles = 0;

        // Paths
        var uploadPath = '/api/content/create';

        // Forms
        var $addcontentUploadContentForm = $('#addcontent_upload_content_form');
        var addcontentForm = '.addcontent_form';
        var addcontentAddLinkForm = '#addcontent_add_link_form';
        var $addcontentAddLinkForm = $('#addcontent_add_link_form');
        var addcontentAddDocumentForm = '#addcontent_add_document_form';
        
        var multifileQueueAddAllowed = true;
        var contentUploaded = false;
        var hideAfterContentUpload = false;

        var currentSelectedLibrary = sakai.data.me.userid;

        // jquery fileupload related variables
        var tmpBrowsedFile = {};
        var filesList = [];
        var contentDataBatch = [];
        // IE does not support XHR file uploads so we fallback to the iframe transport for uploads
        var useIframeTransport = !$.support.xhrFileUpload && !$.support.xhrFormDataFileUpload;
        // When a file is added using the iframe transport, store the submit function
        var fileUploadForms = {};

        ////////////////////////////////
        // Get newly uploaded content //
        ////////////////////////////////

        sakai_global.addcontent.getNewContent = function(library) {
            var newContentLibrary = [];
            // grab all of the newly uploaded content, regardless of target library
            if (!library) {
                newContentLibrary = allNewContent;
            } else if (brandNewContent[library]) {
                newContentLibrary = brandNewContent[library];
            }
            // return a copy
            return $.merge([], newContentLibrary);
        };

        var deleteContent = function(e, paths) {
            if (paths && paths.length) {
                $.each(paths, function(i, path) {
                    $.each(allNewContent, function(j, newContent) {
                        if (newContent && newContent._path === path) {
                            allNewContent.splice(j,1);
                        }
                    });
                    $.each(brandNewContent, function(lib, items) {
                        $.each(items, function(k, item) {
                            if (item && item._path === path) {
                                items.splice(k,1);
                            }
                        });
                    });
                });
            }
        };

        /////////////////
        // ITEMS QUEUE //
        /////////////////

        /**
         * Checks if all the items are in the selected library already
         */
        var libraryHasAllItems = function() {
            var hasAllItems = true;
            $.each(itemsToUpload, function(i, content) {
                if (!content.currentSelectedLibraryHasItem) {
                    hasAllItems = false;
                    return false;
                }
            });
            return hasAllItems;
        };

        /**
         * Render the queue
         * @param {Boolean} append Append added content to the exisitng queue, rather than re-rending the entire content list to upload.
         * @param {Array} contentToAdd Array of objects containing data about the content to be appended to the queue
         */
        var renderQueue = function(append, contentToAppend) {
            sakai.api.Groups.getMyMemberships(function(err, groups) {
                markLibraryHasContentItems(function() {
                    var templateData = {
                        'append': false,
                        'items': itemsToUpload,
                        'sakai': sakai,
                        'me': sakai.data.me,
                        'groups': groups,
                        'currentSelectedLibrary': currentSelectedLibrary
                    };

                    var $queueList = $addcontentContainerSelectedItemsContainer.children('ul');

                    if (append && $queueList.length) {
                        templateData.append = true;
                        templateData.items = contentToAppend;
                        $queueList.append(
                            sakai.api.Util.TemplateRenderer(addcontentSelectedItemsTemplate, templateData)
                        );
                    } else {
                        $addcontentContainerSelectedItemsContainer.html(
                            sakai.api.Util.TemplateRenderer(addcontentSelectedItemsTemplate, templateData)
                        );
                    }
                });
            });
        };

        var resetQueue = function() {
            itemsToUpload = [];
            itemsUploaded = 0;
            disableAddToQueue();
            renderQueue();
            $('#addcontent_container input, #addcontent_container textarea').val('');
            tmpBrowsedFile = {};
            filesList = [];
            contentDataBatch = [];
        };

        /**
         * Add an item to the queue
         * @param {Object/Array} contentToAdd Object or array of objects containing data about the object to be added to the queue
         * @param {Boolean} disableRender Disable rendering of the queue.
         */
        var addContentToQueue = function(contentToAdd, disableRender, append) {
            if ($.isArray(contentToAdd)) {
                itemsToUpload = itemsToUpload.concat(contentToAdd);
            } else {
                itemsToUpload.push(contentToAdd);
            }

            disableAddToQueue();

            if (!disableRender) {
                renderQueue(append, contentToAdd);
            }
        };

        /**
         * Remove an item from the queue
         */
        var removeItemToAdd = function() {
            $addcontentSelectedItemsEditPermissionsContainer.hide();
            $addcontentSelecteditemsEditDataContainer.hide();

            var index = $(this).parent()[0].id.split('addcontent_selecteditems_')[1];
            var obj = itemsToUpload[index];

            var filename = obj['sakai:originaltitle'];

            if (filename) {
                // Remove item from the file upload list
                filesList = $.grep(filesList, function(val) {
                    return filename !== val.name;
                });
            }

            switch (obj.type) {
                case 'content':
                    var $found = $('*:contains(\'' + obj.originaltitle + '\')');
                    $found.last().prev('a').click();
                    // If the user removes an item that was selected through browsing the OS reduce the file count to avoid bug (https://jira.sakaiproject.org/browse/SAKIII-3269)
                    if (obj.origin === 'user') {
                        numberOfBrowsedFiles--;
                    }
                    break;
            }

            itemsToUpload.splice(index,1);

            if (!itemsToUpload.length) {
                disableStartUpload();
            } else {
                var disableUpload = libraryHasAllItems();
                if (disableUpload) {
                    disableStartUpload();
                }
            }

            renderQueue();
        };

        /**
         * Construct an item to add to the queue
         * Depending on the type of the item to add construct a different object
         */
        var constructItemToAdd = function() {
            var uniqueId = sakai.api.Util.generateWidgetId();
            var $thisForm = $(this).parents($addcontentNewItemContainer).children(addcontentForm);
            if ($(this).attr('id') === 'addcontent_container_newitem_raquo_right') {
                $thisForm = $(this).prev().children(':visible').find(addcontentForm);
            }

            switch ($thisForm.attr('id')) {

                //////////////////////////
                // Uploading a new file //
                //////////////////////////

                case 'addcontent_upload_content_form':
                    var originalTitle = $thisForm.find(addcontentUploadContentOriginalTitle)[0].id;

                    // Calculate the file extension
                    var splitOnDot = originalTitle.split('.');
                    var contentObj = {
                        'sakai:pooled-content-file-name': $thisForm.find(addcontentUploadContentTitle).val(),
                        'description': $thisForm.find(addcontentUploadContentDescription).val(),
                        'visibility': $thisForm.find(addcontentUploadContentPermissions).val(),
                        'originaltitle': originalTitle,
                        'fileextension': splitOnDot[splitOnDot.length - 1],
                        'css_class': sakai.config.MimeTypes[sakai.config.Extensions[(originalTitle).slice(originalTitle.lastIndexOf('.') + 1, originalTitle.length).toLowerCase()] || 'other'].cssClass || 'oae-icon-unknown',
                        'type': 'content',
                        'origin':'user' // 'origin' tells Sakai that this file was selected from the users hard drive
                    };
                    // Store the temporary browsed file in the upload array
                    filesList.push(tmpBrowsedFile);
                    addContentToQueue(contentObj);
                    multifileQueueAddAllowed = true;
                    $thisForm.find(addcontentUploadContentTitle + ', ' + addcontentUploadContentDescription).val('');
                    // Increase the number of files that the user browsed for and added to the list
                    numberOfBrowsedFiles++;
                    break;

                ///////////////////
                // Adding a link //
                ///////////////////

                case 'addcontent_add_link_form':
                    var linkObj = {
                        'link': $thisForm.find(addcontentAddLinkURL).val(),
                        'name': $thisForm.find(addcontentAddLinkTitle).val() || $thisForm.find(addcontentAddLinkURL).val(),
                        'description': $thisForm.find(addcontentAddLinkDescription).val(),
                        'visibility': sakai.config.Permissions.Links.defaultaccess,
                        'css_class': 'oae-icon-url',
                        'type':'link'
                    };
                    addContentToQueue(linkObj);
                    $thisForm[0].reset();
                    break;

                /////////////////////////////
                // Creating a new document //
                /////////////////////////////

                case 'addcontent_add_document_form':
                    if ($thisForm.valid()) {
                        var documentObj = {
                            'sakai:pooled-content-file-name': $thisForm.find(addcontentAddDocumentTitle).val(),
                            'sakai:permissions': $thisForm.find(addcontentAddDocumentPermissions).val(),
                            'sakai:description': $thisForm.find(addcontentAddDocumentDescription).val(),
                            'css_class': 'oae-icon-sakaidoc',
                            'type': 'document'
                        };
                        addContentToQueue(documentObj);
                        $thisForm[0].reset();
                    }
                    break;

            }
        };

        ////////////////////
        // D&D'ing a file //
        ////////////////////

       /**
        * This function is invoken when a file is dropped from the desktop into
        * the collection panel. The file is added to the list of items to upload.
        * @param {Object} file    File that has been dropped in from the desktop
        */
       var fileDropped = function(file) {
            filesList.push(file);
            var extension = file.name.split('.');
            extension = extension[extension.length - 1];
            var contentObj = {
                'sakai:originaltitle': file.name,
                'sakai:fileextension': extension,
                'sakai:pooled-content-file-name': file.name,
                'sakai:description': '',
                'sakai:permissions': sakai.config.Permissions.Content.defaultaccess,
                'css_class': sakai.api.Content.getMimeTypeData(file.type).cssClass,
                'type': 'content',
                'fileReader': file
            };
            // SAKIII-4264 - we need to disable the renderQueue function in here
            // so we don't get an unresponsive script error in Firefox
            addContentToQueue(contentObj, true);
        };

        ////////////////////////////////////////////////
        // Edit details and Add permissions pop-overs //
        ////////////////////////////////////////////////

        /**
         * Show the pop up to enable the user to edit the permissions of a file in queue (permissions and copyright)
         */
        var changePermissions = function() {
            $addcontentSelecteditemsEditDataContainer.hide();
            var index = $(this).parents('li')[0].id.split('_')[2];
            $addcontentSelectedItemsEditPermissionsContainer.html(sakai.api.Util.TemplateRenderer(addcontentSelectedItemsEditPermissionsTemplates,{item: itemsToUpload[index], i:index, sakai:sakai}));
            $addcontentSelectedItemsEditPermissionsContainer.show();
            $addcontentSelectedItemsEditPermissionsContainer.css('left', $(this).parents('li').position().left + 'px');
            $addcontentSelectedItemsEditPermissionsContainer.css('top', $(this).parents('li').position().top + 40 + 'px');
        };

        /**
         * Show the pop up to enable the user to edit the data of a file in queue (description and title)
         */
        var editData = function() {
            $addcontentSelectedItemsEditPermissionsContainer.hide();
            var index = $(this).parents('li')[0].id.split('_')[2];
            $addcontentSelecteditemsEditDataContainer.html(sakai.api.Util.TemplateRenderer(addcontentSelectedItemsEditDataTemplate,{item: itemsToUpload[index], i:index}));
            $addcontentSelecteditemsEditDataContainer.show();
            $addcontentSelecteditemsEditDataContainer.css('left', $(this).parents('li').position().left + 'px');
            $addcontentSelecteditemsEditDataContainer.css('top', $(this).parents('li').position().top + 40 + 'px');

            var editValidateOpts = {
                onclick: true,
                onkeyup: function(element) {
                    $(element).valid();
                },
                onfocusout: true,
                success: function() {
                    $(addcontentContainerNewItemSaveChanges).removeAttr('disabled');
                },
                error: function() {
                    $(addcontentContainerNewItemSaveChanges).attr('disabled','disabled');
                }
            };

            sakai.api.Util.Forms.validate($(addcontentSelectedItemsEditDataForm), editValidateOpts, true);            
        };

        /**
         * Close the edit popup
         */
        var closeEditData = function() {
            $(this).parent().parent().hide();
        };

        /**
         * Save the changes made to a file in the queue
         */
        var saveEdit = function() {
            var index = $( addcontentSelectedItemsEditIndex ).attr( 'id' );
            if ( $addcontentSelecteditemsEditDataContainer.is( ':visible' ) ) {
                itemsToUpload[index]['sakai:pooled-content-file-name'] = $(addcontentSelecteditemsEditDataContainer + ' ' + addcontentSelectedItemsEditDataTitle).val();
                itemsToUpload[index]['sakai:description'] = $(addcontentSelecteditemsEditDataContainer + ' ' + addcontentSelectedItemsEditDataDescription).val();
            } else {
                itemsToUpload[index]['sakai:permissions'] = $(addcontentSelectedItemsEditPermissionsContainer + ' ' + addcontentSelectedItemsEditPermissionsPermissions).val();
            }
            $(this).parent().parent().hide();
            renderQueue();
        };


        ///////////////////////
        // UPLOADING ACTIONS //
        ///////////////////////

        /**
         * Check if all items have been uploaded
         */
        var checkUploadCompleted = function(files, contentObj) {
            itemsUploaded++;
            if (itemsToUpload.length === itemsUploaded) {
                sakai.api.Util.Modal.close($addcontentContainer);
                sakai.api.Util.progressIndicator.hideProgressIndicator();
                var librarytitle = $(addcontentSaveTo + ' option:selected').text();
                sakai.api.Util.notification.show(sakai.api.i18n.getValueForKey('LIBRARY'), sakai.api.Util.TemplateRenderer('addcontent_notification_finished_template', {
                    uploadcount: itemsUploaded,
                    contenturl: itemsToUpload[0].homePath,
                    contenttitle: itemsToUpload[0].name,
                    libraryid: libraryToUploadTo,
                    librarytitle: librarytitle
                }));
            }
        };

        /////////////////////////
        // Uploading new files //
        /////////////////////////

        /**
         * Do processing on uploaded files
         * @param {Object} data The data returned from the createfile service
         */
        var postFileUpload = function(data) {
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    for (var itemToUpload = 0; itemToUpload < itemsToUpload.length; itemToUpload++) {
                        if (itemsToUpload[itemToUpload]['sakai:originaltitle'] === i) {
                            itemsToUpload[itemToUpload] = $.extend({}, data[i].item, itemsToUpload[itemToUpload]);
                            if (data[i].type === 'imscp') {
                                setIMSCPContent(itemsToUpload[itemToUpload], data[i].item);
                            } else {
                                prepareSetDataOnContent(itemsToUpload[itemToUpload]);
                            }
                        }
                    }
                }
            }
        };

        /**
         * Execute the upload
         */
        var setXhrUpload = function() {
            var jqXHR = $('#addcontent_file_upload').fileupload('send', {
                files: filesList,
                success: function(data) {
                    data = $.parseJSON(data);
                    var extractedData = [];
                    postFileUpload(data);
                },
                error: function() {
                    checkUploadCompleted();
                }
            });
        };

        //////////////////////////////
        // Creating a new Sakai Doc //
        //////////////////////////////

        /**
         * Creates a Sakai document
         * @param {Number} index    Index of the current Sakai Doc in the itemsToUpload array
         */
        var createDocument = function(index) {
            var documentObj = itemsToUpload[index];
            var refID = sakai.api.Util.generateWidgetId();
            var title = documentObj['sakai:pooled-content-file-name'];
            var doc = {
                'structure0': JSON.stringify({
                    'page1': {
                        '_ref': refID,
                        '_order': 0,
                        '_title': title,
                        'main': {
                            '_ref': refID,
                            '_order': 0,
                            '_title': title
                        }
                    }
                }),
                'mimeType': 'x-sakai/document',
                'sakai:schemaversion': sakai.config.schemaVersion
            };

            $.ajax({
                url: uploadPath,
                data: doc,
                type: 'POST',
                dataType: 'json',
                success: function(data) {
                    documentObj = $.extend({}, data['_contentItem'].item, documentObj);
                    itemsToUpload[index] = documentObj;
                    var content = {};
                    content[refID] = sakai.config.defaultSakaiDocContent;
                    finishSakaiDoc(documentObj, content);
                },
                error: function(err) {
                    checkUploadCompleted();
                }
            });
        };

        /**
         * Add the page content for each of the pages in the Sakai Doc
         * @param {Object} documentObj    Content object of the ZIP file that contained the package
         * @param {Object} content        Initial page content for the IMS-CP package
         */
        var finishSakaiDoc = function(documentObj, content) {
            sakai.api.Server.saveJSON('/p/' + documentObj._path, content, function() {
                var batchRequests = [];
                for (var i in content) {
                    if (content.hasOwnProperty(i)) {
                        batchRequests.push({
                            url: '/p/' + documentObj['_path'] + '/' + i + '.save.json',
                            parameters: {
                                'sling:resourceType': 'sakai/pagecontent',
                                'sakai:pagecontent': JSON.stringify(content[i]),
                                '_charset_': 'utf-8'
                            },
                            method: 'POST'
                        });
                    }
                }
                sakai.api.Server.batch(batchRequests, function(success, response) {
                     prepareSetDataOnContent(documentObj);
                });
            });
        };

        ///////////////////
        // Adding a link //
        ///////////////////

        /**
         * Upload a link
         * @param {Number} index   Index of the current link in the itemsToUpload array
         */
        var uploadLink = function(index) {
            var linkObj = itemsToUpload[index];
            var preview = sakai.api.Content.getPreviewUrl(linkObj['sakai:pooled-content-url']);
            var link = {
                'contentType': 'link',
                'link': linkObj.link,
                'name': linkObj.name,
                'description': linkObj.description,
                'visibility': linkObj.visibility,
            };

            $.ajax({
                url: uploadPath,
                data: link,
                type: 'POST',
                dataType: 'JSON',
                success: function(data) {
                    linkObj = $.extend({}, data, linkObj);
                    itemsToUpload[index] = linkObj;
                    prepareSetDataOnContent(linkObj);
                },
                error: function() {
                    checkUploadCompleted();
                }
            });
        };

        //////////////////////////////
        // General metadata setting //
        //////////////////////////////

        var prepareSetDataOnContent = function(contentObj) {
            var setContent = function(obj) {
                checkUploadCompleted();
            };

            if ($.isArray(contentObj)) {
                $.each(contentObj, function(index, obj) {
                    setContent(obj);
                    lastUpload.push(obj);
                });
            } else {
                setContent(contentObj);
                lastUpload.push(contentObj);
            }
        };

        /////////////////////////////////////////////
        // Add all collected content to the system //
        /////////////////////////////////////////////

        /**
         * Execute the upload of the files in the queue by calling the functions needed for the specific type of content
         */
        var doUpload = function() {
            sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey('UPLOADING_YOUR_CONTENT'), sakai.api.i18n.getValueForKey('PROCESSING_UPLOAD'));
            libraryToUploadTo = $(addcontentSaveTo).val();

            // If iframe transport is used we have to submit the file upload forms
            if (useIframeTransport) {
                $.each(filesList, function(i, val) {
                    if (fileUploadForms[val.name]) {
                        fileUploadForms[val.name].submit();
                    }
                });
            }

            $.each(itemsToUpload, function(index,item) {
                switch(item.type) {
                    case 'link':
                        uploadLink(index);
                        break;
                    case 'content':
                        if (!contentUploaded) {
                            if (!useIframeTransport) {
                                setXhrUpload();
                            }
                            contentUploaded = true;
                        }
                        break;
                    case 'document':
                        createDocument(index);
                        break;
                }
            });
        };

        /**
         * Prefill some of the extra data a file can have
         * @param {String} fileName Name of the selected file
         */
        var preFillContentFields = function(fileName) {
            if (fileName.indexOf('\\') !== -1) {
                fileName = fileName.split('\\')[fileName.split('\\').length - 1];
            }
            $(addcontentUploadContentFields + ' ' + addcontentUploadContentTitle).val(fileName);
            $(addcontentUploadContentFields + ' ' + addcontentUploadContentOriginalTitle)[0].id = fileName;
            $(addcontentUploadContentTitle).select();
        };

        ////////////////
        // NAVIGATION //
        ////////////////

        /**
         * Reset the menu to its original state
         */
        var resetMenu = function() {
            $addcontentContainerNewItem.removeClass(addcontentContainerNewItemExtraRoundedBorderClass);
            $addcontentContainerLHChoiceItem.removeClass(addcontentContainerLHChoiceSelectedItem);
            $('#addcontent_upload_content').addClass(addcontentContainerLHChoiceSelectedItem);

            if (sakai.config.Permissions.Content.defaultaccess) {
                $('#addcontent_upload_content_permissions [value=' + sakai.config.Permissions.Content.defaultaccess + ']').attr('selected', 'selected');
            }
            if (sakai.config.Permissions.Documents.defaultaccess) {
                $('#addcontent_add_document_permissions [value=' + sakai.config.Permissions.Documents.defaultaccess + ']').attr('selected', 'selected');
            }
        };

        /**
         * Executed when a subitem in the navigation has been clicked
         */
        var navigateSubItem = function() {
            $(addcontentContainerLHChoiceSelectedSubitem).removeClass(addcontentContainerLHChoiceSelectedSubitemClass);
            $(this).addClass(addcontentContainerLHChoiceSelectedSubitemClass);
        };

        /////////////
        // BINDING //
        /////////////

        /**
         * Remove binding on all elements
         */
        var removeBinding = function() {
            $addcontentContainerLHChoiceItem.off('click', navigateMenu);
            $addcontentContainerLHChoiceSubItem.off('click', navigateSubItem);
            $addcontentContainerNewItemAddToList.off('click', constructItemToAdd);
            $(addcontentContainerStartUploadButton).off('click', doUpload);
            $addcontentContainer.off('click', addcontentSelectedItemsEditDataClose, closeEditData);
            $addcontentContainer.off('click', addcontentContainerNewItemSaveChanges, saveEdit);
            $addcontentContainer.off('click', addcontentSelectedItemsRemove, removeItemToAdd);
            $addcontentContainer.off('click', addcontentSelectedItemsActionsPermissions, changePermissions);
            $addcontentContainer.off('click', addcontentSelectedItemsActionsEdit, editData);
            $(window).off('init.deletecontent.sakai', deleteContent);
        };

        /**
         * Add binding to all elements
         */
        var addBinding = function() {
            $addcontentContainerLHChoiceItem.on('click', navigateMenu);
            $addcontentContainerLHChoiceSubItem.on('click', navigateSubItem);
            $addcontentContainerNewItemAddToList.on('click', constructItemToAdd);
            $(addcontentContainerStartUploadButton).on('click', doUpload);
            $addcontentContainer.on('click', addcontentSelectedItemsEditDataClose, closeEditData);
            $addcontentContainer.on('click', addcontentContainerNewItemSaveChanges, saveEdit);
            $addcontentContainer.on('click', addcontentSelectedItemsRemove, removeItemToAdd);
            $addcontentContainer.on('click', addcontentSelectedItemsActionsPermissions, changePermissions);
            $addcontentContainer.on('click', addcontentSelectedItemsActionsEdit, editData);
            sakai.api.Util.hideOnClickOut($addcontentSelecteditemsEditDataContainer, addcontentSelectedItemsActionsEdit + ', #assignlocation_container');
            sakai.api.Util.hideOnClickOut($addcontentSelectedItemsEditPermissionsContainer, addcontentSelectedItemsActionsPermissions);

            var fileuploadOptions = {
                url: uploadPath,
                sequentialUploads: true,
                singleFileUploads: false,
                dropZone: $('#addcontent_container_selecteditems'),
                drop: function(ev, data) {
                    ev.stopPropagation();
                    ev.preventDefault();
                    // We only support browsers that have XMLHttpRequest Level 2
                    if (!window.FormData) {
                        return false;
                    }
                    if ($(ev.target).is($('#addcontent_file_upload'))) {
                        var error = false;
                        $.each(data.files, function(index, file) {
                            if (file.size > 0) {
                                fileDropped(file);
                            } else {
                                error = true;
                            }
                        });
                        if (error) {
                            sakai.api.Util.notification.show(
                                sakai.api.i18n.getValueForKey('DRAG_AND_DROP_ERROR', 'addcontent'),
                                sakai.api.i18n.getValueForKey('ONE_OR_MORE_DROPPED_FILES_HAS_AN_ERROR', 'addcontent'));
                        }
                        renderQueue();
                    }
                },
                change: function(e, data) {
                    multifileQueueAddAllowed = false;
                    preFillContentFields(data.files[0].name);
                },
                add: function(e, data) {
                    tmpBrowsedFile = data.files[0];
                    if (useIframeTransport) {
                        fileUploadForms[data.files[0].name] = data;
                    }
                }
            };

            if (useIframeTransport) {
                fileuploadOptions.done = function(e, data) {
                    var result = {};
                    // In IE the result is inserted to the iframe
                    if ($('pre', data.result).length) {
                        result = $.parseJSON($('pre', data.result).text());
                    } else {
                        result = $.parseJSON(data.result);
                    }
                    postFileUpload(result);
                };
            }

            $('#addcontent_file_upload').fileupload(fileuploadOptions);

            $(document).on('done.deletecontent.sakai', deleteContent);
        };

        ////////////////////
        // INITIALIZATION //
        ////////////////////

        var setCurrentlySelectedLibrary = function() {
            if (sakai_global.group && sakai_global.group.groupId) {
                currentSelectedLibrary = sakai_global.group.groupId;
            }
        };

        /**
         * Call all functions and reset all variables needed to get the widget
         * into the original startup state
         */
        var resetWidget = function() {
            removeBinding();
            resetQueue();
            resetMenu();
            disableAddToQueue();
            disableStartUpload();
            multifileQueueAddAllowed = true;
            contentUploaded = false;
            hideAfterContentUpload = false;
            numberOfBrowsedFiles = 0;
            fileUploadForms = {};
        };

        /**
         * Initialize the widget
         */
        var initialize = function() {
            setCurrentlySelectedLibrary();
            resetWidget();
            addBinding();
            renderUploadNewContent();
        };

    };
});<commit_msg>Set up default values for content visibility<commit_after>/*!
 * Copyright 2012 Sakai Foundation (SF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

define(['jquery', 'underscore', 'oae/api/oae.core', 'jquery-plugins/jquery.fileupload', 'jquery-plugins/jquery.iframe-transport'], function($, _, oae) {

    return function(uid, showSettings) {

        ////////////////////
        // Initialization //
        ////////////////////

        // Initialize the modal dialog
        var modalContainer = oae.api.util.modal($('#addcontent_container'));

        /**
         * Initialize the add content overlay. We show the modal container,
         * and fill out the user's group memberships in the target libraries
         */
        var initAddContent = function() {
            // Show the modal dialog every time the trigger is clicked
            $(document).on('click', '.oae-trigger-addcontent', function() {
                modalContainer.open();
            });
        };

        ////////////////////
        // Left hand menu //
        ////////////////////

        /**
         * Make the left hand items clickable, so the user can switch between the form for
         * uploading a file, creating a document and adding a link
         */
        var setUpLeftMenu = function() {
            $(document).on('click', '.addcontent-container-lhchoice-item', function() {
                // Give the clicked element the selected style
                $('.addcontent-container-lhchoice-item').removeClass('addcontent-container-lhchoice-selected-item');
                $(this).addClass('addcontent-container-lhchoice-selected-item');
                // Show the correct container
                $('.addcontent-newitem-container').hide();
                $('#' + $(this).attr('id') + '_container').show();
            });
        };

        ////////////////////////
        // Content collection //
        ////////////////////////

        // Variable that keeps track of the content items that are queued for adding
        var contentToAdd = [];

        /**
         * Set up the validation for the add content form. This will be a single form containing upload file,
         * create document and add link, but only one of them will be visible at a time, which is the part
         * of the form that will be validated.
         */
        var setUpValidation = function() {
            var validateOpts = {
                'insertAfterLabel': true,
                'messages': {
                    'addcontent_upload_content_title': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_FILENAME__', 'addcontent'),
                    'addcontent_add_document_title': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_DOCUMENT_TITLE__', 'addcontent'),
                    'addcontent_add_link_url': oae.api.i18n.translate('__MSG__PLEASE_ENTER_A_VALID_URL__', 'addcontent')
                },
                'submitHandler': addContentToList
            };
            oae.api.util.validation().validate($('#addcontent_upload_content_form'), validateOpts);
        };

        /**
         * Select the right default value for content visibility for each of the different content types, based on 
         * the configuration options set in the admin UI
         */
        var setUpDefaultValues = function() {
            $('#addcontent_upload_content_permissions').val(oae.api.config.getValue('oae-content', 'visibility', 'files'));
            $('#addcontent_add_document_permissions').val(oae.api.config.getValue('oae-content', 'visibility', 'sakaidocs'));
            $('#addcontent_add_link_permissions').val(oae.api.config.getValue('oae-content', 'visibility', 'links'));
        };

        /**
         * When the add form validation has succeeded, this function will add the added items into the right hand
         * `Collected items` panel
         */
        var addContentToList = function() {
            var contentObj = null;
            // Adding a document
            if ($('#addcontent_add_document_container').is(':visible')) {
                contentObj = {
                    'name': $('#addcontent_add_document_title').val(),
                    'description': $('#addcontent_add_document_description').val(),
                    'visibility': $('#addcontent_add_document_permissions').val(),
                    'type': 'document'
                };
            // Adding a link
            } else if ($('#addcontent_add_link_container').is(':visible')) {
                contentObj = {
                    'link': $('#addcontent_add_link_url').val(),
                    'name': $('#addcontent_add_link_title').val() || $('#addcontent_add_link_url').val(),
                    'description': $('#addcontent_add_link_description').val(),
                    'visibility': $('#addcontent_add_link_permissions').val(),
                    'type': 'link'
                };
            }
            // Add the item to the queue
            contentToAdd.push(contentObj);
            oae.api.util.renderTemplate($('#addcontent_container_selecteditems_template'), {'items': contentToAdd}, $('#addcontent_container_selecteditems_list'));
            // Clear the form
            $('#addcontent_upload_content_form')[0].reset();
            // Enable the Done, add collected button
            $('#addcontent_done_add_collected').removeAttr('disabled');
        };

        /////////////////
        // MEMBERSHIPS //
        /////////////////

        /**
         * Fill the 'Save all to' dropdown with all of the current user's
         * group memberships
         */
        var initMemberships = function() {
            oae.api.group.memberOf(null, null, null, function(err, memberships) {
                oae.api.util.renderTemplate($('#addcontent_saveto_template'), memberships, $('#addcontent_saveto'));
            });
        };

        initAddContent();
        setUpLeftMenu();
        setUpValidation();
        setUpDefaultValues();
        initMemberships();

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        return;




























        /////////////////////////////
        // CONFIGURATION VARIABLES //
        /////////////////////////////

        // Containers
        var $addcontentContainer = $('#addcontent_container');
        var $addcontentContainerNewItem = $('#addcontent_container_newitem');
        var $addcontentContainerSelectedItemsContainer = $('#addcontent_container_selecteditems_container');
        var $addcontentSelecteditemsEditDataContainer = $('#addcontent_selecteditems_edit_data_container');
        var addcontentSelecteditemsEditDataContainer = '#addcontent_selecteditems_edit_data_container';
        var $addcontentSelectedItemsEditPermissionsContainer = $('#addcontent_selecteditems_edit_permissions_container');
        var addcontentSelectedItemsEditPermissionsContainer = '#addcontent_selecteditems_edit_permissions_container';
        var $addcontentNewItemContainer = $('.addcontent_newitem_container');

        // Templates
        var addcontentUploadContentTemplate = '#addcontent_upload_content_template';
        var addcontentAddDocumentTemplate = '#addcontent_add_document_template';
        var addcontentAddLinkTemplate = '#addcontent_add_link_template';
        var addcontentSelectedItemsTemplate = 'addcontent_selecteditems_template';
        var addcontentSelectedItemsEditPermissionsTemplates = 'addcontent_selecteditems_edit_permissions_template';
        var addcontentSelectedItemsEditDataTemplate = 'addcontent_selecteditems_edit_data_template';
        
        // Elements
        var $addcontentContainerLHChoiceItem = $('.addcontent_container_lhchoice_item');
        var addcontentContainerLHChoiceSelectedSubitem = '.addcontent_container_lhchoice_selected_subitem';
        var $addcontentContainerLHChoiceSubItem = $('.addcontent_container_lhchoice_subitem');
        var $addcontentContainerNewItemAddToList = $('.addcontent_container_newitem_add_to_list');
        var addcontentContainerStartUploadButton = '.addcontent_container_start_upload';
        var addcontentSelectedItemsRemove = '.addcontent_selecteditems_remove';
        var addcontentSelectedItemsActionsEdit = '.addcontent_selecteditems_actions_edit';
        var addcontentSelectedItemsActionsPermissions = '.addcontent_selecteditems_actions_permissions';
        var addcontentSelectedItemsEditDataClose = '.addcontent_selecteditems_edit_data_close';
        var addcontentContainerNewItemSaveChanges = '.addcontent_container_newitem_save_changes';
        var addcontentSelectedItemsEditIndex = '.addcontent_selecteditems_edit_index';
        var $addcontentContainerNewItemRaquoRight = $('#addcontent_container_newitem_raquo_right');
        var addcontentAddLinkURL = '#addcontent_add_link_url';
        var addcontentAddLinkTitle = '#addcontent_add_link_title';
        var addcontentAddLinkDescription = '#addcontent_add_link_description';
        var addcontentUploadContentOriginalTitle = '.addcontent_upload_content_originaltitle';
        var addcontentUploadContentTitle = '#addcontent_upload_content_title';
        var addcontentUploadContentDescription = '#addcontent_upload_content_description';
        var addcontentUploadContentPermissions = '#addcontent_upload_content_permissions';
        var addcontentAddDocumentTitle = '#addcontent_add_document_title';
        var addcontentAddDocumentPermissions = '#addcontent_add_document_permissions';
        var addcontentAddDocumentDescription = '#addcontent_add_document_description';
        var addcontentSelectedItemsEditDataTitle = '#addcontent_selecteditems_edit_data_title';
        var addcontentSelectedItemsEditDataDescription = ' #addcontent_selecteditems_edit_data_description';
        var addcontentSelectedItemsEditPermissionsPermissions = '#addcontent_selecteditems_edit_permissions_permissions';
        var addcontentUploadContentFields = '#addcontent_upload_content_fields';
        var addcontentSaveTo = '#addcontent_saveto';
        var addcontentSelectedItemsEditDataForm = '#addcontent_selecteditems_edit_data_form';

        // Classes
        var addcontentContainerLHChoiceSelectedItem = 'addcontent_container_lhchoice_selected_item';
        var addcontentContainerLHChoiceItemClass = 'addcontent_container_lhchoice_item';
        var addcontentContainerNewItemExtraRoundedBorderClass = 'addcontent_container_newitem_extraroundedborder';
        var addcontentContainerLHChoiceSelectedSubitemClass = 'addcontent_container_lhchoice_selected_subitem';
        var addcontentContainerNewItemRaquoRightDocumentsposition = 'addcontent_container_newitem_raquo_right_documentsposition';
        var addcontentContainerNewItemAddToListDocumentsposition = 'addcontent_container_newitem_add_to_list_documentsposition';
        var addcontentContainerNewItemAddToListUploadNewContent = 'addcontent_container_newitem_add_to_list_upload_new_content';
        var addcontentContainerNewItemAddToListAddLink = 'addcontent_container_newitem_add_to_list_add_link';
        
        // List Variables
        var itemsToUpload = [];
        var itemsUploaded = 0;
        var brandNewContent = {};
        var allNewContent = [];
        var lastUpload = [];
        var libraryToUploadTo = '';
        // Keep track of number of files in the upload list selected by browsing the OS
        // This number will later be used to check against the multifile list of uploads to avoid bug (https://jira.sakaiproject.org/browse/SAKIII-3269)
        var numberOfBrowsedFiles = 0;

        // Paths
        var uploadPath = '/api/content/create';

        // Forms
        var $addcontentUploadContentForm = $('#addcontent_upload_content_form');
        var addcontentForm = '.addcontent_form';
        var addcontentAddLinkForm = '#addcontent_add_link_form';
        var $addcontentAddLinkForm = $('#addcontent_add_link_form');
        var addcontentAddDocumentForm = '#addcontent_add_document_form';
        
        var multifileQueueAddAllowed = true;
        var contentUploaded = false;
        var hideAfterContentUpload = false;

        var currentSelectedLibrary = sakai.data.me.userid;

        // jquery fileupload related variables
        var tmpBrowsedFile = {};
        var filesList = [];
        var contentDataBatch = [];
        // IE does not support XHR file uploads so we fallback to the iframe transport for uploads
        var useIframeTransport = !$.support.xhrFileUpload && !$.support.xhrFormDataFileUpload;
        // When a file is added using the iframe transport, store the submit function
        var fileUploadForms = {};

        ////////////////////////////////
        // Get newly uploaded content //
        ////////////////////////////////

        sakai_global.addcontent.getNewContent = function(library) {
            var newContentLibrary = [];
            // grab all of the newly uploaded content, regardless of target library
            if (!library) {
                newContentLibrary = allNewContent;
            } else if (brandNewContent[library]) {
                newContentLibrary = brandNewContent[library];
            }
            // return a copy
            return $.merge([], newContentLibrary);
        };

        var deleteContent = function(e, paths) {
            if (paths && paths.length) {
                $.each(paths, function(i, path) {
                    $.each(allNewContent, function(j, newContent) {
                        if (newContent && newContent._path === path) {
                            allNewContent.splice(j,1);
                        }
                    });
                    $.each(brandNewContent, function(lib, items) {
                        $.each(items, function(k, item) {
                            if (item && item._path === path) {
                                items.splice(k,1);
                            }
                        });
                    });
                });
            }
        };

        /////////////////
        // ITEMS QUEUE //
        /////////////////

        /**
         * Checks if all the items are in the selected library already
         */
        var libraryHasAllItems = function() {
            var hasAllItems = true;
            $.each(itemsToUpload, function(i, content) {
                if (!content.currentSelectedLibraryHasItem) {
                    hasAllItems = false;
                    return false;
                }
            });
            return hasAllItems;
        };

        /**
         * Render the queue
         * @param {Boolean} append Append added content to the exisitng queue, rather than re-rending the entire content list to upload.
         * @param {Array} contentToAdd Array of objects containing data about the content to be appended to the queue
         */
        var renderQueue = function(append, contentToAppend) {
            sakai.api.Groups.getMyMemberships(function(err, groups) {
                markLibraryHasContentItems(function() {
                    var templateData = {
                        'append': false,
                        'items': itemsToUpload,
                        'sakai': sakai,
                        'me': sakai.data.me,
                        'groups': groups,
                        'currentSelectedLibrary': currentSelectedLibrary
                    };

                    var $queueList = $addcontentContainerSelectedItemsContainer.children('ul');

                    if (append && $queueList.length) {
                        templateData.append = true;
                        templateData.items = contentToAppend;
                        $queueList.append(
                            sakai.api.Util.TemplateRenderer(addcontentSelectedItemsTemplate, templateData)
                        );
                    } else {
                        $addcontentContainerSelectedItemsContainer.html(
                            sakai.api.Util.TemplateRenderer(addcontentSelectedItemsTemplate, templateData)
                        );
                    }
                });
            });
        };

        var resetQueue = function() {
            itemsToUpload = [];
            itemsUploaded = 0;
            disableAddToQueue();
            renderQueue();
            $('#addcontent_container input, #addcontent_container textarea').val('');
            tmpBrowsedFile = {};
            filesList = [];
            contentDataBatch = [];
        };

        /**
         * Add an item to the queue
         * @param {Object/Array} contentToAdd Object or array of objects containing data about the object to be added to the queue
         * @param {Boolean} disableRender Disable rendering of the queue.
         */
        var addContentToQueue = function(contentToAdd, disableRender, append) {
            if ($.isArray(contentToAdd)) {
                itemsToUpload = itemsToUpload.concat(contentToAdd);
            } else {
                itemsToUpload.push(contentToAdd);
            }

            disableAddToQueue();

            if (!disableRender) {
                renderQueue(append, contentToAdd);
            }
        };

        /**
         * Remove an item from the queue
         */
        var removeItemToAdd = function() {
            $addcontentSelectedItemsEditPermissionsContainer.hide();
            $addcontentSelecteditemsEditDataContainer.hide();

            var index = $(this).parent()[0].id.split('addcontent_selecteditems_')[1];
            var obj = itemsToUpload[index];

            var filename = obj['sakai:originaltitle'];

            if (filename) {
                // Remove item from the file upload list
                filesList = $.grep(filesList, function(val) {
                    return filename !== val.name;
                });
            }

            switch (obj.type) {
                case 'content':
                    var $found = $('*:contains(\'' + obj.originaltitle + '\')');
                    $found.last().prev('a').click();
                    // If the user removes an item that was selected through browsing the OS reduce the file count to avoid bug (https://jira.sakaiproject.org/browse/SAKIII-3269)
                    if (obj.origin === 'user') {
                        numberOfBrowsedFiles--;
                    }
                    break;
            }

            itemsToUpload.splice(index,1);

            if (!itemsToUpload.length) {
                disableStartUpload();
            } else {
                var disableUpload = libraryHasAllItems();
                if (disableUpload) {
                    disableStartUpload();
                }
            }

            renderQueue();
        };

        /**
         * Construct an item to add to the queue
         * Depending on the type of the item to add construct a different object
         */
        var constructItemToAdd = function() {
            var uniqueId = sakai.api.Util.generateWidgetId();
            var $thisForm = $(this).parents($addcontentNewItemContainer).children(addcontentForm);
            if ($(this).attr('id') === 'addcontent_container_newitem_raquo_right') {
                $thisForm = $(this).prev().children(':visible').find(addcontentForm);
            }

            switch ($thisForm.attr('id')) {

                //////////////////////////
                // Uploading a new file //
                //////////////////////////

                case 'addcontent_upload_content_form':
                    var originalTitle = $thisForm.find(addcontentUploadContentOriginalTitle)[0].id;

                    // Calculate the file extension
                    var splitOnDot = originalTitle.split('.');
                    var contentObj = {
                        'sakai:pooled-content-file-name': $thisForm.find(addcontentUploadContentTitle).val(),
                        'description': $thisForm.find(addcontentUploadContentDescription).val(),
                        'visibility': $thisForm.find(addcontentUploadContentPermissions).val(),
                        'originaltitle': originalTitle,
                        'fileextension': splitOnDot[splitOnDot.length - 1],
                        'css_class': sakai.config.MimeTypes[sakai.config.Extensions[(originalTitle).slice(originalTitle.lastIndexOf('.') + 1, originalTitle.length).toLowerCase()] || 'other'].cssClass || 'oae-icon-unknown',
                        'type': 'content',
                        'origin':'user' // 'origin' tells Sakai that this file was selected from the users hard drive
                    };
                    // Store the temporary browsed file in the upload array
                    filesList.push(tmpBrowsedFile);
                    addContentToQueue(contentObj);
                    multifileQueueAddAllowed = true;
                    $thisForm.find(addcontentUploadContentTitle + ', ' + addcontentUploadContentDescription).val('');
                    // Increase the number of files that the user browsed for and added to the list
                    numberOfBrowsedFiles++;
                    break;

                ///////////////////
                // Adding a link //
                ///////////////////

                case 'addcontent_add_link_form':
                    var linkObj = {
                        'link': $thisForm.find(addcontentAddLinkURL).val(),
                        'name': $thisForm.find(addcontentAddLinkTitle).val() || $thisForm.find(addcontentAddLinkURL).val(),
                        'description': $thisForm.find(addcontentAddLinkDescription).val(),
                        'visibility': sakai.config.Permissions.Links.defaultaccess,
                        'css_class': 'oae-icon-url',
                        'type':'link'
                    };
                    addContentToQueue(linkObj);
                    $thisForm[0].reset();
                    break;

                /////////////////////////////
                // Creating a new document //
                /////////////////////////////

                case 'addcontent_add_document_form':
                    if ($thisForm.valid()) {
                        var documentObj = {
                            'sakai:pooled-content-file-name': $thisForm.find(addcontentAddDocumentTitle).val(),
                            'sakai:permissions': $thisForm.find(addcontentAddDocumentPermissions).val(),
                            'sakai:description': $thisForm.find(addcontentAddDocumentDescription).val(),
                            'css_class': 'oae-icon-sakaidoc',
                            'type': 'document'
                        };
                        addContentToQueue(documentObj);
                        $thisForm[0].reset();
                    }
                    break;

            }
        };

        ////////////////////
        // D&D'ing a file //
        ////////////////////

       /**
        * This function is invoken when a file is dropped from the desktop into
        * the collection panel. The file is added to the list of items to upload.
        * @param {Object} file    File that has been dropped in from the desktop
        */
       var fileDropped = function(file) {
            filesList.push(file);
            var extension = file.name.split('.');
            extension = extension[extension.length - 1];
            var contentObj = {
                'sakai:originaltitle': file.name,
                'sakai:fileextension': extension,
                'sakai:pooled-content-file-name': file.name,
                'sakai:description': '',
                'sakai:permissions': sakai.config.Permissions.Content.defaultaccess,
                'css_class': sakai.api.Content.getMimeTypeData(file.type).cssClass,
                'type': 'content',
                'fileReader': file
            };
            // SAKIII-4264 - we need to disable the renderQueue function in here
            // so we don't get an unresponsive script error in Firefox
            addContentToQueue(contentObj, true);
        };

        ////////////////////////////////////////////////
        // Edit details and Add permissions pop-overs //
        ////////////////////////////////////////////////

        /**
         * Show the pop up to enable the user to edit the permissions of a file in queue (permissions and copyright)
         */
        var changePermissions = function() {
            $addcontentSelecteditemsEditDataContainer.hide();
            var index = $(this).parents('li')[0].id.split('_')[2];
            $addcontentSelectedItemsEditPermissionsContainer.html(sakai.api.Util.TemplateRenderer(addcontentSelectedItemsEditPermissionsTemplates,{item: itemsToUpload[index], i:index, sakai:sakai}));
            $addcontentSelectedItemsEditPermissionsContainer.show();
            $addcontentSelectedItemsEditPermissionsContainer.css('left', $(this).parents('li').position().left + 'px');
            $addcontentSelectedItemsEditPermissionsContainer.css('top', $(this).parents('li').position().top + 40 + 'px');
        };

        /**
         * Show the pop up to enable the user to edit the data of a file in queue (description and title)
         */
        var editData = function() {
            $addcontentSelectedItemsEditPermissionsContainer.hide();
            var index = $(this).parents('li')[0].id.split('_')[2];
            $addcontentSelecteditemsEditDataContainer.html(sakai.api.Util.TemplateRenderer(addcontentSelectedItemsEditDataTemplate,{item: itemsToUpload[index], i:index}));
            $addcontentSelecteditemsEditDataContainer.show();
            $addcontentSelecteditemsEditDataContainer.css('left', $(this).parents('li').position().left + 'px');
            $addcontentSelecteditemsEditDataContainer.css('top', $(this).parents('li').position().top + 40 + 'px');

            var editValidateOpts = {
                onclick: true,
                onkeyup: function(element) {
                    $(element).valid();
                },
                onfocusout: true,
                success: function() {
                    $(addcontentContainerNewItemSaveChanges).removeAttr('disabled');
                },
                error: function() {
                    $(addcontentContainerNewItemSaveChanges).attr('disabled','disabled');
                }
            };

            sakai.api.Util.Forms.validate($(addcontentSelectedItemsEditDataForm), editValidateOpts, true);            
        };

        /**
         * Close the edit popup
         */
        var closeEditData = function() {
            $(this).parent().parent().hide();
        };

        /**
         * Save the changes made to a file in the queue
         */
        var saveEdit = function() {
            var index = $( addcontentSelectedItemsEditIndex ).attr( 'id' );
            if ( $addcontentSelecteditemsEditDataContainer.is( ':visible' ) ) {
                itemsToUpload[index]['sakai:pooled-content-file-name'] = $(addcontentSelecteditemsEditDataContainer + ' ' + addcontentSelectedItemsEditDataTitle).val();
                itemsToUpload[index]['sakai:description'] = $(addcontentSelecteditemsEditDataContainer + ' ' + addcontentSelectedItemsEditDataDescription).val();
            } else {
                itemsToUpload[index]['sakai:permissions'] = $(addcontentSelectedItemsEditPermissionsContainer + ' ' + addcontentSelectedItemsEditPermissionsPermissions).val();
            }
            $(this).parent().parent().hide();
            renderQueue();
        };


        ///////////////////////
        // UPLOADING ACTIONS //
        ///////////////////////

        /**
         * Check if all items have been uploaded
         */
        var checkUploadCompleted = function(files, contentObj) {
            itemsUploaded++;
            if (itemsToUpload.length === itemsUploaded) {
                sakai.api.Util.Modal.close($addcontentContainer);
                sakai.api.Util.progressIndicator.hideProgressIndicator();
                var librarytitle = $(addcontentSaveTo + ' option:selected').text();
                sakai.api.Util.notification.show(sakai.api.i18n.getValueForKey('LIBRARY'), sakai.api.Util.TemplateRenderer('addcontent_notification_finished_template', {
                    uploadcount: itemsUploaded,
                    contenturl: itemsToUpload[0].homePath,
                    contenttitle: itemsToUpload[0].name,
                    libraryid: libraryToUploadTo,
                    librarytitle: librarytitle
                }));
            }
        };

        /////////////////////////
        // Uploading new files //
        /////////////////////////

        /**
         * Do processing on uploaded files
         * @param {Object} data The data returned from the createfile service
         */
        var postFileUpload = function(data) {
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    for (var itemToUpload = 0; itemToUpload < itemsToUpload.length; itemToUpload++) {
                        if (itemsToUpload[itemToUpload]['sakai:originaltitle'] === i) {
                            itemsToUpload[itemToUpload] = $.extend({}, data[i].item, itemsToUpload[itemToUpload]);
                            if (data[i].type === 'imscp') {
                                setIMSCPContent(itemsToUpload[itemToUpload], data[i].item);
                            } else {
                                prepareSetDataOnContent(itemsToUpload[itemToUpload]);
                            }
                        }
                    }
                }
            }
        };

        /**
         * Execute the upload
         */
        var setXhrUpload = function() {
            var jqXHR = $('#addcontent_file_upload').fileupload('send', {
                files: filesList,
                success: function(data) {
                    data = $.parseJSON(data);
                    var extractedData = [];
                    postFileUpload(data);
                },
                error: function() {
                    checkUploadCompleted();
                }
            });
        };

        //////////////////////////////
        // Creating a new Sakai Doc //
        //////////////////////////////

        /**
         * Creates a Sakai document
         * @param {Number} index    Index of the current Sakai Doc in the itemsToUpload array
         */
        var createDocument = function(index) {
            var documentObj = itemsToUpload[index];
            var refID = sakai.api.Util.generateWidgetId();
            var title = documentObj['sakai:pooled-content-file-name'];
            var doc = {
                'structure0': JSON.stringify({
                    'page1': {
                        '_ref': refID,
                        '_order': 0,
                        '_title': title,
                        'main': {
                            '_ref': refID,
                            '_order': 0,
                            '_title': title
                        }
                    }
                }),
                'mimeType': 'x-sakai/document',
                'sakai:schemaversion': sakai.config.schemaVersion
            };

            $.ajax({
                url: uploadPath,
                data: doc,
                type: 'POST',
                dataType: 'json',
                success: function(data) {
                    documentObj = $.extend({}, data['_contentItem'].item, documentObj);
                    itemsToUpload[index] = documentObj;
                    var content = {};
                    content[refID] = sakai.config.defaultSakaiDocContent;
                    finishSakaiDoc(documentObj, content);
                },
                error: function(err) {
                    checkUploadCompleted();
                }
            });
        };

        /**
         * Add the page content for each of the pages in the Sakai Doc
         * @param {Object} documentObj    Content object of the ZIP file that contained the package
         * @param {Object} content        Initial page content for the IMS-CP package
         */
        var finishSakaiDoc = function(documentObj, content) {
            sakai.api.Server.saveJSON('/p/' + documentObj._path, content, function() {
                var batchRequests = [];
                for (var i in content) {
                    if (content.hasOwnProperty(i)) {
                        batchRequests.push({
                            url: '/p/' + documentObj['_path'] + '/' + i + '.save.json',
                            parameters: {
                                'sling:resourceType': 'sakai/pagecontent',
                                'sakai:pagecontent': JSON.stringify(content[i]),
                                '_charset_': 'utf-8'
                            },
                            method: 'POST'
                        });
                    }
                }
                sakai.api.Server.batch(batchRequests, function(success, response) {
                     prepareSetDataOnContent(documentObj);
                });
            });
        };

        ///////////////////
        // Adding a link //
        ///////////////////

        /**
         * Upload a link
         * @param {Number} index   Index of the current link in the itemsToUpload array
         */
        var uploadLink = function(index) {
            var linkObj = itemsToUpload[index];
            var preview = sakai.api.Content.getPreviewUrl(linkObj['sakai:pooled-content-url']);
            var link = {
                'contentType': 'link',
                'link': linkObj.link,
                'name': linkObj.name,
                'description': linkObj.description,
                'visibility': linkObj.visibility,
            };

            $.ajax({
                url: uploadPath,
                data: link,
                type: 'POST',
                dataType: 'JSON',
                success: function(data) {
                    linkObj = $.extend({}, data, linkObj);
                    itemsToUpload[index] = linkObj;
                    prepareSetDataOnContent(linkObj);
                },
                error: function() {
                    checkUploadCompleted();
                }
            });
        };

        //////////////////////////////
        // General metadata setting //
        //////////////////////////////

        var prepareSetDataOnContent = function(contentObj) {
            var setContent = function(obj) {
                checkUploadCompleted();
            };

            if ($.isArray(contentObj)) {
                $.each(contentObj, function(index, obj) {
                    setContent(obj);
                    lastUpload.push(obj);
                });
            } else {
                setContent(contentObj);
                lastUpload.push(contentObj);
            }
        };

        /////////////////////////////////////////////
        // Add all collected content to the system //
        /////////////////////////////////////////////

        /**
         * Execute the upload of the files in the queue by calling the functions needed for the specific type of content
         */
        var doUpload = function() {
            sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey('UPLOADING_YOUR_CONTENT'), sakai.api.i18n.getValueForKey('PROCESSING_UPLOAD'));
            libraryToUploadTo = $(addcontentSaveTo).val();

            // If iframe transport is used we have to submit the file upload forms
            if (useIframeTransport) {
                $.each(filesList, function(i, val) {
                    if (fileUploadForms[val.name]) {
                        fileUploadForms[val.name].submit();
                    }
                });
            }

            $.each(itemsToUpload, function(index,item) {
                switch(item.type) {
                    case 'link':
                        uploadLink(index);
                        break;
                    case 'content':
                        if (!contentUploaded) {
                            if (!useIframeTransport) {
                                setXhrUpload();
                            }
                            contentUploaded = true;
                        }
                        break;
                    case 'document':
                        createDocument(index);
                        break;
                }
            });
        };

        /**
         * Prefill some of the extra data a file can have
         * @param {String} fileName Name of the selected file
         */
        var preFillContentFields = function(fileName) {
            if (fileName.indexOf('\\') !== -1) {
                fileName = fileName.split('\\')[fileName.split('\\').length - 1];
            }
            $(addcontentUploadContentFields + ' ' + addcontentUploadContentTitle).val(fileName);
            $(addcontentUploadContentFields + ' ' + addcontentUploadContentOriginalTitle)[0].id = fileName;
            $(addcontentUploadContentTitle).select();
        };

        ////////////////
        // NAVIGATION //
        ////////////////

        /**
         * Reset the menu to its original state
         */
        var resetMenu = function() {
            $addcontentContainerNewItem.removeClass(addcontentContainerNewItemExtraRoundedBorderClass);
            $addcontentContainerLHChoiceItem.removeClass(addcontentContainerLHChoiceSelectedItem);
            $('#addcontent_upload_content').addClass(addcontentContainerLHChoiceSelectedItem);

            if (sakai.config.Permissions.Content.defaultaccess) {
                $('#addcontent_upload_content_permissions [value=' + sakai.config.Permissions.Content.defaultaccess + ']').attr('selected', 'selected');
            }
            if (sakai.config.Permissions.Documents.defaultaccess) {
                $('#addcontent_add_document_permissions [value=' + sakai.config.Permissions.Documents.defaultaccess + ']').attr('selected', 'selected');
            }
        };

        /**
         * Executed when a subitem in the navigation has been clicked
         */
        var navigateSubItem = function() {
            $(addcontentContainerLHChoiceSelectedSubitem).removeClass(addcontentContainerLHChoiceSelectedSubitemClass);
            $(this).addClass(addcontentContainerLHChoiceSelectedSubitemClass);
        };

        /////////////
        // BINDING //
        /////////////

        /**
         * Remove binding on all elements
         */
        var removeBinding = function() {
            $addcontentContainerLHChoiceItem.off('click', navigateMenu);
            $addcontentContainerLHChoiceSubItem.off('click', navigateSubItem);
            $addcontentContainerNewItemAddToList.off('click', constructItemToAdd);
            $(addcontentContainerStartUploadButton).off('click', doUpload);
            $addcontentContainer.off('click', addcontentSelectedItemsEditDataClose, closeEditData);
            $addcontentContainer.off('click', addcontentContainerNewItemSaveChanges, saveEdit);
            $addcontentContainer.off('click', addcontentSelectedItemsRemove, removeItemToAdd);
            $addcontentContainer.off('click', addcontentSelectedItemsActionsPermissions, changePermissions);
            $addcontentContainer.off('click', addcontentSelectedItemsActionsEdit, editData);
            $(window).off('init.deletecontent.sakai', deleteContent);
        };

        /**
         * Add binding to all elements
         */
        var addBinding = function() {
            $addcontentContainerLHChoiceItem.on('click', navigateMenu);
            $addcontentContainerLHChoiceSubItem.on('click', navigateSubItem);
            $addcontentContainerNewItemAddToList.on('click', constructItemToAdd);
            $(addcontentContainerStartUploadButton).on('click', doUpload);
            $addcontentContainer.on('click', addcontentSelectedItemsEditDataClose, closeEditData);
            $addcontentContainer.on('click', addcontentContainerNewItemSaveChanges, saveEdit);
            $addcontentContainer.on('click', addcontentSelectedItemsRemove, removeItemToAdd);
            $addcontentContainer.on('click', addcontentSelectedItemsActionsPermissions, changePermissions);
            $addcontentContainer.on('click', addcontentSelectedItemsActionsEdit, editData);
            sakai.api.Util.hideOnClickOut($addcontentSelecteditemsEditDataContainer, addcontentSelectedItemsActionsEdit + ', #assignlocation_container');
            sakai.api.Util.hideOnClickOut($addcontentSelectedItemsEditPermissionsContainer, addcontentSelectedItemsActionsPermissions);

            var fileuploadOptions = {
                url: uploadPath,
                sequentialUploads: true,
                singleFileUploads: false,
                dropZone: $('#addcontent_container_selecteditems'),
                drop: function(ev, data) {
                    ev.stopPropagation();
                    ev.preventDefault();
                    // We only support browsers that have XMLHttpRequest Level 2
                    if (!window.FormData) {
                        return false;
                    }
                    if ($(ev.target).is($('#addcontent_file_upload'))) {
                        var error = false;
                        $.each(data.files, function(index, file) {
                            if (file.size > 0) {
                                fileDropped(file);
                            } else {
                                error = true;
                            }
                        });
                        if (error) {
                            sakai.api.Util.notification.show(
                                sakai.api.i18n.getValueForKey('DRAG_AND_DROP_ERROR', 'addcontent'),
                                sakai.api.i18n.getValueForKey('ONE_OR_MORE_DROPPED_FILES_HAS_AN_ERROR', 'addcontent'));
                        }
                        renderQueue();
                    }
                },
                change: function(e, data) {
                    multifileQueueAddAllowed = false;
                    preFillContentFields(data.files[0].name);
                },
                add: function(e, data) {
                    tmpBrowsedFile = data.files[0];
                    if (useIframeTransport) {
                        fileUploadForms[data.files[0].name] = data;
                    }
                }
            };

            if (useIframeTransport) {
                fileuploadOptions.done = function(e, data) {
                    var result = {};
                    // In IE the result is inserted to the iframe
                    if ($('pre', data.result).length) {
                        result = $.parseJSON($('pre', data.result).text());
                    } else {
                        result = $.parseJSON(data.result);
                    }
                    postFileUpload(result);
                };
            }

            $('#addcontent_file_upload').fileupload(fileuploadOptions);

            $(document).on('done.deletecontent.sakai', deleteContent);
        };

        ////////////////////
        // INITIALIZATION //
        ////////////////////

        var setCurrentlySelectedLibrary = function() {
            if (sakai_global.group && sakai_global.group.groupId) {
                currentSelectedLibrary = sakai_global.group.groupId;
            }
        };

        /**
         * Call all functions and reset all variables needed to get the widget
         * into the original startup state
         */
        var resetWidget = function() {
            removeBinding();
            resetQueue();
            resetMenu();
            disableAddToQueue();
            disableStartUpload();
            multifileQueueAddAllowed = true;
            contentUploaded = false;
            hideAfterContentUpload = false;
            numberOfBrowsedFiles = 0;
            fileUploadForms = {};
        };

        /**
         * Initialize the widget
         */
        var initialize = function() {
            setCurrentlySelectedLibrary();
            resetWidget();
            addBinding();
            renderUploadNewContent();
        };

    };
});
{'fraction_non_alphanumeric': 0.11815623115241138, 'fraction_numerical': 0.001697679093975473, 'mean_word_length': 1.6060950052392595, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4816978', 'n_tokens_mistral': 21440, 'n_tokens_neox': 20544, 'n_words': 4230}