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