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