Full-record template invokes {{translate}} on fieldnames.
[mkws-moved-to-github.git] / tools / htdocs / mkws.js
index c0171d9..cacc8d0 100644 (file)
@@ -1,5 +1,4 @@
-/* A very simple client that shows a basic usage of the pz2.js
-*/
+/*! MKWS, the MasterKey Widget Set. Copyright (C) 2013, Index Data */
 
 "use strict"; // HTML5: disable for debug_level >= 2
 
@@ -7,20 +6,20 @@
 var mkws = {
     sort: 'relevance',
     authenticated: false,
-    filters: [],
+    filters: []
 };
 
-/*
- * global config object: mkws_config
- *
- * Needs to be defined in the HTML header before including this JS file.
- * Define empty mkws_config for simple applications that don't define it.
- */
-if (!mkws_config)
+// Define empty mkws_config for simple applications that don't define it.
+if (mkws_config == null || typeof mkws_config != 'object') {
     var mkws_config = {};
+}
 
-// Wrapper for jQuery
-(function ($) {
+// wrapper for jQuery lib
+function _mkws($) {
+    // if (console && console.log) console.log("run _mkws()");
+
+    // call this function only once
+    if (mkws.init) return;
 
 mkws.locale_lang = {
     "de": {
@@ -89,7 +88,7 @@ mkws.debug_function = function (string) {
     }
 
     var now = $.now();
-    var timestamp = (now - mkws.debug_time.start)/1000 + " (+" + (now - mkws.debug_time.last)/1000 + ") "
+    var timestamp = ((now - mkws.debug_time.start)/1000).toFixed(3) + " (+" + ((now - mkws.debug_time.last)/1000).toFixed(3) + ") "
     mkws.debug_time.last = now;
 
     // you need to disable use strict at the top of the file!!!
@@ -101,10 +100,17 @@ mkws.debug_function = function (string) {
     console.log(timestamp + string);
 }
 var debug = mkws.debug_function; // local alias
+debug("start running MKWS");
 
 
 Handlebars.registerHelper('json', function(obj) {
-    return JSON.stringify(obj);
+    return $.toJSON(obj);
+});
+
+
+Handlebars.registerHelper('translate', function(s) {
+    debug("translating '" + s + "'");
+    return M(s);
 });
 
 
@@ -157,9 +163,11 @@ Handlebars.registerHelper('commaList', function(items, options) {
 
 
 {
+
     /* 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"]],
@@ -185,6 +193,12 @@ Handlebars.registerHelper('commaList', function(items, options) {
        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')
@@ -196,6 +210,8 @@ Handlebars.registerHelper('commaList', function(items, options) {
 mkws.sort = mkws_config.sort_default;
 debug("copied mkws_config.sort_default '" + mkws_config.sort_default + "' to mkws.sort");
 
+mkws.usesessions = mkws_config.use_service_proxy ? false : true;
+
 if (mkws_config.query_width < 5 || mkws_config.query_width > 150) {
     debug("Reset query width: " + mkws_config.query_width);
     mkws_config.query_width = 50;
@@ -212,19 +228,19 @@ for (var key in mkws_config) {
     }
 }
 
-
+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 my_paz = new pz2( { "onshow": my_onshow,
                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
-                    "pazpar2path": mkws_config.pazpar2_url || "http://mkws.indexdata.com/service-proxy/",
+                    "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,
+                   "usesessions" : mkws.usesessions,
                     "showResponseType": '', // or "json" (for debugging?)
                     "onrecord": my_onrecord } );
 
@@ -417,18 +433,20 @@ function onFormSubmitEventHandler()
     return false;
 }
 
-function newSearch(query, sort)
+function newSearch(query, sort, targets, windowid)
 {
-    if (!mkws.authenticated) {
+    debug("newSearch: " + query);
+
+    if (mkws_config.use_service_proxy && !mkws.authenticated) {
        alert("searching before authentication");
        return;
     }
 
     mkws.filters = []
-    redraw_navi();
-    resetPage();
-    loadSelect();
-    triggerSearch(query, sort);
+    redraw_navi(); // ### should use windowid
+    resetPage(); // ### the globals it resents should be indexed by windowid
+    loadSelect(); // ### should use windowid
+    triggerSearch(query, sort, targets, windowid);
     mkws.switchView('records'); // In case it's configured to start off as hidden
     submitted = true;
 }
@@ -448,7 +466,7 @@ function resetPage()
     totalRec = 0;
 }
 
-function triggerSearch (query, sort)
+function triggerSearch (query, sort, targets, windowid)
 {
     var pp2filter = "";
     var pp2limit = "";
@@ -460,13 +478,22 @@ function triggerSearch (query, sort)
     if (sort) {
        mkws.sort = sort;
     }
+    if (targets) {
+       // ### should support multiple |-separated targets
+       mkws.filters.push({ id: targets, name: targets });
+    }
 
     for (var i in mkws.filters) {
        var filter = mkws.filters[i];
        if (filter.id) {
            if (pp2filter)
                pp2filter += ",";
-           pp2filter += 'pz:id=' + filter.id;
+           if (filter.id.match(/^[a-z:]+[=~]/)) {
+               debug("filter '" + filter.id + "' already begins with SETTING OP");
+           } else {
+               filter.id = 'pz:id=' + filter.id;
+           }
+           pp2filter += filter.id;
        } else {
            if (pp2limit)
                pp2limit += ",";
@@ -474,8 +501,16 @@ function triggerSearch (query, sort)
        }
     }
 
-    debug("triggerSearch(" + mkws.query + "): filters = " + JSON.stringify(mkws.filters) + ", pp2filter = " + pp2filter + ", pp2limit = " + pp2limit);
-    my_paz.search(mkws.query, recPerPage, mkws.sort, pp2filter, undefined, { limit: pp2limit });
+    var params = {};
+    if (pp2limit) {
+       params.limit = pp2limit;
+    }
+    if (windowid) {
+       params.windowid = windowid;
+    }
+    debug("triggerSearch(" + mkws.query + "): filters = " + $.toJSON(mkws.filters) + ", pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
+
+    my_paz.search(mkws.query, recPerPage, mkws.sort, pp2filter, undefined, params);
 }
 
 function loadSelect ()
@@ -514,16 +549,16 @@ mkws.limitTarget  = function (id, name)
 
 mkws.delimitQuery = function (field, value)
 {
-    debug("delimitQuery(field=" + field + ", value=" + value + ")");    
+    debug("delimitQuery(field=" + field + ", value=" + value + ")");
     var newFilters = [];
     for (var i in mkws.filters) {
        var filter = mkws.filters[i];
        if (filter.field &&
            field == filter.field &&
            value == filter.value) {
-           debug("delimitTarget() removing filter " + JSON.stringify(filter));
+           debug("delimitTarget() removing filter " + $.toJSON(filter));
        } else {
-           debug("delimitTarget() keeping filter " + JSON.stringify(filter));
+           debug("delimitTarget() keeping filter " + $.toJSON(filter));
            newFilters.push(filter);
        }
     }
@@ -539,14 +574,14 @@ mkws.delimitQuery = function (field, value)
 
 mkws.delimitTarget = function (id)
 {
-    debug("delimitTarget(id=" + id + ")");    
+    debug("delimitTarget(id=" + id + ")");
     var newFilters = [];
     for (var i in mkws.filters) {
        var filter = mkws.filters[i];
        if (filter.id) {
-           debug("delimitTarget() removing filter " + JSON.stringify(filter));
+           debug("delimitTarget() removing filter " + $.toJSON(filter));
        } else {
-           debug("delimitTarget() keeping filter " + JSON.stringify(filter));
+           debug("delimitTarget() keeping filter " + $.toJSON(filter));
            newFilters.push(filter);
        }
     }
@@ -580,7 +615,7 @@ function redraw_navi ()
                ');return false;">' + filter.value + '</a>';
        }
     }
-    
+
     navi.innerHTML = text;
 }
 
@@ -753,7 +788,7 @@ function defaultTemplate(name)
        return '\
       <table>\
        <tr>\
-         <th>Title</th>\
+         <th>{{translate "Title"}}</th>\
          <td>\
            {{md-title}}\
            {{#if md-title-remainder}}\
@@ -766,19 +801,19 @@ function defaultTemplate(name)
        </tr>\
        {{#if md-date}}\
        <tr>\
-         <th>Date</th>\
+         <th>{{translate "Date"}}</th>\
          <td>{{md-date}}</td>\
        </tr>\
        {{/if}}\
        {{#if md-author}}\
        <tr>\
-         <th>Author</th>\
+         <th>{{translate "Author"}}</th>\
          <td>{{md-author}}</td>\
        </tr>\
        {{/if}}\
        {{#if md-electronic-url}}\
        <tr>\
-         <th>URL</th>\
+         <th>{{translate "URL"}}</th>\
          <td>\
            {{#each md-electronic-url}}\
              <a href="{{this}}">{{this}}</a><br/>\
@@ -788,7 +823,7 @@ function defaultTemplate(name)
        {{/if}}\
        {{#if-any location having="md-subject"}}\
        <tr>\
-         <th>Subject</th>\
+         <th>{{translate "Subject"}}</th>\
          <td>\
            {{#first location having="md-subject"}}\
              {{#if md-subject}}\
@@ -799,7 +834,7 @@ function defaultTemplate(name)
        </tr>\
        {{/if-any}}\
        <tr>\
-         <th>Locations</th>\
+         <th>{{translate "Locations"}}</th>\
          <td>\
            {{#commaList location}}\
              {{attr "@name"}}{{/commaList}}\
@@ -892,9 +927,14 @@ function mkws_html_all() {
 
     mkws_html_switch();
 
-    if (mkws_config.use_service_proxy)
-         mkws_service_proxy_auth(mkws_config.service_proxy_auth, 
-          mkws_config.service_proxy_auth_domain);
+    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
@@ -919,22 +959,46 @@ function mkws_html_all() {
 
 
 function run_auto_searches() {
-    var node = $('#mkwsRecords');
-    if (node.attr('autosearch')) {
+    debug("running auto searches");
+
+    $('[id^="mkwsRecords"]').each(function () {
+       var node = $(this);
        var query = node.attr('autosearch');
-       var sort = node.attr('sort');
-       var targets = node.attr('targets');
-       var s = "running auto search: '" + query + "'";
-       if (sort) s += " sorted by '" + sort + "'";
-       if (targets) s += " in targets '" + targets + "'";
-       debug(s);
-       newSearch(query, sort, targets);
-    }
+
+       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 = {};
+    var qs = window.location.search.replace('?', '');
+    var pairs = qs.split('&');
+    $.each(pairs, function(i, v){
+       var pair = v.split('=');
+       nvpair[pair[0]] = pair[1];
+    });
+    return nvpair;
+}
+
 function mkws_set_lang()  {
-    var lang = $.parseQuerystring().lang || mkws_config.lang;
+    var lang = parseQuerystring().lang || mkws_config.lang;
     if (!lang || !mkws.locale_lang[lang]) {
        mkws_config.lang = ""
     } else {
@@ -1003,9 +1067,14 @@ function mkws_html_perpage() {
  * The username/password is configured in the apache config file
  * for the site.
  */
-function mkws_service_proxy_auth(auth_url, auth_domain) {
+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(/^http:\/\/(.*?)\/.*/, '$1');
+       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;
@@ -1107,25 +1176,72 @@ function M(word) {
     return mkws.locale_lang[lang][word] || word;
 }
 
+// main
+(function() {
+    try {
+       mkws_html_all()
+    }
+
+    catch (e) {
+       mkws_config.error = e.message;
+       // alert(e.message);
+    }
+})();
+
+    // done
+    mkws.init = true;
+};
+
+
 /*
- * implement jQuery plugins
+ * implement jQuery plugin $.pazpar2({})
  */
-$.extend({
-    // implement $.parseQuerystring() for parsing URL parameters
-    parseQuerystring: function() {
-       var nvpair = {};
-       var qs = window.location.search.replace('?', '');
-       var pairs = qs.split('&');
-       $.each(pairs, function(i, v){
-           var pair = v.split('=');
-           nvpair[pair[0]] = pair[1];
+function _mkws_jquery_plugin ($) {
+    // delayed debug, internal variables are set after dom ready
+    function debug (string) {
+       setTimeout(function() { mkws.debug_function(string); }, 500);
+    }
+
+    function init_popup(obj) {
+       var config = obj ? obj : {};
+
+       var height = config.height || 760;
+       var width = config.width || 880;
+       var id_button = config.id_button || "input#mkwsButton";
+       var id_popup = config.id_popup || "#mkwsPopup";
+
+       debug("popup height: " + height + ", width: " + width);
+
+       // make sure that jquery-ui was loaded afte jQuery core lib, e.g.:
+       // <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
+       if (!$.ui) {
+           debug("Error: jquery-ui.js is missing, did you included it after jquery core in the HTML file?");
+           return;
+       }
+
+       $(id_popup).dialog({
+         closeOnEscape: true,
+         autoOpen: false,
+         height: height,
+         width: width,
+         modal: true,
+         resizable: true,
+         buttons: {
+                 Cancel: function() {
+                         $(this).dialog("close");
+                 }
+         },
+         close: function() { }
        });
-       return nvpair;
-    },
 
-    debug2: function(string) { // delayed debug, internal variables are set after dom ready
-       setTimeout(function() { debug(string); }, 500);
-    },
+       $(id_button)
+         .button()
+         .click(function() {
+                 $(id_popup).dialog("open");
+         });
+    };
+
+    $.extend({
 
     // service-proxy or pazpar2
     pazpar2: function(config) {
@@ -1197,71 +1313,27 @@ $.extend({
          </div>'
 
        if (config && config.layout == 'div') {
-           this.debug2("jquery plugin layout: div");
+           debug("jquery plugin layout: div");
            document.write(div);
        } else if (config && config.layout == 'popup') {
-           this.debug2("jquery plugin layout: popup with id: " + id_popup);
+           debug("jquery plugin layout: popup with id: " + id_popup);
            document.write(popup);
            $(document).ready( function() { init_popup(config); } );
        } else {
-           this.debug2("jquery plugin layout: table");
+           debug("jquery plugin layout: table");
            document.write(table);
        }
     }
 });
-
-function init_popup(obj) {
-    var config = obj ? obj : {};
-
-    var height = config.height || 760;
-    var width = config.width || 880;
-    var id_button = config.id_button || "input#mkwsButton";
-    var id_popup = config.id_popup || "#mkwsPopup";
-
-    debug("popup height: " + height + ", width: " + width);
-
-    // make sure that jquery-ui was loaded afte jQuery core lib, e.g.:
-    // <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
-    if (!$.ui) {
-       debug("Error: jquery-ui.js is missing, did you included it after jquery core in the HTML file?");
-       return;
-    }
-
-    $(id_popup).dialog({
-      closeOnEscape: true,
-      autoOpen: false,
-      height: height,
-      width: width,
-      modal: true,
-      resizable: true,
-      buttons: {
-             Cancel: function() {
-                     $(this).dialog("close");
-             }
-      },
-      close: function() { }
-    });
-
-    $(id_button)
-      .button()
-      .click(function() {
-             $(id_popup).dialog("open");
-      });
 };
 
+// wrapper to call _mkws after page load
+(function (j) {
+    // enable before page load, so we could call it before mkws() runs
+    _mkws_jquery_plugin(j);
 
-
-
-/* magic */
-$(document).ready(function() {
-    try {
-       mkws_html_all()
-    }
-
-    catch (e) {
-       mkws_config.error = e.message;
-       // alert(e.message);
-    }
-});
-
+    $(document).ready(function() {
+       // if (console && console.log) console.log("on load ready");
+       _mkws(j);
+    });
 })(jQuery);