Fix spelling of m_teamName
[mkws-moved-to-github.git] / tools / htdocs / mkws.js
index c00252d..5a18aa9 100644 (file)
@@ -144,7 +144,7 @@ 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_teamName = teamName;
     var m_submitted = false;
     var m_query; // initially undefined
     var m_sort = 'relevance';
@@ -159,6 +159,7 @@ function _make_mkws_team($, teamName) {
        "start": $.now(),
        "last": $.now()
     };
+    var m_paz; // will be initialised below
 
 
     // if (console && console.log) // disabled, will fail in IE8
@@ -189,53 +190,6 @@ function _make_mkws_team($, teamName) {
     var debug = mkws.debug_function; // local alias
     debug("start running MKWS");
 
-
-    {
-
-       /* default mkws config */
-       var config_default = {
-           use_service_proxy: true,
-           pazpar2_url: "http://mkws.indexdata.com/service-proxy/",
-           service_proxy_auth: "http://mkws.indexdata.com/service-proxy-auth",
-           lang: "",
-           sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
-           perpage_options: [10, 20, 30, 50],
-           sort_default: "relevance",
-           perpage_default: 20,
-           query_width: 50,
-           show_lang: true,    /* show/hide language menu */
-           show_sort: true,    /* show/hide sort menu */
-           show_perpage: true,         /* show/hide perpage menu */
-           lang_options: [],   /* display languages links for given languages, [] for all */
-           facets: ["sources", "subjects", "authors"], /* display facets, in this order, [] for none */
-           responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
-           debug_level: 1,     /* debug level for development: 0..2 */
-
-           dummy: "dummy"
-       };
-
-       /* 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') {
-           mkws.debug_level = config_default.debug_level;
-       }
-
-       // make sure the mkws_config is a valid hash
-       if (!$.isPlainObject(mkws_config)) {
-           debug("ERROR: mkws_config is not an JS object, ignore it....");
-           mkws_config = {};
-       }
-
-       /* override standard config values by function parameters */
-       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]);
-       }
-    }
-
-
     m_sort = mkws_config.sort_default;
     debug("copied mkws_config.sort_default '" + mkws_config.sort_default + "' to m_sort");
 
@@ -255,29 +209,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
-    if (!mkws.paz) {
-       mkws.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);
@@ -287,13 +240,15 @@ function _make_mkws_team($, teamName) {
     //
     // pz2.js event handlers:
     //
-    function my_oninit() {
-       mkws.paz.stat();
-       mkws.paz.bytarget();
+    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");
@@ -307,7 +262,7 @@ function _make_mkws_team($, teamName) {
        }
 
        // navi
-       var results = document.getElementById("mkwsRecords");
+       var results = $("#mkwsRecords");
 
        var html = [];
        for (var i = 0; i < data.hits.length; i++) {
@@ -319,7 +274,7 @@ function _make_mkws_team($, teamName) {
                html.push(renderDetails(m_curDetRecData));
            }
        }
-       replaceHtml(results, html.join(''));
+       results.html(html.join(''));
     }
 
 
@@ -332,7 +287,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;
@@ -345,7 +301,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();
@@ -371,9 +328,9 @@ function _make_mkws_team($, teamName) {
            }
        }
 
-       var termlist = document.getElementById("mkwsTermlists");
+       var termlist = $("#mkwsTermlists");
        if (termlist)
-           replaceHtml(termlist, acc.join(''));
+           termlist.html(acc.join(''));
     }
 
 
