]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Holdings Maintenance link next to Update Barcodes in Acq
[Evergreen.git] / Open-ILS / web / js / ui / default / acq / common / li_table.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.acq.Lineitem');
12 dojo.require('openils.acq.PO');
13 dojo.require('openils.acq.Picklist');
14 dojo.require('openils.widget.AutoFieldWidget');
15 dojo.require('dojo.data.ItemFileReadStore');
16 dojo.require('openils.widget.ProgressDialog');
17 dojo.require('openils.PermaCrud');
18 dojo.require('openils.XUL');
19
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
24
25 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
27
28 function nodeByName(name, context) {
29     return dojo.query('[name='+name+']', context)[0];
30 }
31
32
33 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
34 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
35
36 function AcqLiTable() {
37
38     var self = this;
39     this.liCache = {};
40     this.plCache = {};
41     this.poCache = {};
42     this.realDfaCache = {};
43     this.virtDfaCounts = {};
44     this.virtDfaId = -1;
45     this.dfeOffset = 0;
46     this.toggleState = false;
47     this.tbody = dojo.byId('acq-lit-tbody');
48     this.selectors = [];
49     this.noteAcks = {};
50     this.authtoken = openils.User.authtoken;
51     this.pcrud = new openils.PermaCrud();
52     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
53     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
54     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
55     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
56     this.copyBatchWidgets = {};
57     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
58     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
59     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
60     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
61     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
62
63     dojo.connect(acqLitLiActionsSelector, 'onChange', 
64         function() { 
65             self.applySelectedLiAction(this.attr('value')) 
66             acqLitLiActionsSelector.attr('value', '_');
67         });
68
69     acqLitCreatePoSubmit.onClick = function() {
70         acqLitPoCreateDialog.hide();
71         self._createPO(acqLitPoCreateDialog.getValues());
72     }
73
74     acqLitSavePlButton.onClick = function() {
75         acqLitSavePlDialog.hide();
76         self._savePl(acqLitSavePlDialog.getValues());
77     }
78
79     acqLitCancelLiStateButton.onClick = function() {
80         acqLitChangeLiStateDialog.hide();
81     }
82     acqLitSaveLiStateButton.onClick = function() {
83         acqLitChangeLiStateDialog.hide();
84         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
85     }
86
87
88     //dojo.byId('acq-lit-notes-new-button').onclick = function(){acqLitCreateLiNoteDialog.show();}
89
90     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
91     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
92     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
93     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
94     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
95
96     this.reset = function() {
97         while(self.tbody.childNodes[0])
98             self.tbody.removeChild(self.tbody.childNodes[0]);
99         self.selectors = [];
100         self.noteAcks = {};
101     };
102     
103     this.setNext = function(handler) {
104         var link = dojo.byId('acq-lit-next');
105         if(handler) {
106             dojo.style(link, 'visibility', 'visible');
107             link.onclick = handler;
108         } else {
109             dojo.style(link, 'visibility', 'hidden');
110         }
111     };
112
113     this.setPrev = function(handler) {
114         var link = dojo.byId('acq-lit-prev');
115         if(handler) {
116             dojo.style(link, 'visibility', 'visible'); 
117             link.onclick = handler; 
118         } else {
119             dojo.style(link, 'visibility', 'hidden');
120         }
121     };
122
123     this.show = function(div) {
124         openils.Util.hide('acq-lit-table-div');
125         openils.Util.hide('acq-lit-info-div');
126         openils.Util.hide('acq-lit-li-details');
127         openils.Util.hide('acq-lit-notes-div');
128         openils.Util.hide('acq-lit-real-copies-div');
129         switch(div) {
130             case 'list':
131                 openils.Util.show('acq-lit-table-div');
132                 break;
133             case 'info':
134                 openils.Util.show('acq-lit-info-div');
135                 break;
136             case 'copies':
137                 openils.Util.show('acq-lit-li-details');
138                 break;
139             case 'real-copies':
140                 openils.Util.show('acq-lit-real-copies-div');
141                 break;
142             case 'notes':
143                 openils.Util.show('acq-lit-notes-div');
144                 break;
145             default:
146                 if(div) 
147                     openils.Util.show(div);
148         }
149     }
150
151     this.hide = function() {
152         this.show(null);
153     }
154
155     this.toggleSelect = function() {
156         if(self.toggleState) 
157             dojo.forEach(self.selectors, function(i){i.checked = false});
158         else 
159             dojo.forEach(self.selectors, function(i){i.checked = true});
160         self.toggleState = !self.toggleState;
161     };
162
163
164     /** @param all If true, assume all are selected */
165     this.getSelected = function(all) {
166         var selected = [];
167         dojo.forEach(self.selectors, 
168             function(i) { 
169                 if(i.checked || all)
170                     selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
171             }
172         );
173         return selected;
174     };
175
176     this.setRowAttr = function(td, liWrapper, field, type) {
177         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
178         td.appendChild(document.createTextNode(val));
179     };
180
181     /**
182      * Inserts a single lineitem into the growing table of lineitems
183      * @param {Object} li The lineitem object to insert
184      */
185     this.addLineitem = function(li, skip_final_placement) {
186         this.liCache[li.id()] = li;
187
188         // sort the lineitem notes on edit_time
189         if(!li.lineitem_notes()) li.lineitem_notes([]);
190
191         var liWrapper = new openils.acq.Lineitem({lineitem:li});
192         var row = self.rowTemplate.cloneNode(true);
193         row.setAttribute('li', li.id());
194         var tds = dojo.query('[attr]', row);
195         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
196         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
197
198         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
199         if(isbn) {
200             // XXX media prefix for added content
201             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
202         }
203
204         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
205         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
206         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
207
208         this.updateLiNotesCount(li, row);
209
210         // show which PO this lineitem is a member of
211         if(li.purchase_order() && !this.isPO) {
212             var po = 
213                 this.poCache[li.purchase_order()] =
214                 this.poCache[li.purchase_order()] ||
215                 fieldmapper.standardRequest(
216                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
217                     {params: [
218                         this.authtoken, li.purchase_order(), {
219                             "flesh_price_summary": true,
220                             "flesh_lineitem_count": true
221                         }
222                     ]});
223             if(po && !this.isMeta) {
224                 openils.Util.show(nodeByName('po', row), 'inline');
225                 var link = nodeByName('po_link', row);
226                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
227                 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
228             }
229         }
230
231         // show which picklist this lineitem is a member of
232         if(li.picklist() && (this.isPO || this.isMeta)) {
233             var pl = 
234                 this.plCache[li.picklist()] = 
235                 this.plCache[li.picklist()] || 
236                 fieldmapper.standardRequest(
237                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
238                     {params: [this.authtoken, li.picklist()]});
239             if(pl) {
240                 openils.Util.show(nodeByName('pl', row), 'inline');
241                 var link = nodeByName('pl_link', row);
242                 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
243                 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
244             }
245         }
246
247         var countNode = nodeByName('count', row);
248         var count = li.item_count() || 0;
249         if (typeof(this._copy_count_cb) == "function") {
250             this._copy_count_cb(li.id(), count);
251         }
252         countNode.innerHTML = count;
253         countNode.id = 'acq-lit-copy-count-label-' + li.id();
254
255         // lineitem state
256         nodeByName('li_state', row).innerHTML = li.state(); // TODO i18n state labels
257         
258         // lineitem price
259         var priceInput = dojo.query('[name=price]', row)[0];
260         priceInput.value = li.estimated_unit_price() || '';
261         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
262
263         // show either "mark received" or "unreceive" as appropriate
264         this.updateLiReceivedness(li, row);
265
266         if (!skip_final_placement) {
267             self.tbody.appendChild(row);
268             self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
269         } else {
270             return row;
271         }
272     };
273
274     this.updateLiNotesCount = function(li, row) {
275         if (typeof(row) == "undefined")
276             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
277
278         var has_notes = (li.lineitem_notes().filter(
279                 function(o) { return Boolean (o.alert_text()); }
280             ).length > 0);
281
282         /* U+2691 is the code point for a filled-in flag character */
283         nodeByName("notes_alert_flag", row).innerHTML =
284              has_notes ? "⚑" : "";
285         nodeByName("noteslink", row).style.fontStyle =
286             has_notes ? "italic" : "normal";
287         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
288     };
289
290     this.updateLiReceivedness = function(li, row) {
291         if (typeof(row) == "undefined")
292             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
293
294         var recv_link = nodeByName("receive_link", row);
295         var unrecv_link = nodeByName("unreceive_link", row);
296         var real_copies_link = nodeByName("real_copies_link", row);
297         var holdings_maintenance_link = nodeByName("holdings_maintenance_link", row);
298
299         /* handle row coloring for based on LI state */
300         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
301         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
302
303         /* handle links that appear/disappear based on whether LI is received */
304         if (this.isPO) {
305             var self = this;
306             switch(li.state()) {
307                 case "on-order":
308                     openils.Util.hide(real_copies_link);
309                     openils.Util.hide(unrecv_link);
310                     openils.Util.show(recv_link, "inline");
311                     recv_link.onclick = function() {
312                         if (self.checkLiAlerts(li.id()))
313                             self.issueReceive(li);
314                     };
315                     return;
316                 case "received":
317                     openils.Util.hide(recv_link);
318                     openils.Util.show(unrecv_link, "inline");
319                     unrecv_link.onclick = function() {
320                         if (confirm(localeStrings.UNRECEIVE_LI))
321                             self.issueReceive(li, /* rollback */ true);
322                     };
323                     // TODO we should allow editing before receipt, in which case the
324                     // test should be "if 1 or more real (acp) copies exist
325                     openils.Util.show(real_copies_link);
326                     real_copies_link.onclick = function() {
327                         self.showRealCopyEditUI(li);
328                     }
329                     openils.Util.show(holdings_maintenance_link);
330                     holdings_maintenance_link.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser' );
331                     return;
332             }
333         }
334
335         openils.Util.hide(recv_link);
336         openils.Util.hide(unrecv_link);
337         openils.Util.hide(real_copies_link);
338     };
339
340
341     this._setAlertStore = function() {
342         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
343             {
344                 "data": acqliat.toStoreData(
345                     this.pcrud.search(
346                         "acqliat", {"id": {"!=": null}}
347                     )
348                 )
349             }
350         );
351         acqLitAlertAlertText.setValue(); /* make the store "live" */
352         acqLitAlertAlertText._store_ready = true;
353     };
354
355     /**
356      * Draws and shows the lineitem notes pane
357      */
358     this.drawLiNotes = function(li) {
359         var self = this;
360
361         if (!acqLitAlertAlertText._store_ready)
362             this._setAlertStore();
363
364         li.lineitem_notes(
365             li.lineitem_notes().sort(
366                 function(a, b) { 
367                     if(a.edit_time() < b.edit_time()) return 1;
368                     return -1;
369                 }
370             )
371         );
372
373         while(this.liNotesTbody.childNodes[0])
374             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
375         this.show('notes');
376
377         acqLitCreateLiNoteSubmit.onClick = function() {
378             var value = acqLitCreateNoteText.attr('value');
379             if(!value) return;
380             var note = new fieldmapper.acqlin();
381             note.isnew(true);
382             note.value(value);
383             note.lineitem(li.id());
384
385             self.updateLiNotes(li, note);
386         }
387
388         acqLitCreateAlertSubmit.onClick = function() {
389             if (!acqLitAlertAlertText.item) {
390                 alert(localeStrings.ALERT_UNSELECTED);
391                 return;
392             }
393
394             var alert_text = new fieldmapper.acqliat().fromStoreItem(
395                 acqLitAlertAlertText.item
396             );
397             var value = acqLitAlertNoteValue.attr("value") || "";
398
399             var note = new fieldmapper.acqlin();
400             note.isnew(true);
401             note.lineitem(li.id());
402             note.value(value);
403             note.alert_text(alert_text);
404
405             self.updateLiNotes(li, note);
406         }
407
408         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
409     }
410
411     /**
412      * Draws a single lineitem note in the notes pane
413      */
414     this.addLiNote = function(li, note) {
415         if(note.isdeleted()) return;
416         var self = this;
417         var row = self.liNotesRow.cloneNode(true);
418         nodeByName("value", row).innerHTML = note.value();
419         var alert_node = nodeByName("alert_code", row);
420         if (note.alert_text()) {
421             alert_node.innerHTML = note.alert_text().code();
422             if (note.alert_text().description()) {
423                 new dijit.Tooltip(
424                     {
425                         "connectId": [alert_node],
426                         "label": note.alert_text().description()
427                     }, dojo.create("span", null, alert_node, "after")
428                 );
429             }
430         }
431
432         nodeByName("delete", row).onclick = function() {
433             note.isdeleted(true);
434             self.liNotesTbody.removeChild(row);
435             self.updateLiNotes(li);
436         };
437
438         if(note.edit_time()) {
439             nodeByName("edit_time", row).innerHTML =
440                 dojo.date.locale.format(
441                     dojo.date.stamp.fromISOString(note.edit_time()), 
442                     {formatLength:'short'});
443         }
444
445         self.liNotesTbody.appendChild(row);
446     }
447
448     /**
449      * Updates any new/changed/deleted notes on the server
450      */
451     this.updateLiNotes = function(li, newNote) {
452
453         var notes;
454         if(newNote) {
455             notes = [newNote];
456         } else {
457             notes = li.lineitem_notes().filter(
458                 function(note) {
459                     if(note.ischanged() || note.isnew() || note.isdeleted())
460                         return note;
461                 }
462             );
463         }
464
465         if(notes.length == 0) return;
466         progressDialog.show();
467
468         fieldmapper.standardRequest(
469             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
470             {   async : true,
471                 params : [this.authtoken, notes],
472                 onresponse : function(r) {
473                     var resp = openils.Util.readResponse(r);
474
475                     if(resp.complete) {
476
477                         if(!newNote) {
478                             // remove the old changed notes
479                             var list = [];
480                             dojo.forEach(li.lineitem_notes(), 
481                                 function(note) {
482                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
483                                         list.push(note);
484                                 }
485                             );
486                             li.lineitem_notes(list);
487                         }
488
489                         progressDialog.hide();
490                         self.updateLiNotesCount(li);
491                         self.drawLiNotes(li);
492                         return;
493                     }
494
495                     progressDialog.update(resp);
496                     var newnote = resp.note;
497
498                     if(!newnote.isdeleted()) {
499                         newnote.isnew(false);
500                         newnote.ischanged(false);
501                         li.lineitem_notes().push(newnote);
502                     }
503                 },
504             }
505         );
506     }
507
508     this.updateLiPrice = function(input, li) {
509
510         var price = input.value;
511         if(Number(price) == Number(li.estimated_unit_price())) return;
512
513         fieldmapper.standardRequest(
514             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
515             {   async : true,
516                 params : [this.authtoken, li.id(), price],
517                 oncomplete : function(r) {
518                     openils.Util.readResponse(r);
519                 }
520             }
521         );
522     }
523
524     this.removeLineitem = function(liId) {
525         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
526         delete this.liCache[liId];
527         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
528     }
529
530     this.drawInfo = function(liId) {
531         this.show('info');
532         openils.acq.Lineitem.fetchAttrDefs(
533             function() { 
534                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
535             } 
536         );
537     };
538
539     this._fetchLineitem = function(liId, handler) {
540
541         var li = this.liCache[liId];
542         if(li && li.marc() && li.lineitem_details())
543             return handler(li);
544         
545         fieldmapper.standardRequest(
546             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
547             {   async: true,
548
549                 params: [self.authtoken, liId, {
550                     flesh_attrs: true,
551                     flesh_li_details: true,
552                     flesh_fund_debit: true }],
553
554                 oncomplete: function(r) {
555                     var li = openils.Util.readResponse(r);
556                     handler(li)
557                 }
558             }
559         );
560     };
561
562     this._drawInfo = function(li) {
563
564         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
565
566         if(li.eg_bib_id()) {
567             openils.Util.hide('acq-lit-marc-order-record-label');
568             openils.Util.hide(acqLitEditOrderMarc.domNode);
569             openils.Util.show('acq-lit-marc-real-record-label');
570         } else {
571             openils.Util.show('acq-lit-marc-order-record-label');
572             openils.Util.show(acqLitEditOrderMarc.domNode);
573             openils.Util.hide('acq-lit-marc-real-record-label');
574         }
575
576         this.drawMarcHTML(li);
577         this.infoTbody = dojo.byId('acq-lit-info-tbody');
578
579         if(!this.infoRow)
580             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
581         while(this.infoTbody.childNodes[0])
582             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
583
584         for(var i = 0; i < li.attributes().length; i++) {
585             var attr = li.attributes()[i];
586             var row = this.infoRow.cloneNode(true);
587
588             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
589             var name = openils.acq.Lineitem.attrDefs[type].filter(
590                 function(a) {
591                     return (a.code() == attr.attr_name());
592                 }
593             ).pop().description();
594
595             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
596             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
597             this.infoTbody.appendChild(row);
598         }
599
600         if(li.eg_bib_id()) {
601             openils.Util.show('acq-lit-info-cat-link');
602             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
603
604             if(openils.XUL.isXUL()) {
605
606                 link.setAttribute('href', 'javascript:void(0);');
607                 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
608
609             } else {
610                 var href = link.getAttribute('href');
611                 if(href.match(/=$/))
612                     link.setAttribute('href',  href + li.eg_bib_id());
613             }
614         } else {
615             openils.Util.hide('acq-lit-info-cat-link');
616         }
617     };
618
619     this.generateMakeRecTab = function(bib_id,default_view) {
620         return function() {
621             xulG.new_tab(
622                 XUL_OPAC_WRAPPER,
623                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
624                 {
625                     no_xulG : false, 
626                     show_nav_buttons : true, 
627                     show_print_button : true, 
628                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
629                     default_view : default_view
630                 }
631             );
632         }
633     };
634
635     this.drawMarcHTML = function(li) {
636         var params = [null, true, li.marc()];
637         if(li.eg_bib_id()) 
638             params = [li.eg_bib_id(), true];
639
640         fieldmapper.standardRequest(
641             ['open-ils.search', 'open-ils.search.biblio.record.html'],
642             {   async: true,
643                 params: params,
644                 oncomplete: function(r) {
645                     dojo.byId('acq-lit-marc-div').innerHTML = 
646                         openils.Util.readResponse(r);
647                 }
648             }
649         );
650     }
651
652     this.drawCopies = function(liId) {
653         this.show('copies');
654         var self = this;
655         this.copyCache = {};
656         this.copyWidgetCache = {};
657         this.oldCopyWidgetCache = {};
658         this.virtDfaCounts = {};
659         this.realDfaCache = {};
660         this.dfeOffset = 0;
661
662         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
663         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
664         acqLitCopyCountInput.attr('value', '0');
665
666         while(this.copyTbody.childNodes[0])
667             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
668
669         this._drawBatchCopyWidgets();
670
671         this._drawDistribApplied(liId);
672
673         this._fetchDistribFormulas(
674             function() {
675                 openils.acq.Lineitem.fetchAttrDefs(
676                     function() { 
677                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
678                     } 
679                 );
680             }
681         );
682     };
683
684     this._saveDistribAppliedTemplates = function() {
685         if (!this._appliedDistribTemplate) {
686             this._appliedDistribTemplate =
687                 dojo.byId("acq-lit-distrib-applied-tbody").
688                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
689             dojo.attr(this._appliedDistribTemplate, "id");
690         }
691     };
692
693     this._drawDistribApplied = function(liId) {
694         /* Build this table while hidden to prevent rendering artifacts */
695         openils.Util.hide("acq-lit-distrib-applied-tbody");
696
697         this._saveDistribAppliedTemplates();
698
699         /* Remove any rows in the table from previous populations */
700         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
701             forEach(dojo.destroy);
702
703         /* Unregister all dijits previously created (for some reason this isn't
704          * covered by the above destroy calls). */
705         dijit.registry.forEach(
706             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
707         );
708
709         /* Populate the table with our liId */
710         var total = 0;
711         fieldmapper.standardRequest(
712             ["open-ils.acq",
713             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
714             {
715                 "async": true,
716                 "params": [self.authtoken, liId],
717                 "onresponse": function(r) {
718                     var dfa = openils.Util.readResponse(r);
719                     if (dfa) {
720                         total++;
721                         self.realDfaCache[dfa.id()] = dfa;
722                         self._drawDistribAppliedUnit(dfa);
723                     }
724                 },
725                 "oncomplete": function() {
726                     /* Reveal built table */
727                     if (total) {
728                         openils.Util.show(
729                             "acq-lit-distrib-applied-tbody", "table-row-group"
730                         );
731                     }
732                 }
733             }
734         );
735     };
736
737     this._drawDistribAppliedUnit = function(dfa) {
738         var new_row = false;
739         var row = dojo.query(
740             'tr[formula="' + dfa.formula().id() + '"]',
741             "acq-lit-distrib-applied-tbody"
742         )[0];
743
744         if (!row) {
745             new_row = true;
746             row = dojo.clone(this._appliedDistribTemplate);
747             dojo.attr(row, "formula", dfa.formula().id());
748             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
749         }
750
751         var td = dojo.query("td", row)[0];
752
753         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
754         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
755
756         if (new_row)
757             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
758
759         new dijit.form.Button(
760             {
761                 "onClick": function() {
762                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
763                         self.deleteDfa(dfa);
764                 },
765                 "label": "X",
766                 /* XXX I /cannot/ make the following work in as a CSS class
767                  * for some reason. So frustrating... */
768                 "style": function(id) {
769                      return (id > 0 ?
770                         "font-weight: bold; color: #c00;" :
771                         "color: #666;");
772                      }(dfa.id()) + "margin: 0 6px;display: inline;"
773             }, "dfa-button-" + dfa.id()
774         );
775         new dijit.Tooltip(
776             {
777                 "connectId": ["dfa-button-" + dfa.id()],
778                 "label": dojo.string.substitute(
779                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
780                         openils.User.formalName(dfa.creator()),
781                         dojo.date.locale.format(
782                             dojo.date.stamp.fromISOString(dfa.create_time()),
783                             {"formatLength":"short"}
784                         )
785                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
786                 )
787             }, "dfa-tip-" + dfa.id()
788         );
789     }
790
791     this.deleteDfa = function(dfa) {
792         if (dfa.id() > 0) { /* real */
793             this.pcrud.eliminate(
794                 dfa, {
795                     "async": true,
796                     "oncomplete": function() {
797                         self._removeDistribApplied(dfa.id());
798                         delete self.realDfaCache[dfa.id()];
799                     }
800                 }
801             );
802         } else { /* virtual */
803             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
804             this.virtDfaCounts[dfa.formula().id()] = 0;
805             /* hasn't been saved yet, so no need to do anything server side */
806             this._removeDistribApplied(dfa.id());
807         }
808
809     };
810
811     this._removeDistribApplied = function(dfaId) {
812         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
813         dijit.registry.forEach(
814             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
815         );
816         this._removeDistribAppliedEmptyRows();
817     };
818
819     this._removeAllDistribAppliedVirtual = function() {
820         /* Unregister dijits */
821         dijit.registry.forEach(
822             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
823         );
824         this._removeDistribAppliedEmptyRows();
825     };
826
827     this._removeDistribAppliedEmptyRows = function() {
828         /* Remove any rows with no DFA at all */
829         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
830             function(o) {
831                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
832             }
833         );
834     };
835
836     /**
837      * Insert a new row into the distribution formula selection form
838      */
839     this._addDistribFormulaRow = function() {
840         var self = this;
841
842         if (!self.distribForms) {
843             // no formulas, hide the form
844             openils.Util.hide('acq-lit-distrib-formula-tbody');
845             return;
846         }
847
848         if(!this.distribFormulaTemplate) 
849             this.distribFormulaTemplate = 
850                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
851
852         var row = this.distribFormulaTemplate.cloneNode(true);
853         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
854
855         this.dfSelector = new dijit.form.FilteringSelect(
856             {"labelAttr": "dynLabel", "labelType": "html"},
857             nodeByName("selector", row)
858         );
859         this._updateFormulaStore();
860         this.dfSelector.fetchProperties =
861             {"sort": [{"attribute": "use_count", "descending": true}]};
862
863         var apply = new dijit.form.Button(
864             {"label": localeStrings.APPLY},
865             nodeByName('set_button', row)
866         ); 
867
868         var reset = new dijit.form.Button(
869             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
870             nodeByName("reset_button", row)  
871         );
872
873         dojo.connect(apply, 'onClick', 
874             function() {
875                 var form_id = self.dfSelector.attr("value");
876                 if(!form_id) return;
877                 self._applyDistribFormula(form_id);
878                 reset.attr("disabled", false);
879             }
880         );
881
882         dojo.connect(reset, 'onClick', 
883             function() {
884                 self.restoreCopyFieldsBeforeDF();
885                 self.virtDfaCounts = {};
886                 self.virtDfaId = -1;
887                 self.dfeOffset = 0;
888                 self._updateFormulaStore();
889                 self._removeAllDistribAppliedVirtual();
890                 reset.attr("disabled", "true");
891             }
892         );
893
894     };
895
896     /**
897      * Applies a distrib formula to the current set of copies
898      */
899     this._applyDistribFormula = function(formula) {
900         if(!formula) return;
901
902         formula = this.distribForms.filter(
903             function(form) { return form.id() == formula; }
904         )[0];
905
906         var copyRows = dojo.query('tr', self.copyTbody);
907
908         if (this.dfeOffset >= copyRows.length) {
909             alert(localeStrings.OUT_OF_COPIES);
910             return;
911         }
912
913         var entries_applied = 0;
914         for(
915             var rowIndex = this.dfeOffset;
916             rowIndex < copyRows.length;
917             rowIndex++
918         ) {
919             
920             var row = copyRows[rowIndex];
921             var copy_id = row.getAttribute('copy_id');
922             var copyWidgets = this.copyWidgetCache[copy_id];
923             var entryIndex = this.dfeOffset;
924             var entry = null;
925
926             // find the correct entry for the current row
927             dojo.forEach(formula.entries(), 
928                 function(e) {
929                     if(!entry) {
930                         entryIndex += e.item_count();
931                         if(entryIndex > rowIndex)
932                             entry = e;
933                     }
934                 }
935             );
936
937             if(entry) {
938                 
939                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
940                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
941     
942                 entries_applied++;
943                 this.saveCopyFieldsBeforeDF(copy_id);
944                 this._copy_fields_for_acqdf.forEach(
945                     function(field) {
946                         if(entry[field]()) {
947                             copyWidgets[field].attr('value', (entry[field]()));
948                         }
949                     }
950                 );
951             }
952         }
953
954         if (entries_applied) {
955             this.virtDfaCounts[formula.id()] =
956                 ++(this.virtDfaCounts[formula.id()]) || 1;
957             this._updateFormulaStore();
958             this._drawDistribAppliedUnit(
959                 function(df) {
960                     var dfa = new acqdfa();
961                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
962                 }(formula)
963             );
964             this.dfeOffset += entries_applied;
965         };
966     };
967
968     /**
969      * This function updates the DF store for the dropdown so that use_counts
970      * can reflect DF applications from this session before they're saved
971      * server-side.
972      */
973     this._updateFormulaStore = function() {
974         this.dfSelector.store = new dojo.data.ItemFileReadStore(
975             {
976                 "data": self._labelFormulasWithCounts(
977                     acqdf.toStoreData(self.distribForms)
978                 )
979             }
980         );
981     };
982
983     this.saveCopyFieldsBeforeDF = function(copy_id) {
984         var self = this;
985         if (!this.oldCopyWidgetCache[copy_id]) {
986             var copyWidgets = this.copyWidgetCache[copy_id];
987
988             this.oldCopyWidgetCache[copy_id] = {};
989             this._copy_fields_for_acqdf.forEach(
990                 function(f) {
991                     self.oldCopyWidgetCache[copy_id][f] =
992                         copyWidgets[f].attr("value");
993                 }
994             );
995         }
996     };
997
998     this.restoreCopyFieldsBeforeDF = function() {
999         var self = this;
1000         for (var copy_id in this.oldCopyWidgetCache) {
1001             this._copy_fields_for_acqdf.forEach(
1002                 function(f) {
1003                     self.copyWidgetCache[copy_id][f].attr(
1004                         "value", self.oldCopyWidgetCache[copy_id][f]
1005                     );
1006                 }
1007             );
1008         }
1009     };
1010
1011     this._labelFormulasWithCounts = function(store_data) {
1012         for (var key in store_data.items) {
1013             var obj = store_data.items[key];
1014             obj.use_count = Number(obj.use_count); /* needed for sorting */
1015
1016             if (this.virtDfaCounts[obj.id])
1017                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1018
1019             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1020                 obj.use_count + "]</span>&nbsp; " + obj.name;
1021         }
1022         return store_data;
1023     };
1024
1025     /**
1026      * This method formerly would not refetch the DF formulas if they'd been
1027      * loaded already, but now it always re-fetches, since use_count changes.
1028      */
1029     this._fetchDistribFormulas = function(onload) {
1030         fieldmapper.standardRequest(
1031             ["open-ils.acq",
1032                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1033             {
1034                 "async": true,
1035                 "params": [openils.User.authtoken],
1036                 "oncomplete": function(r) {
1037                     self.distribForms = openils.Util.readResponse(r);
1038                     if(!self.distribForms || self.distribForms.length == 0) {
1039                         self.distribForms = [];
1040                     }
1041                     self._addDistribFormulaRow();
1042                     onload();
1043                 }
1044             }
1045         );
1046     }
1047
1048     this._drawBatchCopyWidgets = function() {
1049         var row = this.copyBatchRow;
1050         dojo.forEach(liDetailBatchFields, 
1051             function(field) {
1052                 if(self.copyBatchRowDrawn) {
1053                     self.copyBatchWidgets[field].attr('value', null);
1054                 } else {
1055                     var widget = new openils.widget.AutoFieldWidget({
1056                         fmField : field,
1057                         fmClass : 'acqlid',
1058                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1059                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1060                         parentNode : dojo.query('[name='+field+']', row)[0],
1061                         orgLimitPerms : ['CREATE_PICKLIST'],
1062                         dijitArgs : {required:false},
1063                         forceSync : true
1064                     });
1065                     widget.build(
1066                         function(w, ww) {
1067                             self.copyBatchWidgets[field] = w;
1068                         }
1069                     );
1070                 }
1071             }
1072         );
1073         this.copyBatchRowDrawn = true;
1074     };
1075
1076     this.batchCopyUpdate = function() {
1077         var self = this;
1078         for(var k in this.copyWidgetCache) {
1079             var cache = this.copyWidgetCache[k];
1080             dojo.forEach(liDetailBatchFields, function(f) {
1081                 var newval = self.copyBatchWidgets[f].attr('value');
1082                 if(newval) cache[f].attr('value', newval);
1083             });
1084         }
1085     };
1086
1087     this._drawCopies = function(li) {
1088         var self = this;
1089
1090         // this button sets the total number of copies for a given lineitem
1091         acqLitAddCopyCount.onClick = function() { 
1092             var count = acqLitCopyCountInput.attr('value');
1093
1094             // add new rows
1095             while(self.copyCount() < count)
1096                 self.addCopy(li); 
1097             
1098             // delete rows if necessary
1099             var diff = self.copyCount() - count;
1100             if(diff > 0) {
1101                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1102                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1103                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1104                 } else {
1105                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1106                 }
1107             }
1108         }
1109
1110
1111         if(li.lineitem_details().length > 0) {
1112             dojo.forEach(li.lineitem_details(),
1113                 function(copy) {
1114                     self.addCopy(li, copy);
1115                 }
1116             );
1117         } else {
1118             self.addCopy(li);
1119         }
1120     };
1121
1122     this.copyCount = function() {
1123         var count = 0;
1124         for(var id in this.copyCache) {
1125             if(!this.copyCache[id].isdeleted())
1126                 count++;
1127         }
1128         return count;
1129     }
1130
1131     this.virtCopyId = -1;
1132     this.addCopy = function(li, copy) {
1133         var row = this.copyRow.cloneNode(true);
1134         this.copyTbody.appendChild(row);
1135         var self = this;
1136
1137         if(!copy) {
1138             copy = new fieldmapper.acqlid();
1139             copy.isnew(true);
1140             copy.id(this.virtCopyId--);
1141             copy.lineitem(li.id());
1142         }
1143
1144         this.copyCache[copy.id()] = copy;
1145         row.setAttribute('copy_id', copy.id());
1146         self.copyWidgetCache[copy.id()] = {};
1147
1148         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1149
1150         dojo.forEach(liDetailFields,
1151             function(field) {
1152                 var widget = new openils.widget.AutoFieldWidget({
1153                     fmObject : copy,
1154                     fmField : field,
1155                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1156                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1157                     fmClass : 'acqlid',
1158                     parentNode : dojo.query('[name='+field+']', row)[0],
1159                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1160                     readOnly : Boolean(copy.eg_copy_id())
1161                 });
1162                 widget.build(
1163                     // make sure we capture the value from any async widgets
1164                     function(w, ww) { 
1165                         copy[field](ww.getFormattedValue()) 
1166                         self.copyWidgetCache[copy.id()][field] = w;
1167                     }
1168                 );
1169                 dojo.connect(widget.widget, 'onChange', 
1170                     function(val) { 
1171                         if(copy.isnew() || val != copy[field]()) {
1172                             // prevent setting ischanged() automatically on widget load for existing copies
1173                             copy[field](widget.getFormattedValue()) 
1174                             copy.ischanged(true);
1175                         }
1176                     }
1177                 );
1178             }
1179         );
1180
1181         this.updateLidReceivedness(copy, row);
1182     };
1183
1184     this.updateLidReceivedness = function(copy, row) {
1185         if (typeof(row) == "undefined") {
1186             row = dojo.query(
1187                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1188             )[0];
1189         }
1190
1191         var self = this;
1192         var recv_link = nodeByName("receive", row);
1193         var unrecv_link = nodeByName("unreceive", row);
1194         var del_link = nodeByName("delete", row);
1195
1196         if (this.isPO) {
1197             openils.Util.hide(del_link.parentNode);
1198
1199             /* Avoid showing (un)receive links for virtual copies */
1200             if (copy.id() > 0) {
1201                 if(copy.recv_time()) {
1202                     openils.Util.hide(recv_link);
1203                     openils.Util.show(unrecv_link);
1204                     unrecv_link.onclick = function() {
1205                         if (confirm(localeStrings.UNRECEIVE_LID))
1206                             self.issueReceive(copy, /* rollback */ true);
1207                     };
1208                 } else {
1209                     openils.Util.hide(unrecv_link);
1210                     openils.Util.show(recv_link);
1211                     recv_link.onclick = function() {
1212                         if (self.checkLiAlerts(copy.lineitem()))
1213                             self.issueReceive(copy);
1214                     };
1215                 }
1216             } else {
1217                 openils.Util.hide(unrecv_link);
1218                 openils.Util.hide(recv_link);
1219             }
1220         } else {
1221             openils.Util.hide(unrecv_link);
1222             openils.Util.hide(recv_link);
1223
1224             del_link.onclick = function() { self.deleteCopy(row) };
1225             openils.Util.show(del_link.parentNode);
1226         }
1227     }
1228
1229     this._confirmAlert = function(li, lin) {
1230         return confirm(
1231             dojo.string.substitute(
1232                 localeStrings.CONFIRM_LI_ALERT, [
1233                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1234                         "title", "lineitem_marc_attr_definition"
1235                     ),
1236                     lin.alert_text().code(),
1237                     lin.alert_text().description() || "",
1238                     lin.value()
1239                 ]
1240             )
1241         );
1242     };
1243
1244     this.checkLiAlerts = function(li_id) {
1245         var li = this.liCache[li_id];
1246
1247         var alert_notes = li.lineitem_notes().filter(
1248             function(o) { return Boolean(o.alert_text()); }
1249         );
1250
1251         /* this is _intentionally_ not done in a call to forEach() ... */
1252         for (var i = 0; i < alert_notes.length; i++) {
1253             if (this.noteAcks[alert_notes[i].id()])
1254                 continue;
1255             else if (!this._confirmAlert(li, alert_notes[i]))
1256                 return false;
1257             else
1258                 this.noteAcks[alert_notes[i].id()] = true;
1259         }
1260
1261         return true;
1262     };
1263
1264     this.deleteCopy = function(row) {
1265         var copy = this.copyCache[row.getAttribute('copy_id')];
1266         copy.isdeleted(true);
1267         if(copy.isnew())
1268             delete this.copyCache[copy.id()];
1269         this.copyTbody.removeChild(row);
1270     }
1271
1272     this._virtDfaCountsAsList = function() {
1273         var L = [];
1274         for (var key in this.virtDfaCounts) {
1275             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1276                 L.push(key);
1277         }
1278         return L;
1279     }
1280
1281     this.saveCopyChanges = function(liId) {
1282         var self = this;
1283         var copies = [];
1284
1285
1286         var total = 0;
1287         for(var id in this.copyCache) {
1288             var c = this.copyCache[id];
1289             if(!c.isdeleted()) total++;
1290             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1291                 if(c.id() < 0) c.id(null);
1292                 copies.push(c);
1293             }
1294         }
1295
1296         if (typeof(this._copy_count_cb) == "function") {
1297             this._copy_count_cb(liId, total);
1298         }
1299
1300         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1301
1302
1303         if (copies.length > 0) {
1304             openils.Util.show("acq-lit-update-copies-progress");
1305             fieldmapper.standardRequest(
1306                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1307                 {   async: true,
1308                     params: [openils.User.authtoken, copies],
1309                     onresponse: function(r) {
1310                         var res = openils.Util.readResponse(r);
1311                         litUpdateCopiesProgress.update(res);
1312                     },
1313                     oncomplete: function() {
1314                         self.drawCopies(liId);
1315                         openils.Util.hide("acq-lit-update-copies-progress");
1316                     }
1317                 }
1318             );
1319         }
1320
1321         var dfa_list = this._virtDfaCountsAsList();
1322         if (dfa_list.length > 0) {
1323             fieldmapper.standardRequest(
1324                 ["open-ils.acq",
1325                 "open-ils.acq.distribution_formula.record_application"],
1326                 {
1327                     "async": true,
1328                     "params": [openils.User.authtoken, dfa_list, liId],
1329                     "onresponse": function(r) {
1330                         var res = openils.Util.readResponse(r);
1331                         if (res && res.length < dfa_list.length)
1332                             alert(localeStrings.DFA_NOT_ALL);
1333                     }
1334                 }
1335             );
1336             this.virtDfaCounts = {};
1337         }
1338     }
1339
1340     this.applySelectedLiAction = function(action) {
1341         var self = this;
1342         switch(action) {
1343
1344             case 'delete_selected':
1345                 this._deleteLiList(self.getSelected());
1346                 break;
1347
1348             case 'create_order':
1349
1350                 if(!this.createPoProviderSelector) {
1351                     var widget = new openils.widget.AutoFieldWidget({
1352                         fmField : 'provider',
1353                         fmClass : 'acqpo',
1354                         searchFilter: {"active": "t"},
1355                         parentNode : dojo.byId('acq-lit-po-provider'),
1356                     });
1357                     widget.build(
1358                         function(w) { self.createPoProviderSelector = w; }
1359                     );
1360                 }
1361
1362                 if(!this.createPoAgencySelector) {
1363                     var widget = new openils.widget.AutoFieldWidget({
1364                         fmField : 'ordering_agency',
1365                         fmClass : 'acqpo',
1366                         parentNode : dojo.byId('acq-lit-po-agency'),
1367                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1368                     });
1369                     widget.build(
1370                         function(w) { self.createPoAgencySelector = w; }
1371                     );
1372                 }
1373
1374          
1375                 acqLitPoCreateDialog.show();
1376                 break;
1377
1378             case 'save_picklist':
1379                 this._loadPLSelect();
1380                 acqLitSavePlDialog.show();
1381                 break;
1382
1383             case 'selector_ready':
1384             case 'order_ready':
1385                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1386                 acqLitChangeLiStateDialog.show();
1387                 break;
1388
1389             case 'print_po':
1390                 this.printPO();
1391                 break;
1392
1393             case 'receive_po':
1394                 this.receivePO();
1395                 break;
1396
1397             case 'rollback_receive_po':
1398                 this.rollbackPoReceive();
1399                 break;
1400
1401             case 'create_assets':
1402                 this.createAssets();
1403                 break;
1404
1405             case 'export_attr_list':
1406                 this.chooseExportAttr();
1407                 break;
1408
1409             case 'add_brief_record':
1410                 if(this.isPO)
1411                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1412                 else
1413                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1414         }
1415     }
1416
1417     this.createAssets = function() {
1418         if(!this.isPO) return;
1419         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1420         this.show('acq-lit-progress-numbers');
1421         var self = this;
1422         fieldmapper.standardRequest(
1423             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1424             {   async: true,
1425                 params: [this.authtoken, this.isPO],
1426                 onresponse: function(r) {
1427                     var resp = openils.Util.readResponse(r);
1428                     self._updateProgressNumbers(resp, true);
1429                 }
1430             }
1431         );
1432     }
1433
1434     this.chooseExportAttr = function() {
1435         if (!acqLitExportAttrSelector._li_setup) {
1436             var self = this;
1437             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1438                 {
1439                     "data": acqliad.toStoreData(
1440                         this.pcrud.search(
1441                             "acqliad", {"code": li_exportable_attrs}
1442                         )
1443                     )
1444                 }
1445             );
1446             acqLitExportAttrSelector.setValue();
1447             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1448             acqLitExportAttrSelector._li_setup = true;
1449         }
1450         openils.Util.show("acq-lit-export-attr-holder", "inline");
1451     };
1452
1453     this.exportAttrList = function() {
1454         var attr_def = acqLitExportAttrSelector.item;
1455         var li_list = this.getSelected();
1456         var value_list = li_list.map(
1457             function(li) {
1458                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1459                     attr_def.code, "lineitem_marc_attr_definition"
1460                 );
1461             }
1462         ).filter(function(attr) { return Boolean(attr); });
1463
1464         if (value_list.length > 0) {
1465             if (value_list.length < li_list.length) {
1466                 if (!confirm(
1467                     dojo.string.substitute(
1468                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1469                     )
1470                 )) {
1471                     return;
1472                 }
1473             }
1474             try {
1475                 openils.XUL.contentToFileSaveDialog(
1476                     value_list.join("\n"),
1477                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
1478                 );
1479             } catch (E) {
1480                 alert(E);
1481             }
1482         } else {
1483             alert(dojo.string.substitute(
1484                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1485             ));
1486         }
1487
1488         openils.Util.hide("acq-lit-export-attr-holder");
1489     };
1490
1491     this.printPO = function() {
1492         if(!this.isPO) return;
1493         progressDialog.show(true);
1494         fieldmapper.standardRequest(
1495             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1496             {   async: true,
1497                 params: [this.authtoken, this.isPO, 'html'],
1498                 oncomplete: function(r) {
1499                     progressDialog.hide();
1500                     var evt = openils.Util.readResponse(r);
1501                     if(evt && evt.template_output()) {
1502                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1503                         win.document.body.innerHTML = evt.template_output().data();
1504                     }
1505                 }
1506             }
1507         );
1508     }
1509
1510
1511     this.receivePO = function() {
1512         if (!this.isPO) return;
1513
1514         for (var id in this.liCache) {
1515             /* assumption: liCache reflects exactly the
1516              * set of LIs that belong to our PO */
1517             if (this.liCache[id].state() != "received" &&
1518                 !this.checkLiAlerts(id)) return;
1519         }
1520
1521         this.show('acq-lit-progress-numbers');
1522         var self = this;
1523         fieldmapper.standardRequest(
1524             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1525             {   async: true,
1526                 params: [this.authtoken, this.isPO],
1527                 onresponse : function(r) {
1528                     var resp = openils.Util.readResponse(r);
1529                     self._updateProgressNumbers(resp, true);
1530                 },
1531             }
1532         );
1533     }
1534
1535     this.issueReceive = function(obj, rollback) {
1536         /* (For now) there shall be no marking LI or LIDs (un)received
1537          * except from the actual "view PO" interface. */
1538         if (!this.isPO) return;
1539
1540         var part =
1541             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1542         var method =
1543             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1544
1545         progressDialog.show(true);
1546         fieldmapper.standardRequest(
1547             ["open-ils.acq", method], {
1548                 "async": true,
1549                 "params": [this.authtoken, obj.id()],
1550                 "onresponse": function(r) {
1551                     self.handleReceive(openils.Util.readResponse(r));
1552                 },
1553                 "oncomplete": function() { progressDialog.hide(); }
1554             }
1555         );
1556     };
1557
1558     /**
1559      * Handles the responses from receive and rollback ML calls.
1560      */
1561     this.handleReceive = function(resp) {
1562         if (resp) {
1563             if (resp.li) {
1564                 for (var li_id in resp.li) {
1565                     for (var key in resp.li[li_id])
1566                         self.liCache[li_id][key](resp.li[li_id][key]);
1567                     self.updateLiReceivedness(self.liCache[li_id]);
1568                 }
1569             }
1570             if (resp.po) {
1571                 if (typeof(self.poUpdateCallback) == "function")
1572                     self.poUpdateCallback(resp.po);
1573             }
1574             if (resp.lid) {
1575                 for (var lid_id in resp.lid) {
1576                     for (var key in resp.lid[lid_id])
1577                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1578                     self.updateLidReceivedness(self.copyCache[lid_id]);
1579                 }
1580             }
1581         }
1582     };
1583
1584     this.rollbackPoReceive = function() {
1585         if(!this.isPO) return;
1586         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1587         this.show('acq-lit-progress-numbers');
1588         var self = this;
1589         fieldmapper.standardRequest(
1590             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1591             {   async: true,
1592                 params: [this.authtoken, this.isPO],
1593                 onresponse : function(r) {
1594                     var resp = openils.Util.readResponse(r);
1595                     self._updateProgressNumbers(resp, true);
1596                 },
1597             }
1598         );
1599     }
1600
1601     this._updateProgressNumbers = function(resp, reloadOnComplete) {
1602         if(!resp) return;
1603         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1604         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1605         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1606         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1607         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1608         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1609         if(resp.complete && reloadOnComplete) 
1610             location.href = location.href;
1611     }
1612
1613
1614     this._createPO = function(fields) {
1615         this.show('acq-lit-progress-numbers');
1616         var po = new fieldmapper.acqpo();
1617         po.provider(this.createPoProviderSelector.attr('value'));
1618         po.ordering_agency(this.createPoAgencySelector.attr('value'));
1619
1620         var selected = this.getSelected( (fields.create_from == 'all') );
1621         if(selected.length == 0) return;
1622
1623         var max = selected.length * 3;
1624
1625         var self = this;
1626         fieldmapper.standardRequest(
1627             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1628             {   async: true,
1629                 params: [
1630                     openils.User.authtoken, 
1631                     po, 
1632                     {
1633                         lineitems : selected.map(function(li) { return li.id() }),
1634                         create_assets : fields.create_assets[0],
1635                     }
1636                 ],
1637
1638                 onresponse : function(r) {
1639                     var resp = openils.Util.readResponse(r);
1640                     self._updateProgressNumbers(resp);
1641                     if(resp.complete) 
1642                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1643                 }
1644             }
1645         );
1646     }
1647
1648     this._deleteLiList = function(list, idx) {
1649         if(idx == null) idx = 0;
1650         if(idx >= list.length) return;
1651         var liId = list[idx].id();
1652         fieldmapper.standardRequest(
1653             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1654             {   async: true,
1655                 params: [openils.User.authtoken, liId],
1656                 oncomplete: function(r) {
1657                     self.removeLineitem(liId);
1658                     self._deleteLiList(list, ++idx);
1659                 }
1660             }
1661         );
1662     }
1663
1664     this.editOrderMarc = function(li) {
1665
1666         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
1667             to true in about:config */
1668
1669         if(!openils.XUL.enableXPConnect()) return;
1670
1671         if(openils.XUL.isXUL()) {
1672             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1673         } else {
1674             win = window.open('/xul/server/cat/marcedit.xul'); 
1675         }
1676         var self = this;
1677         win.xulG = {
1678             record : {marc : li.marc()},
1679             save : {
1680                 label: 'Save Record', // XXX I18N
1681                 func: function(xmlString) {
1682                     li.marc(xmlString);
1683                     fieldmapper.standardRequest(
1684                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1685                         {   async: true,
1686                             params: [openils.User.authtoken, li],
1687                             oncomplete: function(r) {
1688                                 openils.Util.readResponse(r);
1689                                 win.close();
1690                                 self.drawInfo(li.id())
1691                             }
1692                         }
1693                     );
1694                 },
1695             }
1696         };
1697     }
1698
1699     this._savePl = function(values) {
1700         var self = this;
1701         var selected = this.getSelected( (values.which == 'all') );
1702         openils.Util.show('acq-lit-generic-progress');
1703
1704         if(values.new_name) {
1705             openils.acq.Picklist.create(
1706                 {name: values.new_name}, 
1707                 function(id) {
1708                     self._updateLiList(id, selected, 0, 
1709                         function(){
1710                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1711                         });
1712                 }
1713             );
1714         } else if(values.existing_pl) {
1715             // update lineitems to use an existing picklist
1716             self._updateLiList(values.existing_pl, selected, 0, 
1717                 function(){
1718                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1719                 });
1720         }
1721     }
1722
1723     this._updateLiState = function(values, state) {
1724         var self = this;
1725         var selected = this.getSelected( (values.which == 'all') );
1726         if(!selected.length) return;
1727         dojo.forEach(selected, function(li) {li.state(state);});
1728         self._updateLiList(null, selected, 0, 
1729             // TODO consider inline updates for efficiency
1730             function() { location.href = location.href }
1731         );
1732     }
1733
1734     this._updateLiList = function(pl, list, idx, oncomplete) {
1735         if(idx >= list.length) return oncomplete();
1736         var li = list[idx];
1737         if(pl != null) li.picklist(pl);
1738         litGenericProgress.update({maximum: list.length, progress: idx});
1739         new openils.acq.Lineitem({lineitem:li}).update(
1740             function(r) {
1741                 self._updateLiList(pl, list, ++idx, oncomplete);
1742             }
1743         );
1744     }
1745
1746     this._loadPLSelect = function() {
1747         if(this._plSelectLoaded) return;
1748         var plList = [];
1749         function handleResponse(r) {
1750             plList.push(r.recv().content());
1751         }
1752         var method = 'open-ils.acq.picklist.user.retrieve';
1753         fieldmapper.standardRequest(
1754             ['open-ils.acq', method],
1755             {   async: true,
1756                 params: [this.authtoken],
1757                 onresponse: handleResponse,
1758                 oncomplete: function() {
1759                     self._plSelectLoaded = true;
1760                     acqLitAddExistingSelect.store = 
1761                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1762                     acqLitAddExistingSelect.setValue();
1763                 }
1764             }
1765         );
1766     }
1767
1768     this.showRealCopyEditUI = function(li) {
1769         copyList = [];
1770         var self = this;
1771         this.volCache = {};
1772
1773         this._fetchLineitem(li.id(), 
1774             function(fullLi) {
1775                 li = self.liCache[li.id()] = fullLi;
1776
1777                 self.pcrud.search(
1778                     'acp', {
1779                         id : li.lineitem_details().map(
1780                             function(item) { return item.eg_copy_id() }
1781                         )
1782                     }, {
1783                         async : true,
1784                         oncomplete : function(r) {
1785                             try {
1786                                 var r_list = openils.Util.readResponse( r );
1787                                 for (var i = 0; i < r_list.length; i++) {
1788                                     var copy = r_list[i];
1789                                     var volId = copy.call_number();
1790                                     var volume = self.volCache[volId];
1791                                     if(!volume) {
1792                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
1793                                     }
1794                                     copy.call_number(volume);
1795                                     copyList.push(copy);
1796                                 }
1797                                 if (xulG) {
1798                                     // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
1799                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
1800                                 }
1801                             } catch(E) {
1802                                 alert('error in oncomplete: ' + E);
1803                             }
1804                         }
1805                     }
1806                 );
1807             }
1808         );
1809     }
1810
1811     
1812     /*
1813     this.saveRealCopies = function() {
1814         progressDialog.show(true);
1815         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1816         this.pcrud.update(list, {oncomplete: function() { 
1817             progressDialog.hide();
1818             self.show('list');
1819         }});
1820     }
1821
1822     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1823     this.showRealCopies = function(li) {
1824         while(this.realCopiesTbody.childNodes[0])
1825             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1826         this.show('real-copies');
1827
1828         this.realCopyList = [];
1829         this.volCache = {};
1830         var tabIndex = 1000;
1831         var self = this;
1832
1833         acqLitSaveRealCopies.onClick = function() {
1834             self.saveRealCopies();
1835         }
1836
1837         this._fetchLineitem(li.id(), 
1838             function(fullLi) {
1839                 li = self.liCache[li.id()] = fullLi;
1840
1841                 self.pcrud.search(
1842                     'acp', {
1843                         id : li.lineitem_details().map(
1844                             function(item) { return item.eg_copy_id() }
1845                         )
1846                     }, {
1847                         async : true,
1848                         streaming : true,
1849                         onresponse : function(r) {
1850                             var copy = openils.Util.readResponse(r);
1851                             var volId = copy.call_number();
1852                             var volume = self.volCache[volId];
1853                             if(!volume) {
1854                                 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
1855                             }
1856                             self.addRealCopy(volume, copy, tabIndex++);
1857                         }
1858                     }
1859                 );
1860             }
1861         );
1862     }
1863
1864     this.addRealCopy = function(volume, copy, tabIndex) {
1865         var row = this.realCopiesRow.cloneNode(true);
1866         this.realCopyList.push(copy);
1867
1868         var selectNode;
1869         dojo.forEach(
1870             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1871
1872             function(field) {
1873                 var isvol = (field == 'owning_lib' || field == 'label');
1874                 var widget = new openils.widget.AutoFieldWidget({
1875                     fmField : field,
1876                     fmObject : isvol ? volume : copy,
1877                     parentNode : nodeByName(field, row),
1878                     readOnly : (field != 'barcode'),
1879                 });
1880
1881                 var widgetDrawn = null;
1882
1883                 if(field == 'barcode') {
1884
1885                     widgetDrawn = function(w, ww) {
1886                         var node = w.domNode;
1887                         node.setAttribute('tabindex', ''+tabIndex);
1888
1889                         // on enter, select the next barcode input
1890                         dojo.connect(w, 'onKeyDown',
1891                             function(e) {
1892                                 if(e.keyCode == dojo.keys.ENTER) {
1893                                     var ti = node.getAttribute('tabindex');
1894                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1895                                     if(nextNode) nextNode.select();
1896                                 }
1897                             }
1898                         );
1899
1900                         dojo.connect(w, 'onChange', 
1901                             function(val) { 
1902                                 if(!val || val == copy.barcode()) return;
1903                                 copy.ischanged(true);
1904                                 copy.barcode(val);
1905                             }
1906                         );
1907
1908
1909                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1910                             selectNode = node;
1911                     }
1912                 }
1913
1914                 widget.build(widgetDrawn);
1915             }
1916         );
1917
1918         this.realCopiesTbody.appendChild(row);
1919         if(selectNode) selectNode.select();
1920     };
1921     */
1922
1923 }