var SB;
if (!SB) {
    SB = {};
}

SB.clearElem = function (elem) {
    elem.val('');
};

SB.addPlayEvents = function (tracks) {
    var i;

    tracks = tracks || [];

    for (i = 0; i < tracks.length; i ++) {
        $('#play-' + i).click(function (index) {
            return function () {
                if (!SB.checkPlayer()) {
                    return false;
                }
                $("#player-info").text(tracks[index].songTitle);
                niftyplayer('niftyPlayer').loadAndPlay(tracks[index].songURL);
                SB.increaseListenCount(tracks[index].id);
                SB.trackID = tracks[index].id;
                return false;
            }
        }(i));
    }
    $('#play-track, #play-button').click(function () {
        if (!SB.checkPlayer()) {
            return false;
        }
        niftyplayer('niftyPlayer').play();
        SB.increaseListenCount(SB.trackID);
        return false;
    });
};

SB.increaseListenCount = function (trackID) {
    $.ajax({
        type: 'GET',
        url:  SB.urlbase + '/_artist/inc_listens/' + trackID
    });
};

SB.openCommentDialog = function () {
    var dialog;
    var closeButton;

    $("#comment-name").val('');
    $("#comment-body").val('');
    dialog = $("#comment-dialog");
    closeButton = $("#comment-close");
    closeButton.click(function () {
        $(dialog).dialog('destroy');
    });
    $(dialog).dialog({title: 'Post a comment'});
    $(dialog).dialog('open');
    return dialog;
};

SB.message = function (message) {
    var dialog;
    var titleBar;
    var closeButton;
    var body;

    dialog = $('<div class="dialog"></div>');
    titleBar = $('<div class="title-bar"></div>');
    closeButton = $('<a href="#"><img src="' +
        SB.staticbase +
        '/img/closebutton.png"/></a>');
    body = $('<div class="message">' + message + '</div>');

    $(titleBar).append(closeButton);
    $(dialog).append(titleBar);
    $(dialog).append(body);

    $(dialog).dialog();
    $(closeButton).click(function () {
        $(dialog).dialog('destroy');
    });
    $(dialog).dialog('open');
};

SB.postComment = function (id, name, body, all) {
    if (!(id !== null && body)) {
        return;
    }
    $.ajax({
        type: 'POST',
        url:  SB.urlbase + '/_artist/comment',
        data: {track_id: id, name: name, body: body},
        success: function () {
            SB.showComments(id, all);
            $("#comment-dialog").dialog('close');
        },
        error: function () {
            SB.message('Error adding comment');
        }
    });
};

SB.displayComment = function(id, comment) {
    var commentsDiv;
    var commentDiv;
    var commentHTML;
    comments = $("#comments-" + id);
    comment.name = SB.htmlEncode(comment.name);
    comment.body = SB.htmlEncode(comment.body);
    commentHTML = (SB.commentDiv
                  ).replace('##id##', id
                  ).replace('##name##', comment.name
                  ).replace('##tstamp##', comment.tstamp
                  ).replace('##body##', comment.body);
    commentDiv = $(commentHTML);
    comments.append(commentDiv);
};

SB.htmlEncode = function (text) {
    var output;
    var tmp = $("<div></div>");
    $(tmp).text(text);
    output = $(tmp).text();
    delete tmp;
    output = output.replace(/\n/g, '<br/>');
    return output;
};

SB.showComments = function (id, all) {
    if (!id) {
        return;
    }
    $('#comments-' + id).empty();
    $.ajax({
        type: 'GET',
        url: SB.urlbase + '/_artist/getcomments/' + id,
        success: function (data) {
            var limit;
            var i;
            var json;
            var moreLink;
            var comments;

            comments = $("#comments-" + id);
            comments.html('');

            json = JSON.parse(data);
            limit = all ? json.length : Math.min(json.length, 10);
            for (i = 0; i < limit; i ++) {
                SB.displayComment(id, json[i]);
            }
            if (json.length > 10 && !all) {
                moreLink = $('<a>View all ' + json.length + ' comments</a>'
                    ).attr('href', SB.urlbase + '/_artist/track/' + id
                    ).addClass('more-link');
                $("#comments-" + id).append(moreLink);
            }
            $("#comments-" + id).show("slow");
        },
        error: function () {
            SB.message('Error loading comments.');
        }
    });
};

SB.hideComments = function (id) {
    if (!id) {
        return;
    }
    $('#comments-' + id).hide("slow");
};

