Bug 29933: Fix stray usage of jquery.cookie.js plugin
[koha.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 }
209
210 function openHelp(){
211     window.open( "/cgi-bin/koha/help.pl", "_blank");
212 }
213
214 jQuery.fn.preventDoubleFormSubmit = function() {
215     jQuery(this).submit(function() {
216         $("body, form input[type='submit'], form button[type='submit'], form a").addClass('waiting');
217         if (this.beenSubmitted)
218             return false;
219         else
220             this.beenSubmitted = true;
221     });
222 };
223
224 function openWindow(link,name,width,height) {
225     name = (typeof name == "undefined")?'popup':name;
226     width = (typeof width == "undefined")?'600':width;
227     height = (typeof height == "undefined")?'400':height;
228     //IE <= 9 can't handle a "name" with whitespace
229     try {
230         window.open(link,name,'width='+width+',height='+height+',resizable=yes,toolbar=false,scrollbars=yes,top');
231     } catch(e) {
232         window.open(link,null,'width='+width+',height='+height+',resizable=yes,toolbar=false,scrollbars=yes,top');
233     }
234 }
235
236 // Use this function to remove the focus from any element for
237 // repeated scanning actions on errors so the librarian doesn't
238 // continue scanning and miss the error.
239 function removeFocus() {
240     $(':focus').blur();
241 }
242
243 function toUC(f) {
244     var x=f.value.toUpperCase();
245     f.value=x;
246     return true;
247 }
248
249 function confirmDelete(message) {
250     return (confirm(message) ? true : false);
251 }
252
253 function confirmClone(message) {
254     return (confirm(message) ? true : false);
255 }
256
257 function playSound( sound ) {
258     if ( ! ( sound.indexOf('http://') === 0 || sound.indexOf('https://') === 0  ) ) {
259         sound = AUDIO_ALERT_PATH + sound;
260     }
261     document.getElementById("audio-alert").innerHTML = '<audio src="' + sound + '" autoplay="autoplay" autobuffer="autobuffer"></audio>';
262 }
263
264 // For keeping the text when navigating the search tabs
265 function keep_text(clicked_index) {
266     var searchboxes = document.getElementsByClassName("head-searchbox");
267     var persist = searchboxes[0].value;
268
269     for (var i = 0; i < searchboxes.length - 1; i++) {
270         if (searchboxes[i].value != searchboxes[i+1].value) {
271             if (i === searchboxes.length-2) {
272                 if (searchboxes[i].value != searchboxes[0].value) {
273                     persist = searchboxes[i].value;
274                 } else if (searchboxes.length === 2) {
275                     if (clicked_index === 0) {
276                         persist = searchboxes[1].value;
277                     }
278                 } else {
279                     persist = searchboxes[i+1].value;
280                 }
281             } else if (searchboxes[i+1].value != searchboxes[i+2].value) {
282                 persist = searchboxes[i+1].value;
283             }
284         }
285     }
286
287     for (i = 0; i < searchboxes.length; i++) {
288         searchboxes[i].value = persist;
289     }
290 }
291
292 // Extends jQuery API
293 jQuery.extend({uniqueArray:function(array){
294     return $.grep(array, function(el, index) {
295         return index === $.inArray(el, array);
296     });
297 }});
298
299 function removeByValue(arr, val) {
300     for(var i=0; i<arr.length; i++) {
301         if(arr[i] == val) {
302             arr.splice(i, 1);
303             break;
304         }
305     }
306 }
307
308 function addBibToContext( bibnum ) {
309     bibnum = parseInt(bibnum, 10);
310     var bibnums = getContextBiblioNumbers();
311     bibnums.push(bibnum);
312     setContextBiblioNumbers( bibnums );
313     setContextBiblioNumbers( $.uniqueArray( bibnums ) );
314 }
315
316 function delBibToContext( bibnum ) {
317     var bibnums = getContextBiblioNumbers();
318     removeByValue( bibnums, bibnum );
319     setContextBiblioNumbers( $.uniqueArray( bibnums ) );
320 }
321
322 function setContextBiblioNumbers( bibnums ) {
323     $.cookie('bibs_selected', JSON.stringify( bibnums ));
324 }
325
326 function getContextBiblioNumbers() {
327     var r = $.cookie('bibs_selected');
328     if ( r ) {
329         return JSON.parse(r);
330     }
331     r = new Array();
332     return r;
333 }
334
335 function resetSearchContext() {
336     setContextBiblioNumbers( new Array() );
337 }
338
339 function saveOrClearSimpleSearchParams() {
340     // Simple masthead search - pass value for display on details page
341     var pulldown_selection;
342     var searchbox_value;
343     if( $("#cat-search-block select.advsearch").length ){
344         pulldown_selection = $("#cat-search-block select.advsearch").val();
345     } else {
346         pulldown_selection ="";
347     }
348     if( $("#cat-search-block #search-form").length ){
349         searchbox_value = $("#cat-search-block #search-form").val();
350     } else {
351         searchbox_value ="";
352     }
353     localStorage.setItem('cat_search_pulldown_selection', pulldown_selection );
354     localStorage.setItem('searchbox_value', searchbox_value );
355 }