@@ -399,9 +356,10 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function my_onrecord(data) {
+    function my_onrecord(data, teamName) {
+       debug("record for " + teamName);
        // FIXME: record is async!!
-       clearTimeout(mkws.paz.recordTimer);
+       clearTimeout(m_paz.recordTimer);
        // in case on_show was faster to redraw element
        var detRecordDiv = document.getElementById('mkwsDet_'+data.recid);
        if (detRecordDiv) return;
@@ -412,7 +370,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.
@@ -460,12 +419,12 @@ function _make_mkws_team($, teamName) {
     // when search button pressed
     function onFormSubmitEventHandler()
     {
-       newSearch(document.mkwsSearchForm.mkwsQuery.value);
+       that.newSearch(document.mkwsSearchForm.mkwsQuery.value);
        return false;
     }
 
 
-    function newSearch(query, sort, targets, windowid)
+    that.newSearch = function(query, sort, targets, windowid)
     {
        debug("newSearch: " + query);
 
@@ -489,7 +448,7 @@ function _make_mkws_team($, teamName) {
        if (!m_submitted) return false;
        resetPage();
        loadSelect();
-       mkws.paz.show(0, m_recPerPage, m_sort);
+       m_paz.show(0, m_recPerPage, m_sort);
        return false;
     }
 
@@ -545,7 +504,7 @@ function _make_mkws_team($, teamName) {
        }
        debug("triggerSearch(" + m_query + "): filters = " + $.toJSON(m_filters) + ", pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
 
-       mkws.paz.search(m_query, m_recPerPage, m_sort, pp2filter, undefined, params);
+       m_paz.search(m_query, m_recPerPage, m_sort, pp2filter, undefined, params);
     }
 
 
@@ -709,21 +668,21 @@ function _make_mkws_team($, teamName) {
     mkws.showPage = function (pageNum)
     {
        m_curPage = pageNum;
-       mkws.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) {
-            mkws.paz.showNext();
+            m_paz.showNext();
             m_curPage++;
        }
     }
 
 
     mkws.pagerPrev = function () {
-       if (mkws.paz.showPrev() != false)
+       if (m_paz.showPrev() != false)
             m_curPage--;
     }
 
@@ -782,25 +741,10 @@ function _make_mkws_team($, teamName) {
             return;
        }
        // request the record
-       mkws.paz.record(recId);
+       m_paz.record(recId);
     }
 
 
-    function replaceHtml(el, html) {
-       var oldEl = typeof el === "string" ? document.getElementById(el) : el;
-       /*@cc_on // Pure innerHTML is slightly faster in IE
-         oldEl.innerHTML = html;
-         return oldEl;
-         @*/
-       var newEl = oldEl.cloneNode(false);
-       newEl.innerHTML = html;
-       oldEl.parentNode.replaceChild(newEl, oldEl);
-       /* Since we just removed the old element from the DOM, return a reference
-          to the new element, which can be used to restore variable references. */
-       return newEl;
-    };
-
-
     function renderDetails(data, marker)
     {
        var template = loadTemplate("Record");
@@ -995,33 +939,6 @@ function _make_mkws_team($, teamName) {
     }
 
 
-    function run_auto_searches() {
-       debug("running auto searches");
-
-       $('[id^="mkwsRecords"]').each(function () {
-           var node = $(this);
-           var query = node.attr('autosearch');
-
-           if (query) {
-               var windowid = undefined;
-               var id = node.attr('id');
-               if (id.match(/^mkwsRecords_/, '')) {
-                   windowid = id.replace(/^mkwsRecords_/, '');
-               }
-
-               var sort = node.attr('sort');
-               var targets = node.attr('targets');
-               var s = "running auto search: '" + query + "'";
-               if (windowid) s += " [windowid '" + windowid + "']";
-               if (sort) s += " sorted by '" + sort + "'";
-               if (targets) s += " in targets '" + targets + "'";
-               debug(s);
-               newSearch(query, sort, targets, windowid);
-           }
-       });
-    }
-
-
     // implement $.parseQuerystring() for parsing URL parameters
     function parseQuerystring() {
        var nvpair = {};
@@ -1104,42 +1021,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.
-     */
-    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;
-           run_auto_searches();
-       });
-    }
-
-
     /* create locale language menu */
     function mkws_html_lang() {
        var lang_default = "en";
@@ -1387,13 +1268,18 @@ 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);
+        if (typeof console === "undefined" || typeof console.log === "undefined") { /* ARGH!!! old IE */
+            return;
+        }
+       console.log(s);
     }
+
     // enable before page load, so we could call it before mkws() runs
     _mkws_jquery_plugin(j);
 
     $(document).ready(function() {
        log("on load ready");
+       default_mkws_config();
 
        // Backwards compatibility: set new magic class names on any
        // elements that have the old magic IDs.
@@ -1411,7 +1297,7 @@ function _mkws_jquery_plugin ($) {
 
        // Backwards compatibility: the special-case undefined team
        // ### Will not be necessary when non-default teams are working
-       mkws.teams[''] = _make_mkws_team(j, undefined);
+       mkws.teams['AUTO'] = _make_mkws_team(j, "AUTO");
        log("Made the unnamed MKWS team");
 
        // Find all nodes with class (NOT id) mkwsRecords, and
@@ -1442,12 +1328,118 @@ function _mkws_jquery_plugin ($) {
        });
 
        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);
+           authenticate_session(mkws_config.service_proxy_auth,
+                                mkws_config.service_proxy_auth_domain,
+                                mkws_config.pazpar2_url);
        } else {
            // raw pp2
            run_auto_searches();
        }
     });
