////////////////////////////////////
// adekker 17/08/2009
// Citation Services 
////////////////////////////////////

function dbCitation(data, type, source) {
    this.data = data;
    this.type = type;
    this.source = source;
}
var dbCitations = new Array();
var countAdded = 0;
var citationForSorting = new Array();


function loadCitation(dbCitation) {
    CitationDWR.getCitationID(dbCitation.type, dbCitation.data, {
        callback:function(citation) {
            drawCitation(citation, dbCitation);

            //After rendering the last item, sort & re-render
            if (dbCitations.length == countAdded) {

                var citationsBody = document.getElementById("citations");
                var citationsHTML = citationsBody.innerHTML;
                citationForSorting.sort(function (a, b) {
                    return (b.year - a.year ||  a.journalTitle.localeCompare(b.journalTitle));
                });

                try {
                    citationsBody.innerHTML = "";
                    for (var i = 0; i < citationForSorting.length; i++) {

                        var row = document.createElement("tr");
                        citationsBody.appendChild(row);
                        var col = row.insertCell(0);
                        col.outerHTML = "<td class=chebiDataContent>" + getCitationHTML(citationForSorting[i]) + "</td>";

                    }
                } catch (err) {
                    //incase of error render the unsorted list.
                    citationsBody.innerHTML = citationsHTML;
                }
            }
        },
        timeout: 500000
    });
}

function drawCitation(citation, dbCitation) {

    // Remove citation suffix
    var type = dbCitation.type;
    var source = dbCitation.source;
    var cit = "citation";
    var srcLabel = type.substring(0,type.indexOf(cit)-1);

    var cellFuncs = [
        // Cell 1
        function(data) {
            countAdded++;

            var cite = new Object();
            cite.authors = data.authorString;
            cite.year = data.journalInfo.yearOfPublication;
            cite.title = data.title;
            cite.journalTitle = data.journalInfo.journal.title;
            cite.volume = data.journalInfo.volume;
            cite.pageInfo = data.pageInfo;
            cite.source = source;
            cite.srcAbr = data.source;
            cite.id = data.id;
            cite.srcLabel = srcLabel;
            cite.abstractText = data.abstractText;
            citationForSorting.push(cite);

            return getCitationHTML(cite);
        }
    ];

    var options = {
        rowCreator:function(options) { return document.createElement("tr"); },
        cellCreator:function(options) {

            var td = document.createElement("td");
            td.className = "chebiDataContent";

            return td;
        },
        escapeHtml:false
    };

    dwr.util.addRows("citations", [citation], cellFuncs, options);
}

function toggleAbstract(id) {

    var citAbs = document.getElementById("citAbstract"+id);

    if(citAbs.style.display !="none") {
        dwr.util.setValue("toggleCitAbstract"+id,"[show Abstract]");
        citAbs.style.display ="none";
    } else {
        dwr.util.setValue("toggleCitAbstract"+id,"[hide Abstract]");
        citAbs.style.display ="block";
    }
}

//Before and After DWR runs
dwr.engine.setPreHook(function() {
    document.getElementById("citationWait").style.display = 'inline';
});

dwr.engine.setPostHook(postHook);
function postHook() {
    document.getElementById("citationWait").style.display = 'none';
}

function errorHandler(msg) {
    postHook();
}

function testCitationConnection() {

    dwr.engine.setErrorHandler(errorHandler);

    CitationDWR.getCitationID("PubMed citation", "11304127", {
        callback: function(msg) {
            dwr.util.removeAllRows("citations");
            document.getElementById("citationHeader").deleteCell(2);
            document.getElementById("citationHeader").deleteCell(1);
            for (i in dbCitations) loadCitation(dbCitations[i]);
        },
        timeout: 4000
    });
}

//Remove the white spaces from begin and end.
function trim(str) {
    return str.replace(/^\s+|\s+$/g, '') ;
}

function getCitationHTML(cite) {
    var html = "";
    if (cite.authors != null)
        html += "<span class=pubauthors>" + cite.authors.slice(0, -1) + "</span> ";
    if (cite.year != null && cite.year > 0)
        html += "<span class=pubauthors>(" + cite.year + ")</span>";
    if (cite.title != null)
        html += "<br><span class=pubtitle>" + cite.title + "</span> ";
    if (cite.journalTitle != null)
        html += "<br><span class=pubjournal>" + cite.journalTitle + "</span>";
    if (cite.volume != null)
        html += " <span class=pubvolume>" + cite.volume + ",</span> ";
    if (cite.pageInfo != null)
        html += "<span class=pubjournal>" + cite.pageInfo + "</span> ";
    if (cite.source != null && cite.source != "Europe PMC")
        html += "<span class=pubjournal>(Source: " + cite.source + ")</span>";
    if (cite.id != null && cite.srcAbr != null && cite.srcLabel != null)
        html += " [<span><a target=_blank href='http://europepmc.org/abstract/" + cite.srcAbr + "/" + cite.id + "' title='Search " + cite.id + " at Europe PMC'>" + cite.srcLabel + ":" + cite.id + "</a></span>]";
    if (cite.abstractText != null && trim(cite.abstractText).length > 0) {
        html += "<br><a href='#" + cite.id + "' id=toggleCitAbstract" + cite.id + " onclick=\"javascript: toggleAbstract('" + cite.id + "')\" style=\"cursor: pointer\">[show Abstract]</a>"
            + "<br><span class=citAbstract style='display: none' id=citAbstract" + cite.id + ">" + cite.abstractText + "</span>";
    }
    return html;
}