(function(context,$) {

    /**
    * Javascript for managing the header (account dropdown) 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
        var invitationDialog = new context.JK.InvitationDialog(app);
        var rest = new JK.Rest();

        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 = '#/home';
            });

            $('.userinfo').on('click', function() {
                $('ul.shortcuts', this).toggle();
            });

            $('.userinfo .invite-friends .menuheader').on('click', function(e) {
                $(this).closest('li').css('height', 'auto').find('ul').toggle();
                e.stopPropagation();
                return false;
            });

            /**
            $('.userinfo .sign-out a').on('click', function(e) {
                e.stopPropagation();

             /**   rest.signout()
                    .done(function() {

                    })

            });   */

            $('.invite-friends .google-invite a').on('click', function(e) {
                invitationDialog.showGoogleDialog();
            });

            $('.invite-friends .email-invite a').on('click', function(e) {
                invitationDialog.showEmailDialog();
            })

            $('#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);

            $('#header-avatar').on('avatar_changed', function(event, newAvatarUrl) {
                updateAvatar(newAvatarUrl);
                event.preventDefault();
                return false;
            })
        }

        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;
        }

        function loadMe() {
            $.ajax({
                url: '/api/users/' + context.JK.currentUserId
            }).done(function(r) {
                userMe = r;
                // TODO - Setting global variable for local user.
                context.JK.userMe = r;
                updateHeader();
            }).fail(app.ajaxError);
        }

        function updateHeader() {

            $('#user').html(userMe.name);
            showAvatar();
        }

        // initially show avatar
        function showAvatar() {
            var photoUrl = context.JK.resolveAvatarUrl(userMe.photo_url);
            $('#header-avatar').attr('src', photoUrl);
        }

        // handle update avatar event
        function updateAvatar(avatar_url) {
            var photoUrl = context.JK.resolveAvatarUrl(avatar_url);
            var avatar = $(new Image());
            avatar.attr('src', photoUrl + '?cache_bust=' + new Date().getTime());
            avatar.attr('alt', "Avatar");
            avatar.attr('id', 'header-avatar');
            $('#header-avatar').replaceWith(avatar);
        }

        this.initialize = function() {

            events();
            loadInstruments();
            loadMe();
            invitationDialog.initialize();


            //searcher = new context.JK.Searcher(app);
            //searcher.initialize();
        };

        this.loadMe = loadMe;
    };

 })(window,jQuery);