﻿$(document).ready(function () {

    // prepare the bookshelf, dialogs and all
    //linkedpapers_bookshelf_initialize();

    $('#lp_dialogs_bookshelf_labels_create_empty').keyup(function (event) {
        if (validate_label_text_characters($(this).attr('value'))) {
            $('#lp_dialogs_bookshelf_labels_new_icon').removeClass();
            $('#lp_dialogs_bookshelf_labels_new_icon').addClass('ok');
        }
        else {
            $('#lp_dialogs_bookshelf_labels_new_icon').removeClass();
            $('#lp_dialogs_bookshelf_labels_new_icon').addClass('error');
        }
    });
});

function lp_ajax_error(result) {

    $("#lp_dialogs_ajax_error_type").text(result.get_exceptionType());
    $("#lp_dialogs_ajax_error_message").text(result.get_message());
    $("#lp_dialogs_ajax_error_stacktrace").text(result.get_stackTrace())
    
    $("div#lp_dialogs_ajax_error").dialog("open");
}

function getReferencedLabelFromReferencedLabelList(label, list) {

    for (var t = 0; t < list.length; t++) {
        if (list[t].label == label) {
            return list[t];
        }
    }
    
    return null;
}

function validate_label_text_characters(str) {

    str = jQuery.trim(str);

    var allowed_characters = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ-1234567890";

    for (var t = 0; t < str.length; t++) {
        if (allowed_characters.indexOf(str.charAt(t))==-1) {
            return false;
        }
    }

    return true;

}

function validate_input(str, min_length, max_length, allowed_characters, trim_first) {

    if (trim_first) str = jQuery.trim(str);

    if (str.length < min_length) {
        return 0;
    }
    else if (str.length > max_length) {
        return -1;
    }

    for (var t = 0; t < str.length; t++) {
        if (allowed_characters.indexOf(str.charAt(t)) == -1) {
            return -1;
        }
    }

    return 1;

}

function linkedpaper(pmid, title, body, authors, journal, journal_title, date_published, labels, has_comments, _has_notes) {
    this.pmid = pmid;
    this.title = title;
    this.body = body;
    this.authors = authors;
    this.journal = journal;
    this.journal_title = journal_title;
    this.date_published = date_published;
    this.labels = labels;
    this.has_comments = has_comments;
    this.has_notes = _has_notes;
}

function labellistlabel(label, articles) {
    this.label = label;
    this.articles = articles;
}

function referencedlabel(label, set) {
    this.label = label;
    this.set = set;
}

referencedlabel.prototype.toString = function() {
    return this.label + ": " + this.set + "\n";
}


var databind_counter = 0;

var start_time;
var end_time;

function linkedpaper_databind(linkedpapers, selector) {

    // linkedpapers: the array with linkedpapers (object: linkedpaper)
    // selector: the jQuery selector of the element to add list items to (usually ul#foo or ol#foo)

    // get the actual id from the selector, so we can use it when creating id's for the children

    if (selector.indexOf('#') == -1) {
        // this selector *must* have an id, otherwise, don't do anything
        return;
    }
    
    var list_id = selector.substring(selector.indexOf('#') + 1, selector.length);

    for (var t = 0; t < linkedpapers.length; t++) {

        log += t + ": ";

        // add this linkedpaper to the named selector
        $(selector).append(linkedpaper_render(linkedpapers[t], list_id));

        var current_item_id = "linkedpaper_" + list_id + "_" + linkedpapers[t].pmid;
        $("#" + current_item_id).data('linkedpaper', linkedpapers[t]);

        linkedpaper_decorate($("#" + current_item_id));

     }



}

var log = "log\n";


function linkedpaper_decorate_discuss(jqo) {

    jqo.children("div.menu").first().children("a.discuss").first().attr('href', '/LinkedPaper.aspx?pmid=' + jqo.data('linkedpaper').pmid);

    if (jqo.data('linkedpaper').has_comments) {
        jqo.children("div.menu").first().children("a.discuss").first().addClass("has_comments");
    }
    else {
        jqo.children("div.menu").first().children("a.discuss").first().addClass("has_no_comments");
    }

}

function linkedpaper_decorate_label(jqo) {

    // decide what icon to use

    if ($("body").hasClass('logged_in')) {
        if (BookShelf.containsArticle(jqo.data('linkedpaper').pmid)) {
            jqo.addClass("in_bookshelf");
        }
        else {
            jqo.addClass("not_in_bookshelf");
        }
    }
    else {
        jqo.addClass("not_logged_in");
    }

    // unfix the href

    jqo.children("div.menu").first().children("a.label").first().attr('href', 'Javascript: void(0);');
	        	            
    // create the onclick

    jqo.children("div.menu").first().children("a.label").first().click(function() {
        lp_bookshelf_dialog_label_open(jqo.data('linkedpaper').pmid);
    });

}

function isValidEmailAddress(emailAddress) {  
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);  
    return pattern.test(emailAddress);  
} 

