﻿$(document).ready(function () {

    $("div#lp_dialogs_bookshelf_labels").dialog({
        title: 'BookShelf',
        autoOpen: false,
        modal: true,
        width: 300,
        resizable: false,
        draggable: false,
        buttons: {
            "Save": function () {

                $("#lp_dialogs_bookshelf_labels").addClass('ui-state-disabled').attr('disabled', true);
                $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").addClass('saving_button');


                // get the pmid
                var pmid = $("div#lp_dialogs_bookshelf_labels").data('pmid');

                // get all checked boxes
                var labels = [];

                $('ul#lp_dialogs_bookshelf_labels_checkboxlist>li>input:checkbox:checked').each(function () {
                    labels[labels.length] = $(this).attr('value');
                });

                // get the new label
                var new_label = jQuery.trim($('#lp_dialogs_bookshelf_labels_create').attr('value'));

                if (new_label != "" && new_label != bookshelf_labels_dialog_create_label_initial_text) {
                    labels[labels.length] = new_label;
                }
                else {
                    // make the new label empty so we can easily test later if a new label must be added to the label list
                    new_label = "";
                }

                wsLinkedPapers.User_Citation_Labels_Save(
                    pmid
                    ,
                    labels
                    ,
                    function (result) {
                        var $li = $(".linkedpaper_" + pmid);

                        if ($li.hasClass("is_in_bookshelf")) {
                        }
                        else {
                            $li.addClass('is_in_bookshelf');

                            var i = parseInt($li.find("div.title > div.menu > a.bookshelf").text()) + 1;
                            $li
                                .addClass('is_in_bookshelf')
                                .find("div.title > div.menu > a.bookshelf")
                                .text(i.toString())
                                .attr("title", getCitationToolBookshelfMouseOverMessage(true, i));
                        }

                        $li.find("div.menu a.label").text(labels.join(','));

                        if (new_label != "") {
                            lp_bookshelf_labels_create(new_label, 1);
                        }

                        if (labels.length == 0) {
                            $li.removeClass('has_labels').addClass('has_no_labels');
                        }
                        else {
                            $li.removeClass('has_no_labels').addClass('has_labels');
                        }

                        lp_bookshelf_recalculate_label_citations();

                        bookshelf_articlelist_update();

                        $("div#lp_dialogs_bookshelf_labels").dialog("close");
                    }
                    ,
                    function (result) {
                    }
                );

            }
            ,
            "Cancel": function () {
                $("div#lp_dialogs_bookshelf_labels").dialog("close");
            }
        }
    });

    $("div#lp_dialogs_bookshelf_login").dialog({
        title: 'BookShelf',
        autoOpen: false,
        modal: true,
        width: 300,
        resizable: false,
        draggable: false,
        buttons: {
            "Close": function () {
                $("div#lp_dialogs_bookshelf_login").dialog("close");
            }
            ,
            "Log in": function () {
                $("div#lp_dialogs_note_not_logged_in").dialog("close");
                document.location = "/Secure/LogIn.aspx?ReturnUrl=" + window.location.href;
            }
            ,
            "Sign up": function () {
                $("div#lp_dialogs_note_not_logged_in").dialog("close");
                document.location = "/SignUp.aspx";
            }
        }
    });

    $("div#lp_dropbox_bookshelf_login").dialog({
        title: 'BookShelf',
        autoOpen: false,
        modal: true,
        width: 300,
        resizable: false,
        draggable: false,
        buttons: {
            "Close": function () {
                $(this).dialog("close");
            }
            ,
            "Log in": function () {
                $("div#lp_dropbox_bookshelf_login").dialog("close");
                document.location = "/Secure/LogIn.aspx?ReturnUrl=" + window.location.href;
            }
            ,
            "Sign up": function () {
                $("div#lp_dropbox_bookshelf_login").dialog("close");
                document.location = "/SignUp.aspx";
            }
        }
    });

    $("div#lp_add_bookshelf_login").dialog({
        title: 'BookShelf',
        autoOpen: false,
        modal: true,
        width: 300,
        resizable: false,
        draggable: false,
        buttons: {
            "Close": function () {
                $(this).dialog("close");
            }
            ,
            "Log in": function () {
                $("div#lp_dropbox_bookshelf_login").dialog("close");
                document.location = "/Secure/LogIn.aspx?ReturnUrl=" + window.location.href;
            }
            ,
            "Sign up": function () {
                $("div#lp_dropbox_bookshelf_login").dialog("close");
                document.location = "/SignUp.aspx";
            }
        }
    });

    $('#lp_dialogs_bookshelf_labels_create').keyup(function (event) {

        if ($('#lp_dialogs_bookshelf_labels_create').val().length == 0) {
            // the label is empty, blur to 
            $('#lp_dialogs_bookshelf_labels_create').blur();
        }
        else if ($('#lp_dialogs_bookshelf_labels_create').val().length > 36) {
            // the label is too long
            $('#lp_dialogs_bookshelf_labels_create_icon').removeClass().addClass('error');
            $('#lp_dialogs_bookshelf_labels_create_icon_error_message').text('the label is too long');
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").addClass('ui-state-disabled').attr('disabled', true);
        }
        else if (!validate_label_text_characters($('#lp_dialogs_bookshelf_labels_create').val())) {
            // the label contains invalid characters
            $('#lp_dialogs_bookshelf_labels_create_icon').removeClass().addClass('error');
            $('#lp_dialogs_bookshelf_labels_create_error_message').text('Only letters, numbers, spaces and dashes allowed');
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").addClass('ui-state-disabled').attr('disabled', true);
        }
        else if (lp_bookshelf_label_exists($('#lp_dialogs_bookshelf_labels_create').val())) {
            // this label already exists
            $('#lp_dialogs_bookshelf_labels_create_icon').removeClass().addClass('error');
            $('#lp_dialogs_bookshelf_labels_create_error_message').text('this label already exists');
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").addClass('ui-state-disabled').attr('disabled', true);
        }
        else if (event.keyCode == 13) {
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").click();
        }
        else {

            $('#lp_dialogs_bookshelf_labels_create_icon').removeClass().addClass('ok');
            $('#lp_dialogs_bookshelf_labels_create_error_message').text('');
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").removeClass('ui-state-disabled').attr('disabled', false);
        }
    });


});

