Save displayName of authenticated library, if any, as mkws.authName.
[mkws-moved-to-github.git] / src / mkws-team.js
index 1b003e1..872f957 100644 (file)
@@ -1,10 +1,12 @@
 // Factory function for team objects. As much as possible, this uses
 // only member variables (prefixed "m_") and inner functions with
-// private scope. Some functions are visibl as member-functions to be
-// called from outside code -- specifically, from generated
-// HTML. These functions are that.switchView(), showDetails(),
-// limitTarget(), limitQuery(), delimitTarget(), delimitQuery(),
-// pagerPrev(), pagerNext(), showPage().
+// private scope.
+//
+// Some functions are visible as member-functions to be called from
+// outside code -- specifically, from generated HTML. These functions
+// are that.switchView(), showDetails(), limitTarget(), limitQuery(),
+// delimitTarget(), delimitQuery(), showPage(), pagerPrev(),
+// pagerNext().
 //
 function team($, teamName) {
     var that = {};
@@ -26,6 +28,9 @@ function team($, teamName) {
     var m_paz; // will be initialised below
     var m_template = {};
 
+    that.toString = function() { return '[Team ' + teamName + ']'; }
+
+    // Accessor methods for individual widgets: readers
     that.name = function() { return m_teamName; }
     that.submitted = function() { return m_submitted; }
     that.perpage = function() { return m_perpage; }
@@ -35,11 +40,12 @@ function team($, teamName) {
     that.currentRecordData = function() { return m_currentRecordData; }
     that.filters = function() { return m_filters; }
 
+    // Accessor methods for individual widgets: writers
     that.set_sortOrder = function(val) { m_sortOrder = val };
     that.set_perpage = function(val) { m_perpage = val };
 
 
-    var log = function (s) {
+    function log(s) {
        var now = $.now();
        var timestamp = ((now - m_logTime.start)/1000).toFixed(3) + " (+" + ((now - m_logTime.last)/1000).toFixed(3) + ") "
        m_logTime.last = now;
@@ -71,34 +77,28 @@ function team($, teamName) {
                    });
 
 
-    //
     // pz2.js event handlers:
-    //
     function onInit() {
        log("init");
        m_paz.stat();
        m_paz.bytarget();
     }
 
-
     function onBytarget(data) {
        log("target");
        queue("targets").publish(data);
     }
 
-
     function onStat(data) {
        log("stat");
        queue("stat").publish(data);
     }
 
-
     function onTerm(data) {
        log("term");
        queue("termlists").publish(data);
     }
 
-
     function onShow(data, teamName) {
        log("show");
        m_totalRecordCount = data.merged;
@@ -106,14 +106,12 @@ function team($, teamName) {
        queue("records").publish(data);
     }
 
-
     function onRecord(data, args, teamName) {
        log("record");
        // FIXME: record is async!!
        clearTimeout(m_paz.recordTimer);
-       // ##### restrict to current team
-       var detRecordDiv = document.getElementById(recordDetailsId(data.recid[0]));
-       if (detRecordDiv) {
+       var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
+       if (detRecordDiv.length) {
            // in case on_show was faster to redraw element
            return;
        }
@@ -124,7 +122,7 @@ function team($, teamName) {
     }
 
 
-    // Used by promoteRecords() and onRecord()
+    // Used by the Records widget and onRecord()
     function recordElementId(s) {
        return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
     }
@@ -134,7 +132,6 @@ function team($, teamName) {
     function recordDetailsId(s) {
        return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
     }
-    that.recordElementId = recordElementId;
 
 
     that.targetFiltered = function(id) {
@@ -148,36 +145,6 @@ function team($, teamName) {
     }
 
 
-    ////////////////////////////////////////////////////////////////////////////////
-    ////////////////////////////////////////////////////////////////////////////////
-
-
-    // when search button pressed
-    function onFormSubmitEventHandler()
-    {
-       var val = findnode('.mkwsQuery').val();
-       newSearch(val);
-       return false;
-    }
-
-
-    function newSearch(query, sortOrder, targets)
-    {
-       log("newSearch: " + query);
-
-       if (mkws_config.use_service_proxy && !mkws.authenticated) {
-           alert("searching before authentication");
-           return;
-       }
-
-       m_filters = []
-       triggerSearch(query, sortOrder, targets);
-       switchView('records'); // In case it's configured to start off as hidden
-       m_submitted = true;
-    }
-
-
-    // limit by target functions
     that.limitTarget  = function (id, name)
     {
        log("limitTarget(id=" + id + ", name=" + name + ")");
@@ -187,7 +154,6 @@ function team($, teamName) {
     }
 
 
-    // limit the query after clicking the facet
     that.limitQuery = function (field, value)
     {
        log("limitQuery(field=" + field + ", value=" + value + ")");
@@ -239,6 +205,32 @@ function team($, teamName) {
     }
 
 
+    that.showPage = function (pageNum)
+    {
+       m_currentPage = pageNum;
+       m_paz.showPage(m_currentPage - 1);
+    }
+
+
+    that.pagerNext = function () {
+       if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
+            m_paz.showNext();
+            m_currentPage++;
+       }
+    }
+
+
+    that.pagerPrev = function () {
+       if (m_paz.showPrev() != false)
+            m_currentPage--;
+    }
+
+
+    that.reShow = function() {
+       m_paz.show(0, m_perpage, m_sortOrder);
+    }
+
+
     function resetPage()
     {
        m_currentPage = 1;
@@ -247,6 +239,22 @@ function team($, teamName) {
     that.resetPage = resetPage;
 
 
+    function newSearch(query, sortOrder, targets)
+    {
+       log("newSearch: " + query);
+
+       if (mkws_config.use_service_proxy && !mkws.authenticated) {
+           alert("searching before authentication");
+           return;
+       }
+
+       m_filters = []
+       triggerSearch(query, sortOrder, targets);
+       switchView('records'); // In case it's configured to start off as hidden
+       m_submitted = true;
+    }
+
+
     function triggerSearch (query, sortOrder, targets)
     {
        resetPage();
@@ -297,34 +305,6 @@ function team($, teamName) {
     }
 
 
-    that.reShow = function() {
-       m_paz.show(0, m_perpage, m_sortOrder);
-    }
-
-
-
-    that.showPage = function (pageNum)
-    {
-       m_currentPage = pageNum;
-       m_paz.showPage(m_currentPage - 1);
-    }
-
-
-    // simple paging functions
-    that.pagerNext = function () {
-       if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
-            m_paz.showNext();
-            m_currentPage++;
-       }
-    }
-
-
-    that.pagerPrev = function () {
-       if (m_paz.showPrev() != false)
-            m_currentPage--;
-    }
-
-
     // switching view between targets and records
     function switchView(view) {
        var targets = findnode('.mkwsTargets');
@@ -393,13 +373,11 @@ function team($, teamName) {
            mkwsHtmlLang();
 
        log("HTML search form");
-       mkws.handleNodeWithTeam(findnode('.mkwsSearch'), function(tname) {
-           this.html('\
-<form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + tname + '" action="" >\
-  <input class="mkwsQuery mkwsTeam_' + tname + '" type="text" size="' + mkws_config.query_width + '" />\
-  <input class="mkwsButton mkwsTeam_' + tname + '" type="submit" value="' + M('Search') + '" />\
+       findnode('.mkwsSearch').html('\
+<form name="mkwsSearchForm" class="mkwsSearchForm mkwsTeam_' + m_teamName + '" action="" >\
+  <input class="mkwsQuery mkwsTeam_' + m_teamName + '" type="text" size="' + mkws_config.query_width + '" />\
+  <input class="mkwsButton mkwsTeam_' + m_teamName + '" type="submit" value="' + M('Search') + '" />\
 </form>');
-       });
 
        log("HTML records");
        // If the team has a .mkwsResults, populate it in the usual
@@ -443,7 +421,11 @@ function team($, teamName) {
 
        mkwsHtmlSwitch();
 
-       findnode('.mkwsSearchForm').submit(onFormSubmitEventHandler);
+       findnode('.mkwsSearchForm').submit(function() {
+           var val = findnode('.mkwsQuery').val();
+           newSearch(val);
+           return false;
+       });
 
        // on first page, hide the termlist
        $(document).ready(function() { findnode(".mkwsTermlists").hide(); });
@@ -456,7 +438,7 @@ function team($, teamName) {
 
 
     function mkwsSetLang()  {
-       var lang = mkws.getParameterByName("lang") || mkws_config.lang;
+       var lang = getParameterByName("lang") || mkws_config.lang;
        if (!lang || !mkws.locale_lang[lang]) {
            mkws_config.lang = ""
        } else {
@@ -577,7 +559,7 @@ function team($, teamName) {
 
        if (query.match(/^!param!/)) {
            var param = query.replace(/^!param!/, '');
-           query = mkws.getParameterByName(param);
+           query = getParameterByName(param);
            log("obtained query '" + query + "' from param '" + param + "'");
            if (!query) {
                alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
@@ -605,6 +587,16 @@ function team($, teamName) {
     }
 
 
+    // This function is taken from a StackOverflow answer
+    // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
+    function getParameterByName(name) {
+       name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
+       var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
+           results = regex.exec(location.search);
+       return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
+    }
+
+
     // Translation function. At present, this is properly a
     // global-level function (hence the assignment to mkws.M) but we
     // want to make it per-team so different teams can operate in
@@ -632,7 +624,9 @@ function team($, teamName) {
            return s + '.mkwsTeam_' + teamName;
        }).join(',');
 
-       return $(selector);
+       var node = $(selector);
+       //log('findnode(' + selector + ') found ' + node.length + ' nodes');
+       return node;
     }
 
 
@@ -658,7 +652,7 @@ function team($, teamName) {
 
            var source = node.html();
            if (!source) {
-               source = mkws.defaultTemplate(name);
+               source = defaultTemplate(name);
            }
 
            template = Handlebars.compile(source);
@@ -671,6 +665,87 @@ function team($, teamName) {
     that.loadTemplate = loadTemplate;
 
 
+    function defaultTemplate(name)
+    {
+       if (name === 'Record') {
+           return '\
+<table>\
+  <tr>\
+    <th>{{translate "Title"}}</th>\
+    <td>\
+      {{md-title}}\
+      {{#if md-title-remainder}}\
+       ({{md-title-remainder}})\
+      {{/if}}\
+      {{#if md-title-responsibility}}\
+       <i>{{md-title-responsibility}}</i>\
+      {{/if}}\
+    </td>\
+  </tr>\
+  {{#if md-date}}\
+  <tr>\
+    <th>{{translate "Date"}}</th>\
+    <td>{{md-date}}</td>\
+  </tr>\
+  {{/if}}\
+  {{#if md-author}}\
+  <tr>\
+    <th>{{translate "Author"}}</th>\
+    <td>{{md-author}}</td>\
+  </tr>\
+  {{/if}}\
+  {{#if md-electronic-url}}\
+  <tr>\
+    <th>{{translate "Links"}}</th>\
+    <td>\
+      {{#each md-electronic-url}}\
+       <a href="{{this}}">Link{{index1}}</a>\
+      {{/each}}\
+    </td>\
+  </tr>\
+  {{/if}}\
+  {{#if-any location having="md-subject"}}\
+  <tr>\
+    <th>{{translate "Subject"}}</th>\
+    <td>\
+      {{#first location having="md-subject"}}\
+       {{#if md-subject}}\
+         {{#commaList md-subject}}\
+           {{this}}{{/commaList}}\
+       {{/if}}\
+      {{/first}}\
+    </td>\
+  </tr>\
+  {{/if-any}}\
+  <tr>\
+    <th>{{translate "Locations"}}</th>\
+    <td>\
+      {{#commaList location}}\
+       {{attr "@name"}}{{/commaList}}\
+    </td>\
+  </tr>\
+</table>\
+';
+       } else if (name === "Summary") {
+           return '\
+<a href="#" id="{{_id}}" onclick="{{_onclick}}">\
+  <b>{{md-title}}</b>\
+</a>\
+{{#if md-title-remainder}}\
+  <span>{{md-title-remainder}}</span>\
+{{/if}}\
+{{#if md-title-responsibility}}\
+  <span><i>{{md-title-responsibility}}</i></span>\
+{{/if}}\
+';
+       }
+
+       var s = "There is no default '" + name +"' template!";
+       alert(s);
+       return s;
+    }
+
+
     // The following PubSub code is modified from the jQuery manual:
     // https://api.jquery.com/jQuery.Callbacks/
     //
@@ -692,20 +767,7 @@ function team($, teamName) {
     }
     that.queue = queue;
 
+    mkwsHtmlAll()
 
-    // main
-    (function() {
-       try {
-           mkwsHtmlAll()
-       }
-
-       catch (e) {
-           mkws_config.error = e.message;
-           // alert(e.message);
-       }
-    })();
-
-    // Bizarrely, 'that' is just an empty hash. All its state is in
-    // the closure variables defined earlier in this function.
     return that;
 };