+
+
+    function default_mkws_config() {
+       /* default mkws config */
+       var config_default = {
+           use_service_proxy: true,
+           pazpar2_url: "http://mkws.indexdata.com/service-proxy/",
+           service_proxy_auth: "http://mkws.indexdata.com/service-proxy-auth",
+           lang: "",
+           sort_options: [["relevance"], ["title:1", "title"], ["date:0", "newest"], ["date:1", "oldest"]],
+           perpage_options: [10, 20, 30, 50],
+           sort_default: "relevance",
+           perpage_default: 20,
+           query_width: 50,
+           show_lang: true,    /* show/hide language menu */
+           show_sort: true,    /* show/hide sort menu */
+           show_perpage: true,         /* show/hide perpage menu */
+           lang_options: [],   /* display languages links for given languages, [] for all */
+           facets: ["sources", "subjects", "authors"], /* display facets, in this order, [] for none */
+           responsive_design_width: undefined, /* a page with less pixel width considered as narrow */
+           debug_level: 1,     /* debug level for development: 0..2 */
+
+           dummy: "dummy"
+       };
+
+       /* 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') {
+           mkws.debug_level = config_default.debug_level;
+       }
+
+       // make sure the mkws_config is a valid hash
+       if (!$.isPlainObject(mkws_config)) {
+           debug("ERROR: mkws_config is not an JS object, ignore it....");
+           mkws_config = {};
+       }
+
+       /* override standard config values by function parameters */
+       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]);
+       }
+    }
+
+
+    /*
+     * Run service-proxy authentication in background (after page load).
+     * The username/password is configured in the apache config file
+     * for the site.
+     */
+    function authenticate_session(auth_url, auth_domain, pp2_url) {
+       console.log("Run service proxy auth URL: " + auth_url);
+
+       if (!auth_domain) {
+           auth_domain = pp2_url.replace(/^(https?:)?\/\/(.*?)\/.*/, '$2');
+           console.log("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;
+           }
+
+           console.log("Service proxy auth successfully done");
+           mkws.authenticated = true;
+           run_auto_searches();
+       });
+    }
+
+
+    function run_auto_searches() {
+       console.log("running auto searches");
+
+       for (var teamName in mkws.teams) {
+           // ### should check mkwsTermlist as well, for facet-only teams
+           var node = $('.mkwsRecords.mkwsTeam_' + teamName);
+           var query = node.attr('autosearch');
+           console.log("teamName '" + teamName + "', node=" + node + ", class='" + node.className + "', query=" + query);
+
+           if (query) {
+               var sort = node.attr('sort');
+               var targets = node.attr('targets');
+               var s = "running auto search: '" + query + "'";
+               if (teamName) s += " [teamName '" + teamName + "']";
+               if (sort) s += " sorted by '" + sort + "'";
+               if (targets) s += " in targets '" + targets + "'";
+               console.log(s);
+               var team = mkws.teams[teamName];
+               console.log($.toJSON(team));
+               team.newSearch(query, sort, targets, teamName);
+           }
+       }
+    }
 })(jQuery);