]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/common/js/utils.js
fixed delete
[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                                         return true;
174                                 }
175                         }
176                 }
177         }
178         return false;
179 }
180
181 function setSelectorRegex( sel, regex ) {
182         if(sel && regex != null) {
183                 for( var i = 0; i!= sel.options.length; i++ ) { 
184                         if( sel.options[i] ) {
185                                 var val = sel.options[i].value;
186                                 if( val == null || val == "" ) /* for IE */
187                                         val = sel.options[i].innerHTML;
188                                 value += ""; /* in case of number */ 
189                                 if( val && val.match(regex) ) {
190                                         sel.selectedIndex = i;
191                                         sel.options[i].selected = true;
192                                         return true;
193                                 }
194                         }
195                 }
196         }
197         return false;
198 }
199
200 function getSelectorVal( sel ) {
201         if(!sel) return null;
202         var o = sel.options[sel.selectedIndex];
203         var v = o.value; 
204         if(v == null) v = o.innerHTML;
205         return v;
206 }
207
208 function getSelectorName( sel ) {
209         var o = sel.options[sel.selectedIndex];
210         var v = o.name;
211         if(v == null || v == undefined || v == "") v = o.innerHTML;
212         return v;
213 }
214
215 function setSelectorByName( sel, name ) {
216         for( var o in sel.options ) {
217                 var opt = sel.options[o];
218                 if( opt.name == name || opt.innerHTML == name ) {
219                         sel.selectedIndex = o;
220                         opt.selected = true;
221                 }
222         }
223 }
224
225 function findSelectorOptByValue( sel, val ) {
226         for( var i = 0; i < sel.options.length; i++ ) {
227                 var opt = sel.options[i];
228                 if( opt.value == val ) return opt;
229         }
230         return null;
231 }
232
233 function debugSelector(sel) {
234         var s = 'Selector\n';
235         for( var i = 0; i != sel.options.length; i++ ) {
236                 var o = sel.options[i];
237                 s += "\t" + o.innerHTML + "\n";
238         }
239         return s;
240 }
241
242 function findParentByNodeName(node, name) {
243         while( ( node = node.parentNode) ) 
244                 if (node.nodeName == name) return node;
245         return null;
246 }
247
248 /* returns only elements in nodes childNodes list, not sub-children */
249 function getElementsByTagNameFlat( node, name ) {
250         var elements = [];
251         for( var e in node.childNodes ) {
252                 var n = node.childNodes[e];
253                 if( n && n.nodeName == name ) elements.push(n);
254         }
255         return elements;
256 }
257
258 /* expects a tree with a id() method on each node and a 
259 children() method to get to each node */
260 function findTreeItemById( tree, id ) {
261         if( tree.id() == id ) return tree;
262         for( var c in tree.children() ) {
263                 var found = findTreeItemById( tree.children()[c], id );
264                 if(found) return found;
265         }
266         return null;
267 }
268
269 /* returns null if none of the tests are true.  returns sub-array of 
270 matching array items otherwise */
271 function grep( arr, func ) {
272         var results = [];
273         for( var i in arr ) {
274                 if( func(arr[i]) ) 
275                         results.push(arr[i]);
276         }
277         if(results.length > 0) return results;
278         return null;
279 }
280
281 function doSelectorActions(sel) {
282         if(IE && sel) { 
283                 sel.onchange = function() {
284                         var o = sel.options[sel.selectedIndex];
285                         if(o && o.onclick) o.onclick()
286                 }
287         }
288 }
289
290 /* if index < 0, the item is pushed onto the end */
291 function insertSelectorVal( selector, index, name, value, action, indent ) {
292         if( index < 0 ) index = selector.options.length;
293         var a = [];
294         for( var i = selector.options.length; i != index; i-- ) 
295                 a[i] = selector.options[i-1];
296
297         var opt = setSelectorVal( selector, index, name, value, action, indent );
298
299         for( var i = index + 1; i < a.length; i++ ) 
300                 selector.options[i] = a[i];
301
302         return opt;
303 }
304
305 /* changes the value of the option at the specified index */
306 function setSelectorVal( selector, index, name, value, action, indent ) {
307         if(!indent || indent < 0) indent = 0;
308         indent = parseInt(indent);
309
310         var option;
311
312         if(IE) {
313                 var pre = elem("pre");
314                 for( var i = 0; i != indent; i++ )
315                         pre.appendChild(text("   "));
316
317                 pre.appendChild(text(name));
318                 option = new Option("", value);
319                 selector.options[index] = option;
320                 option.appendChild(pre);
321         
322         } else {
323                 indent = indent * 14;
324                 option= new Option(name, value);
325                 option.setAttribute("style", "padding-left: "+indent+'px;');
326                 selector.options[index] = option;
327                 if(action) option.onclick = action;
328         }
329
330         if(action) option.onclick = action;
331         return option;
332 }
333
334
335 /* split on spaces.  capitalize the first /\w/ character in
336    each substring */
337 function normalize(val) {
338
339    if(!val) return ""; 
340
341    var newVal = '';
342    try {val = val.split(' ');} catch(E) {return val;}
343    var reg = /\w/;
344
345    for( var c = 0; c < val.length; c++) {
346
347       var string = val[c];
348       var cap = false; 
349       for(var x = 0; x != string.length; x++) {
350
351          if(!cap) {
352             var ch = string.charAt(x);
353             if(reg.exec(ch + "")) {
354                newVal += string.charAt(x).toUpperCase();
355                cap = true;
356                continue;
357             }
358          }
359
360          newVal += string.charAt(x).toLowerCase();
361       }
362       if(c < (val.length-1)) newVal += " ";
363    }
364
365    newVal = newVal.replace(/\s*\.\s*$/,'');
366    newVal = newVal.replace(/\s*\/\s*\/\s*$/,' / ');
367    newVal = newVal.replace(/\s*\/\s*$/,'');
368
369    return newVal;
370 }
371
372
373 /* returns true if n is null or stringifies to 'undefined' */
374 function isNull(n) {
375         if( n == null || n == undefined || n.toString().toLowerCase() == "undefined" 
376                 || n.toString().toLowerCase() == "null" )
377                 return true;
378         return false;
379 }
380
381
382 /* find nodes with an attribute of 'name' that equals nodeName */
383
384 function $n( root, nodeName ) { return findNodeByName(root,nodeName); }
385
386 function findNodeByName(root, nodeName) {
387         if( !root || !nodeName) return null;
388
389         if(root.nodeType != 1) return null;
390
391         if(root.getAttribute("name") == nodeName || root.name == nodeName ) 
392                 return root;
393
394         var children = root.childNodes;
395
396         for( var i = 0; i != children.length; i++ ) {
397                 var n = findNodeByName(children[i], nodeName);
398                 if(n) return n;
399         }
400
401         return null;
402 }
403
404
405 /* truncates the string at 'size' characters and appends a '...' to the end */
406 function truncate(string, size) {
407         if(string && size != null && 
408                         size > -1 && string.length > size) 
409                 return string.substr(0, size) + "... "; 
410         return string;
411 }
412
413
414 /* style sheets must have a 'name' attribute for these functions to work */
415 function setActivateStyleSheet(name) {
416         var i, a, main;
417         for (i = 0; (a = document.getElementsByTagName ("link")[i]); i++) {
418                 if (a.getAttribute ("rel").indexOf ("style") != -1 && a.getAttribute ("name")) {
419                         a.disabled = true;
420                         if (a.getAttribute ("name").indexOf(name) != -1)
421                                 a.disabled = false;
422                 }
423         }
424 }
425
426
427 /* ----------------------------------------------------- */
428 var currentFontSize;
429 function scaleFonts(type) {
430
431         var size                = "";
432         var ssize       = "";
433         var size2       = "";
434         var a;
435         
436         if(!currentFontSize) currentFontSize = 'regular';
437         if(currentFontSize == 'regular' && type == 'regular' ) return;
438         if( currentFontSize == type ) return;
439         currentFontSize = type;
440
441         switch(type) {
442                 case "large":  /* these are arbitrary.. but they seem to work ok in FF/IE */
443                         size = "142%"; 
444                         size2 = "107%"; 
445                         ssize = "94%";
446                         break;
447         }
448
449         document.getElementsByTagName('body')[0].style.fontSize = size;
450         for (i = 0; (a = document.getElementsByTagName ("td")[i]); i++) a.style.fontSize = size;;
451         for (i = 0; (a = document.getElementsByTagName ("div")[i]); i++) a.style.fontSize = ssize;
452         for (i = 0; (a = document.getElementsByTagName ("option")[i]); i++) a.style.fontSize = ssize;
453         for (i = 0; (a = document.getElementsByTagName ("li")[i]); i++) a.style.fontSize = ssize;
454         for (i = 0; (a = document.getElementsByTagName ("span")[i]); i++) a.style.fontSize = ssize;
455         for (i = 0; (a = document.getElementsByTagName ("select")[i]); i++) a.style.fontSize = ssize;
456         for (i = 0; (a = document.getElementsByTagName ("a")[i]); i++) a.style.fontSize = size2;
457 }
458
459
460 function sortWordsIgnoreCase(a, b) {
461         a = a.toLowerCase();
462         b = b.toLowerCase();
463         if(a>b) return 1;
464         if(a<b) return -1;
465         return 0;
466 }
467
468
469 function getSelectedList(sel) {
470         if(!sel) return [];
471         var vals = [];
472         for( var i = 0; i != sel.options.length; i++ ) {
473                 if(sel.options[i].selected)
474                         vals.push(sel.options[i].value);
475         }
476         return vals;
477 }
478
479
480 function setEnterFunc(node, func) {
481         if(!(node && func)) return;
482         node.onkeydown = function(evt) {
483                 if( userPressedEnter(evt)) func();
484         }
485 }
486
487 function iterate( arr, callback ) {
488         for( var i = 0; i < arr.length; i++ ) 
489                 callback(arr[i]);
490 }
491
492
493
494
495 /* taken directly from the JSAN util.date library */
496 /* but changed from the util.date.interval_to_seconds invocation, 
497 because JSAN will assume the whole library is already loaded if 
498 it sees that, and the staff client uses both this file and the
499 JSAN library*/
500 function interval_to_seconds( $interval ) {
501
502         $interval = $interval.replace( /and/, ',' );
503         $interval = $interval.replace( /,/, ' ' );
504         
505         var $amount = 0;
506         var results = $interval.match( /\s*\+?\s*(\d+)\s*(\w{1})\w*\s*/g);  
507         for( var i = 0; i < results.length; i++ ) {
508                 if(!results[i]) continue;
509                 var result = results[i].match( /\s*\+?\s*(\d+)\s*(\w{1})\w*\s*/ );
510                 if (result[2] == 's') $amount += result[1] ;
511                 if (result[2] == 'm') $amount += 60 * result[1] ;
512                 if (result[2] == 'h') $amount += 60 * 60 * result[1] ;
513                 if (result[2] == 'd') $amount += 60 * 60 * 24 * result[1] ;
514                 if (result[2] == 'w') $amount += 60 * 60 * 24 * 7 * result[1] ;
515                 if (result[2] == 'M') $amount += ((60 * 60 * 24 * 365)/12) * result[1] ;
516                 if (result[2] == 'y') $amount += 60 * 60 * 24 * 365 * result[1] ;
517         }
518         return $amount;
519 }
520
521
522 function openWindow( data ) {
523         if( isXUL() ) {
524                 var data = window.escape(
525                         '<html><head><title></title></head><body>' + data + '</body></html>');
526
527                 xulG.window_open(
528                         'data:text/html,' + data,
529                         '', 
530                         'chrome,resizable,width=700,height=500'); 
531
532         } else {
533                 win = window.open('','', 'resizable,width=700,height=500'); 
534                 win.document.body.innerHTML = data;
535         }
536 }
537
538
539 /* alerts the innerhtml of the node with the given id */
540 function alertId(id) {
541         var node = $(id);
542         if(node) alert(node.innerHTML);
543 }
544
545 function confirmId(id) {
546         var node = $(id);
547         if(node) return confirm(node.innerHTML);
548 }
549
550
551 function goBack() { history.back(); }
552 function goForward() { history.forward(); }
553
554
555 function uniquify(arr) {
556         if(!arr) return [];
557         var newarr = [];
558         for( var i = 0; i < arr.length; i++ ) {
559                 var item = arr[i];
560                 if( ! grep( newarr, function(x) {return (x == item);}))
561                         newarr.push(item);
562         }
563         return newarr;
564 }
565
566 function contains(arr, item) {
567         for( var i = 0; i < arr.length; i++ ) 
568                 if( arr[i] == item ) return true;
569         return false;
570 }