]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/common/js/utils.js
more work on metarecord holds
[Evergreen.git] / Open-ILS / web / opac / common / js / utils.js
1 function $(id) { return getId(id); }
2 function getId(id) {
3         return document.getElementById(id);
4 }
5
6 function swapCSSClass(obj, old, newc ) {
7         removeCSSClass(obj, old );
8         addCSSClass(obj, newc );
9 }
10
11
12 function addCSSClass(e,c) {
13         if(!e || !c) return;
14
15         var css_class_string = e.className;
16         var css_class_array;
17
18         if(css_class_string)
19                 css_class_array = css_class_string.split(/\s+/);
20
21         var string_ip = ""; /*strip out nulls*/
22         for (var css_class in css_class_array) {
23                 if (css_class_array[css_class] == c) { return; }
24                 if(css_class_array[css_class] !=null)
25                         string_ip += css_class_array[css_class] + " ";
26         }
27         string_ip += c;
28         e.className = string_ip;
29 }
30
31 function removeCSSClass(e, c) {
32         if(!e || !c) return;
33
34         var css_class_string = '';
35
36         var css_class_array = e.className;
37         if( css_class_array )
38                 css_class_array = css_class_array.split(/\s+/);
39
40         var first = 1;
41         for (var css_class in css_class_array) {
42                 if (css_class_array[css_class] != c) {
43                         if (first == 1) {
44                                 css_class_string = css_class_array[css_class];
45                                 first = 0;
46                         } else {
47                                 css_class_string = css_class_string + ' ' +
48                                         css_class_array[css_class];
49                         }
50                 }
51         }
52         e.className = css_class_string;
53 }
54
55
56 /*returns the character code pressed that caused the event */
57 function grabCharCode(evt) {
58    evt = (evt) ? evt : ((window.event) ? event : null); 
59    if( evt ) {
60       return (evt.charCode ? evt.charCode : 
61          ((evt.which) ? evt.which : evt.keyCode ));
62    } else { return -1; }
63 }       
64
65
66 /* returns true if the user pressed enter */
67 function userPressedEnter(evt) {
68    var code = grabCharCode(evt);
69    if(code==13||code==3) return true;
70    return false;
71 }   
72
73
74 function goTo(url) {
75         /* setTimeout because ie sux */
76         setTimeout( function(){ location.href = url; }, 0 );
77 }
78
79
80 function removeChildren(dom) {
81         if(!dom) return;
82         while(dom.childNodes[0])
83                 dom.removeChild(dom.childNodes[0]);
84 }
85
86 function appendClear(node, child) {
87         removeChildren(node);
88         node.appendChild(child);
89 }
90
91
92 function instanceOf(object, constructorFunction) {
93
94    if(!IE) {
95       while (object != null) {
96          if (object == constructorFunction.prototype)
97             return true;
98          object = object.__proto__;
99       }
100    } else {
101       while(object != null) {
102          if( object instanceof constructorFunction )
103             return true;
104          object = object.__proto__;
105       }
106    }
107    return false;
108 }         
109
110
111 /* ------------------------------------------------------------------------------------------- */
112 /* detect my browser */
113 var isMac, NS, NS4, NS6, IE, IE4, IE4mac, IE4plus, IE5, IE5plus, IE6, IEMajor, ver4;
114 function detect_browser() {       
115
116    isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
117    NS = (navigator.appName == "Netscape") ? true : false;
118    NS4 = (document.layers) ? true : false;
119    IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false;
120    IEmac = ((document.all)&&(isMac)) ? true : false;
121    IE4plus = (document.all) ? true : false;
122    IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
123    IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
124    IE6 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 6.")!=-1)) ? true : false;
125    ver4 = (NS4 || IE4plus) ? true : false;
126    NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;
127
128    IE5plus = IE5 || IE6;
129    IEMajor = 0;
130
131    if (IE4plus) {
132       var start = navigator.appVersion.indexOf("MSIE");
133       var end = navigator.appVersion.indexOf(".",start);
134       IEMajor = parseInt(navigator.appVersion.substring(start+5,end));
135       IE5plus = (IEMajor>=5) ? true : false;
136    }
137 }  
138 detect_browser();
139 /* ------------------------------------------------------------------------------------------- */
140
141
142 function text(t) {
143         if(t == null) t = "";
144         return document.createTextNode(t);
145 }
146
147 function elem(name, attrs, txt) {
148     var e = document.createElement(name);
149     if (attrs) {
150         for (key in attrs) {
151                           if( key == 'id') e.id = attrs[key];
152                           else e.setAttribute(key, attrs[key]);
153         }
154     }
155     if (txt) e.appendChild(text(txt));
156     return e;
157 }                   
158
159
160 /* sel is the selector object, sets selected on the 
161         option with the given value. case does not matter...*/
162 function setSelector( sel, value ) {
163         if(sel && value != null) {
164                 for( var i = 0; i!= sel.options.length; i++ ) { 
165                         if( sel.options[i] ) {
166                                 var val = sel.options[i].value;
167                                 if( val == null || val == "" ) /* for IE */
168                                         val = sel.options[i].innerHTML;
169                                 value += ""; /* in case of number */ 
170                                 if( val && val.toLowerCase() == value.toLowerCase() ) {
171                                         sel.selectedIndex = i;
172                                         sel.options[i].selected = true;
173                                 }
174                         }
175                 }
176         }
177 }
178
179 function setSelectorRegex( sel, regex ) {
180         if(sel && regex != null) {
181                 for( var i = 0; i!= sel.options.length; i++ ) { 
182                         if( sel.options[i] ) {
183                                 var val = sel.options[i].value;
184                                 if( val == null || val == "" ) /* for IE */
185                                         val = sel.options[i].innerHTML;
186                                 value += ""; /* in case of number */ 
187                                 if( val && val.match(regex) ) {
188                                         sel.selectedIndex = i;
189                                         sel.options[i].selected = true;
190                                 }
191                         }
192                 }
193         }
194 }
195
196 function getSelectorVal( sel ) {
197         if(!sel) return null;
198         var o = sel.options[sel.selectedIndex];
199         var v = o.value; 
200         if(v == null) v = o.innerHTML;
201         return v;
202 }
203
204 function getSelectorName( sel ) {
205         var o = sel.options[sel.selectedIndex];
206         var v = o.name;
207         if(v == null || v == undefined || v == "") v = o.innerHTML;
208         return v;
209 }
210
211 function setSelectorByName( sel, name ) {
212         for( var o in sel.options ) {
213                 var opt = sel.options[o];
214                 if( opt.name == name || opt.innerHTML == name ) {
215                         sel.selectedIndex = o;
216                         opt.selected = true;
217                 }
218         }
219 }
220
221 function findSelectorOptByValue( sel, val ) {
222         for( var i = 0; i < sel.options.length; i++ ) {
223                 var opt = sel.options[i];
224                 if( opt.value == val ) return opt;
225         }
226         return null;
227 }
228
229 function debugSelector(sel) {
230         var s = 'Selector\n';
231         for( var i = 0; i != sel.options.length; i++ ) {
232                 var o = sel.options[i];
233                 s += "\t" + o.innerHTML + "\n";
234         }
235         return s;
236 }
237
238 function findParentByNodeName(node, name) {
239         while( ( node = node.parentNode) ) 
240                 if (node.nodeName == name) return node;
241         return null;
242 }
243
244 /* returns only elements in nodes childNodes list, not sub-children */
245 function getElementsByTagNameFlat( node, name ) {
246         var elements = [];
247         for( var e in node.childNodes ) {
248                 var n = node.childNodes[e];
249                 if( n && n.nodeName == name ) elements.push(n);
250         }
251         return elements;
252 }
253
254 /* expects a tree with a id() method on each node and a 
255 children() method to get to each node */
256 function findTreeItemById( tree, id ) {
257         if( tree.id() == id ) return tree;
258         for( var c in tree.children() ) {
259                 var found = findTreeItemById( tree.children()[c], id );
260                 if(found) return found;
261         }
262         return null;
263 }
264
265 /* returns null if none of the tests are true.  returns sub-array of 
266 matching array items otherwise */
267 function grep( arr, func ) {
268         var results = [];
269         for( var i in arr ) {
270                 if( func(arr[i]) ) 
271                         results.push(arr[i]);
272         }
273         if(results.length > 0) return results;
274         return null;
275 }
276
277 function doSelectorActions(sel) {
278         if(IE && sel) { 
279                 sel.onchange = function() {
280                         var o = sel.options[sel.selectedIndex];
281                         if(o && o.onclick) o.onclick()
282                 }
283         }
284 }
285
286 /* if index < 0, the item is pushed onto the end */
287 function insertSelectorVal( selector, index, name, value, action, indent ) {
288         if( index < 0 ) index = selector.options.length;
289         var a = [];
290         for( var i = selector.options.length; i != index; i-- ) 
291                 a[i] = selector.options[i-1];
292
293         var opt = setSelectorVal( selector, index, name, value, action, indent );
294
295         for( var i = index + 1; i < a.length; i++ ) 
296                 selector.options[i] = a[i];
297
298         return opt;
299 }
300
301 /* changes the value of the option at the specified index */
302 function setSelectorVal( selector, index, name, value, action, indent ) {
303         if(!indent || indent < 0) indent = 0;
304         indent = parseInt(indent);
305
306         var option;
307
308         if(IE) {
309                 var pre = elem("pre");
310                 for( var i = 0; i != indent; i++ )
311                         pre.appendChild(text("   "));
312
313                 pre.appendChild(text(name));
314                 option = new Option("", value);
315                 selector.options[index] = option;
316                 option.appendChild(pre);
317         
318         } else {
319                 indent = indent * 14;
320                 option= new Option(name, value);
321                 option.setAttribute("style", "padding-left: "+indent+'px;');
322                 selector.options[index] = option;
323                 if(action) option.onclick = action;
324         }
325
326         if(action) option.onclick = action;
327         return option;
328 }
329
330
331 /* split on spaces.  capitalize the first /\w/ character in
332    each substring */
333 function normalize(val) {
334
335    if(!val) return ""; 
336
337    var newVal = '';
338    try {val = val.split(' ');} catch(E) {return val;}
339    var reg = /\w/;
340
341    for( var c = 0; c < val.length; c++) {
342
343       var string = val[c];
344       var cap = false; 
345       for(var x = 0; x != string.length; x++) {
346
347          if(!cap) {
348             var ch = string.charAt(x);
349             if(reg.exec(ch + "")) {
350                newVal += string.charAt(x).toUpperCase();
351                cap = true;
352                continue;
353             }
354          }
355
356          newVal += string.charAt(x).toLowerCase();
357       }
358       if(c < (val.length-1)) newVal += " ";
359    }
360
361    newVal = newVal.replace(/\s*\.\s*$/,'');
362    newVal = newVal.replace(/\s*\/\s*\/\s*$/,' / ');
363    newVal = newVal.replace(/\s*\/\s*$/,'');
364
365    return newVal;
366 }
367
368
369 /* returns true if n is null or stringifies to 'undefined' */
370 function isNull(n) {
371         if( n == null || n == undefined || n.toString().toLowerCase() == "undefined" 
372                 || n.toString().toLowerCase() == "null" )
373                 return true;
374         return false;
375 }
376
377
378 /* find nodes with an attribute of 'name' that equals nodeName */
379
380 function $n( root, nodeName ) { return findNodeByName(root,nodeName); }
381
382 function findNodeByName(root, nodeName) {
383         if( !root || !nodeName) return null;
384
385         if(root.nodeType != 1) return null;
386
387         if(root.getAttribute("name") == nodeName || root.name == nodeName ) 
388                 return root;
389
390         var children = root.childNodes;
391
392         for( var i = 0; i != children.length; i++ ) {
393                 var n = findNodeByName(children[i], nodeName);
394                 if(n) return n;
395         }
396
397         return null;
398 }
399
400
401 /* truncates the string at 'size' characters and appends a '...' to the end */
402 function truncate(string, size) {
403         if(string && size != null && 
404                         size > -1 && string.length > size) 
405                 return string.substr(0, size) + "... "; 
406         return string;
407 }
408
409
410 /* style sheets must have a 'name' attribute for these functions to work */
411 function setActivateStyleSheet(name) {
412         var i, a, main;
413         for (i = 0; (a = document.getElementsByTagName ("link")[i]); i++) {
414                 if (a.getAttribute ("rel").indexOf ("style") != -1 && a.getAttribute ("name")) {
415                         a.disabled = true;
416                         if (a.getAttribute ("name").indexOf(name) != -1)
417                                 a.disabled = false;
418                 }
419         }
420 }
421
422
423 /* ----------------------------------------------------- */
424 var currentFontSize;
425 function scaleFonts(type) {
426
427         var size                = "";
428         var ssize       = "";
429         var size2       = "";
430         var a;
431         
432         if(!currentFontSize) currentFontSize = 'regular';
433         if(currentFontSize == 'regular' && type == 'regular' ) return;
434         if( currentFontSize == type ) return;
435         currentFontSize = type;
436
437         switch(type) {
438                 case "large":  /* these are arbitrary.. but they seem to work ok in FF/IE */
439                         size = "142%"; 
440                         size2 = "107%"; 
441                         ssize = "94%";
442                         break;
443         }
444
445         document.getElementsByTagName('body')[0].style.fontSize = size;
446         for (i = 0; (a = document.getElementsByTagName ("td")[i]); i++) a.style.fontSize = size;;
447         for (i = 0; (a = document.getElementsByTagName ("div")[i]); i++) a.style.fontSize = ssize;
448         for (i = 0; (a = document.getElementsByTagName ("option")[i]); i++) a.style.fontSize = ssize;
449         for (i = 0; (a = document.getElementsByTagName ("li")[i]); i++) a.style.fontSize = ssize;
450         for (i = 0; (a = document.getElementsByTagName ("span")[i]); i++) a.style.fontSize = ssize;
451         for (i = 0; (a = document.getElementsByTagName ("select")[i]); i++) a.style.fontSize = ssize;
452         for (i = 0; (a = document.getElementsByTagName ("a")[i]); i++) a.style.fontSize = size2;
453 }
454
455
456 function sortWordsIgnoreCase(a, b) {
457         a = a.toLowerCase();
458         b = b.toLowerCase();
459         if(a>b) return 1;
460         if(a<b) return -1;
461         return 0;
462 }
463
464
465 function getSelectedList(sel) {
466         if(!sel) return [];
467         var vals = [];
468         for( var i = 0; i != sel.options.length; i++ ) {
469                 if(sel.options[i].selected)
470                         vals.push(sel.options[i].value);
471         }
472         return vals;
473 }
474
475
476 function setEnterFunc(node, func) {
477         if(!(node && func)) return;
478         node.onkeydown = function(evt) {
479                 if( userPressedEnter(evt)) func();
480         }
481 }
482
483 function iterate( arr, callback ) {
484         for( var i = 0; i < arr.length; i++ ) 
485                 callback(arr[i]);
486 }
487
488
489
490
491 /* taken directly from the JSAN util.date library */
492 /* but changed from the util.date.interval_to_seconds invocation, 
493 because JSAN will assume the whole library is already loaded if 
494 it sees that, and the staff client uses both this file and the
495 JSAN library*/
496 function interval_to_seconds( $interval ) {
497
498         $interval = $interval.replace( /and/, ',' );
499         $interval = $interval.replace( /,/, ' ' );
500         
501         var $amount = 0;
502         var results = $interval.match( /\s*\+?\s*(\d+)\s*(\w{1})\w*\s*/g);  
503         for( var i = 0; i < results.length; i++ ) {
504                 if(!results[i]) continue;
505                 var result = results[i].match( /\s*\+?\s*(\d+)\s*(\w{1})\w*\s*/ );
506                 if (result[2] == 's') $amount += result[1] ;
507                 if (result[2] == 'm') $amount += 60 * result[1] ;
508                 if (result[2] == 'h') $amount += 60 * 60 * result[1] ;
509                 if (result[2] == 'd') $amount += 60 * 60 * 24 * result[1] ;
510                 if (result[2] == 'w') $amount += 60 * 60 * 24 * 7 * result[1] ;
511                 if (result[2] == 'M') $amount += ((60 * 60 * 24 * 365)/12) * result[1] ;
512                 if (result[2] == 'y') $amount += 60 * 60 * 24 * 365 * result[1] ;
513         }
514         return $amount;
515 }
516
517
518 function openWindow( data ) {
519         if( isXUL() ) {
520                 var data = window.escape(
521                         '<html><head><title></title></head><body>' + data + '</body></html>');
522
523                 xulG.window_open(
524                         'data:text/html,' + data,
525                         '', 
526                         'chrome,resizable,width=700,height=500'); 
527
528         } else {
529                 win = window.open('','', 'resizable,width=700,height=500'); 
530                 win.document.body.innerHTML = data;
531         }
532 }
533
534
535 /* alerts the innerhtml of the node with the given id */
536 function alertId(id) {
537         var node = $(id);
538         if(node) alert(node.innerHTML);
539 }
540
541 function confirmId(id) {
542         var node = $(id);
543         if(node) return confirm(node.innerHTML);
544 }
545
546
547 function goBack() { history.back(); }
548 function goForward() { history.forward(); }
549
550
551 function uniquify(arr) {
552         if(!arr) return [];
553         var newarr = [];
554         for( var i = 0; i < arr.length; i++ ) {
555                 var item = arr[i];
556                 if( ! grep( newarr, function(x) {return (x == item);}))
557                         newarr.push(item);
558         }
559         return newarr;
560 }