(function(context,$) {

    "use strict";

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

        var proficiencyDescriptionMap = {
            "1": "BEGINNER",
            "2": "INTERMEDIATE",
            "3": "EXPERT"
        };

        var proficiencyCssMap = {
            "1": "proficiency-beginner",
            "2": "proficiency-intermediate",
            "3": "proficiency-expert"
        };

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

        function afterShow(data) {
            resetForm();
            events();
            renderActive();
        }

        function resetForm() {
            $('#profile-instruments').empty();

            $('#profile-about').show();
            $('#profile-history').hide();
            $('#profile-bands').hide();
            $('#profile-social').hide();
            $('#profile-favorites').hide();

            $('.profile-nav a.active').removeClass('active');
            $('.profile-nav a.#profile-about-link').addClass('active');
        }

        /****************** MAIN PORTION OF SCREEN *****************/
        // events for main screen
        function events() {
            // wire up panel clicks
            $('#profile-about-link').click(renderAbout);
            $('#profile-history-link').click(renderHistory);
            $('#profile-bands-link').click(renderBands);
            $('#profile-social-link').click(renderSocial);
            $('#profile-favorites-link').click(renderFavorites);

            // wire up buttons if you're not viewing your own profile 
            if (userId != context.JK.currentUserId) {
                // wire up Add Friend click
                var friend = isFriend();
                configureFriendButton(friend);

                // wire up Follow click
                var following = isFollowing();
                configureFollowingButton(following);
            }
            else {
                $('#btn-add-friend').hide();
                $('#btn-follow-user').hide();
            }
        }

        function sendFriendRequest(evt) {
            evt.stopPropagation();
            context.JK.sendFriendRequest(app, userId, friendRequestCallback);
        }

        function removeFriend(evt) {
            evt.stopPropagation();

            var url = "/api/users/" + context.JK.currentUserId + "/friends/" + userId;
            $.ajax({
                type: "DELETE",
                dataType: "json",
                url: url,
                processData: false,
                success: function(response) {
                    renderActive();  // refresh stats
                    configureFriendButton(false);
                },
                error: app.ajaxError
            });
        }

        function isFriend() {
            var alreadyFriend = false;

            var url = "/api/users/" + context.JK.currentUserId + "/friends/" + userId;
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData: false,
                success: function(response) {
                    if (response.id !== undefined) {
                        alreadyFriend = true;
                    }
                    else {
                        alreadyFriend = false;
                    }
                },
                error: app.ajaxError
            });

            return alreadyFriend;
        }

        function friendRequestCallback() {
            configureFriendButton(true);
        }

        function configureFriendButton(friend) {
            $('#btn-add-friend').unbind("click");

            if (friend) {
                $('#btn-add-friend').text('REMOVE FRIEND');
                $('#btn-add-friend').click(removeFriend);
            }
            else {
                $('#btn-add-friend').text('ADD FRIEND');
                $('#btn-add-friend').click(sendFriendRequest);
            }
        }

        function addFollowing() {
            var newFollowing = {};
            newFollowing.user_id = userId;

            var url = "/api/users/" + context.JK.currentUserId + "/followings";
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: url,
                data: JSON.stringify(newFollowing),
                processData: false,
                success: function(response) {
                    renderActive();  // refresh stats
                    configureFollowingButton(true);
                },
                error: app.ajaxError
            });
        }

        function removeFollowing(isBand, id) {
            var following = {};

            if (!isBand) {
                following.user_id = id;
            }
            else {
                following.band_id = id;
            }

            var url = "/api/users/" + context.JK.currentUserId + "/followings";
            $.ajax({
                type: "DELETE",
                dataType: "json",
                contentType: 'application/json',
                url: url,
                data: JSON.stringify(following),
                processData: false,
                success: function(response) {
                    renderActive();  // refresh stats
                    if (!isBand) {
                        configureFollowingButton(false);
                    }
                    else {
                        configureBandFollowingButton(false, id);
                    }
                },
                error: app.ajaxError
            });
        }

        function isFollowing() {
            var alreadyFollowing = false;

            var url = "/api/users/" + context.JK.currentUserId + "/followings/" + userId;
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData: false,
                success: function(response) {
                    if (response.id !== undefined) {
                        alreadyFollowing = true;
                    }
                    else {
                        alreadyFollowing = false;
                    }
                },
                error: app.ajaxError
            });

            return alreadyFollowing;
        }

        function configureFollowingButton(following) {
            $('#btn-follow-user').unbind("click");

            if (following) {
                $('#btn-follow-user').text('STOP FOLLOWING');
                $('#btn-follow-user').click(function() {
                    removeFollowing(false, userId);
                });
            }
            else {
                $('#btn-follow-user').text('FOLLOW');
                $('#btn-follow-user').click(addFollowing);
            }
        }

        // refreshes the currently active tab
        function renderActive() {
            if ($('#profile-about-link').hasClass('active')) {
                renderAbout();
            }
            else if ($('#profile-history-link').hasClass('active')) {
                renderHistory();
            }
            else if ($('#profile-bands-link').hasClass('active')) {
                renderBands();
            }
            else if ($('#profile-social-link').hasClass('active')) {
                renderSocial();
            }
            else if ($('#profile-favorites-link').hasClass('active')) {
                renderFavorites();
            }
        }

        /****************** ABOUT TAB *****************/
        function renderAbout() {
            $('#profile-instruments').empty();

            $('#profile-about').show();
            $('#profile-history').hide();
            $('#profile-bands').hide();
            $('#profile-social').hide();
            $('#profile-favorites').hide();

            $('.profile-nav a.active').removeClass('active');
            $('.profile-nav a.#profile-about-link').addClass('active');

            bindAbout();
        }

        function bindAbout() {
            $('#profile-instruments').empty();
            var url = "/api/users/" + userId;
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData:false,
                success: function(response) {
                    user = response;
                },
                error: app.ajaxError
            });

            if (user) {

                // name
                $('#profile-username').html(user.name);

                // avatar
                $('#profile-avatar').attr('src', context.JK.resolveAvatarUrl(user.photo_url));

                // instruments
                if (user.instruments) {
                    for (var i=0; i < user.instruments.length; i++) {
                        var instrument = user.instruments[i];
                        var description = instrument.instrument_id;
                        var proficiency = instrument.proficiency_level;
                        var instrument_icon_url = context.JK.getInstrumentIcon45(description);

                        // add instrument info to layout
                        var template = $('#template-profile-instruments').html();
                        var instrumentHtml = context.JK.fillTemplate(template, {
                            instrument_logo_url: instrument_icon_url,
                            instrument_description: description,
                            proficiency_level: proficiencyDescriptionMap[proficiency],
                            proficiency_level_css: proficiencyCssMap[proficiency]
                        });

                        $('#profile-instruments').append(instrumentHtml);
                    }
                }

                // location
                $('#profile-location').html(user.location);

                // stats
                var text = user.friend_count > 1 || user.friend_count == 0 ? " Friends" : " Friend";
                $('#profile-friend-stats').html(user.friend_count + text);

                text = user.follower_count > 1 || user.follower_count == 0 ? " Followers" : " Follower";
                $('#profile-follower-stats').html(user.follower_count + text);

                text = user.session_count > 1 || user.session_count == 0 ? " Sessions" : " Session";
                $('#profile-session-stats').html(user.session_count + text);

                text = user.recording_count > 1 || user.recording_count == 0 ? " Recordings" : " Recording";
                $('#profile-recording-stats').html(user.recording_count + text);

                //$('#profile-biography').html(user.biography);
            }
            else {

            }
        }

        /****************** SOCIAL TAB *****************/
        function renderSocial() {
            $('#profile-social-friends').empty();
            $('#profile-social-followings').empty();
            $('#profile-social-followers').empty();

            $('#profile-about').hide();
            $('#profile-history').hide();
            $('#profile-bands').hide();
            $('#profile-social').show();
            $('#profile-favorites').hide();

            $('.profile-nav a.active').removeClass('active');
            $('.profile-nav a.#profile-social-link').addClass('active');

            bindSocial();
        }

        function bindSocial() {
            // FRIENDS
            var url = "/api/users/" + userId + "/friends";
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData:false,
                success: function(response) {
                    $.each(response, function(index, val) {
                        var template = $('#template-profile-social').html();
                        var friendHtml = context.JK.fillTemplate(template, {
                            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
                            userName: val.name,
                            location: val.location,
                            type: "Friends"
                        });

                        $('#profile-social-friends').append(friendHtml);
                    });
                },
                error: app.ajaxError
            });

            // FOLLOWINGS (USERS)
            url = "/api/users/" + userId + "/followings";
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData:false,
                success: function(response) {
                    $.each(response, function(index, val) {
                        var template = $('#template-profile-social').html();
                        var followingHtml = context.JK.fillTemplate(template, {
                            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
                            userName: val.name,
                            location: val.location
                        });

                        $('#profile-social-followings').append(followingHtml);
                    });
                },
                error: app.ajaxError
            });

            // FOLLOWINGS (BANDS)
            url = "/api/users/" + userId + "/band_followings";
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData:false,
                success: function(response) {
                    $.each(response, function(index, val) {
                        var template = $('#template-profile-social').html();
                        var followingHtml = context.JK.fillTemplate(template, {
                            avatar_url: context.JK.resolveAvatarUrl(val.logo_url),
                            userName: val.name,
                            location: val.location
                        });

                        $('#profile-social-followings').append(followingHtml);
                    });
                },
                error: app.ajaxError
            });

            // FOLLOWERS
            url = "/api/users/" + userId + "/followers";
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData:false,
                success: function(response) {
                    $.each(response, function(index, val) {
                        var template = $('#template-profile-social').html();
                        var followerHtml = context.JK.fillTemplate(template, {
                            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
                            userName: val.name,
                            location: val.location
                        });

                        $('#profile-social-followers').append(followerHtml);
                    });
                },
                error: app.ajaxError
            });
        }

        /****************** HISTORY TAB *****************/
        function renderHistory() {
            $('#profile-about').hide();
            $('#profile-history').show();
            $('#profile-bands').hide();
            $('#profile-social').hide();
            $('#profile-favorites').hide();

            $('.profile-nav a.active').removeClass('active');
            $('.profile-nav a.#profile-history-link').addClass('active');

            bindHistory();        
        }

        function bindHistory() {

        }

        /****************** BANDS TAB *****************/
        function renderBands() {
            $('#profile-bands').empty();

            $('#profile-about').hide();
            $('#profile-history').hide();
            $('#profile-bands').show();
            $('#profile-social').hide();
            $('#profile-favorites').hide();

            $('.profile-nav a.active').removeClass('active');
            $('.profile-nav a.#profile-bands-link').addClass('active');

            bindBands();
        }

        function bindBands() {
            var url = "/api/users/" + userId + "/bands";
            $.ajax({
                 type: "GET",
                 dataType: "json",
                 url: url,
                 async: false,
                 processData:false,
                 success: function(response) {
                     $.each(response, function(index, val) {
                         var template = $('#template-profile-bands').html();
                         var bandHtml = context.JK.fillTemplate(template, {
                             bandId: val.id,
                             avatar_url: context.JK.resolveAvatarUrl(val.logo_url),
                             name: val.name,
                             location: val.location,
                             genres: formatGenres(val.genres)
                         });

                         $('#profile-bands').append(bandHtml);

                         // wire up Band Follow button click handler
                         var following = isFollowingBand(val.id);
                         configureBandFollowingButton(following, val.id);
                     });
                 },
                 error: app.ajaxError
            });
        }

        function formatGenres(genres) {
            var formattedGenres = '';
            for (var i=0; i < genres.length; i++) {
                var genre = genres[i];
                formattedGenres += genre.description;
                if (i < genres.length -1) {
                    formattedGenres += ', ';
                }
            }
            return formattedGenres;
        }

        function addBandFollowing(evt) {
            evt.stopPropagation();
            var bandId = $(this).parent().attr('band-id');

            var newFollowing = {};
            newFollowing.band_id = bandId;

            var url = "/api/users/" + context.JK.currentUserId + "/followings";
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: url,
                data: JSON.stringify(newFollowing),
                processData: false,
                success: function(response) {
                    renderActive();  // refresh stats
                    configureBandFollowingButton(true, bandId);
                },
                error: app.ajaxError
            });
        }

        function isFollowingBand(bandId) {
            var alreadyFollowing = false;

            var url = "/api/users/" + context.JK.currentUserId + "/band_followings/" + bandId;
            $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: false,
                processData: false,
                success: function(response) {
                    if (response.id !== undefined) {
                        alreadyFollowing = true;
                    }
                    else {
                        alreadyFollowing = false;
                    }
                },
                error: app.ajaxError
            });

            return alreadyFollowing;
        }

        function configureBandFollowingButton(following, bandId) {
            var $btnFollowBand = $('div[band-id=' + bandId + ']', '#profile-bands').find('#btn-follow-band');
            $btnFollowBand.unbind("click");

            if (following) {
                $btnFollowBand.text('UN-FOLLOW');
                $btnFollowBand.click(function() {
                    removeFollowing(true, bandId);
                });
            }
            else {
                $btnFollowBand.text('FOLLOW');
                $btnFollowBand.click(addBandFollowing);
            }
        }

        /****************** FAVORITES TAB *****************/
        function renderFavorites() {
            $('#profile-about').hide();
            $('#profile-history').hide();
            $('#profile-bands').hide();
            $('#profile-social').hide();
            $('#profile-favorites').show();

            $('.profile-nav a.active').removeClass('active');
            $('.profile-nav a.#profile-favorites-link').addClass('active');

            bindFavorites();
        }

        function bindFavorites() {
        }

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

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

 })(window,jQuery);