/*
 * Created by Florian Leitner on 2007-09-20.
 * Copyright (c) 2007 Florian Leitner.
 * All rights reserved.
 *  
 * GNU GPL LICENSE
 * 
 * This module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; latest version thereof,
 * available at: <http://www.gnu.org/licenses/gpl.txt>.
 * 
 * This module is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this module; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
 */

var PROGRESS_STATE = null;
var INITIALIZE = true;

function initAJAX(pmid) {
    loadData("" + pmid);
}

function loadData(pmid) {
    $.getJSON(
        '/pubmed/' + pmid + '/progress/',
        function(data) {
            if (INITIALIZE) {
                fetchStaticBar(pmid);
                PROGRESS_STATE = data;
                fetchDynamicBars(pmid);
            }
            if (data['missing'] > 0) {
                for (key in data) {
                    if (data[key] != PROGRESS_STATE[key]) {
                        fetchDynamicBars(pmid);
                        break
                    }
                }
                PROGRESS_STATE = data;
                // try get more data every 10 secs
                setTimeout("loadData('" + pmid + "')", 10000);
            } else {
                if (! INITIALIZE) fetchDynamicBars(pmid);
                complete();
            }
            INITIALIZE = false;
        }
    )
}

function fetchStaticBar(pmid) {
    $("#sidebar-right").load('/pubmed/' + pmid + '/controls/', function() {
        $('.tooltips').cluetip({splitTitle:'|'});
        $('table.tablesorter').tablesorter({widgets: ['zebra']});
        $('div.MAP').click(function() {$('#mappings').slideToggle('slow')});
    });
}

function fetchDynamicBars(pmid) {
    fetchServerBar(pmid);
    fetchResultsBar(pmid);
}

function fetchServerBar(pmid) {
    $("#annotation_servers").load('/pubmed/' + pmid + '/servers/', function() {
        $('.tooltips').cluetip({splitTitle:'|'});
        $('table.tablesorter').tablesorter({widgets: ['zebra']});
    });
}

function fetchResultsBar(pmid) {
    $("#sidebar-left").load('/pubmed/' + pmid + '/results/', function() {
        $.getScript('/pubmed/' + pmid + '/resultsJS/');
        $('.tooltips').cluetip({splitTitle:'|',width:'auto'});
        $('table.tablesorter').tablesorter({widgets: ['zebra']});
    });
}

function complete() {
    $("#loading_icon").remove();
}