SB.toggleComments = function (elem) {
    var id = $(elem).attr('id').replace('comment-view-', '');
    if (SB.commentToggleMap[id]) {
        SB.hideComments(id);
        $(elem).text('View Comments');
        SB.commentToggleMap[id] = false;
    } else {
        SB.showComments(id);
        $(elem).text('Hide Comments');
        SB.commentToggleMap[id] = true;
    }
};

SB.hideInfoMessage = function () {
    SB.infoMessage = $("#info-message");

    if (!SB.infoMessage) {
        return;
    }

    SB.infoMessage.slideDown();
    SB.flashCount = 0;
    SB.flashInfoMessage();
};

SB.flashInfoMessage = function () {
    if (SB.flashCount % 2) {
        SB.infoMessage.addClass('flash-on');
        SB.infoMessage.removeClass('flash-off');
    } else {
        SB.infoMessage.addClass('flash-off');
        SB.infoMessage.removeClass('flash-on');
    }

    SB.flashCount ++;

    if (SB.flashCount < 5) {
        setTimeout(SB.flashInfoMessage, 750);
    } else {
        SB.infoMessage.slideUp();
    }
};

SB.checkPlayer = function () {
    try {
        niftyplayer("niftyPlayer");
        return true;
    } catch (e) {
        // No flash, :(
        alert("Sorry, it looks like you don't have Flash, please" +
              "download the track instead.");
        return false;
    }
};

SB.init = function () {
    if (SB.active) {
        $('#' + SB.active + '-link').addClass('active');
    }
    SB.commentToggleMap = {};

    $('#login-username').focus(function () {
        SB.clearElem($(this));
    });
    $('#login-password').focus(function () {
        SB.clearElem($(this));
    });
    $(document).find('.comment-link').each(function () {
        $(this).click(function () {
            var dialog;
            var all = $(this).hasClass('showall');
            var id = $(this).attr('id').replace('comment-', '');
            dialog = SB.openCommentDialog();
            $("#comment-submit").unbind();
            $("#comment-submit").click(function () {
                SB.postComment(id,
                              $("#comment-name").val(),
                              $("#comment-body").val(),
                              all);
                return false;
            });
            return false;
        });
    });
    $(document).find('.comment-view').each(function () {
        $(this).click(function () {
            SB.toggleComments(this);
            return false;
        });
    });
    SB.addPlayEvents(SB.tracks);

    SB.hideInfoMessage();

    $("button.delete-track-button", "#maintext").button(
        {icons: {primary: "ui-icon-closethick"}});

    $("button.edit-track-button", "#maintext").button(
        {icons: {primary: "ui-icon-pencil"}});

    $("div.track-box", "#maintext"
        ).hover(function () {
                    $(this).find("button.delete-track-button, button.edit-track-button"
                        ).css("visibility", "visible");
                },
                function () {
                    $(this).find("button.delete-track-button, button.edit-track-button"
                        ).css("visibility", "hidden");
                });
    $("button.delete-track-button", "#maintext"
        ).click(
        function () {
            var that = this;
            $("#delete-confirm-dialog").dialog({
                resizable: false,
                height: 200,
                title: "Delete",
                modal: true,
                buttons: [
                    {
                     text: "Yes",
                     click: function () { $(this).dialog("close"); console.log(that); }
                    },
                    {
                     text: "No",
                     click: function () { $(this).dialog("close"); }
                    }]

        });
    });

    $("#contact-artist").button({icons: {primary: "ui-icon-mail-closed"}});

    $("#read-more").toggle(
        function () {
            // Animating max-height to "none" doesn't work so we need an exact
            // value.
            var height = $("#artist-description").get(0).scrollHeight;
            $("#artist-description").animate({"max-height": height}, 100);
            $(this).text("Show less");
            return false;
        },
        function () {
            $("#artist-description").animate({"max-height": "100px"}, 100);
            $(this).text("Show more");
            return false;
        });

    $("#contact-submit").button();

    $("#contact-artist").click(function () {
        $("#contact-dialog").dialog({
            resizable: false,
            width: 500,
            title: "Contact Artist",
            modal: true
        });
    });
};

$(document).ready(function () {
    SB.init();
});

SB.commentDiv = '<div id="comment-##id##" class="comment"><span class="comment-name">##name##</span><br/><span class="comment-tstamp">##tstamp##</span><div class="comment-body">##body##</div></div>';

