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