# Source: themes/ess-dive/views/metadata/EMLFundingOrganizationsSubView.js

    define(['underscore', 'jquery', 'backbone', 'models/metadata/eml211/EMLParty',
            'text!themes/ess-dive/templates/metadata/fundingOrganization.html'],
        function (_, $, Backbone, EMLParty, Template) {

            /***
             * SubView for managing Funding Organizations
             *
             * @type {void|*}
             */
            var EMLFundingOrganizationsSubView = Backbone.View.extend({

                tagName: "div",

                attributes: {
                    "data-category":"fundingOrganization"
                },

                events: {
                    "change input#new-funding-organization-value"   : "handleAdd",
                    "autocompletechange input#new-funding-organization-value"   : "handleAdd",
                    "click  .remove" : "handleRemove"
                },

                id: null,

                template: _.template(Template),

                /**
                 * Load the Funding Organizations from JSON file
                 */
                getFundingOrganizationsJSON: function(){

                    // Synchronous call
                    return JSON.parse($.ajax({type: "GET", url: MetacatUI.root + "/js/themes/ess-dive/data/doe_funding_organizations.json", async: false}).responseText);

                },

                /**
                 * Get the list of DOE contract numbers
                 * @returns {Array}
                 */
                getFundingOrganizationNames: function () {
                    var json = this.getFundingOrganizationsJSON();
                    return  _.map( json, function(x){return x.organizationName;});
                },

                /**
                 * Creates an new EMLParty of type 'associatedParty' with role 'fundingOrganization'
                 *
                 * @param userId
                 * @param organizationName
                 * @returns {EMLParty}
                 */
                createModel: function (userId, organizationName) {
                   var fundingOrganization =  new EMLParty({
                            parentModel: this.parentModel,
                            role:"fundingOrganization",
                            type:"associatedParty",
                            userId:[userId],
                            organizationName: organizationName
                        });
                    return fundingOrganization;

                },

                /**
                 * Get the Funding Organization Models
                 * @returns {Array}
                 */
                getModels: function(){
                    return  _.filter(this.parentModel.get("associatedParty"),
                            function(party){ return party.get("role") == "fundingOrganization" });
                },

                /**
                 * Initialize the Sub View
                 * @param options
                 */
                initialize: function(options){

                    // Assign the member variables to this instance
                    this.parentModel = options.parentModel;

            	},

                /**
                 * Render the template with the data
                 *
                 * @returns {EMLFundingOrganizationsSubView}
                 */
                render: function () {
                    // Render the template with the selected funding organizations
                    this.$el.html(this.template(
                        {"fundingOrganizations":this.getModels().map(function(x){return  x.toJSON();})}
                    ));

                    // Add the Funder Names for the autocomplete list
                    var input = this.$el.find("#new-funding-organization-value")[0];
                    $(input).autocomplete({
                      source: this.getFundingOrganizationNames()
                    });

                    // This is a Subview
                    this.delegateEvents();

                    return this;
                },

                /**
                 * Remove the funding organization
                 * @param e
                 */
                handleRemove: function(e) {

                    // get the targe from the EML Model
                    var removeItem = _.filter(this.parentModel.get("associatedParty"),
                            function(party){ return party.get("userId")[0] == $(e.target).data('userid') ||
                                party.get("organizationName") == $(e.target).data('organization-name')});

                    // Remove funding organization from the EML Model
                    _.each(removeItem, this.parentModel.removeParty, this.parentModel);

                    this.render();

                    // Trigger a change on the entire package
    			    MetacatUI.rootDataPackage.packageModel.set("changed", true);

                },

                /**
                 * Event on select change. Update the model with the selected value
                 *
                 * @param e
                 */
                handleAdd: function(e) {

                    // Create a new funding Organization object
                    var userId = null;

                    // Search the list for the funding organization
                    var funder = _.find(this.getFundingOrganizationsJSON(), function (option) {
                        return option.organizationName == $(e.target).val();
                    });

                    // Grab the userId from the  funder
                    if (funder) userId = funder.userId;

                    // Create an EMLParty object with a fundingOrganization role
                    var fundingOrganization = this.createModel(userId,
                        $(e.target).val());

                    // Add the funding organization to the EML Model
                    this.parentModel.get("associatedParty").push(fundingOrganization);

                    //Re-render this view to update changes
                    this.render();

                    // Trigger a change on the entire package
    			    MetacatUI.rootDataPackage.packageModel.set("changed", true);

                }

            });

            return EMLFundingOrganizationsSubView;
        }
    );