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