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

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

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

                tagName: "div",

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

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

                id: null,

                template: _.template(Template),

                /**
                 * Load the DOE contracts from JSON file
                 */
                getDOEContractsJSON: function(){

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

                },

                /**
                 * Get the list of DOE contract numbers
                 * @returns {Array}
                 */
                getDOEContractNumbers: function () {
                    var doeContractsJSON = this.getDOEContractsJSON();

                    return  _.mapObject(doeContractsJSON, function(val, key){return key + " ("+val+")";});
                },

                /**
                 * Return the Funding paragraphs
                 */
                getModels: function(){
                    return this.getProject().parse(this.getProject().updateDOM());
                },

                /**
                 * Get the current project, if it exists, otherwise create a new one
                 * @returns {*}
                 */
                getProject: function(){

                    var project = this.parentModel.get("project");
                    if (!project)
                        return new EMLProject({ parentModel: this.parentModel});
                    return project;
                },

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

                    // Assign the member variables to this instance
                    this.parentModel = options.parentModel;
                    this.contractNumbers = this.getDOEContractNumbers();
                    this.contractsJSON = this.getDOEContractsJSON();

            	},

                /**
                 * Render the template with the data
                 *
                 * @returns {EMLDOEContractsSubView}
                 */
                render: function () {
                    // Render the template with the selected funding organizations
                    this.$el.html(this.template(
                        {"doeContracts":_.filter(this.getModels().funding ,function(x){ return x.startsWith("DOE:")}),
                         "contractsJSON": this.contractsJSON}
                    ));

                    // Add the Funder Names for the autocomplete list
                    var input = this.$el.find("#new-doe-contract-value")[0];
                    $(input).autocomplete({
                      source: _.values(this.contractNumbers)
                    });

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

                    return this;
                },

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

                    // Get the Funding array
                    var project = this.getProject();
                    var funding = project.get("funding");

                    // Was this contract number already added?
                    var exists =_.find(funding, function(f){ return f.startsWith($(e.target).data('contract-number'));});

                    project.set("funding",_.without(funding, exists));

                    // Update the objectDOM
                    project.set("objectDOM",project.updateDOM());

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

                    this.render();

                },

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

                    // Get the Funding array
                    var project = this.getProject();
                    var funding = project.get("funding");

                    // Was this contract number already added?
                    var exists = _.find(funding, function(f){ return f.startsWith($(e.target).val());})

                    if (!exists || exists.length == 0){
                        // The contract number is new

                        // Add it to the project object (PREFIX with DOE if it doesn't have it)
                        var contractNumber = $(e.target).val();
                        if (! contractNumber.startsWith("DOE:")) contractNumber = "DOE:" + contractNumber

                        funding.push(contractNumber.split("(")[0].trim());
                        project.set("funding", funding);

                        // remove ObjectDOM
                        project.set("objectDOM",project.updateDOM());

                        // Create a new EML Project with the updated DOM
                        this.parentModel.set("project", project);

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

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

                }

            });

            return EMLDOEContractsSubView;
        }
    );