Bug 29932: Use localStorage instead of cookie for bibs_selected
[koha-ffzg.git] / koha-tmpl / intranet-tmpl / prog / js / staff-global.js
1 /* global shortcut delBasket Sticky AUDIO_ALERT_PATH Cookies */
2 /* exported addBibToContext delBibToContext escape_str escape_price openWindow _ removeFocus toUC confirmDelete confirmClone playSound */
3 if ( KOHA === undefined ) var KOHA = {};
4
5 function _(s) { return s; } // dummy function for gettext
6
7 // http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery/5341855#5341855
8 String.prototype.format = function() { return formatstr(this, arguments); };
9 function formatstr(str, col) {
10     col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);
11     var idx = 0;
12     return str.replace(/%%|%s|%(\d+)\$s/g, function (m, n) {
13         if (m == "%%") { return "%"; }
14         if (m == "%s") { return col[idx++]; }
15         return col[n];
16     });
17 }
18
19 var HtmlCharsToEscape = {
20     '&': '&',
21     '<': '&lt;',
22     '>': '&gt;'
23 };
24 String.prototype.escapeHtml = function() {
25     return this.replace(/[&<>]/g, function(c) {
26         return HtmlCharsToEscape[c] || c;
27     });
28 };
29 function escape_str(s){
30     return s != null ? s.escapeHtml() : "";
31 }
32
33 /*
34  * Void method for numbers, for consistency
35  */
36 Number.prototype.escapeHtml = function() {
37     return this;
38 };
39 function escape_price(p){
40     return p != null ? p.escapeHtml().format_price() : "";
41 }
42
43 // http://stackoverflow.com/questions/14859281/select-tab-by-name-in-jquery-ui-1-10-0/16550804#16550804
44 $.fn.tabIndex = function () {
45     return $(this).parent().children('div').index(this);
46 };
47 $.fn.selectTabByID = function (tabID) {
48     $(this).tabs("option", "active", $( tabID ).tabIndex());
49 };
50
51 $(document).ready(function() {
52     $('#header_search').tabs().on( "tabsactivate", function() { $(this).find("div:visible").find('input').eq(0).focus(); });
53
54     $(".close").click(function(){ window.close(); });
55
56     $("#checkin_search form").preventDoubleFormSubmit();
57
58     if($("#header_search #checkin_search").length > 0){ shortcut.add('Alt+r',function (){ $("#header_search").selectTabByID("#checkin_search"); $("#ret_barcode").focus(); }); } else { shortcut.add('Alt+r',function (){ location.href="/cgi-bin/koha/circ/returns.pl"; }); }
59     if($("#header_search #circ_search").length > 0){ shortcut.add('Alt+u',function (){ $("#header_search").selectTabByID("#circ_search"); $("#findborrower").focus(); }); } else { shortcut.add('Alt+u',function(){ location.href="/cgi-bin/koha/circ/circulation.pl"; }); }
60     if($("#header_search #catalog_search").length > 0){ shortcut.add('Alt+q',function (){ $("#header_search").selectTabByID("#catalog_search"); $("#search-form").focus(); }); } else { shortcut.add('Alt+q',function(){ location.href="/cgi-bin/koha/catalogue/search.pl"; }); }
61     if($("#header_search #renew_search").length > 0){ shortcut.add('Alt+w',function (){ $("#header_search").selectTabByID("#renew_search"); $("#ren_barcode").focus(); }); } else { shortcut.add('Alt+w',function(){ location.href="/cgi-bin/koha/circ/renew.pl"; }); }
62
63     $("#header_search > ul > li").show();
64
65     $(".focus").focus();
66     $(".validated").each(function() {
67         $(this).validate();
68     });
69
70     $("#logout").on("click",function(){
71         logOut();
72     });
73     $("#helper").on("click",function(){
74         openHelp();
75         return false;
76     });
77
78     $("body").on("keypress", ".noEnterSubmit", function(e){
79         return checkEnter(e);
80     });
81
82     $(".keep_text").on("click",function(){
83         var field_index = $(this).parent().index();
84         keep_text( field_index );
85     });
86
87     $(".toggle_element").on("click",function(e){
88         e.preventDefault();
89         $( $(this).data("element") ).toggle();
90         if (typeof Sticky !== "undefined" && typeof hcSticky === "function") {
91             Sticky.hcSticky('update');
92         }
93     });
94
95     var navmenulist = $("#navmenulist");
96     if( navmenulist.length > 0 ){
97         var path = location.pathname.substring(1);
98         var url = window.location.toString();
99         var params = '';
100         if ( url.match(/\?(.+)$/) ) {
101             params = "?" + RegExp.$1;
102         }
103         $("a[href$=\"/" + path + params + "\"]", navmenulist).addClass("current");
104     }
105
106     $("#catalog-search-link a").on("hover", function(){
107         $("#catalog-search-dropdown a").toggleClass("catalog-search-dropdown-hover");
108     });
109
110     if ( localStorage.getItem("lastborrowernumber") ){
111         if( $("#hiddenborrowernumber").val() != localStorage.getItem("lastborrowernumber") ) {
112             $("#lastborrower-window").detach().appendTo("#breadcrumbs");
113             $("#lastborrowerlink").show();
114             $("#lastborrowerlink").prop("title", localStorage.getItem("lastborrowername") + " (" + localStorage.getItem("lastborrowercard") + ")");
115             $("#lastborrowerlink").prop("href", "/cgi-bin/koha/circ/circulation.pl?borrowernumber=" + localStorage.getItem("lastborrowernumber"));
116             $("#lastborrower-window").css("display", "inline-block");
117         }
118     }
119
120     if( !localStorage.getItem("lastborrowernumber") || ( $("#hiddenborrowernumber").val() != localStorage.getItem("lastborrowernumber") && localStorage.getItem("currentborrowernumber") != $("#hiddenborrowernumber").val())) {
121         if( $("#hiddenborrowernumber").val() ){
122             localStorage.setItem("lastborrowernumber", $("#hiddenborrowernumber").val() );
123             localStorage.setItem("lastborrowername", $("#hiddenborrowername").val() );
124             localStorage.setItem("lastborrowercard", $("#hiddenborrowercard").val() );
125         }
126     }
127
128     if( $("#hiddenborrowernumber").val() ){
129         localStorage.setItem("currentborrowernumber", $("#hiddenborrowernumber").val() );
130     }
131
132     $("#lastborrower-remove").click(function() {
133         removeLastBorrower();
134         $("#lastborrower-window").hide();
135     });
136
137     /* Search results browsing */
138     /* forms with action leading to search */
139     $("form[action*='search.pl']").submit(function(){
140         $('[name^="limit"]').each(function(){
141             if( $(this).val() == '' ){
142                 $(this).prop("disabled","disabled");
143             }
144         });
145         var disabledPrior = false;
146         $(".search-term-row").each(function(){
147             if( disabledPrior ){
148                 $(this).find('select[name="op"]').prop("disabled","disabled");
149                 disabledPrior = false;
150             }
151             if( $(this).find('input[name="q"]').val() == "" ){
152                 $(this).find('input').prop("disabled","disabled");
153                 $(this).find('select').prop("disabled","disabled");
154                 disabledPrior = true;
155             }
156         });
157         resetSearchContext();
158         saveOrClearSimpleSearchParams();
159     });
160     /* any link to launch a search except navigation links */
161     $("[href*='search.pl?']").not(".nav").not('.searchwithcontext').click(function(){
162         resetSearchContext();
163     });
164     /* any link to a detail page from the results page. */
165     $("#bookbag_form a[href*='detail.pl?']").click(function(){
166         resetSearchContext();
167     });
168
169 });
170
171 function removeLastBorrower(){
172     localStorage.removeItem("lastborrowernumber");
173     localStorage.removeItem("lastborrowername");
174     localStorage.removeItem("lastborrowercard");
175     localStorage.removeItem("currentborrowernumber");
176 }
177
178 // http://jennifermadden.com/javascript/stringEnterKeyDetector.html
179 function checkEnter(e){ //e is event object passed from function invocation
180     var characterCode; // literal character code will be stored in this variable
181     if(e && e.which){ //if which property of event object is supported (NN4)
182         characterCode = e.which; //character code is contained in NN4's which property
183     } else {
184         characterCode = e.keyCode; //character code is contained in IE's keyCode property
185     }
186     if( characterCode == 13 //if generated character code is equal to ascii 13 (if enter key)
187         && e.target.nodeName == "INPUT"
188         && e.target.type != "submit" // Allow enter to submit using the submit button
189     ){
190         return false;
191     } else {
192         return true;
193     }
194 }
195
196 function clearHoldFor(){
197     Cookies.remove("holdfor", { path: '/' });
198 }
199
200 function logOut(){
201     if( typeof delBasket == 'function' ){
202         delBasket('main', true);
203     }
204     clearHoldFor();
205     removeLastBorrower();
206     localStorage.removeItem("sql_reports_activetab");
207     localStorage.removeItem("searches");
208     localStorage.removeItem("bibs_selected");
209 }
210
211 function openHelp(){
212     window.open( "/cgi-bin/koha/help.pl", "_blank");
213 }
214
215 jQuery.fn.preventDoubleFormSubmit = function() {
216     jQuery(this).submit(function() {
217         $("body, form input[type='submit'], form button[type='submit'], form a").addClass('waiting');
218         if (this.beenSubmitted)
219             return false;
220         else
221             this.beenSubmitted = true;
222     });
223 };
224
225 function openWindow(link,name,width,height) {
226     name = (typeof name == "undefined")?'popup':name;
227     width = (typeof width == "undefined")?'600':width;
228     height = (typeof height == "undefined")?'400':height;
229     //IE <= 9 can't handle a "name" with whitespace
230     try {
231         window.open(link,name,'width='+width+',height='+height+',resizable=yes,toolbar=false,scrollbars=yes,top');
232     } catch(e) {
233         window.open(link,null,'width='+width+',height='+height+',resizable=yes,toolbar=false,scrollbars=yes,top');
234     }
235 }
236
237 // Use this function to remove the focus from any element for
238 // repeated scanning actions on errors so the librarian doesn't
239 // continue scanning and miss the error.
240 function removeFocus() {
241     $(':focus').blur();
242 }
243
244 function toUC(f) {
245     var x=f.value.toUpperCase();
246     f.value=x;
247     return true;
248 }
249
250 function confirmDelete(message) {
251     return (confirm(message) ? true : false);
252 }
253
254 function confirmClone(message) {
255     return (confirm(message) ? true : false);
256 }
257
258 function playSound( sound ) {
259     if ( ! ( sound.indexOf('http://') === 0 || sound.indexOf('https://') === 0  ) ) {
260         sound = AUDIO_ALERT_PATH + sound;
261     }
262     document.getElementById("audio-alert").innerHTML = '<audio src="' + sound + '" autoplay="autoplay" autobuffer="autobuffer"></audio>';
263 }
264
265 // For keeping the text when navigating the search tabs
266 function keep_text(clicked_index) {
267     var searchboxes = document.getElementsByClassName("head-searchbox");
268     var persist = searchboxes[0].value;
269
270     for (var i = 0; i < searchboxes.length - 1; i++) {
271         if (searchboxes[i].value != searchboxes[i+1].value) {
272             if (i === searchboxes.length-2) {
273                 if (searchboxes[i].value != searchboxes[0].value) {
274                     persist = searchboxes[i].value;
275                 } else if (searchboxes.length === 2) {
276                     if (clicked_index === 0) {
277                         persist = searchboxes[1].value;
278                     }
279                 } else {
280                     persist = searchboxes[i+1].value;
281                 }
282             } else if (searchboxes[i+1].value != searchboxes[i+2].value) {
283                 persist = searchboxes[i+1].value;
284             }
285         }
286     }
287
288     for (i = 0; i < searchboxes.length; i++) {
289         searchboxes[i].value = persist;
290     }
291 }
292
293 // Extends jQuery API
294 jQuery.extend({uniqueArray:function(array){
295     return $.grep(array, function(el, index) {
296         return index === $.inArray(el, array);
297     });
298 }});
299
300 function removeByValue(arr, val) {
301     for(var i=0; i<arr.length; i++) {
302         if(arr[i] == val) {
303             arr.splice(i, 1);
304             break;
305         }
306     }
307 }
308
309 function addBibToContext( bibnum ) {
310     bibnum = parseInt(bibnum, 10);
311     var bibnums = getContextBiblioNumbers();
312     bibnums.push(bibnum);
313     setContextBiblioNumbers( bibnums );
314     setContextBiblioNumbers( $.uniqueArray( bibnums ) );
315 }
316
317 function delBibToContext( bibnum ) {
318     var bibnums = getContextBiblioNumbers();
319     removeByValue( bibnums, bibnum );
320     setContextBiblioNumbers( $.uniqueArray( bibnums ) );
321 }
322
323 function setContextBiblioNumbers( bibnums ) {
324     localStorage.setItem('bibs_selected', JSON.stringify( bibnums ) );
325 }
326
327 function getContextBiblioNumbers() {
328     var r = localStorage.getItem('bibs_selected');
329     if ( r ) {
330         return JSON.parse(r);
331     }
332     r = new Array();
333     return r;
334 }
335
336 function resetSearchContext() {
337     setContextBiblioNumbers( new Array() );
338 }
339
340 function saveOrClearSimpleSearchParams() {
341     // Simple masthead search - pass value for display on details page
342     var pulldown_selection;
343     var searchbox_value;
344     if( $("#cat-search-block select.advsearch").length ){
345         pulldown_selection = $("#cat-search-block select.advsearch").val();
346     } else {
347         pulldown_selection ="";
348     }
349     if( $("#cat-search-block #search-form").length ){
350         searchbox_value = $("#cat-search-block #search-form").val();
351     } else {
352         searchbox_value ="";
353     }
354     localStorage.setItem('cat_search_pulldown_selection', pulldown_selection );
355     localStorage.setItem('searchbox_value', searchbox_value );
356 }