var bookshelf_labels_dialog_create_label_initial_text = "Click to create a new label...";

function lp_bookshelf_dialog_label_open(_pmid)
{

    if ($("body").hasClass('logged_in')) {

        // reset the dialog
        $("div#lp_dialogs_bookshelf_labels_no_labels").hide();

        $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").removeClass('ui-state-disabled').attr('disabled', false);

        $("input#lp_dialogs_bookshelf_labels_create").attr("value", bookshelf_labels_dialog_create_label_initial_text);
        $("input#lp_dialogs_bookshelf_labels_create").removeClass();
        $("input#lp_dialogs_bookshelf_labels_create").addClass("initial");

        $("input#lp_dialogs_bookshelf_labels_create").focus(function () {
            if ($(this).attr('value') == bookshelf_labels_dialog_create_label_initial_text) {
                $(this).attr('value', '');
                $("input#lp_dialogs_bookshelf_labels_create").removeClass("initial");
            }
        });

        $("input#lp_dialogs_bookshelf_labels_create").blur(function () {
            if ($(this).attr('value') == "") {
                $(this).attr('value', bookshelf_labels_dialog_create_label_initial_text);
                $("input#lp_dialogs_bookshelf_labels_create").addClass("initial");

                $('#lp_dialogs_bookshelf_labels_create_icon').removeClass();
                $('#lp_dialogs_bookshelf_labels_create_error_message').text('');
                $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").removeClass('ui-state-disabled').attr('disabled', false);
            }
        });

        $("span#lp_dialogs_bookshelf_labels_create_icon").removeClass();

        $("div#lp_dialogs_bookshelf_labels_loading").show();
        $("ul#lp_dialogs_bookshelf_labels_checkboxlist").children().remove();

        // store the pmid for use when pressing 'ok'
        $('div#lp_dialogs_bookshelf_labels').data('pmid', _pmid);

        // hide remove button. show later if we encounter a label
        if ($('#bookshelf_articles').length == 1) {
            // we are in the bookshelf. show the remove button
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Remove')").show();
        }
        else {
            // we are not in the bookshelf. hide the remove button
            $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Remove')").hide();
        }

        // create the checkboxes
        var attached_labels = $(".linkedpaper_" + _pmid + " div.menu a.label").text().split(",");

        $("#bookshelf_user_labels li a.label").each(function () {

            var value = $(this).attr('title');

            var checkbox_label_id = "checkbox_label_" + value.replace(/ /g, "_");

            $li = $('ul#lp_dialogs_bookshelf_labels_checkboxlist').append("<li></li>").children("li:last");

            $checkbox = $li.append("<input type='checkbox' style='vertical-align: middle;'>").children(":last");
            $checkbox.attr('id', checkbox_label_id)
            $checkbox.attr('checked', jQuery.inArray(value, attached_labels) > -1);
            $checkbox.attr('value', value);

            $label = $li.append("<label style='margin-left: 4px;'></label>").children(":last");
            $label.text(value)
            $label.attr('title', value)
            $label.attr('for', checkbox_label_id)
            $label.hover(
                function () { $(this).css('cursor', 'default').css('text-decoration', 'underline'); },
                function () { $(this).css('cursor', 'default').css('text-decoration', 'none'); }
            );

            if (jQuery.inArray(value, attached_labels) > -1) {
                $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Remove')").removeClass('ui-state-disabled').removeAttr('disabled');
            }

        });

        // sort the lot
        $('ul#lp_dialogs_bookshelf_labels_checkboxlist>li:has(input:checkbox:checked)').tsort();
        $('ul#lp_dialogs_bookshelf_labels_checkboxlist>li:has(input:checkbox:not(:checked))').tsort();

        // enable all controls
        $("#lp_dialogs_bookshelf_labels").removeClass('ui-state-disabled').removeAttr('disabled');
        $('[aria-labelledby$=lp_dialogs_bookshelf_labels]').find(":button:contains('Save')").removeClass('saving_button');

        // open it
        $('div#lp_dialogs_bookshelf_labels').dialog('open');

        return;

    }
    else {
        $("div#lp_dialogs_bookshelf_login").dialog('open');
    }

    return;
}


