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