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