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

    define(['underscore', 'jquery', 'backbone', 'models/metadata/eml211/EMLProject',
            'models/metadata/eml211/EMLParty',
            'text!themes/ess-dive/templates/metadata/project.html',
            'json!/js/themes/ess-dive/data/projects.json'],
        function (_, $, Backbone, EMLProject, EMLParty, Template, Projects) {

            /***
             * SubView for managing Funding Organizations
             *
             * @type {void|*}
             */
            var EMLProjectSubView = Backbone.View.extend({
                tagName: "div",

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

                events: {
                    "change input#new-project-value"   : "handleAdd",
                    "autocompletechange input#new-project-value"   : "handleAdd"
                },

                id: null,

                template: _.template(Template),

                projects: Projects,

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

                    // Assign the member variables to this instance
                    this.parentModel = options.parentModel;
                    this.doeProjects = this.getDOEProjects()

            	},

                            /**
                 * Get the list of DOE contract numbers
                 * @returns {Array}
                 */
                getDOEProjects: function () {
                    var doeProjectsJSON = this.projects;

                    return  _.mapObject(doeProjectsJSON, function(val, key){return key+" [PI: "+val.piFirstName+" "+ val.piLastName+"]";});
                },

                /**
                 * Render the template with the data
                 *
                 * @returns {EMLProjectSubView}
                 */
                render: function () {
                    // Render the template with the selected funding organizations
                    this.$el.html(this.template({
                            "project": this.getProject().toJSON(),
                        }
                    ));

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

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

                    return this;
                },

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

                    // Get the EML Project
                    var project = this.getProject();

                    // Get the project title  from the form
                    var projectTitle = $(e.target).val().split(" [")[0];
                    project.set("title",projectTitle);

                    // Does this project exist in our lookup?
                    if (this.projects.hasOwnProperty(projectTitle)){
                        // Get the PI detail from there
                        var projectDetail = this.projects[projectTitle];
                        var piInstitutions = projectDetail.piInstitution.split("\n");
                        var piFirstNames = projectDetail.piFirstName.split("\n");
                        var piLastNames = projectDetail.piLastName.split("\n");
                        var piEmails = projectDetail.piEmail.split("\n");
                        var pis = [];

                        for (i=0; i<piFirstNames.length; i++) {
                            var pi = new EMLParty({
                                role: "principalInvestigator",
                                parentModel: this.parentModel,
                                type: "personnel",
                                organizationName: piInstitutions[i].trim(),
                                individualName: {givenName: piFirstNames[i].trim(), surName: piLastNames[i].trim()},
                                email: [piEmails[i].trim()]
                            });
                            pis.push(pi)

                        }
                        project.set("personnel", pis);
                    }
                    else
                    {
                        // Set the project name as the metadata provider
                        project.set("personnel", [new EMLParty({
                                role: "metadataProvider",
    							parentModel: this.parentModel,
    							type: "personnel",
                                organizationName:$(e.target).val()
    						})]);
                    }

                    // Remove the old project DOM otherwise title change
                    // will not take
                    project.set("objectDOM",null);

                    // Create a new EML Project with the updated DOM
                    this.parentModel.set("project",new EMLProject({
                        parentModel: this.parentModel,
                        objectDOM: project.updateDOM()
                    }));

                    this.parentModel.set("publisher", [new EMLParty({ parentModel:this.parentModel,
                        organizationName:projectTitle,
                        type:"publisher"})]);

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

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

                },

                /**
                 * 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;
                }
            });

            return EMLProjectSubView;

        }
    );