Array.prototype.occurences = function (value, array) {
    var i = 0;
    for (var t = 0; t < array.length; t++) {
        if (value == array[t]) i++;
    }
    return i;
}

function lp_bookshelf_recalculate_label_citations() {
    // all
    $("#bookshelf_special_labels_all a.label span.citations").text($('#bookshelf_articles li').length);

    // unlabelled
    var c = 0;
    $("#bookshelf_articles li div.title div.menu a.label").each(function () {
        if ($(this).text() == "") c++;
    });
    $("#bookshelf_special_labels_unlabelled a.label span.citations").text(c);

    // with notes
    c = 0;
    $("#bookshelf_articles li div.title div.menu a.note").each(function () {
        if ($(this).text() != "") c++;
    });
    $("#bookshelf_special_labels_with_notes a.label span.citations").text(c);

    // with comments
    c = 0;
    $("#bookshelf_articles li").each(function () {
        if ($(this).hasClass('has_comments')) c++;
    });
    $("#bookshelf_special_labels_with_comments a.label span.citations").text(c);

    // with PDF
    c = 0;
    $("#bookshelf_articles li").each(function () {
        if ($(this).hasClass('has_pdf')) c++;
    });
    $("#bookshelf_special_labels_with_pdf a.label span.citations").text(c);

    // with my_comments
    // TODO: make

    // labels
    $("#bookshelf_user_labels li").each(function () {

        var label_text = $(this).children("a.label:first").attr('title');
        c = 0;

        $("ol#bookshelf_articles li").each(function (i, e) {

            var labels = $(this).children("div.title").children("div.menu").children("a.label:first").text().split(',');

            if ($.inArray(label_text, labels) > -1) {
                c++;
            }
        });

        $(this).children('a.label').children('span.citations:first').text(c);
    });
}

function lp_bookshelf_labels_create(_text, _citations) {

    // the spaces inside the appends make for the same layout as does the html!!!

    var $li = $("#bookshelf_user_labels").append("<li></li>").children('li:last');

    $a_label = $li.append("<a class='label' href='Javascript: void(0);' onclick='bookshelf_label_click($(this))' title='"+_text+"'></a>  ").children('a:last');


    $a_label.append("<span class='text'>" + _text.cutline(14) + "</span> ");
    $a_label.append(' (');
    $a_label.append("<span class='citations'>" + _citations + "</span>");
    $a_label.append(') ');    

    $li.append(" <a class='rename' title='rename' href='Javascript: void(0);' onclick='lp_dialogs_bookshelf_rename_label_open($(this).siblings(\"a.label:first\").attr(\"title\"));'>rename label</a>");
    $li.append(" <a class='delete' title='delete' href='Javascript: void(0);' onclick='lp_dialogs_bookshelf_delete_label_open($(this).siblings(\"a.label:first\").attr(\"title\"));'>delete label</a>");

    // resort the list
    $('ul#bookshelf_user_labels li').tsort("a.label span.text");

    // make the li height 0
    $li.css('height', '0px');

    // make the li almost invisible
    $li.fadeTo("fast", 0.01, function () {
        //$li.show();
        $li.animate({ height: '14px' }, 500, function () {
            $li.fadeTo("slow", 1, function () {
                if ($.browser.msie) this.style.removeAttribute('filter');
            });
        });
    });

}

