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