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