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