New hold status for "Wrong Shelf"
[Evergreen.git] / Open-ILS / web / opac / skin / default / js / myopac.js
1
2 attachEvt("common", "run", myOPACInit );
3 //attachEvt("common", "loggedIn", myOPACInit );
4 attachEvt('common','locationUpdated', myopacReload );
5
6 dojo.requireLocalization("openils.opac", "opac");
7
8 var opac_strings = dojo.i18n.getLocalization("openils.opac", "opac");
9 var fleshedUser = null;
10 var fleshedContainers = {};
11 var holdCache = {};
12 var holdStatusCache = {};
13 var showHoldQueuePosition = false;
14 var allowPendingAddr = false;
15 var myopacEnableRefWorks = false;
16 var myopacRefWorksHost = 'http://www.refworks.com';
17
18 function clearNodes( node, keepArray ) {
19         if(!node) return;
20         for( var n in keepArray ) node.removeChild(keepArray[n]);
21         removeChildren(node);
22         for( var n in keepArray ) node.appendChild(keepArray[n]);
23 }
24
25 function myOPACInit() {
26
27     fieldmapper.IDL.load(['mous']);
28
29     var orgHiding = checkOrgHiding();
30     if (orgHiding) {
31         hideMe($('prefs_def_location_row'));
32         hideMe($('prefs_def_range_row'));
33     }
34
35         if(!(G.user && G.user.session)) {
36         initLogin();
37
38     } else {
39
40         allowPendingAddr = fetchOrgSettingDefault(G.user.home_ou(), 'opac.allow_pending_address');
41         if(allowPendingAddr)
42             unHideMe($('myopac_pending_addr_td'));
43             myOPACChangePage( "summary" );
44     }
45
46     $('myopac_holds_thaw_date_input').onkeyup = 
47         function(){holdsVerifyThawDateUI('myopac_holds_thaw_date_input'); }
48     $('myopac_holds_thaw_date_input').onchange = 
49         function(){holdsVerifyThawDateUI('myopac_holds_thaw_date_input'); }
50
51 }
52
53 function myopacReload() {
54         //swapCanvas($('myopac_reloading'));
55         var a = {};
56         a[PARAM_LOCATION] = getNewSearchLocation();
57         a[PARAM_DEPTH] = getNewSearchDepth();
58         hideMe($('canvas_main'));
59         goTo(buildOPACLink(a, true));
60 }
61
62
63 function myOPACChangePage( page ) {
64         showCanvas();
65
66         var s = $("myopac_summary_td");
67         var c = $("myopac_checked_td");
68         var f = $("myopac_fines_td");
69         var h = $("myopac_holds_td");
70         var p = $("myopac_prefs_td");
71         var b = $('myopac_bookbag_td');
72
73         var ss = $("myopac_summary_div");
74         var cc = $("myopac_checked_div");
75         var ff = $("myopac_fines_div");
76         var hh = $("myopac_holds_div");
77         var pp = $("myopac_prefs_div");
78         var bb = $('myopac_bookbag_div');
79
80         var cls = "myopac_link";
81         var acls = "myopac_link_active";
82
83         hideMe(ss);
84         hideMe(cc); hideMe(ff);
85         hideMe(hh); hideMe(pp);
86         hideMe(bb);
87
88         removeCSSClass(s, acls );
89         removeCSSClass(c, acls );
90         removeCSSClass(f, acls );
91         removeCSSClass(h, acls );
92         removeCSSClass(p, acls );
93         removeCSSClass(b, acls );
94
95         switch( page ) {
96
97                 case "summary": 
98                         unHideMe(ss);
99                         addCSSClass(s, acls );
100                         myOPACShowSummary();
101                         break;
102
103                 case "checked": 
104                         unHideMe(cc);
105                         addCSSClass(c, acls );
106                         myOPACShowChecked();
107                         break;
108
109                 case "holds": 
110                         unHideMe(hh);
111                         addCSSClass(h, acls );
112                         myOPACShowHolds();
113                         break;
114
115                 case "fines": 
116                         unHideMe(ff);
117                         addCSSClass(f, acls );
118                         myOPACShowFines();
119                         break;
120
121                 case "prefs": 
122                         unHideMe(pp);
123                         addCSSClass(p, acls );
124                         myOPACShowPrefs();
125                         break;
126
127                 case 'bookbag':
128                         unHideMe(bb);
129                         addCSSClass(b, acls);
130                         myOPACShowBookbags();
131                         break;
132         }
133 }
134
135 function myOPACShowChecked() {
136         if(checkedDrawn) return;
137         var req = new Request(FETCH_CHECKED_OUT_SUM, G.user.session, G.user.id());      
138         req.callback(myOPACDrawCheckedOutSlim);
139         req.send();
140
141         var nreq = new Request(FETCH_NON_CAT_CIRCS, G.user.session);
142         nreq.callback(myOPACDrawNonCatCircs);
143         nreq.send();
144 }
145
146
147 var checkedRowTemplate;
148 var circsCache = new Array();
149 var checkedDrawn = false;
150
151 function moClearCheckedTable() {
152         var tbody                       = $("myopac_checked_tbody");
153         var loading                     = $("myopac_checked_loading");
154         var none                                = $("myopac_checked_none");
155         clearNodes( tbody, [ loading, none ] );
156 }
157
158 var __can_renew_one = false;
159
160 function myOPACDrawCheckedOutSlim(r) {
161
162         var checked                     = r.getResultObject();
163         var tbody                       = $("myopac_checked_tbody");
164         var loading                     = $("myopac_checked_loading");
165         var none                                = $("myopac_checked_none");
166
167    __can_renew_one = false;
168
169         if(checkedDrawn) return;
170         checkedDrawn = true;
171         if(!checkedRowTemplate) 
172                 checkedRowTemplate = tbody.removeChild($("myopac_checked_row"));
173
174    moClearCheckedTable();
175
176         hideMe(loading); /* remove all children and start over */
177         if(!(checked && (checked.out || checked.overdue))) {
178                 unHideMe(none);
179                 return;
180         }
181
182     var totalAsync = checked.overdue.length + checked.out.length;
183     var fetchedCircs = [];
184     var collectCircs = function(r) {
185         var circ = r.getResultObject();
186         circ._od = r.od;
187         fetchedCircs.push(circ);
188         if(fetchedCircs.length < totalAsync) return;
189
190         // sort by due date, oldest to newest
191         fetchedCircs = fetchedCircs.sort(
192             function(a, b) {
193                 if(a.due_date() > b.due_date()) return 1;
194                 return -1;
195             }
196         )
197
198         dojo.forEach(fetchedCircs, 
199             function(circ) { 
200                 myOPACDrawCheckedItem(circ, tbody);
201             }
202         );
203     }
204
205         for( var i = 0; i < checked.overdue.length; i++ ) {
206                 var req = new Request(FETCH_CIRC_BY_ID, G.user.session, checked.overdue[i]);
207                 //req.request.tbody = tbody;
208                 req.request.od = true;
209                 req.callback(collectCircs);
210                 req.send();
211         }
212
213
214         for( var i = 0; i < checked.out.length; i++ ) {
215                 var req = new Request(FETCH_CIRC_BY_ID, G.user.session, checked.out[i]);
216                 //req.request.tbody = tbody;
217                 req.callback(collectCircs);
218                 req.send();
219         }
220
221    appendClear($('mo_items_out_count'), 
222       text(new String( parseInt(checked.overdue.length) + parseInt(checked.out.length) )) );
223
224    if( checked.overdue.length > 0 ) {
225       addCSSClass($('mo_items_overdue_count'), 'overdue');
226       appendClear($('mo_items_overdue_count'),
227          text(new String( parseInt(checked.overdue.length) )) );
228    }
229
230 }
231
232
233 //function myOPACDrawCheckedItem(r) {
234 function myOPACDrawCheckedItem(circ, tbody) {
235
236         //var circ = r.getResultObject();
237         //var tbody = r.tbody;
238         var row = checkedRowTemplate.cloneNode(true);
239         row.id = 'myopac_checked_row_ ' + circ.id();
240     row.setAttribute('circid', circ.id());
241
242         var due = _trimTime(circ.due_date());
243
244         var dlink = $n( row, "myopac_checked_due" );
245         var rlink = $n( row, "myopac_checked_renewals" );
246         //var rnlink = $n( row, "myopac_checked_renew_link" );
247
248         //if( r.od ) due = elem('b', {style:'color:red;font-size:110%'},due);
249         if( circ._od ) {
250       due = elem('b', null, due);
251       addCSSClass(due, 'overdue');
252    } else {
253       due = text(due);
254    }
255
256         dlink.appendChild(due);
257         rlink.appendChild(text(circ.renewal_remaining()));
258         unHideMe(row);
259         //rnlink.setAttribute('href', 'javascript:myOPACRenewCirc("'+circ.id()+'");');
260         circsCache.push(circ);
261
262    if( circ.renewal_remaining() < 1 ) {
263       $n(row, 'selectme').disabled = true;
264       if(!__can_renew_one)
265          $('mo_renew_button').disabled = true;
266    } else {
267       __can_renew_one = true;
268       $('mo_renew_button').disabled = false;
269       $n(row, 'selectme').disabled = false;
270    }
271
272         tbody.appendChild(row);
273
274         var req = new Request(FETCH_MODS_FROM_COPY, circ.target_copy() );
275         req.request.alertEvent = false;
276         req.request.circ = circ.id();
277         req.request.copy = circ.target_copy();
278         req.callback(myOPACDrawCheckedTitle);
279         req.send();
280 }
281
282 var __circ_titles = {};
283
284 function myOPACDrawCheckedTitle(r) {
285         var record = r.getResultObject();
286         var circid = r.circ;
287
288         /* Draw pre-cataloged items */
289         if(!record || checkILSEvent(record) || !(record.title() || record.author())) {
290                 var req = new Request( FETCH_COPY, r.copy );
291                 req.request.circ = circid;
292                 req.callback(myOPACDrawPreCatalogedItem);
293                 req.send();
294                 return;
295         }
296
297         var row = $('myopac_checked_row_ ' + circid);
298         var tlink = $n( row, "myopac_checked_title_link" );
299         var alink = $n( row, "myopac_checked_author_link" );
300
301         buildTitleDetailLink(record, tlink);
302         buildSearchLink(STYPE_AUTHOR, record.author(), alink);
303    __circ_titles[circid] = record.title();
304 }
305
306 function myOPACDrawPreCatalogedItem(r) {
307         var copy = r.getResultObject();
308         var circid = r.circ;
309
310         var row = $('myopac_checked_row_ ' + circid);
311         var tlink = $n( row, "myopac_checked_title_link" );
312         var alink = $n( row, "myopac_checked_author_link" );
313
314         tlink.parentNode.appendChild(text(copy.dummy_title()));
315         alink.parentNode.appendChild(text(copy.dummy_author()));
316    __circ_titles[circid] = copy.dummy_title();
317 }
318
319
320 /*
321 function myOPACRenewCirc(circid) {
322
323         var circ;
324         for( var i = 0; i != circsCache.length; i++ ) 
325                 if(circsCache[i].id() == circid)
326                         circ = circsCache[i];
327
328         if(!confirm($('myopac_renew_confirm').innerHTML)) return;
329
330         var req = new Request(RENEW_CIRC, G.user.session, 
331                 { patron : G.user.id(), copyid : circ.target_copy(), opac_renewal : 1 } );
332         req.request.alertEvent = false;
333         req.send(true);
334         var res = req.result();
335
336         if(checkILSEvent(res) || checkILSEvent(res[0])) {
337                 alertId('myopac_renew_fail');
338                 return;
339         }
340
341         alert($('myopac_renew_success').innerHTML);     
342         checkedDrawn = false;
343         myOPACShowChecked();
344 }
345 */
346
347
348
349 function myOPACShowHolds() {
350         var req = new Request(FETCH_HOLDS, G.user.session, G.user.id());        
351         req.callback(myOPACDrawHolds);
352         req.send();
353     $('myopac_holds_actions_none').selected = true;
354 }
355
356 var holdsTemplateRowOrig;
357 var holdsTemplateRow;
358 var myopacForceHoldsRedraw = false;
359 function myOPACDrawHolds(r) {
360
361         var tbody = $("myopac_holds_tbody");
362         if(holdsTemplateRow && !myopacForceHoldsRedraw) return;
363     myopacForceHoldsRedraw = false;
364
365         if(holdsTemplateRowOrig) {
366                 holdsTemplateRow = holdsTemplateRowOrig;
367                 removeChildren(tbody);
368         } else {
369                 holdsTemplateRow = tbody.removeChild($("myopac_holds_row"));
370                 holdsTemplateRowOrig = holdsTemplateRow;
371         }
372
373         hideMe($('myopac_holds_loading'));
374
375         var holds = r.getResultObject();
376
377         if(!holds || holds.length < 1) unHideMe($('myopac_holds_none'));
378         for( var i = 0; i != holds.length; i++ ) {
379
380                 var h = holds[i];
381                 holdCache[h.id()] = h;
382
383                 var row = holdsTemplateRow.cloneNode(true);
384                 row.id = "myopac_holds_row_" + h.id();
385
386                 var form = $n(row, "myopac_holds_formats");
387                 form.id = "myopac_holds_form_" + h.id();
388
389                 var orglink = $n(row, "myopac_holds_location");
390                 orglink.appendChild(text(findOrgUnit(h.pickup_lib()).name()));
391
392                 tbody.appendChild(row);
393
394                 $n(row,'myopac_holds_edit_link').setAttribute(
395                         'href','javascript:myOPACEditHold("'+ h.id()+'");'); 
396
397         if(isTrue(h.frozen())) {
398             hideMe($n(row, 'myopac_hold_unfrozen_true'))
399             unHideMe($n(row, 'myopac_hold_unfrozen_false'))
400             if(h.thaw_date()) {
401                 var d = dojo.date.stamp.fromISOString(h.thaw_date());
402                 $n(row, 'myopac_holds_frozen_until').appendChild(text(dojo.date.locale.format(d, {selector: 'date', fullYear: true})));
403             }
404         } else {
405             unHideMe($n(row, 'myopac_hold_unfrozen_true'))
406             hideMe($n(row, 'myopac_hold_unfrozen_false'))
407         }
408
409         $n(row, 'myopac_holds_selected_chkbx').checked = false;
410
411         var exp_date;
412         if(h.expire_time()) {
413             exp_date = dojo.date.stamp.fromISOString(h.expire_time().replace(/(T\d\d:\d\d:\d\d)([+-]\d\d)(\d)/, "$1$2:$3"));
414             $n(row, 'myopac_hold_expire_time').appendChild(
415                 text(dojo.date.locale.format(exp_date, {selector:'date'})));
416         }
417
418                 unHideMe(row);
419
420         var interval = fetchOrgSettingDefault(G.user.home_ou(), 'circ.hold_expire_alert_interval');
421         if(interval && exp_date) {
422             secs = interval_to_seconds(interval) * 1000;
423             var diff = exp_date.getTime() - new Date().getTime();
424             if(diff < secs)
425                 addCSSClass($n(row, 'myopac_hold_expire_time'), 'hold_expire_warning');
426         }
427
428         myOPACDrawHoldTitle(h);
429         myOPACDrawHoldStatus(h);
430     }
431 }
432
433 function myOPACEditHold(holdid) {
434         var hold = holdCache[holdid];
435
436         holdsDrawEditor( 
437                 { 
438                         editHold : hold,
439                         onComplete : function(){ 
440                                 holdsTemplateRow = null;
441                                 myOPACShowHolds(); 
442                         }
443                 }
444         );
445 }
446
447
448 function myOPACDrawHoldStatus(hold) {
449         var req = new Request(FETCH_HOLD_STATUS, G.user.session, hold.id() );
450         req.callback(myOShowHoldStatus);
451         req.request.hold = hold;
452         req.send();
453 }
454
455 var myopacShowHoldEstimate = false;
456 function myOShowHoldStatus(r) {
457
458         var hold = r.hold;
459         var qstats = r.getResultObject();
460     holdStatusCache[hold.id()] = qstats;
461
462         var row = $("myopac_holds_row_" + r.hold.id());
463
464     if(qstats.estimated_wait || myopacShowHoldEstimate) {
465         myopacShowHoldEstimate = true;
466         if(qstats.estimated_wait) {
467             // wait is currently returned in seconds, but displayed in days
468             var wait = Math.ceil(qstats.estimated_wait / 86400);
469             $n(row, 'myopac_holds_estimated_wait').appendChild(text(wait));
470         }
471         unHideMe($('myopac_holds_estimated_wait_column'));
472         unHideMe($n(row, 'myopac_holds_estimated_wait'));
473     } 
474
475         if( qstats.status == 4 ) {
476                 unHideMe($n(row, 'hold_status_available'));
477                 hideMe($n(row, 'myopac_holds_cancel_link'));
478         }
479
480     if( qstats.status == 7 ) {
481         unHideMe($n(row, 'hold_status_suspended'));
482     } else if (showHoldQueuePosition) {
483         var node = $n(row, 'hold_qstats');
484         if (qstats.potential_copies == 1) {
485             node.appendChild(text(dojo.string.substitute(opac_strings.HOLD_STATUS_SINGULAR, [qstats.queue_position, qstats.total_holds, qstats.potential_copies])));
486         } else {
487             node.appendChild(text(dojo.string.substitute(opac_strings.HOLD_STATUS_PLURAL, [qstats.queue_position, qstats.total_holds, qstats.potential_copies])));
488         }
489         unHideMe(node);
490
491     } else {
492             if( qstats.status < 3 )
493                     unHideMe($n(row, 'hold_status_waiting'));
494     
495             if( qstats.status == 3 || qstats.status == 8 )
496                     unHideMe($n(row, 'hold_status_transit'));
497     }
498 }
499
500
501 function myOPACDrawHoldTitle(hold) {
502         var method;
503
504         if( hold.hold_type() == 'T' || hold.hold_type() == 'M') {
505                 if(hold.hold_type() == "M") method = FETCH_MRMODS;
506                 if(hold.hold_type() == "T") method = FETCH_RMODS;
507                 var req = new Request(method, hold.target());
508                 req.callback(myOPACFleshHoldTitle);
509                 req.request.hold = hold;
510                 req.request.alertEvent = false;
511                 req.send();
512
513         } else {
514                 holdFetchObjects(hold, 
515                         function(a) { _myOPACFleshHoldTitle(hold, a);});
516         }
517 }
518
519 function myOPACFleshHoldTitle(r) {
520         var rec = r.getResultObject();
521         _myOPACFleshHoldTitle(r.hold, {recordObject: rec});
522 }
523
524 function _myOPACFleshHoldTitle(hold, holdObjects) {
525
526         var record  = holdObjects.recordObject;
527         var volume      = holdObjects.volumeObject;
528         var copy        = holdObjects.copyObject;
529
530         var row = $("myopac_holds_row_" + hold.id());
531         var title_link = $n(row, "myopac_holds_title_link");
532         var author_link = $n(row, "myopac_holds_author_link");
533
534         if(!record || checkILSEvent(record) ) {
535                 addCSSClass(row, 'invalid_hold');
536                 $n(row, 'myopac_holds_edit_link').setAttribute('href', 'javascript:void(0);');
537                 $n(row, 'myopac_holds_edit_link').onclick = function(){alertId('invalid_hold');};
538                 return;
539         }
540
541         buildTitleDetailLink(record, title_link);
542         buildSearchLink(STYPE_AUTHOR, record.author(), author_link);
543
544     if(hold.hold_type() == 'P') {
545         unHideMe($n(row, 'vol_copy'));
546         $n(row, 'part').appendChild(text(holdObjects.partObject.label));
547     }
548
549         if( volume ) {
550                 $n(row, 'volume').appendChild(text(volume.label()));
551                 unHideMe($n(row, 'vol_copy'));
552                 if(copy) $n(row, 'copy').appendChild(text(copy.barcode()));
553         }
554
555         var form = $("myopac_holds_form_" + hold.id());
556
557         if(form) {
558                 var mods_formats = record.types_of_resource();
559
560                 if( hold.hold_type() == 'M' ) {
561                         var data = holdsParseMRFormats(hold.holdable_formats());
562                         mods_formats = data.mods_formats;
563                 }
564
565                 for( var i = 0; i < mods_formats.length; i++ ) {
566                         var img = elem("img");
567                         setResourcePic(img, mods_formats[i]);
568                         form.appendChild(img);
569                 }
570         }
571 }
572
573 var finesShown = false;
574 function myOPACShowFines() {
575         if(finesShown) return; finesShown = true;
576         var req = new Request(FETCH_FINES_SUMMARY, G.user.session, G.user.id() );
577         req.callback(_myOPACShowFines);
578         req.send();
579 }
580
581 function _myOPACShowFines(r) {
582         hideMe($('myopac_fines_summary_loading'));
583         unHideMe($('myopac_fines_summary_row'));
584
585         var summary = r.getResultObject();
586         var total       = "0.00"; /* localization? */
587         var paid                = "0.00";
588         var balance = "0.00";
589         if( instanceOf(summary,mous) ) {
590
591                 total           = _finesFormatNumber(summary.total_owed());
592                 paid            = _finesFormatNumber(summary.total_paid());
593                 balance = _finesFormatNumber(summary.balance_owed());
594
595                 var req = new Request(FETCH_TRANSACTIONS, G.user.session, G.user.id() );
596                 req.callback(myOPACShowTransactions);
597                 req.send();
598         }
599
600         $('myopac_fines_summary_total').appendChild(text(total));
601         $('myopac_fines_summary_paid').appendChild(text(paid));
602         $('myopac_fines_summary_balance').appendChild(text(balance));
603 }
604
605 function _finesFormatNumber(num) {
606         if(isNull(num)) num = 0;
607         num = num + "";
608         if(num.length < 2 || !num.match(/\./)) num += ".00";
609         if(num.match(/\./) && num.charAt(num.length-2) == '.') num += "0";
610         return num;
611 }          
612
613 //function _trimTime(time) { if(!time) return ""; return time.replace(/\ .*/,""); }
614 function _trimTime(time) { 
615         if(!time) return ""; 
616     time = time.replace(/(T\d\d:\d\d:\d\d)([+-]\d\d)(\d)/, "$1$2:$3");
617     var d = dojo.date.stamp.fromISOString(time);
618     if(!d) return ""; /* date parse failed */
619     return dojo.date.locale.format(d, {"formatLength": "medium"});
620 }
621
622 function _trimSeconds(time) { 
623     if(!time) return ""; 
624     var d = dojo.date.stamp.fromISOString(time.replace(/(T\d\d:\d\d:\d\d)([+-]\d\d)(\d)/, "$1$2:$3"));
625     if(!d) return ""; /* date parse failed */
626     return dojo.date.locale.format(d, { "timePattern" : "h:ma", "formatLength" : "medium" });
627 }
628
629 function myOPACShowTransactions(r) {
630
631         if(myopacGenericTransTemplate || myopacCircTransTemplate) return;
632
633         var transactions = r.getResultObject();
634
635         for( var idx in transactions ) {
636
637                 var trans       = transactions[idx].transaction;
638                 var record      = transactions[idx].record;
639                 var circ                = transactions[idx].circ;
640
641                 if(trans.xact_type() == 'circulation') 
642                         myOPACShowCircTransaction(trans, record, circ);
643
644                 else if(trans.xact_type() == 'grocery' ) 
645                         myopacShowGenericTransaction( trans );
646
647 /*      XXX need to copy circulation output function here
648                 else if(trans.xact_type() == 'reservation' ) 
649                         myopacShowReservationTransaction( trans );
650 */
651
652         }
653 }
654
655 var myopacGenericTransTemplate;
656 function myopacShowGenericTransaction( trans ) {
657         var tbody = $('myopac_trans_tbody');
658
659         if(!myopacGenericTransTemplate) {
660                 myopacGenericTransTemplate = 
661                         tbody.removeChild($('myopac_trans_row'));
662                 removeChildren(tbody);
663         }
664
665         var row = myopacGenericTransTemplate.cloneNode(true);
666
667         $n(row,'myopac_trans_start').appendChild(
668                         text(_trimSeconds(trans.xact_start())));
669
670         $n(row,'myopac_trans_last_payment').appendChild(
671                         text(_trimSeconds(trans.last_payment_ts())));
672
673         $n(row,'myopac_trans_init_amount').appendChild(
674                         text(_finesFormatNumber(trans.total_owed())));
675
676         $n(row,'myopac_trans_total_paid').appendChild(
677                         text(_finesFormatNumber(trans.total_paid())));
678
679         $n(row,'myopac_trans_balance').appendChild(
680                         text(_finesFormatNumber(trans.balance_owed())));
681
682         var req = new Request(FETCH_MONEY_BILLING, G.user.session, trans.id());
683         req.send(true);
684         var bills = req.result();
685         if(bills && bills[0])
686                 $n(row,'myopac_trans_bill_type').appendChild(
687                                 text(bills[0].billing_type()));
688
689         tbody.appendChild(row);
690         unHideMe($('myopac_trans_div'));
691 }
692
693
694
695 /* draws a circulation transaction summary */
696 var myopacCircTransTemplate;
697 function myOPACShowCircTransaction(trans, record, circ) {
698         var tbody = $('myopac_circ_trans_tbody');
699
700         if(!myopacCircTransTemplate) {
701                 myopacCircTransTemplate = tbody.removeChild($('myopac_circ_trans_row'));
702                 removeChildren(tbody);
703         }
704
705         var row = myopacCircTransTemplate.cloneNode(true);
706
707         if(record) {
708                 buildTitleDetailLink(record, $n(row,'myopac_circ_trans_title'));
709
710                 $n(row,'myopac_circ_trans_author').appendChild(text(
711                         normalize(truncate(record.author(), 65))));
712
713         } else {
714
715                 var req = new Request( FETCH_COPY, circ.target_copy() );
716                 req.alertEvents = false;
717                 req.send(true);
718                 var copy = req.result();
719                 if( copy ) {
720                         $n(row,'myopac_circ_trans_title').appendChild(text(copy.dummy_title()));
721                         $n(row,'myopac_circ_trans_author').appendChild(text(copy.dummy_author()));
722                 }
723         }
724
725
726         $n(row,'myopac_circ_trans_start').
727                 appendChild(text(_trimTime(trans.xact_start())));
728         var due = _trimTime(circ.due_date());
729         var checkin = _trimTime(circ.checkin_time());
730
731         $n(row,'myopac_circ_trans_due').appendChild(text(due))
732         if(checkin)
733                 appendClear($n(row,'myopac_circ_trans_finished'), text(checkin));
734         if(circ.stop_fines() == 'LOST')
735                 appendClear($n(row,'myopac_circ_trans_finished'), text(circ.stop_fines()));
736         if(circ.stop_fines() == 'CLAIMSRETURNED')
737                 appendClear($n(row,'myopac_circ_trans_finished'), text(""));
738
739
740         $n(row,'myopac_circ_trans_balance').
741                 appendChild(text(_finesFormatNumber(trans.balance_owed())));
742
743         tbody.appendChild(row);
744         unHideMe($('myopac_circ_trans_div'));
745 }
746
747
748 function myOPACSavePrefs() {
749         G.user.prefs[PREF_HITS_PER] = getSelectorVal($('prefs_hits_per'));
750         G.user.prefs[PREF_DEF_FONT] = getSelectorVal($('prefs_def_font'));
751         G.user.prefs[PREF_HOLD_NOTIFY] = getSelectorVal($('prefs_hold_notify'));
752         G.user.prefs[PREF_DEF_DEPTH] = getSelectorVal($('prefs_def_range'));
753
754         if( $('myopac_pref_home_lib').checked == true )
755                 G.user.prefs[PREF_DEF_LOCATION] = null;
756         else
757                 G.user.prefs[PREF_DEF_LOCATION] = getSelectorVal($('prefs_def_location'));
758
759         if(commitUserPrefs())
760                 alert($('prefs_update_success').innerHTML);
761         else alert($('prefs_update_failure').innerHTML);
762 }
763
764
765 function myOPACShowDefFont() {
766         var font;
767         if(G.user.prefs[PREF_DEF_FONT])
768                 font = G.user.prefs[PREF_DEF_FONT];
769         else font = "regular";
770         setSelector($('prefs_def_font'), font);
771 }
772
773 function myOPACShowHoldNotify() {
774         var pref = G.user.prefs[PREF_HOLD_NOTIFY];
775
776         if(pref) {
777                 if(pref.match(/email/i) && pref.match(/phone/i)) {
778                         setSelector($('prefs_hold_notify'), 'phone:email');
779                 } else if( pref.match(/email/i) ) {
780                         setSelector($('prefs_hold_notify'), 'email');
781                 } else if( pref.match(/phone/i) ) {
782                         setSelector($('prefs_hold_notify'), 'phone');
783                 }
784
785         } else {
786                 setSelector($('prefs_hold_notify'), 'phone:email');
787         }
788 }
789
790 function myOPACShowPrefs() {
791         grabUserPrefs();
792         myOPACShowHitsPer();
793         myOPACShowDefFont();
794         myOPACShowHoldNotify();
795         myOPACShowDefLocation();
796         hideMe($('myopac_prefs_loading'));
797 }
798
799 var defSearchLocationDrawn = false;
800 var defDepthIndex = 0;
801 function myOPACShowDefLocation() {
802
803         var selector = $('prefs_def_location');
804         var rsel = $('prefs_def_range');
805
806         if(!defSearchLocationDrawn) {
807
808                 defSearchLocationDrawn = true;
809
810                 var org = G.user.prefs[PREF_DEF_LOCATION];
811
812                 if(!org) {
813                         $('myopac_pref_home_lib').checked = true;
814                         $('prefs_def_location').disabled = true;
815                         org = G.user.home_ou();
816                 }
817
818                 buildOrgSel(selector, globalOrgTree, 0);
819
820                 globalOrgTypes = globalOrgTypes.sort(
821                         function(a, b) {
822                                 if( a.depth() < b.depth() ) return -1;
823                                 return 1;
824                         }
825                 );
826
827                 iterate(globalOrgTypes,
828                         function(t) {
829                                 if( t.depth() <= findOrgDepth(org) ) {
830                                         setSelectorVal(rsel, defDepthIndex++, t.opac_label(), t.depth());
831                                         if( t.depth() == findOrgDepth(org) ) 
832                                                 setSelector(rsel, t.depth());
833                                 }
834                         }
835                 );
836         }
837
838         setSelector(selector, org);
839 }
840
841 function myOPACShowHitsPer() {
842         var hits = 10;
843         if(G.user.prefs[PREF_HITS_PER])
844                 hits = G.user.prefs[PREF_HITS_PER];
845         var hitsSel = $('prefs_hits_per');
846         setSelector(hitsSel, hits);
847 }
848
849 var userShown = false;
850 function myOPACShowSummary() {
851         if(userShown) return; userShown = true;
852         var req = new Request(FETCH_FLESHED_USER,G.user.session, G.user.id());
853         req.callback(_myOPACSummaryShowUer);
854         req.send();
855 }
856
857 var addrRowTemplate;
858 var notesTemplate;
859 function _myOPACSummaryShowUer(r) {
860
861         var user = r.getResultObject();
862         fleshedUser = user;
863         if(!user) return;
864
865     var expireDate = dojo.date.stamp.fromISOString(user.expire_date());
866     if( expireDate < new Date() ) {
867         appendClear($('myopac.expired.date'), dojo.date.locale.format(expireDate, { "formatLength" : "medium", "selector" : "date" }));
868         unHideMe($('myopac.expired.alert'));
869     }
870
871         var iv1 = user.ident_value()+'';
872     if (iv1.length > 4 && iv1.match(/\d{4}/)) iv1 = iv1.substring(0,4) + '***********';
873
874
875         appendClear($('myopac_summary_prefix'),text(user.prefix()));
876         appendClear($('myopac_summary_first'),text(user.first_given_name()));
877         appendClear($('myopac_summary_middle'),text(user.second_given_name()));
878         appendClear($('myopac_summary_dayphone'),text(user.day_phone()));
879         appendClear($('myopac_summary_eveningphone'),text(user.evening_phone()));
880         appendClear($('myopac_summary_otherphone'),text(user.other_phone()));
881         appendClear($('myopac_summary_last'),text(user.family_name()));
882         appendClear($('myopac_summary_suffix'),text(user.suffix()));
883         appendClear($('myopac_summary_username'),text(user.usrname()));
884         appendClear($('myopac_summary_email'),text(user.email()));
885         appendClear($('myopac_summary_barcode'),text(user.card().barcode()));
886         appendClear($('myopac_summary_ident1'),text(iv1));
887         appendClear($('myopac_summary_homelib'),text(findOrgUnit(user.home_ou()).name()));
888         appendClear($('myopac_summary_create_date'),text(_trimTime(user.create_date())));
889
890         var req = new Request( 
891                 FETCH_USER_NOTES, G.user.session, {pub:1, patronid:G.user.id()});
892         req.callback(myopacDrawNotes);
893         req.send();
894
895     r = fetchOrgSettingDefault(G.user.home_ou(), 'opac.lock_usernames');
896     if(r) {
897         // No changing username - Policy Lock
898         hideMe($('myopac_summary_username_change'));
899     } else {
900         r = fetchOrgSettingDefault(G.user.home_ou(), 'opac.unlimit_usernames');
901         if(!r) {
902             r = fetchOrgSettingDefault(G.user.home_ou(), 'opac.barcode_regex');
903             if(r) REGEX_BARCODE = new RegExp(r);
904
905             if(!user.usrname().match(REGEX_BARCODE)) {
906                 // No changing username - You already have one!
907                 hideMe($('myopac_summary_username_change'));
908             }
909         }
910     }
911
912         var tbody = $('myopac_addr_tbody');
913         var template;
914
915         if(addrRowTemplate) { 
916                 template = addrRowTemplate;
917         } else {
918                 template = tbody.removeChild($('myopac_addr_row'));
919                 addrRowTemplate = template;
920         }
921         removeChildren(tbody);
922
923     var addrs = user.addresses();
924         for( var a in addrs ) {
925         var addr = addrs[a];
926         if(!allowPendingAddr && isTrue(addr.pending()))
927             continue;
928         if(addr.replaces() != null) continue;
929                 var row = template.cloneNode(true);
930                 myOPACDrawAddr(row, addr, addrs);
931                 tbody.appendChild(row);
932         }
933 }
934
935
936 function myopacDrawNotes(r) {
937         var notes = r.getResultObject();
938         var tbody = $('myopac.notes.tbody');
939         if(!notesTemplate)
940                 notesTemplate = tbody.removeChild($('myopac.notes.tr'));
941         removeChildren(tbody);
942
943         iterate(notes, 
944                 function(note) {
945                         unHideMe($('myopac.notes.div'));
946                         var row = notesTemplate.cloneNode(true);
947                         $n(row, 'title').appendChild(text(note.title()));
948                         $n(row, 'value').appendChild(text(note.value()));
949                         tbody.appendChild(row);
950                 }
951         );
952 }
953
954
955
956 function myOPACDrawAddr(row, addr, addrs) {
957     appendClear($n(row, 'myopac_addr_type'),text(addr.address_type()));
958     appendClear($n(row, 'myopac_addr_street'),text(addr.street1()));
959     appendClear($n(row, 'myopac_addr_street2'),text(addr.street2()));
960     appendClear($n(row, 'myopac_addr_city'),text(addr.city()));
961     appendClear($n(row, 'myopac_addr_county'),text(addr.county()));
962     appendClear($n(row, 'myopac_addr_state'),text(addr.state()));
963     appendClear($n(row, 'myopac_addr_country'),text(addr.country()));
964     appendClear($n(row, 'myopac_addr_zip'),text(addr.post_code()));
965
966     if(!isTrue(addr.valid()))
967         unHideMe($n(row, 'myopac_invalid_addr_row'));
968
969     if(!allowPendingAddr) return;
970
971     $n(row, 'myopac_addr_edit_link').onclick = function(){myopacEditAddress(addr)};
972     unHideMe($n(row, 'myopac_addr_edit_td'));
973
974     /* if we have a replacement address, plop it into the table next to this addr */
975     var repl = grep(addrs,
976         function(a) { 
977             return a.replaces() == addr.id(); 
978         } 
979     );
980
981     $n(row, 'myopac_pending_addr_td').id = 'myopac_pending_addr_td_' + addr.id();
982
983     if(repl) {
984         hideMe($n(row, 'myopac_addr_edit_td')); // hide the edit link
985         repl = repl[0];
986         myopacSetAddrInputs(row, repl);
987     }
988 }
989
990 function myopacEditAddress(addr) {
991     var td = $('myopac_pending_addr_td_' + addr.id());
992     var row = td.parentNode;
993     myopacSetAddrInputs(row, addr);
994 }
995
996 function myopacSetAddrInputs(row, addr, prefix) {
997     unHideMe($n(row, 'myopac_pending_addr_td'));
998     $n(row, 'myopac_pending_addr_type').value = addr.address_type();
999     $n(row, 'myopac_pending_addr_street').value = addr.street1();
1000     $n(row, 'myopac_pending_addr_street2').value = addr.street2();
1001     $n(row, 'myopac_pending_addr_city').value = addr.city();
1002     $n(row, 'myopac_pending_addr_county').value = addr.county();
1003     $n(row, 'myopac_pending_addr_state').value = addr.state();
1004     $n(row, 'myopac_pending_addr_country').value = addr.country();
1005     $n(row, 'myopac_pending_addr_zip').value = addr.post_code();
1006     $n(row, 'myopac_pending_addr_edit_link').onclick = function(){myopacSaveAddress(row, addr)};
1007     $n(row, 'myopac_pending_addr_del_link').onclick = function(){myopacSaveAddress(row, addr, true)};
1008 }
1009
1010 // if no pending addr exists, this is called with the original address
1011 function myopacSaveAddress(row, addr, deleteMe) {
1012
1013     if(addr.replaces() == null) {
1014         // we are editing a non-pending address.  create a pending address to manage that
1015         var repl = new aua();
1016         repl.usr(addr.usr());
1017         repl.address_type(addr.address_type());
1018         repl.within_city_limits(addr.within_city_limits());
1019         repl.replaces(addr.id());
1020         repl.pending('t');
1021         repl.isnew(true);
1022         repl.id(null);
1023         addr = repl;
1024     }
1025
1026     if(deleteMe) {
1027         if(addr.id() == null) {
1028             hideMe($n(row, 'myopac_pending_addr_td'));
1029             return;
1030         }
1031         addr.isdeleted(true);
1032     } else {
1033         addr.address_type($n(row, 'myopac_pending_addr_type').value);
1034         addr.street1($n(row, 'myopac_pending_addr_street').value);
1035         addr.street2($n(row, 'myopac_pending_addr_street2').value);
1036         addr.city($n(row, 'myopac_pending_addr_city').value);
1037         addr.county($n(row, 'myopac_pending_addr_county').value);
1038         addr.state($n(row, 'myopac_pending_addr_state').value);
1039         addr.country($n(row, 'myopac_pending_addr_country').value);
1040         addr.post_code($n(row, 'myopac_pending_addr_zip').value);
1041     }
1042
1043         var req = new Request(
1044         'open-ils.actor:open-ils.actor.user.address.pending.cud', 
1045         G.user.session, addr);
1046
1047     req.callback(
1048         function(r) {
1049             var resp = r.getResultObject(); 
1050
1051             if(addr.isnew()) {
1052                 // new, add to list of addrs
1053                 addr.id(resp);
1054                 fleshedUser.addresses().push(addr);
1055
1056             } else {
1057                 // deleted, remove from list of addrs
1058                 if(addr.isdeleted()) {
1059                     hideMe($n(row, 'myopac_pending_addr_td'));
1060                     var addrs = [];
1061                     for(var i in fleshedUser.addresses()) {
1062                         var a = fleshedUser.addresses()[i];
1063                         if(a.id() != addr.id())
1064                             addrs.push(a);
1065                     }
1066                     fleshedUser.addresses(addrs);
1067                 }
1068             }
1069            alertId('myopac_addr_changes_saved');
1070         }
1071     );
1072     req.send();
1073 };
1074
1075
1076 function myOPACUpdateUsername() {
1077         var username = $('myopac_new_username').value;
1078         var curpassword = $('myopac_username_current_password').value;
1079         if(username == null || username == "") {
1080                 alert($('myopac_username_error').innerHTML);
1081                 return;
1082         }
1083
1084         if( username.match(/.*\s.*/) ) {
1085                 alert($('myopac_invalid_username').innerHTML);
1086                 return;
1087         }
1088
1089     r = fetchOrgSettingDefault(G.user.home_ou(), 'opac.barcode_regex');
1090     if(r) REGEX_BARCODE = new RegExp(r);
1091
1092     if(username.match(REGEX_BARCODE)) {
1093         alert($('myopac_invalid_username').innerHTML);
1094         return;
1095     }
1096
1097     r = fetchOrgSettingDefault(G.user.home_ou(), 'opac.username_regex');
1098     if(r) {
1099         if(!username.match(new RegExp(r))) {
1100             alert($('myopac_invalid_username').innerHTML);
1101             return;
1102         }
1103     }
1104
1105         /* first see if the requested username is taken */
1106         var req = new Request(CHECK_USERNAME, G.user.session, username);
1107         req.send(true);
1108         var res = req.result();
1109         /* If the username does not already exist, res will be null;
1110          * we can move on to updating the username.
1111          * 
1112          * If the username does exist, then res will be the user ID.
1113          * G.user.id() gives us the currently authenticated user ID.
1114          * If res == G.user.id(), we try to update the username anyways.
1115          */
1116         if( res !== null && res != G.user.id() ) {
1117                 alertId('myopac_username_dup');
1118                 return;
1119         }
1120
1121         var req = new Request(UPDATE_USERNAME, G.user.session, username, curpassword );
1122         req.send(true);
1123         if(req.result()) {
1124
1125                 var evt;
1126                 var res = req.result();
1127                 if(evt = checkILSEvent(res)) {
1128                         alertILSEvent(res);
1129                         return;
1130                 }
1131
1132                 G.user.usrname(username);
1133                 hideMe($('myopac_update_username_row'));
1134                 userShown = false;
1135                 alertId('myopac_username_success');
1136                 myOPACShowSummary();
1137                 return;
1138         }
1139
1140         alert($('myopac_username_failure').innerHTML);
1141 }
1142
1143 function myOPACUpdateEmail() {
1144         var email = $('myopac_new_email').value;
1145         var curpassword = $('myopac_email_current_password').value;
1146         if(email == null || email == "") {
1147                 alert($('myopac_email_error').innerHTML);
1148                 return;
1149         }
1150
1151         var req = new Request(UPDATE_EMAIL, G.user.session, email, curpassword );
1152         req.send(true);
1153         if(req.result()) {
1154                 G.user.email(email);
1155                 hideMe($('myopac_update_email_row'));
1156                 userShown = false;
1157                 alertId('myopac_email_success');
1158                 myOPACShowSummary();
1159                 return;
1160         }
1161
1162         alert($('myopac_email_failure').innerHTML);
1163 }
1164
1165
1166 function myOPACUpdatePassword() {
1167         var curpassword = $('myopac_current_password').value;
1168         var password = $('myopac_new_password').value;
1169         var password2 = $('myopac_new_password2').value;
1170
1171         if(     curpassword == null || curpassword == "" || 
1172                         password == null || password == "" || 
1173                         password2 == null || password2 == "" || password != password2 ) {
1174                 alert($('myopac_password_error').innerHTML);
1175                 return;
1176         }
1177
1178         if(!strongPassword(password, true)) return;
1179
1180         var req = new Request(UPDATE_PASSWORD, G.user.session, password, curpassword );
1181         req.send(true);
1182         if(req.result()) {
1183                 hideMe($('myopac_update_password_row'));
1184                 userShown = false;
1185                 alertId('myopac_password_success');
1186                 myOPACShowSummary();
1187                 return;
1188         }
1189
1190         alert($('myopac_password_failure').innerHTML);
1191 }
1192
1193
1194
1195
1196 var containerTemplate;
1197 function myOPACShowBookbags(force) {
1198
1199         var tbody =$('myopac_bookbag_tbody') ;
1200
1201         if(!containerTemplate) 
1202                 containerTemplate = tbody.removeChild($('myopac_bookbag_tr'));
1203         else if(!force) return;
1204
1205         removeChildren(tbody);
1206
1207         var containers = containerFetchAll();
1208
1209         var found = false;
1210         for( var i in containers ) {
1211                 found = true;
1212                 var cont = containers[i];
1213                 var row = containerTemplate.cloneNode(true);
1214                 row.id = 'myopac_bookbag_row_' + cont.id();
1215                 var link = $n(row, 'myopac_expand_bookbag');
1216                 var dlink = $n(row, 'myopac_container_delete');
1217                 link.appendChild( text(cont.name()) );
1218                 link.setAttribute('href', 
1219                         'javascript:myOPACExpandBookbag("' + cont.id() + '","' + cont.name() + '");');
1220                 myOPACFetchBBItems( cont.id(), row );
1221                 dlink.setAttribute('href', 'javascript:myOPACDeleteBookbag("'+cont.id()+'");');
1222
1223                 if( isTrue(cont.pub()) ) {
1224                         unHideMe($n(row, 'myopac_bb_published_yes'));
1225                         var link = $n(row, 'myopac_bb_published_view');
1226                         link.setAttribute('href', buildExtrasLink( 'feed/bookbag/html-full/'+cont.id(), false));  
1227                         link.setAttribute('target', '_blank' );
1228                         unHideMe(link);
1229
1230                         link = $n(row, 'myopac_bb_published_atom');
1231                         link.setAttribute('href', buildExtrasLink( 'feed/bookbag/rss2-full/'+cont.id(), false));  
1232                         link.setAttribute('target', '_blank' );
1233                         unHideMe(link);
1234
1235                         link = $n(row, 'myopac_bb_make_unpublished');
1236                         link.setAttribute('href', 'javascript:myOPACMakeBBPublished("'+cont.id()+'", true);');
1237                         unHideMe(link);
1238                         
1239                         var RW = $n(row, 'myopac_bb_exp_refworks');
1240                         if (RW && myopacEnableRefWorks) {
1241                                 var here = (findOrgUnit(getLocation())).name();
1242                                 var org_name = here.replace(" ", "+");
1243                                 var cgi = new CGI();
1244
1245                                 RW.setAttribute('href',
1246                                 myopacRefWorksHost + '/express/expressimport.asp?vendor='
1247                                         + org_name
1248                                         + '&filter=MARC+Format&database=All+MARC+Formats&encoding=65001&url=http%3A%2F%2F'
1249                                         + cgi.server_name + '/opac/extras/feed/bookbag/marctxt-full/'
1250                                         + cont.id()
1251                                 );
1252                                 RW.setAttribute('target', 'RefWorksMain');
1253                                 unHideMe($n(row, 'myopac_bb_exp_refworks'));
1254                         }
1255                 } else { 
1256                         unHideMe($n(row, 'myopac_bb_published_no')); 
1257                         var link = $n(row, 'myopac_bb_make_published');
1258                         link.setAttribute('href', 'javascript:myOPACMakeBBPublished("'+cont.id()+'");');
1259                         unHideMe(link);
1260                 }
1261
1262                 tbody.appendChild(row); 
1263         }
1264
1265         if(!found) unHideMe($('myopac_bookbags_none'));
1266         else unHideMe($('myopac_bookbag_table'));       
1267 }
1268
1269 function myOPACMakeBBPublished(bbid, hideme) {
1270
1271         var bb = fleshedContainers[bbid];
1272
1273         if(hideme) {
1274                 if(!confirm($('myopac_make_unpublished_confirm').innerHTML)) return;
1275                 bb.pub('f');
1276         } else {
1277                 if(!confirm($('myopac_make_published_confirm').innerHTML)) return;
1278                 bb.pub('t');
1279         }
1280
1281         var result = containerUpdate(bb);
1282
1283         var code = checkILSEvent(result);
1284         if(code) { alertILSEvent(result); return; }
1285
1286         alert($('myopac_bb_update_success').innerHTML);
1287         myOPACShowBookbags(true);
1288 }
1289
1290
1291
1292 function myOPACDeleteBookbag(id) {
1293         if( confirm( $('myopac_delete_bookbag_warn').innerHTML ) ) {
1294                 var result = containerDelete(id);
1295                 var code = checkILSEvent(result);
1296                 if(code) { alertILSEvent(result); return; }
1297                 alert($('myopac_bb_update_success').innerHTML);
1298                 hideMe($('myopac_bookbag_items_table'));
1299                 hideMe($('myopac_bookbag_items_name'));
1300                 hideMe($('myopac_bookbag_no_items'));
1301                 myOPACShowBookbags(true);
1302         }
1303 }
1304
1305 function myOPACFetchBBItems( id, row, block ) {
1306         if(!block) {
1307                 containerFlesh( id, _myOPACSetBBItems, { row: row }  );
1308         } else {
1309                 var cont = containerFlesh(id);
1310                 myOPACSetBBItems( cont, row );
1311         }
1312 }
1313
1314 function _myOPACSetBBItems(r) { myOPACSetBBItems( r.getResultObject(), r.args.row ); }
1315
1316 function myOPACSetBBItems( container, row ) {
1317         fleshedContainers[container.id()] = container;
1318         var node = $n(row, 'myopac_bookbag_item_count');
1319         removeChildren(node);
1320         node.appendChild( text(container.items().length) );
1321 }
1322
1323 var BBItemsRow;
1324 function myOPACExpandBookbag( id, name ) {
1325         
1326         var tbody = $('myopac_bookbag_items_tbody');
1327         if(!BBItemsRow) BBItemsRow = tbody.removeChild($('myopac_bookbag_items_row'));
1328         removeChildren(tbody);
1329         removeChildren($('myopac_bookbag_items_name'));
1330
1331         $('myopac_bookbag_items_name').appendChild(text(name));
1332
1333         if( fleshedContainers[id] ) {
1334                 var len = fleshedContainers[id].items().length;
1335
1336                 if( len == 0 ) {
1337                         unHideMe($('myopac_bookbag_no_items'));
1338                         hideMe($('myopac_bookbag_items_table'));
1339                         return;
1340                 }
1341
1342                 hideMe($('myopac_bookbag_no_items'));
1343                 unHideMe($('myopac_bookbag_items_table'));
1344
1345                 for( var i = 0; i != len; i++ ) {
1346                         var row = BBItemsRow.cloneNode(true);
1347                         found = true;
1348
1349                         var item = fleshedContainers[id].items()[i];
1350                         var tlink = $n(row,'myopac_bookbag_items_title');
1351                         var alink = $n(row,'myopac_bookbag_items_author');
1352
1353                         var req = new Request( FETCH_RMODS, item.target_biblio_record_entry() );
1354                         req.request.tlink = tlink;
1355                         req.request.alink = alink;
1356                         req.callback(myOPACShowBBItem);
1357                         req.send();
1358
1359                         var clink = $n(row, 'myopac_bookbag_items_remove');
1360                         clink.setAttribute('href', 'javascript:myOPACRemoveBBItem("'+item.id()+'","'+id+'","'+name+'");');
1361
1362                         tbody.appendChild(row);
1363                 }
1364         }
1365 }
1366
1367 function myOPACRemoveBBItem( id, containerid, container_name ) {
1368         if(!confirm($('myopac_remove_bb_item_confirm').innerHTML)) return;
1369         var stat = containerRemoveItem( id );
1370         if(stat) alert($('myopac_bb_update_success').innerHTML);
1371         myOPACFetchBBItems( containerid, $('myopac_bookbag_row_' + containerid), true);
1372         myOPACExpandBookbag( containerid, container_name );
1373 }
1374
1375 function myOPACShowBBItem(r) {
1376         var record = r.getResultObject();
1377         buildTitleDetailLink(record, r.tlink);
1378         buildSearchLink(STYPE_AUTHOR, record.author(), r.alink);
1379 }
1380
1381 function myOPACCreateBookbag() {
1382         var name = $('myopac_bookbag_new_name').value;  
1383         if(!name) return;
1384
1385         var exists = false;
1386         for( var c in fleshedContainers ) { exists = true; break; }
1387
1388         /* let them know what they are getting into... */
1389         if(!exists) if(!confirm($('bb_create_warning').innerHTML)) return;
1390
1391         var result = containerCreate( name, $('bb_public_yes').checked );
1392         var code = checkILSEvent(result);
1393         if(code) { alertILSEvent(result); return; }
1394         if(result) alert($('myopac_bb_update_success').innerHTML);
1395         myOPACShowBookbags(true);
1396 }
1397
1398
1399 /* ---------------------------------------------------------------------- */
1400 /* Non cat circs */
1401 /* ---------------------------------------------------------------------- */
1402
1403 var nonCatCircIds;
1404 var nonCatTypes;
1405 /* if we have some circs, grab the non-cat types */
1406 function myOPACDrawNonCatCircs(r) {
1407         var ids = r.getResultObject();
1408         if(ids.length == 0) return;
1409         nonCatCircIds = ids;
1410         unHideMe($('non_cat_circs_div'));
1411         var req = new Request(FETCH_NON_CAT_TYPES, G.user.home_ou());
1412         req.callback(myOPACDrawNonCatCircs2);
1413         req.send();
1414 }
1415
1416
1417 /* now we have circs and the types.. draw each one */
1418 var nonCatTbody;
1419 var nonCatRow;
1420 function myOPACDrawNonCatCircs2(r) {
1421         nonCatTypes = r.getResultObject();
1422         nonCatTbody = $('non_cat_circs_tbody');
1423         if(!nonCatRow) nonCatRow = 
1424                 nonCatTbody.removeChild($('non_cat_circs_row'));
1425         removeChildren(nonCatTbody);
1426         for( var i in nonCatCircIds ) {
1427                 var req = new Request(FETCH_NON_CAT_CIRC, G.user.session, nonCatCircIds[i]);
1428                 req.callback(myOPACDrawNonCatCirc);
1429                 req.send();
1430         }
1431 }
1432
1433
1434 /* draw a single circ */
1435 function myOPACDrawNonCatCirc(r) {
1436         var circ = r.getResultObject();
1437
1438
1439         var type = grep(nonCatTypes, 
1440                 function(i){
1441                         return (i.id() == circ.item_type());
1442                 }
1443         )[0];
1444
1445
1446         var row = nonCatTbody.appendChild(nonCatRow.cloneNode(true));
1447         appendClear($n(row, 'circ_lib'), text(findOrgUnit(circ.circ_lib()).name()));
1448         appendClear($n(row, 'item_type'), text(type.name()));
1449
1450         appendClear(
1451         $n(row, 'circ_time'), 
1452         text(dojo.date.locale.format(
1453             dojo.date.stamp.fromISOString(circ.duedate()),
1454             {format : 'short'}
1455         ))
1456     );
1457 }
1458
1459
1460
1461
1462 function myopacSelectAllChecked() {
1463    __myopacSelectChecked(true);
1464 }
1465
1466 function myopacSelectNoneChecked() {
1467    __myopacSelectChecked(false);
1468 }
1469
1470 function __myopacSelectChecked(value) {
1471    var rows = myopacGetCheckedOutRows();
1472    for( var i = 0; i < rows.length; i++ ) {
1473       var row = rows[i];
1474       var box = $n(row, 'selectme');
1475       if( box && ! box.disabled )
1476       box.checked = value;
1477    }
1478 }
1479
1480 function myopacGetCheckedOutRows() {
1481    var rows = [];
1482    var tbody = $('myopac_checked_tbody');
1483    var children = tbody.childNodes;
1484    for( var i = 0; i < children.length; i++ ) {
1485       var child = children[i];
1486       if( child.nodeName.match(/^tr$/i) ) 
1487          if( $n(child, 'selectme') ) 
1488             rows.push(child);
1489    }
1490    return rows;
1491 }
1492
1493 var __renew_circs = [];
1494
1495 /* true if 1 renewal succeeded */
1496 var __success_count = 0;
1497
1498 /* renews all selected circulations */
1499 function myOPACRenewSelected() {
1500    var rows = myopacGetCheckedOutRows();
1501         if(!confirm($('myopac_renew_confirm').innerHTML)) return;
1502    __success_count = 0;
1503
1504    for( var i = 0; i < rows.length; i++ ) {
1505
1506       var row = rows[i];
1507       if( ! $n(row, 'selectme').checked ) continue;
1508       var circ_id = row.getAttribute('circid');
1509
1510            var circ;
1511            for( var j = 0; j != circsCache.length; j++ ) 
1512                    if(circsCache[j].id() == circ_id)
1513                            circ = circsCache[j];
1514
1515       __renew_circs.push(circ);
1516    }
1517
1518     if( __renew_circs.length == 0 ) return;
1519
1520     unHideMe($('my_renewing'));
1521     moClearCheckedTable();
1522
1523     for( var i = 0; i < __renew_circs.length; i++ ) {
1524         var circ = __renew_circs[i];
1525         moRenewCirc( circ.target_copy(), G.user.id(), circ );
1526     }
1527 }
1528
1529
1530 /* renews a single circulation */
1531 function moRenewCirc(copy_id, user_id, circ) {
1532
1533    _debug('renewing circ ' + circ.id() + ' with copy ' + copy_id);
1534    var req = new Request(RENEW_CIRC, G.user.session, 
1535       {  patron : user_id, 
1536          copyid : copy_id, 
1537          opac_renewal : 1 
1538       } 
1539    );
1540
1541    req.request.alertEvent = false;
1542    req.callback(myHandleRenewResponse);
1543    req.request.circ = circ;
1544    req.send();
1545 }
1546
1547
1548
1549 /* handles the circ renew results */
1550 function myHandleRenewResponse(r) {
1551    var res = r.getResultObject();
1552    var circ = r.circ;
1553
1554    /* remove this circ from the list of circs to renew */
1555    __renew_circs = grep(__renew_circs, function(i) { return (i.id() != circ.id()); });
1556
1557    _debug("handling renew result for " + circ.id());
1558
1559    if(checkILSEvent(res) || checkILSEvent(res[0])) 
1560       alertIdText('myopac_renew_fail', __circ_titles[circ.id()]);
1561    else __success_count++;
1562
1563    if(__renew_circs) return; /* more to come */
1564
1565    __renew_circs = [];
1566
1567         if( __success_count > 0 )
1568       alertIdText('myopac_renew_success', __success_count);
1569
1570    hideMe($('my_renewing'));
1571    checkedDrawn = false;
1572     myOPACShowChecked();
1573 }
1574
1575 /** ---- batch hold processing ------------ */
1576
1577
1578 /* myopac_holds_checkbx */
1579 function myopacSelectAllHolds() {
1580     var rows = getTableRows($("myopac_holds_tbody"));
1581     for(var i = 0; i < rows.length; i++) {
1582         cb = $n(rows[i], 'myopac_holds_selected_chkbx');
1583         if(cb) cb.checked = true;
1584     }
1585 }
1586
1587 function myopacSelectNoneHolds() {
1588     var rows = getTableRows($("myopac_holds_tbody"));
1589     for(var i = 0; i < rows.length; i++) {
1590         cb = $n(rows[i], 'myopac_holds_selected_chkbx');
1591         if(cb) cb.checked = false;
1592     }
1593 }
1594
1595 function myopacSelectedHoldsRows() {
1596     var r = [];
1597     var rows = getTableRows($("myopac_holds_tbody"));
1598     for(var i = 0; i < rows.length; i++) {
1599         cb = $n(rows[i], 'myopac_holds_selected_chkbx');
1600         if(cb && cb.checked)
1601             r.push(rows[i]);
1602     }
1603     return r;
1604 }
1605
1606 var myopacProcessedHolds = 0;
1607 var myopacHoldsToProcess = 0;
1608 function myopacDoHoldAction() {
1609
1610     var selectedRows = myopacSelectedHoldsRows();
1611     action = getSelectorVal($('myopac_holds_actions'));
1612     $('myopac_holds_actions_none').selected = true;
1613     if(selectedRows.length == 0) return;
1614
1615     myopacProcessedHolds = 0;
1616
1617     if(!confirmId('myopac.holds.'+action+'.confirm')) return;
1618     myopacSelectNoneHolds(); /* clear the selection */
1619
1620
1621     /* first, let's collect the holds that actually need processing and
1622         collect the full process count while we're at it */
1623     var holds = [];
1624     for(var i = 0; i < selectedRows.length; i++) {
1625         hold = holdCache[myopacHoldIDFromRow(selectedRows[i])];
1626         var qstats = holdStatusCache[hold.id()];
1627         switch(action) {
1628             case 'cancel':
1629                 holds.push(hold);
1630                 break;
1631             case 'thaw_date':
1632             case 'thaw':
1633                 if(isTrue(hold.frozen()))
1634                     holds.push(hold);
1635                 break;
1636             case 'freeze':
1637                 if(!isTrue(hold.frozen()) && qstats.status < 3)
1638                     holds.push(hold);
1639                 break;
1640         }
1641     }
1642     myopacHoldsToProcess = holds;
1643     if(myopacHoldsToProcess.length == 0) return;
1644
1645     if(action == 'thaw_date' || action == 'freeze') 
1646         myopacDrawHoldThawDateForm();
1647     else
1648     myopacProcessHolds(action);
1649 }
1650
1651
1652 function myopacProcessHolds(action, thawDate) {
1653
1654     myopacShowHoldProcessing();
1655     /* now we process them */
1656     for(var i = 0; i < myopacHoldsToProcess.length; i++) {
1657
1658         hold = myopacHoldsToProcess[i];
1659         
1660         var req;
1661         switch(action) { 
1662
1663             case 'cancel':
1664                     req = new Request(CANCEL_HOLD, G.user.session, hold.id(), /* Patron via OPAC */ 6);
1665                 break;
1666     
1667             case 'thaw':
1668                 hold.frozen('f');
1669                 hold.thaw_date(null);
1670                 req = new Request(UPDATE_HOLD, G.user.session, hold);
1671                 break;
1672
1673             case 'thaw_date':
1674             case 'freeze':
1675                 hold.frozen('t');
1676                 hold.thaw_date(thawDate); 
1677                 req = new Request(UPDATE_HOLD, G.user.session, hold);
1678                 break;
1679                 //thawDate = prompt($('myopac.holds.freeze.select_thaw').innerHTML);
1680
1681         }
1682
1683         req.callback(myopacBatchHoldCallback);
1684         req.send();
1685         req = null;
1686     }
1687 }
1688
1689 function myopacDrawHoldThawDateForm() {
1690     hideMe($('myopac_holds_main_table'));
1691     unHideMe($('myopac_holds_thaw_date_form'));
1692     $('myopac_holds_thaw_date_input').focus();
1693 }
1694
1695 function myopacApplyThawDate() {
1696     var dateString = dijit.byId('myopac_holds_thaw_date_input').getValue();
1697     if(dateString) {
1698         dateString = dojo.date.stamp.toISOString(dateString);
1699         if(dateString) {
1700             dateString = holdsVerifyThawDate(dateString);
1701             if(!dateString) return;
1702         } else {
1703             dateString = null;
1704         }
1705     }
1706     myopacProcessHolds('freeze', dateString);
1707 }
1708
1709 function myopacHoldIDFromRow(row) {
1710     return row.id.replace(/.*_(\d+)$/, '$1');
1711 }
1712
1713 function myopacShowHoldProcessing() {
1714     unHideMe($('myopac_holds_processing'));
1715     hideMe($('myopac_holds_main_table'));
1716 }
1717
1718 function myopacHideHoldProcessing() {
1719     hideMe($('myopac_holds_processing'));
1720     unHideMe($('myopac_holds_main_table'));
1721     hideMe($('myopac_holds_thaw_date_form'));
1722 }
1723
1724 function myopacBatchHoldCallback(r) {
1725     if(r) /* force load any exceptions */
1726         r.getResultObject();
1727     if(++myopacProcessedHolds >= myopacHoldsToProcess.length) {
1728         myopacHideHoldProcessing();
1729         holdCache = {};
1730         holdStatusCache = {};
1731         myopacForceHoldsRedraw = true;
1732         myOPACShowHolds();
1733     }
1734 }
1735