(function(context,$) {

    /**
    * Javascript for managing the header as well
    * as any dialogs reachable from there. Account settings dialog.
    */

    "use strict";

    context.JK = context.JK || {};
    context.JK.Header = function(app) {

        var logger = context.JK.logger;
        var searcher; // Will hold an instance to a JK.Searcher (search.js)
        var userMe = null;
        var instrumentAutoComplete;
        var instrumentIds = [];
        var instrumentNames = [];
        var instrumentPopularities = {};  // id -> popularity


        function loadInstruments() {
            // TODO: This won't work in the long-term. We'll need to provide
            // a handlers which accepts some characters and only returns users
            // who are musicians who match that input string. Once we get there,
            // we could just use the ajax functionality of the autocomplete plugin.
            //
            // But for now:
            // Load the users list into our local array for autocomplete.
            // var response = context.JK.getInstruments(app);
            // $.each(response, function() {
            //     instrumentNames.push(this.description);
            //     instrumentIds.push(this.id);
            //     // TODO - unused at the moment.
            //     instrumentPopularities[this.id] = this.popularity;
            // });
            // // Hook up the autocomplete.
            // var options = {
            //     lookup: {suggestions:instrumentNames, data: instrumentIds},
            //     onSelect: addInstrument,
            //     width: 120
            // };
            // if (!(instrumentAutoComplete)) { // Shouldn't happen here. Header only drawn once.
            //     instrumentAutoComplete = $('#profile-instruments').autocomplete(options);
            // } else {
            //     instrumentAutoComplete.setOptions(options);
            // }
            
            $.ajax({
                type: "GET",
                url: "/api/instruments"
            }).done(function(response) {
                $.each(response, function() {
                    instrumentNames.push(this.description);
                    instrumentIds.push(this.id);
                    // TODO - unused at the moment.
                    instrumentPopularities[this.id] = this.popularity;
                });
                // Hook up the autocomplete.
                var options = {
                    lookup: {suggestions:instrumentNames, data: instrumentIds},
                    onSelect: addInstrument,
                    width: 120
                };
                if (!(instrumentAutoComplete)) { // Shouldn't happen here. Header only drawn once.
                    instrumentAutoComplete = $('#profile-instruments').autocomplete(options);
                } else {
                    instrumentAutoComplete.setOptions(options);
                }
            });
        }

        function addInstrument(value, data) {
            var instrumentName = value;
            var instrumentId = data;
            var template = $('#template-profile-instrument').html();   // TODO: cache this
            var instrumentHtml = context.JK.fillTemplate(
                template, {instrumentId: instrumentId, instrumentName: instrumentName});
            $('#added-profile-instruments').append(instrumentHtml);
            $('#profile-instruments').select();
        }

        function setProficiency(id, proficiency) {
            logger.debug("setProficiency: " + id + ',' + proficiency);
            var selector = '#added-profile-instruments div.profile-instrument[instrument-id="' +
                id + '"] select';
            logger.debug("Finding select to set proficiency. Length? " + $(selector).length);
            $(selector).val(proficiency);
        }

        function removeInvitation(evt) {
            $(evt.currentTarget).closest('.profile-instrument').remove();
        }

        function events() {
            $('body').on('click', 'div[layout="header"] h1', function() {
                context.location = '/client#/home';
            });

            $('#account-identity-form').submit(handleIdentitySubmit);
            $('#account-profile-form').submit(handleProfileSubmit);
            // Remove added instruments when 'X' is clicked
            $('#added-profile-instruments').on("click", ".instrument span", removeInvitation);
        }

        function handleIdentitySubmit(evt) {
            evt.preventDefault();
            var user = $(evt.currentTarget).formToObject();
            if (!user.password) {
                delete user.password;
                delete user.password_confirmation;
            }
            $.ajax({
                type: "POST",
                url: "/api/users/" + userMe.id,
                contentType: "application/json",
                processData:false,
                data: JSON.stringify(user)
            }).done(function(response) {
                userMe = response;
            }).fail(app.ajaxError);
            return false;
        }

        function handleProfileSubmit(evt) {
            evt.preventDefault();
            var user = {
                name: $('#account-profile-form input[name="name"]').val(),
                instruments: []
            };
            var $added_instruments = $('.profile-instrument', '#added-profile-instruments');
            var count = 1;
            $.each($added_instruments, function() {
                var instrumentId = $(this).attr('instrument-id');
                var proficiency = $('select', this).val();
                logger.debug("Instrument ID:" + instrumentId + ", proficiency: " + proficiency);
                var instrument = {
                    id: instrumentId,
                    proficiency_level: proficiency,
                    priority: count++
                };
                user.instruments.push(instrument);
            });

            logger.debug("About to submit profile. User:");
            logger.debug(user);

            $.ajax({
                type: "POST",
                url: "/api/users/" + userMe.id,
                contentType: "application/json",
                processData:false,
                data: JSON.stringify(user)
            }).done(function(response) {
                userMe = response;
            }).fail(app.ajaxError);

            return false;
        }

        this.initialize = function() {
            events();
            loadInstruments();
            //searcher = new context.JK.Searcher(app);
            //searcher.initialize();
        };
    };

 })(window,jQuery);