]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/dojo/openils/Util.js
Acq: bugfixes for "Import Catalog Records by ID"
[working/Evergreen.git] / Open-ILS / web / js / dojo / openils / Util.js
1 /* ---------------------------------------------------------------------------
2  * Copyright (C) 2008  Georgia Public Library Service
3  * Bill Erickson <erickson@esilibrary.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * ---------------------------------------------------------------------------
15  */
16
17
18 /**
19  * General purpose, static utility functions
20  */
21
22 if(!dojo._hasResource["openils.Util"]) {
23     dojo._hasResource["openils.Util"] = true;
24     dojo.provide("openils.Util");
25     dojo.require('openils.Event');
26     dojo.declare('openils.Util', null, {});
27
28
29     /**
30      * Wrapper for dojo.addOnLoad that verifies a valid login session is active
31      * before adding the function to the onload set
32      */
33     openils.Util.addOnLoad = function(func, noSes) {
34         if(func) {
35             if(!noSes) {
36                 dojo.require('openils.User');
37                 if(!openils.User.authtoken) 
38                     return;
39             }
40             console.log("adding onload " + func.name);
41             dojo.addOnLoad(func);
42         }
43     };
44
45     /**
46      * Returns true if the provided array contains the specified value
47      */
48     openils.Util.arrayContains = function(arr, val) {
49         for(var i = 0; arr && i < arr.length; i++) {
50             if(arr[i] == val)
51                 return true;
52         }
53         return false;
54     };
55
56     /**
57      * Given a HTML select object, returns the currently selected value
58      */
59     openils.Util.selectorValue = function(sel) {
60         if(!sel) return null;
61         var idx = sel.selectedIndex;
62         if(idx < 0) return null;
63         var o = sel.options[idx];
64         var v = o.value; 
65         if(v == null) v = o.innerHTML;
66         return v;
67     }
68
69     /**
70      * Returns the character code of the provided (or current window) event
71      */
72     openils.Util.getCharCode = function(evt) {
73         evt = (evt) ? evt : ((window.event) ? event : null); 
74         if(evt) {
75             return (evt.charCode ? evt.charCode : 
76                 ((evt.which) ? evt.which : evt.keyCode ));
77         } else { return -1; }
78     }
79
80
81     /**
82      * Registers a handler for when the Enter key is pressed while 
83      * the provided DOM node has focus.
84      */
85     openils.Util.registerEnterHandler = function(domNode, func) {
86             if(!(domNode && func)) return;
87             domNode.onkeydown = function(evt) {
88             var code = openils.Util.getCharCode(evt);
89             if(code == 13 || code == 3) 
90                 func();
91         }
92         }
93
94
95     /**
96      * Parses opensrf response objects to see if they contain 
97      * data and/or an ILS event.  This only calls request.recv()
98      * once, so in a streaming context, it's necessary to loop on
99      * this method. 
100      * @param r The OpenSRF Request object
101      * @param eventOK If true, any found events will be returned as responses.  
102      * If false, they will be treated as error conditions and their content will
103      * be alerted if openils.Util.alertEvent is set to true.  Also, if eventOk is
104      * false, the response content will be null when an event is encountered.
105      * @param isList If true, assume the response will be a list of data and
106      * check the 1st item in the list for event-ness instead of the list itself.
107      */
108     openils.Util.alertEvent = true;
109     openils.Util.readResponse = function(r, eventOk, isList) {
110         var msg = r.recv();
111         if(msg == null) return msg;
112         var val = msg.content();
113         var testval = val;
114         if(isList && dojo.isArray(val))
115             testval = val[0];
116         if(e = openils.Event.parse(testval)) {
117             if(eventOk) return e;
118             console.log(e.toString());
119             if(openils.Util.alertEvent)
120                 alert(e);
121             return null;
122         }
123         return val;
124     };
125
126
127     /**
128      * Given a DOM node, adds the provided class to the node 
129      */
130     openils.Util.addCSSClass = function(node, cls) {
131         if(!(node && cls)) return; 
132         var className = node.className;
133
134         if(!className) {
135             node.className = cls;
136             return;
137         }
138
139         var classList = className.split(/\s+/);
140         var newName = '';
141             
142         for (var i = 0; i < classList.length; i++) {
143             if(classList[i] == cls) return;
144             if(classList[i] != null)
145                 newName += classList[i] + " ";
146         }
147
148         newName += cls;
149         node.className = newName;
150     },
151
152     /**
153      * Given a DOM node, removes the provided class from the CSS class 
154      * name list.
155      */
156     openils.Util.removeCSSClass = function(node, cls) {
157         if(!(node && cls && node.className)) return;
158         var classList = node.className.split(/\s+/);
159         var className = '';
160         for(var i = 0; i < classList.length; i++) {
161             if (typeof(cls) == "object") { /* assume regex */
162                 if (!cls.test(classList[i])) {
163                     if(i == 0)
164                         className = classList[i];
165                     else
166                         className += ' ' + classList[i];
167                 }
168             } else {
169                 if (classList[i] != cls) {
170                     if(i == 0)
171                         className = classList[i];
172                     else
173                         className += ' ' + classList[i];
174                 }
175             }
176         }
177         node.className = className;
178     }
179
180     openils.Util.objectSort = function(list, field) {
181         if(dojo.isArray(list)) {
182             if(!field) field = 'id';
183             return list.sort(
184                 function(a, b) {
185                     if(a[field]() > b[field]()) return 1;
186                     return -1;
187                 }
188             );
189         }
190         return [];
191     };
192
193     openils.Util.isTrue = function(val) {
194         return (val && val != '0' && !(val+'').match(/^f$/i));
195     };
196
197     /**
198      * Turns a list into a mapped object.
199      * @param list The list
200      * @param pkey The field to use as the map key 
201      * @param isFunc If true, the map key field is an accessor function 
202      * that will return the value of the map key
203      */
204     openils.Util.mapList = function(list, pkey, isFunc) {
205         if(!(list && pkey)) 
206             return null;
207         var map = {};
208         for(var i in list) {
209             if(isFunc)
210                 map[list[i][pkey]()] = list[i];
211             else
212                 map[list[i][pkey]] = list[i];
213         }
214         return map;
215     };
216
217     /**
218      * Assume a space-separated interval string, with optional comma
219      * E.g. "1 year, 2 days"  "3 days 6 hours"
220      */
221     openils.Util.intervalToSeconds = function(interval) {
222         var d = new Date();
223         var start = d.getTime();
224         var parts = interval.split(' ');
225         for(var i = 0; i < parts.length; i += 2) 
226             d = dojo.date.add(d, parts[i+1].replace(/s?,?$/,''), Number(parts[i]));
227         return Number((d.getTime() - start) / 1000);
228     };
229
230     openils.Util.hide = function(node) {
231         if(typeof node == 'string')
232             node = dojo.byId(node);
233         dojo.style(node, 'display', 'none');
234         dojo.style(node, 'visibility', 'hidden');
235     };
236
237     openils.Util.show = function(node, displayType) {
238         if(typeof node == 'string')
239             node = dojo.byId(node);
240         displayType = displayType || 'block';
241         dojo.style(node, 'display', displayType);
242         dojo.style(node, 'visibility', 'visible');
243     };
244
245     /** Toggles the display using show/hide, depending on the current value for CSS 'display' */
246     openils.Util.toggle = function(node, displayType) {
247         if(typeof node == 'string')
248             node = dojo.byId(node);
249         if(dojo.style(node, 'display') == 'none')
250             openils.Util.show(node, displayType);
251         else
252             openils.Util.hide(node);
253     };
254
255     openils.Util.appendClear = function(node, child) {
256         if(typeof node == 'string')
257             node = dojo.byId(node);
258         while(node.childNodes[0])
259             node.removeChild(node.childNodes[0]);
260         node.appendChild(child);
261     };
262
263     /**
264      * Plays a sound file via URL.  Only works with browsers
265      * that support HTML 5 <audio> element.  E.g. Firefox 3.5
266      */
267     openils.Util.playAudioUrl = function(urlString) {
268         if(!urlString) return;
269         var audio = document.createElement('audio');
270         audio.setAttribute('src', urlString);
271         audio.setAttribute('autoplay', 'true');
272         document.body.appendChild(audio);
273         document.body.removeChild(audio);
274     }
275
276     /**
277      * Return the properties of an object as a list. Saves typing.
278      */
279     openils.Util.objectProperties = function(obj) {
280         var K = [];
281         for (var k in obj) K.push(k);
282         return K;
283     }
284
285     openils.Util.uniqueElements = function(L) {
286         var o = {};
287         for (var k in L) o[L[k]] = true;
288         return openils.Util.objectProperties(o);
289     }
290
291 }
292