(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.AccountScreen = function(app) {
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var userId;
        var user = {};

        function beforeShow(data) {
            userId = data.id;
        }

        function afterShow(data) {
            resetForm();
            renderAccount()
        }

        function resetForm() {
            // remove all display errors
            $('#account-content-scroller form .error-text').remove()
            $('#account-content-scroller form .error').removeClass("error")
        }

        function populateAccount(userDetail) {

            var audioProfiles = prettyPrintAudioProfiles(context.jamClient.TrackGetDevices());

            var template = context.JK.fillTemplate($('#template-account-main').html(), {
                email: userDetail.email,
                name: userDetail.name,
                location : userDetail.location,
                instruments : prettyPrintInstruments(userDetail.instruments),
                photoUrl : context.JK.resolveAvatarUrl(userDetail.photo_url),
                profiles : audioProfiles
            });
            $('#account-content-scroller').html(template );
        }

        function prettyPrintAudioProfiles(devices) {
            if(devices && Object.keys(devices).length > 0) {
                var profiles = "";
                var delimiter = ", ";

                $.each(devices, function(deviceId, deviceLabel) {
                  profiles += deviceLabel;
                  profiles += delimiter;
                })

                return profiles.substring(0, profiles.length - delimiter.length);
            }
            else {
                return "no qualified audio profiles"
            }
        }

        function prettyPrintInstruments(instruments) {
            if(!instruments || instruments.length == 0) {
                return "no instruments";
            }
            else {
                var pp = "";
                $.each(instruments, function(index, item) {
                    pp += item.description;
                    if(index < instruments.length - 1) {
                        pp += ", ";
                    }
                })
                return pp;
            }
        }

            // events for main screen
        function events() {
            // wire up main panel clicks
            $('#account-content-scroller').on('click', '#account-edit-identity-link', function(evt) { evt.stopPropagation(); navToEditIdentity(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-profile-link', function(evt) { evt.stopPropagation(); navToEditProfile(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-subscriptions-link', function(evt) { evt.stopPropagation(); navToEditSubscriptions(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-payments-link', function(evt) { evt.stopPropagation(); navToEditPayments(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-audio-link', function(evt) { evt.stopPropagation(); navToEditAudio(); return false; } );
            $('#account-content-scroller').on('avatar_changed', '#profile-avatar', function(evt, newAvatarUrl) { evt.stopPropagation(); updateAvatar(newAvatarUrl); return false; })
        }

        function renderAccount() {
            rest.getUserDetail()
                .done(populateAccount)
                .error(app.ajaxError)
        }

        function navToEditIdentity() {
            resetForm()
            window.location = '#/account/identity'
        }

        function navToEditProfile() {
            resetForm()
            window.location = '#/account/profile'
        }

        function navToEditSubscriptions() {

        }

        function navToEditPayments() {

        }

        function navToEditAudio() {
            resetForm()
            window.location = "#/account/audio"
        }

        // 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', 'profile-avatar');
            $('#profile-avatar').replaceWith(avatar);
        }

        function navToAccount() {
            resetForm();
            renderAccount();
        }

        function initialize() {
            var screenBindings = {
                'beforeShow': beforeShow,
                'afterShow': afterShow
            };
            app.bindScreen('account', screenBindings);
            events();
        }

        this.initialize = initialize;
        this.beforeShow = beforeShow;
        this.afterShow = afterShow;
        return this;
    };

})(window,jQuery);