Single global mkws.paz changed to per-team m_paz.
[mkws-moved-to-github.git] / tools / htdocs / mkws.js
index 2b34b21..1a0782d 100644 (file)
@@ -71,14 +71,14 @@ Handlebars.registerHelper('commaList', function(items, options) {
 // Handlebars helper 'translate'
 
 
-// Set up global mkws object. Contains a hash of session objects,
+// Set up global mkws object. Contains a hash of team objects,
 // indexed by windowid.
 var mkws = {
     authenticated: false,
-    init: false,
     debug_function: undefined, // will be set during initialisation
     debug_level: undefined, // will be initialised from mkws_config
-    sessions: {},
+    paz: undefined, // will be set up during initialisation
+    teams: {},
     locale_lang: {
        "de": {
            "Authors": "Autoren",
@@ -143,6 +143,8 @@ if (mkws_config == null || typeof mkws_config != 'object') {
 
 // wrapper for jQuery lib
 function _make_mkws_team($, teamName) {
+    var that = {};
+    var m_termName = teamName;
     var m_submitted = false;
     var m_query; // initially undefined
     var m_sort = 'relevance';
@@ -157,14 +159,9 @@ function _make_mkws_team($, teamName) {
        "start": $.now(),
        "last": $.now()
     };
+    var m_paz; // will be initialised below
 
 
-    // call this function only once
-    if (mkws.init) {
-       alert("_make_mkws_team() called twice: how did that happen?!");
-       return;
-    }
-
     // if (console && console.log) // disabled, will fail in IE8
     // console.log("run _make_mkws_team(" + (teamName ? teamName : "") + ")");
 
@@ -218,7 +215,7 @@ function _make_mkws_team($, teamName) {
            dummy: "dummy"
        };
 
-       /* set global debug_level flag early */
+       /* Set global debug_level flag early so that debug() works */
        if (typeof mkws_config.debug_level !== 'undefined') {
            mkws.debug_level = mkws_config.debug_level;
        } else if (typeof config_default.debug_level !== 'undefined') {
@@ -235,7 +232,7 @@ function _make_mkws_team($, teamName) {
        for (var k in config_default) {
            if (typeof mkws_config[k] === 'undefined')
                mkws_config[k] = config_default[k];
-           debug("Set config: " + k + ' => ' + mkws_config[k]);
+           //debug("Set config: " + k + ' => ' + mkws_config[k]);
        }
     }
 
@@ -259,27 +256,28 @@ function _make_mkws_team($, teamName) {
        }
     }
 
-    // protocol independend link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
+    // protocol independent link for pazpar2: "//mkws/sp" -> "https://mkws/sp"
     if (mkws_config.pazpar2_url.match(/^\/\//)) {
        mkws_config.pazpar2_url = document.location.protocol + mkws_config.pazpar2_url;
-       debug("adjust protocol independend links: " + mkws_config.pazpar2_url);
+       debug("adjust protocol independent links: " + mkws_config.pazpar2_url);
     }
 
     debug("Create main pz2 object");
     // create a parameters array and pass it to the pz2's constructor
     // then register the form submit event with the pz2.search function
     // autoInit is set to true on default
-    var m_paz = new pz2( { "onshow": my_onshow,
-                          "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
-                          "pazpar2path": mkws_config.pazpar2_url,
-                          "oninit": my_oninit,
-                          "onstat": my_onstat,
-                          "onterm": my_onterm,
-                          "termlist": "xtargets,subject,author",
-                          "onbytarget": my_onbytarget,
-                          "usesessions" : mkws_config.use_service_proxy ? false : true,
-                          "showResponseType": '', // or "json" (for debugging?)
-                          "onrecord": my_onrecord } );
+    m_paz = new pz2({ "onshow": my_onshow,
+                     "windowid": teamName,
+                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
+                     "pazpar2path": mkws_config.pazpar2_url,
+                     "oninit": my_oninit,
+                     "onstat": my_onstat,
+                     "onterm": my_onterm,
+                     "termlist": "xtargets,subject,author",
+                     "onbytarget": my_onbytarget,
+                     "usesessions" : mkws_config.use_service_proxy ? false : true,
+                     "showResponseType": '', // or "json" (for debugging?)
+                     "onrecord": my_onrecord });
 
     if (!isNaN(parseInt(mkws_config.perpage_default))) {
        m_recPerPage = parseInt(mkws_config.perpage_default);
@@ -289,13 +287,15 @@ function _make_mkws_team($, teamName) {
     //
     // pz2.js event handlers:
     //
-    function my_oninit() {
+    function my_oninit(teamName) {
+       debug("init for " + teamName);
        m_paz.stat();
        m_paz.bytarget();
     }
 
 
-    function my_onshow(data) {
+    function my_onshow(data, teamName) {
+       debug("show for " + teamName);
        m_totalRec = data.merged;
        // move it out
        var pager = document.getElementById("mkwsPager");
@@ -334,7 +334,8 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function my_onstat(data) {
+    function my_onstat(data, teamName) {
+       debug("stat for " + teamName);
        var stat = document.getElementById("mkwsStat");
        if (stat == null)
            return;
@@ -347,7 +348,8 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function my_onterm(data) {
+    function my_onterm(data, teamName) {
+       debug("term for " + teamName);
        // no facets
        if (!mkws_config.facets || mkws_config.facets.length == 0) {
            $("#mkwsTermlists").hide();
@@ -382,7 +384,7 @@ function _make_mkws_team($, teamName) {
     function add_single_facet(acc, caption, data, max, pzIndex) {
        acc.push('<div class="facet" id="mkwsFacet' + caption + '">');
        acc.push('<div class="termtitle">' + M(caption) + '</div>');
-       for (var i = 0; i < data.length && i < max; i++ ) {
+       for (var i = 0; i < data.length && i < max; i++) {
            acc.push('<div class="term">');
             acc.push('<a href="#" ');
            var action;
@@ -401,7 +403,8 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function my_onrecord(data) {
+    function my_onrecord(data, teamName) {
+       debug("record for " + teamName);
        // FIXME: record is async!!
        clearTimeout(m_paz.recordTimer);
        // in case on_show was faster to redraw element
@@ -414,7 +417,8 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function my_onbytarget(data) {
+    function my_onbytarget(data, teamName) {
+       debug("target for " + teamName);
        var targetDiv = document.getElementById("mkwsBytarget");
        if (!targetDiv) {
            // No mkwsTargets div.
@@ -429,7 +433,7 @@ function _make_mkws_team($, teamName) {
            '<td>' + M('State') + '</td>' +
            '</tr></thead><tbody>';
 
-       for (var i = 0; i < data.length; i++ ) {
+       for (var i = 0; i < data.length; i++) {
             table += "<tr><td>" + data[i].id +
                "</td><td>" + data[i].hits +
                "</td><td>" + data[i].diagnostic +
@@ -667,7 +671,7 @@ function _make_mkws_team($, teamName) {
        var onsides = 6;
        var pages = Math.ceil(m_totalRec / m_recPerPage);
 
-       var firstClkbl = ( m_curPage - onsides > 0 )
+       var firstClkbl = (m_curPage - onsides > 0)
             ? m_curPage - onsides
             : 1;
 
@@ -711,13 +715,13 @@ function _make_mkws_team($, teamName) {
     mkws.showPage = function (pageNum)
     {
        m_curPage = pageNum;
-       m_paz.showPage( m_curPage - 1 );
+       m_paz.showPage(m_curPage - 1);
     }
 
 
     // simple paging functions
     mkws.pagerNext = function () {
-       if ( m_totalRec - m_recPerPage*m_curPage > 0) {
+       if (m_totalRec - m_recPerPage*m_curPage > 0) {
             m_paz.showNext();
             m_curPage++;
        }
@@ -725,7 +729,7 @@ function _make_mkws_team($, teamName) {
 
 
     mkws.pagerPrev = function () {
-       if ( m_paz.showPrev() != false )
+       if (m_paz.showPrev() != false)
             m_curPage--;
     }
 
@@ -975,19 +979,10 @@ function _make_mkws_team($, teamName) {
 
        mkws_html_switch();
 
-       if (mkws_config.use_service_proxy) {
-           mkws_service_proxy_auth(mkws_config.service_proxy_auth,
-                                   mkws_config.service_proxy_auth_domain,
-                                   mkws_config.pazpar2_url);
-       } else {
-           // raw pp2
-           run_auto_searches();
-       }
-
        if (mkws_config.responsive_design_width) {
            // Responsive web design - change layout on the fly based on
            // current screen width. Required for mobile devices.
-           $(window).resize( function(e) { mkws_resize_page() });
+           $(window).resize(function(e) { mkws_resize_page() });
            // initial check after page load
            $(document).ready(function() { mkws_resize_page() });
        }
@@ -995,7 +990,7 @@ function _make_mkws_team($, teamName) {
        domReady();
 
        // on first page, hide the termlist
-       $(document).ready(function() { $("#mkwsTermlists").hide(); } );
+       $(document).ready(function() { $("#mkwsTermlists").hide(); });
        var motd = document.getElementById("mkwsMOTD");
        var container = document.getElementById("mkwsMOTDContainer");
        if (motd && container) {
@@ -1006,7 +1001,7 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function run_auto_searches() {
+    mkws.run_auto_searches = function() {
        debug("running auto searches");
 
        $('[id^="mkwsRecords"]').each(function () {
@@ -1115,42 +1110,6 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    /*
-     * Run service-proxy authentication in background (after page load).
-     * The username/password is configured in the apache config file
-     * for the site.
-     */
-    function mkws_service_proxy_auth(auth_url, auth_domain, pp2_url) {
-       debug("Run service proxy auth URL: " + auth_url);
-
-       if (!auth_domain) {
-           auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
-           debug("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
-       }
-
-       var request = new pzHttpRequest(auth_url, function(err) {
-           alert("HTTP call for authentication failed: " + err)
-           return;
-       }, auth_domain);
-
-       request.get(null, function(data) {
-           if (!$.isXMLDoc(data)) {
-               alert("service proxy auth response document is not valid XML document, give up!");
-               return;
-           }
-           var status = $(data).find("status");
-           if (status.text() != "OK") {
-               alert("service proxy auth repsonse status: " + status.text() + ", give up!");
-               return;
-           }
-
-           debug("Service proxy auth successfully done");
-           mkws.authenticated = true;
-           run_auto_searches();
-       });
-    }
-
-
     /* create locale language menu */
     function mkws_html_lang() {
        var lang_default = "en";
@@ -1246,8 +1205,9 @@ function _make_mkws_team($, teamName) {
        }
     })();
 
-    // done
-    mkws.init = true;
+    // Bizarrely, 'that' is just an empty hash. All its state is in
+    // the closure variables defined earlier in this function.
+    return that;
 };
 
 
@@ -1384,7 +1344,7 @@ function _mkws_jquery_plugin ($) {
            } else if (config && config.layout == 'popup') {
                debug("jquery plugin layout: popup with id: " + id_popup);
                document.write(popup);
-               $(document).ready( function() { init_popup(config); } );
+               $(document).ready(function() { init_popup(config); });
            } else {
                debug("jquery plugin layout: table");
                document.write(table);
@@ -1396,11 +1356,104 @@ function _mkws_jquery_plugin ($) {
 
 // wrapper to call _make_mkws_team() after page load
 (function (j) {
+    function log(s) {
+       if (console && console.log) console.log(s);
+    }
     // enable before page load, so we could call it before mkws() runs
     _mkws_jquery_plugin(j);
 
     $(document).ready(function() {
-       // if (console && console.log) console.log("on load ready");
-       _make_mkws_team(j, null);
+       log("on load ready");
+
+       // Backwards compatibility: set new magic class names on any
+       // elements that have the old magic IDs.
+       var ids = [ "Switch", "Lang", "Search", "Pager", "Navi",
+                   "Results", "Records", "Targets", "Ranking",
+                   "Termlists", "Stat" ];
+       for (var i = 0; i < ids.length; i++) {
+           var id = 'mkws' + ids[i];
+           var node = $('#' + id);
+           if (node.attr('id')) {
+               node.addClass(id + " mkwsTeam_AUTO");
+               log("added magic classes to '" + node.attr('id') + "'");
+           }
+       }
+
+       // Backwards compatibility: the special-case undefined team
+       // ### Will not be necessary when non-default teams are working
+       mkws.teams[''] = _make_mkws_team(j, undefined);
+       log("Made the unnamed MKWS team");
+
+       // Find all nodes with class (NOT id) mkwsRecords, and
+       // determine their team from the mkwsTeam_* class. So:
+       //      <div class="mkwsRecords mkwsTeam_foo"/>
+       $('.mkwsResults, .mkwsRecords, .mkwsTermlists').each(function () {
+           var node = this;
+           var classes = this.className;
+           var list = classes.split(/\s+/)
+           var tname;
+           for (var i = 0; i < list.length; i++) {
+               var cname = list[i];
+               if (cname.match(/^mkwsTeam_/)) {
+                   tname = cname.replace(/^mkwsTeam_/, '');
+               }
+           }
+           if (!tname) {
+               alert("No MKWS team specified for mkwsRecords element with classes '" + classes + "'");
+           } else if (mkws.teams[tname]) {
+               log("MKWS team '" + tname + "' already exists, skipping");
+           } else if (tname === "AUTO") {
+               // ### For now: later, this will be how the backwards-compatibility is done
+               log("Skipping MKWS team '" + tname + "'");
+           } else {
+               mkws.teams[tname] = _make_mkws_team(j, tname);
+               log("Made MKWS team '" + tname + "'");
+           }
+       });
+
+       if (mkws_config.use_service_proxy) {
+           mkws.service_proxy_auth(mkws_config.service_proxy_auth,
+                                   mkws_config.service_proxy_auth_domain,
+                                   mkws_config.pazpar2_url);
+       } else {
+           // raw pp2
+           mkws.run_auto_searches();
+       }
     });
+
+
+    /*
+     * Run service-proxy authentication in background (after page load).
+     * The username/password is configured in the apache config file
+     * for the site.
+     */
+    mkws.service_proxy_auth = function(auth_url, auth_domain, pp2_url) {
+       debug("Run service proxy auth URL: " + auth_url);
+
+       if (!auth_domain) {
+           auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
+           debug("guessed auth_domain '" + auth_domain + "' from pp2_url '" + pp2_url + "'");
+       }
+
+       var request = new pzHttpRequest(auth_url, function(err) {
+           alert("HTTP call for authentication failed: " + err)
+           return;
+       }, auth_domain);
+
+       request.get(null, function(data) {
+           if (!$.isXMLDoc(data)) {
+               alert("service proxy auth response document is not valid XML document, give up!");
+               return;
+           }
+           var status = $(data).find("status");
+           if (status.text() != "OK") {
+               alert("service proxy auth repsonse status: " + status.text() + ", give up!");
+               return;
+           }
+
+           debug("Service proxy auth successfully done");
+           mkws.authenticated = true;
+           mkws.run_auto_searches();
+       });
+    }
 })(jQuery);