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