function linkedpaper_decorate_expand(jqo) {

    jqo.children("div.body").first().children("a.expand").first().toggle(
            function () {
                jqo.children("div.body").first().slideUp();
            },
            function () {
                jqo.children("div.body").first().slideDown();
            }
        );

    return;

    var startHeight = jqo.children("div.body").first().height();

    if (startHeight > 34) {

        jqo.children("div.body").first().children("a.expand").first().addClass('contracted');

        jqo.children("div.body").first().height(34);

        jqo.children("div.body").first().children("a.expand").first().toggle(
            function() {
                jqo.children("div.body").first().animate({ height: startHeight });
                jqo.children("div.body").first().children("a.expand").first().removeClass('contracted').addClass('expanded');
                $(this).children("img").fadeTo("medium", 0.0);
            },
            function() {
                jqo.children("div.body").first().animate({ height: 34 });
                jqo.children("div.body").first().children("a.expand").first().removeClass('expanded').addClass('contracted');
                $(this).children("img").fadeTo("medium", 1.0);
            }
        )
        .hover(function () {
            $(this).fadeTo("fast", 1.0);
        }, function () {
            $(this).fadeTo("fast", 0.3);
        });


    }
    else {
        jqo.children("div.body").first().children("a.expand").addClass('unavailable');
    }

    // unfix the href

    jqo.children("div.body").first().children("a.expand").attr('href', 'Javascript: void(0);');

}

function linkedpaper_decorate_full_Text(jqo) {
    var a = jqo.children('div.menu').children('a.full_text');
    a.attr('href', '/FullText.aspx?pmid=' + jqo.data('linkedpaper').pmid + '&title=' + escape(jqo.data('linkedpaper').title) + '&journal=' + escape(jqo.data('linkedpaper').journal));
    a.attr('target', '_blank');
}

function linkedpaper_decorate(jqo) {

    linkedpaper_decorate_full_Text(jqo);

    linkedpaper_decorate_label(jqo);

    linkedpaper_decorate_discuss(jqo);


    linkedpaper_decorate_expand(jqo);

}

function linkedpaper_render(linkedpaper, list_id) {
    build = "<li id='linkedpaper_" + list_id + "_" + linkedpaper.pmid + "' class='linkedpaper_2 linkedpaper_" + linkedpaper.pmid + "'>";
    build += "<div class='menu'>";
    build += "<a class='full_text'></a>";
    build += "<a class='label'></a>";
    build += "<a class='discuss'></a>";
    build += "</div>";
    build += "<div class='title'>" + linkedpaper.title + "</div>";
    build += "<div class='authors'>" + linkedpaper.authors + "</div>";
    build += "<div class='body'>";
    build += "<a class='expand'></a>";
    build += linkedpaper.body;
    build += "</div>";
    build += "<div class='journal'>";
    build += "<span class='date_published'>" + linkedpaper.date_published + "</span>";
    build += ", ";
    build += "<span class='journal_title'><a target='_blank' href='/GoToJournal.aspx?journal_title=" + linkedpaper.journal_title + "'>" + linkedpaper.journal_title + "</a></span>";
    build += "</div>";
    build += "<div class='pmid'>" + linkedpaper.pmid + "</div>";
    build += "</li>";
    return build;
}

function trim(value) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    return value;
}


function lp_dialogs_bookshelf_new_label_open() {

    $("input#lp_dialogs_bookshelf_labels_create_empty").attr("value", '');

    $("span#lp_dialogs_bookshelf_labels_new_icon").removeClass();

    $('#lp_dialogs_bookshelf_new_label').dialog('open');

    $("input#lp_dialogs_bookshelf_labels_create_empty").select().focus();
}

function extract_all_user_labels() {
    parrUserLabels = [];
    $('#bookshelf_labels li').each(function() {
        if ($(this).data('labellistlabel') == null) {
            // this is the 'all' or 'unlabelled' link
        }
        else {
            arrUserLabels[arrUserLabels.length] = $(this).data('labellistlabel').label;
        }
    });
    return arrUserLabels;
}


function compareReferencedLabels(a, b) {
    return b.set - a.set;
}

function get_referenced_labels(linkedpaper) {

    arrReferendedLabels = [];

    all_user_labels = extract_all_user_labels();

    labels_set = linkedpaper.labels;

    for (var t = 0; t < all_user_labels.length; t++) {
        arrReferendedLabels[arrReferendedLabels.length] = new referencedlabel(
            all_user_labels[t], 
            $.inArray(all_user_labels[t], labels_set)>-1
        );
    }

    arrReferendedLabels.sort(compareReferencedLabels);

    return arrReferendedLabels;
}

function lp_create_referencedlabellist_from_checkbox_list(jqo) {
    alert(jqo);
}



function setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

function setCaretToPos(input, pos) {
    setSelectionRange(input, pos, pos);
}

String.prototype.left = function (n) {
    return this.substring(0, n);
}

String.prototype.isnumeric = function () {
    var a = this - 0;
    var b = this.length > 0;
    var c = a && b;
    return c;

    //return (this - 0) == this && this.length > 0;
}

String.prototype.cutline = function (_maxlength) {

    // todo: still something going wrong with spaces:
    // try 'dit is een heel erg lang label', it will cut at er|g

    if (this==null) return "";
    if (this.length <= _maxlength) return this + ""; // "" because otherwise strange things happen with jQuery .text() method

    var t = _maxlength;

    while (t >= 0)
    {
        if (this[t] == " ")
        {
            return this.substring(0, t) + "...";
        }

        t--;
    }

    return this.substring(0, _maxlength) + "...";
}

Array.prototype.unique = function () {
    var vals = this;
    var uniques = [];
    for (var i = vals.length; i--; ) {
        var val = vals[i];
        if ($.inArray(val, uniques) === -1) {
            uniques.unshift(val);
        }
    }
    return uniques;
}
