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