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